bailian-cli-commands 1.17.0 → 1.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1922,6 +1922,15 @@ declare const _default$59: _$bailian_cli_core0.Command<{
1922
1922
  };
1923
1923
  required: true;
1924
1924
  };
1925
+ description: {
1926
+ type: "string";
1927
+ valueHint: string;
1928
+ description: {
1929
+ "en-US": string;
1930
+ "zh-CN": string;
1931
+ };
1932
+ required: true;
1933
+ };
1925
1934
  docId: {
1926
1935
  type: "array";
1927
1936
  valueHint: string;
package/dist/index.mjs CHANGED
@@ -2727,15 +2727,15 @@ Updating agent skill...
2727
2727
  `),process.stderr.write(` ${r}\n\n`)}return}let d=`npm install -g ${l?`${r}@${l}`:`${r}@latest`}`;process.stderr.write(`Updating ${r} via npm...\n\n`);try{Sr(d,{stdio:`inherit`});try{let e=Sr(`${i} --version 2>/dev/null`,{encoding:`utf-8`}).trim().replace(RegExp(`^${i}\\s+`),``);process.stderr.write(`\n${o.green(`\u2713 Update complete: ${a} \u2192 ${e}`)}\n`),Bs(e)}catch{process.stderr.write(`\n${o.green(`✓ Update complete.`)}\n`)}zs(o)}catch{process.stderr.write(`
2728
2728
  Automatic update failed. Please run manually:
2729
2729
  `),process.stderr.write(` ${d}\n\n`)}}}),Ws=w({description:{"en-US":`Call a Bailian application (agent or workflow)`,"zh-CN":`调用百炼应用(智能体或工作流)`},auth:`apiKey`,usageArgs:`--app-id <id> --prompt <text> [flags]`,flags:{appId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Application ID (required)`,"zh-CN":`应用 ID(必填)`},required:!0},prompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Input prompt text`,"zh-CN":`输入提示词文本`},required:!0},image:{type:`array`,valueHint:`<url>`,description:{"en-US":`Image URL(s) to pass to the app (repeatable)`,"zh-CN":`传给应用的图片 URL(可重复)`}},fileId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Pre-uploaded file ID(s) (repeatable)`,"zh-CN":`已上传的文件 ID(可重复)`}},sessionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Session ID for multi-turn conversation`,"zh-CN":`多轮对话的 Session ID`}},stream:{type:`switch`,description:{"en-US":`Stream response (default: on in TTY)`,"zh-CN":`流式输出响应(TTY 中默认开启)`}},pipelineIds:{type:`string`,valueHint:`<ids>`,description:{"en-US":`Knowledge base pipeline IDs (comma-separated)`,"zh-CN":`知识库 Pipeline ID(以逗号分隔)`}},memoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory ID for long-term memory`,"zh-CN":`长期记忆使用的 Memory ID`}},bizParams:{type:`string`,valueHint:`<json>`,description:{"en-US":`Business parameters JSON (workflow variables)`,"zh-CN":`业务参数 JSON(工作流变量)`}},hasThoughts:{type:`switch`,description:{"en-US":`Show agent thinking process`,"zh-CN":`显示智能体思考过程`}}},exampleArgs:[{"en-US":`--app-id abc123 --prompt "Hello"`,"zh-CN":`--app-id abc123 --prompt "你好"`},{"en-US":`--app-id abc123 --prompt "Describe this image" --image https://example.com/photo.jpg`,"zh-CN":`--app-id abc123 --prompt "描述这张图片" --image https://example.com/photo.jpg`},{"en-US":`--app-id abc123 --prompt "Analyze the image" --image img1.jpg --image img2.jpg`,"zh-CN":`--app-id abc123 --prompt "分析这些图片" --image img1.jpg --image img2.jpg`},{"en-US":`--app-id abc123 --prompt "Continue" --session-id sess_xxx --stream`,"zh-CN":`--app-id abc123 --prompt "继续" --session-id sess_xxx --stream`},{"en-US":`--app-id abc123 --prompt "Search for materials" --pipeline-ids pipe1,pipe2`,"zh-CN":`--app-id abc123 --prompt "搜索资料" --pipeline-ids pipe1,pipe2`},{"en-US":`--app-id abc123 --prompt "Start" --biz-params '{"key":"value"}'`,"zh-CN":`--app-id abc123 --prompt "开始" --biz-params '{"key":"value"}'`}],async run(e){let{settings:t,flags:n}=e,r=n.appId,i=n.prompt,a=n.stream||process.stdout.isTTY,o=T(t.output),s={input:{prompt:i},parameters:{incremental_output:a}};n.sessionId&&(s.input.session_id=n.sessionId);let c=n.image;c&&c.length>0&&(s.input.image_list=c);let l=n.fileId;if(l&&l.length>0&&(s.input.file_ids=l),n.hasThoughts&&(s.parameters.has_thoughts=!0),n.pipelineIds){let e=n.pipelineIds.split(`,`).map(e=>e.trim()).filter(Boolean);s.parameters.rag_options={pipeline_ids:e}}if(n.memoryId&&(s.parameters.memory_id=n.memoryId),n.bizParams)try{s.input.biz_params=JSON.parse(n.bizParams)}catch{throw new y(`--biz-params must be valid JSON`)}if(t.dryRun){A({endpoint:e.client.url(S(r)),request:s},o);return}if(a){let i=await e.client.request({path:S(r),method:`POST`,body:s,headers:{"X-DashScope-SSE":`enable`},stream:!0}),a=``,c=``,l=o===`text`,u=O(process.stderr);for await(let e of Et(i)){if(e.data===`[DONE]`)break;try{let t=JSON.parse(e.data),r=t.output?.text;if(r&&(l&&process.stdout.write(r),a+=r),t.output?.session_id&&(c=t.output.session_id),t.output?.thoughts&&n.hasThoughts)for(let e of t.output.thoughts)e.thought&&process.stderr.write(`${u.dim(`[Thinking] ${e.thought}`)}\n`),e.action_name&&process.stderr.write(`${u.dim(`[Action] ${e.action_name}: ${e.action_input||``}`)}\n`),e.observation&&process.stderr.write(`${u.dim(`[Observation] ${e.observation}`)}\n`)}catch{}}c&&!t.quiet&&process.stderr.write(`${u.dim(`Session ID: ${c}`)}\n`),o===`json`?A({text:a,session_id:c},o):process.stdout.write(`
2730
- `)}else{let n=await e.client.requestJson({path:S(r),method:`POST`,body:s}),i=n.output?.text??``;t.quiet||o===`text`?k(i):A(n,o)}}});const Gs=`zeldaEasy.broadscope-bailian.app-control.list`;var Ks=w({description:{"en-US":`List Bailian applications`,"zh-CN":`列出百炼应用`},auth:`console`,usageArgs:`[flags]`,flags:{name:{type:`string`,valueHint:`<name>`,description:{"en-US":`Filter by app name (keyword search)`,"zh-CN":`按应用名称筛选(关键词搜索)`}},page:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Results per page (default: 30)`,"zh-CN":`每页结果数(默认:30)`}}},exampleArgs:[``,{"en-US":`--name customer service`,"zh-CN":`--name 客户服务`},`--page 2 --page-size 10`,`--output json`],async run(e){let{settings:t,flags:n}=e,r=n.name||``,i=n.page||1,a=n.pageSize||30,o=T(t.output),s={reqDTO:{name:r,notInTypes:[10],type:5,statuses:[1,4],page_no:i,page_size:a}};if(t.dryRun){A({api:Gs,data:s},o);return}let c=await e.client.console(Gs,s),l=c?.data?.DataV2?.data?.data?.list??[];A({total:c?.data?.DataV2?.data?.data?.total??0,apps:l.map(e=>({code:e.code,name:e.name,user_prompt_params:e.config?.user_prompt_params??[]}))},o)}}),qs=w({description:{"en-US":`Add memory from messages or custom content`,"zh-CN":`从消息或自定义内容添加记忆`},auth:`apiKey`,usageArgs:`--user-id <id> [--messages <json>] [--content <text>] [flags]`,flags:{userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},messages:{type:`string`,valueHint:`<json>`,description:{"en-US":`Messages JSON array: [{"role":"user","content":"..."},...]`,"zh-CN":`消息 JSON 数组:[{"role":"user","content":"..."},...]`}},content:{type:`string`,valueHint:`<text>`,description:{"en-US":`Custom content text to memorize`,"zh-CN":`要记忆的自定义内容文本`}},profileSchema:{type:`string`,valueHint:`<id>`,description:{"en-US":`Profile schema ID for user profiling`,"zh-CN":`用于用户画像的 Profile Schema ID`}},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID (isolate memory space)`,"zh-CN":`记忆库 ID(用于隔离记忆空间)`}}},exampleArgs:[{"en-US":`--user-id user1 --content "The user likes Python programming"`,"zh-CN":`--user-id user1 --content "用户喜欢使用 Python 编程"`},{"en-US":`--user-id user1 --messages '[{"role":"user","content":"I like traveling"}]'`,"zh-CN":`--user-id user1 --messages '[{"role":"user","content":"我喜欢旅行"}]'`},{"en-US":`--user-id user1 --content "Lives in Beijing" --profile-schema schema_xxx`,"zh-CN":`--user-id user1 --content "居住在北京" --profile-schema schema_xxx`}],validate:e=>!e.messages&&!e.content?`Provide --messages or --content.`:void 0,async run(e){let{settings:t,flags:n}=e,r={user_id:n.userId};if(n.messages)try{r.messages=JSON.parse(n.messages)}catch{throw new y(`--messages must be valid JSON array`)}n.content&&(r.custom_content=n.content),n.profileSchema&&(r.profile_schema=n.profileSchema),n.memoryLibraryId&&(r.memory_library_id=n.memoryLibraryId);let i=T(t.output);if(t.dryRun){A({endpoint:e.client.url(gt()),request:r},i);return}let a=await e.client.requestJson({path:gt(),method:`POST`,body:r});t.quiet||i===`text`?k(`Memory added. IDs: ${a.memory_ids?.join(`, `)||`none`}`):A(a,i)}}),Js=w({description:{"en-US":`Search memory nodes by query or messages`,"zh-CN":`通过查询文本或消息搜索记忆节点`},auth:`apiKey`,usageArgs:`--user-id <id> [--query <text>] [flags]`,flags:{userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},query:{type:`string`,valueHint:`<text>`,description:{"en-US":`Search query text`,"zh-CN":`搜索查询文本`}},messages:{type:`string`,valueHint:`<json>`,description:{"en-US":`Messages JSON array for context-based search`,"zh-CN":`用于上下文搜索的消息 JSON 数组`}},topK:{type:`number`,valueHint:`<n>`,description:{"en-US":`Number of results to return (default: 10)`,"zh-CN":`返回结果数量(默认:10)`}},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID`,"zh-CN":`记忆库 ID`}}},exampleArgs:[{"en-US":`--user-id user1 --query "programming preferences"`,"zh-CN":`--user-id user1 --query "编程偏好"`},{"en-US":`--user-id user1 --messages '[{"role":"user","content":"recommend a book"}]' --top-k 5`,"zh-CN":`--user-id user1 --messages '[{"role":"user","content":"推荐一本书"}]' --top-k 5`}],validate:e=>!e.query&&!e.messages?`Provide --query or --messages.`:void 0,async run(e){let{settings:t,flags:n}=e,r={user_id:n.userId};if(n.query&&(r.query=n.query),n.messages)try{r.messages=JSON.parse(n.messages)}catch{throw new y(`--messages must be valid JSON array`)}!r.messages&&r.query&&(r.messages=[{role:`user`,content:r.query}]),n.topK!==void 0&&(r.top_k=n.topK),n.memoryLibraryId&&(r.memory_library_id=n.memoryLibraryId);let i=T(t.output);if(t.dryRun){A({endpoint:e.client.url(yt()),request:r},i);return}let a=await e.client.requestJson({path:yt(),method:`POST`,body:r});if(t.quiet||i===`text`)if(!a.memory_nodes||a.memory_nodes.length===0)k(`No memory nodes found.`);else for(let e of a.memory_nodes)k(`[${e.memory_node_id}] ${e.content}`);else A(a,i)}}),Ys=w({description:{"en-US":`List memory nodes for a user`,"zh-CN":`列出用户的记忆节点`},auth:`apiKey`,usageArgs:`--user-id <id> [flags]`,flags:{userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Results per page (default: 10)`,"zh-CN":`每页结果数(默认:10)`}},page:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID`,"zh-CN":`记忆库 ID`}}},exampleArgs:[`--user-id user1`,`--user-id user1 --page-size 20 --page 2`],async run(e){let{settings:t,flags:n}=e,r=n.userId,i=T(t.output),a=new URLSearchParams;a.set(`user_id`,r),n.pageSize!==void 0&&a.set(`page_size`,String(n.pageSize)),n.page!==void 0&&a.set(`page_num`,String(n.page)),n.memoryLibraryId&&a.set(`memory_library_id`,n.memoryLibraryId);let o=`${_t()}?${a.toString()}`;if(t.dryRun){A({endpoint:e.client.url(o),method:`GET`},i);return}let s=await e.client.requestJson({path:o,method:`GET`});if(t.quiet||i===`text`)if(!s.memory_nodes||s.memory_nodes.length===0)k(`No memory nodes found.`);else{for(let e of s.memory_nodes)k(`[${e.memory_node_id}] ${e.content}`);s.total!==void 0&&k(`\nTotal: ${s.total}`)}else A(s,i)}}),Xs=w({description:{"en-US":`Update a memory node content`,"zh-CN":`更新记忆节点内容`},auth:`apiKey`,usageArgs:`--node-id <id> --user-id <id> --content <text>`,flags:{nodeId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory node ID (required)`,"zh-CN":`记忆节点 ID(必填)`},required:!0},userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},content:{type:`string`,valueHint:`<text>`,description:{"en-US":`New content for the memory node (required)`,"zh-CN":`记忆节点的新内容(必填)`},required:!0},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID (non-default library)`,"zh-CN":`记忆库 ID(非默认记忆库)`}}},exampleArgs:[{"en-US":`--node-id node_xxx --user-id user1 --content "updated memory content"`,"zh-CN":`--node-id node_xxx --user-id user1 --content "更新后的记忆内容"`}],async run(e){let{settings:t,flags:n}=e,r=n.nodeId,i={user_id:n.userId,custom_content:n.content};n.memoryLibraryId&&(i.memory_library_id=n.memoryLibraryId);let a=T(t.output);if(t.dryRun){A({endpoint:e.client.url(vt(r)),method:`PATCH`,request:i},a);return}let o=await e.client.requestJson({path:vt(r),method:`PATCH`,body:i});t.quiet||a===`text`?k(`Memory node ${r} updated.`):A(o,a)}}),Zs=w({description:{"en-US":`Delete a memory node`,"zh-CN":`删除记忆节点`},auth:`apiKey`,usageArgs:`--node-id <id> --user-id <id>`,flags:{nodeId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory node ID (required)`,"zh-CN":`记忆节点 ID(必填)`},required:!0},userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID (non-default library)`,"zh-CN":`记忆库 ID(非默认记忆库)`}}},exampleArgs:[`--node-id node_xxx --user-id user1`],async run(e){let{settings:t,flags:n}=e,r=n.nodeId,i=n.userId,a=T(t.output),o=new URLSearchParams({user_id:i});n.memoryLibraryId&&o.set(`memory_library_id`,n.memoryLibraryId);let s=`${vt(r)}?${o.toString()}`;if(t.dryRun){A({endpoint:e.client.url(s),method:`DELETE`},a);return}let c=await e.client.requestJson({path:s,method:`DELETE`});t.quiet||a===`text`?k(`Memory node ${r} deleted.`):A(c,a)}}),Qs=w({description:{"en-US":`Create a user profile schema for memory profiling`,"zh-CN":`创建用于记忆画像的用户 Profile Schema`},auth:`apiKey`,usageArgs:`--name <name> --attributes <json> [flags]`,flags:{name:{type:`string`,valueHint:`<name>`,description:{"en-US":`Schema name (required)`,"zh-CN":`Schema 名称(必填)`},required:!0},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`Schema description`,"zh-CN":`Schema 描述`}},attributes:{type:`string`,valueHint:`<json>`,description:{"en-US":`Attributes JSON array: [{"name":"age","description":"age"}]`,"zh-CN":`属性 JSON 数组:[{"name":"age","description":"age"}]`},required:!0}},exampleArgs:[{"en-US":`--name "user_basic" --attributes '[{"name":"age","description":"age"},{"name":"hobby","description":"hobby"}]'`,"zh-CN":`--name "user_basic" --attributes '[{"name":"age","description":"年龄"},{"name":"hobby","description":"爱好"}]'`}],async run(e){let{settings:t,flags:n}=e,r=n.name,i=n.attributes,a;try{a=JSON.parse(i)}catch{throw new y(`--attributes must be valid JSON array`)}let o={name:r,attributes:a};n.description&&(o.description=n.description);let s=T(t.output);if(t.dryRun){A({endpoint:e.client.url(At()),request:o},s);return}let c=await e.client.requestJson({path:At(),method:`POST`,body:o});t.quiet||s===`text`?k(`Profile schema created: ${c.profile_schema_id}`):A(c,s)}}),$s=w({description:{"en-US":`Get user profile by schema ID and user ID`,"zh-CN":`通过 Schema ID 和用户 ID 获取用户画像`},auth:`apiKey`,usageArgs:`--schema-id <id> --user-id <id>`,flags:{schemaId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Profile schema ID (required)`,"zh-CN":`Profile Schema ID(必填)`},required:!0},userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0}},exampleArgs:[`--schema-id schema_xxx --user-id user1`],async run(e){let{settings:t,flags:n}=e,r=n.schemaId,i=n.userId,a=T(t.output),o=new URLSearchParams({user_id:i}),s=`${on(r)}?${o.toString()}`;if(t.dryRun){A({endpoint:e.client.url(s),method:`GET`},a);return}let c=await e.client.requestJson({path:s,method:`GET`});if(t.quiet||a===`text`)if(c.profile?.attributes)for(let e of c.profile.attributes)k(`${e.name}: ${e.value??`(empty)`}`);else k(`No profile data found.`);else A(c,a)}}),ec=w({description:{"en-US":"Retrieve from a Bailian knowledge base (deprecated, use `search` instead)","zh-CN":"从百炼知识库检索(已废弃,请改用 `search`)"},auth:`apiKey`,usageArgs:`--index-id <id> --query <text> [flags]`,flags:{indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base index ID (required)`,"zh-CN":`知识库索引 ID(必填)`},required:!0},query:{type:`string`,valueHint:`<text>`,description:{"en-US":`Search query (required)`,"zh-CN":`搜索查询(必填)`},required:!0},denseSimilarityTopK:{type:`number`,valueHint:`<n>`,description:{"en-US":`Dense retrieval top K`,"zh-CN":`稠密检索 Top K`}},sparseSimilarityTopK:{type:`number`,valueHint:`<n>`,description:{"en-US":`Sparse retrieval top K`,"zh-CN":`稀疏检索 Top K`}},rerank:{type:`switch`,description:{"en-US":`Enable reranking`,"zh-CN":`启用重排序`}},rerankTopN:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rerank top N results`,"zh-CN":`重排序前 N 个结果`}},rerankModel:{type:`string`,valueHint:`<name>`,description:{"en-US":`Rerank model, e.g. qwen3-rerank-hybrid`,"zh-CN":`重排序模型,例如 qwen3-rerank-hybrid`}},rerankMode:{type:`string`,valueHint:`<mode>`,description:{"en-US":`Rerank mode: qa, similar, or custom`,"zh-CN":`重排序模式:qa、similar 或 custom`}},rerankInstruct:{type:`string`,valueHint:`<text>`,description:{"en-US":`Custom rerank instruction, when mode=custom`,"zh-CN":`自定义重排序指令,仅在 mode=custom 时使用`}},topK:{type:`number`,valueHint:`<n>`,description:{"en-US":`Number of results (deprecated, use --rerank-top-n)`,"zh-CN":`结果数量(已废弃,请使用 --rerank-top-n)`}}},exampleArgs:[{"en-US":`--index-id idx_xxx --query "How to use Alibaba Cloud Bailian"`,"zh-CN":`--index-id idx_xxx --query "如何使用阿里云百炼"`},{"en-US":`--index-id idx_xxx --query "RAG retrieval" --rerank --rerank-model qwen3-rerank-hybrid`,"zh-CN":`--index-id idx_xxx --query "RAG 检索" --rerank --rerank-model qwen3-rerank-hybrid`}],async run(e){let{settings:t,flags:n}=e,r=T(t.output);n.topK!==void 0&&n.rerankTopN===void 0&&(process.stderr.write(`Warning: --top-k is deprecated. Use --rerank-top-n instead.
2730
+ `)}else{let n=await e.client.requestJson({path:S(r),method:`POST`,body:s}),i=n.output?.text??``;t.quiet||o===`text`?k(i):A(n,o)}}});const Gs=`zeldaEasy.broadscope-bailian.app-control.list`;var Ks=w({description:{"en-US":`List Bailian applications`,"zh-CN":`列出百炼应用`},auth:`console`,usageArgs:`[flags]`,flags:{name:{type:`string`,valueHint:`<name>`,description:{"en-US":`Filter by app name (keyword search)`,"zh-CN":`按应用名称筛选(关键词搜索)`}},page:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Results per page (default: 30)`,"zh-CN":`每页结果数(默认:30)`}}},exampleArgs:[``,{"en-US":`--name customer service`,"zh-CN":`--name 客户服务`},`--page 2 --page-size 10`,`--output json`],async run(e){let{settings:t,flags:n}=e,r=n.name||``,i=n.page||1,a=n.pageSize||30,o=T(t.output),s={reqDTO:{name:r,notInTypes:[10],type:5,statuses:[1,4],page_no:i,page_size:a}};if(t.dryRun){A({api:Gs,data:s},o);return}let c=await e.client.console(Gs,s),l=c?.data?.DataV2?.data?.data?.list??[];A({total:c?.data?.DataV2?.data?.data?.total??0,apps:l.map(e=>({code:e.code,name:e.name,user_prompt_params:e.config?.user_prompt_params??[]}))},o)}}),qs=w({description:{"en-US":`Add memory from messages or custom content`,"zh-CN":`从消息或自定义内容添加记忆`},auth:`apiKey`,usageArgs:`--user-id <id> [--messages <json>] [--content <text>] [flags]`,flags:{userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},messages:{type:`string`,valueHint:`<json>`,description:{"en-US":`Messages JSON array: [{"role":"user","content":"..."},...]`,"zh-CN":`消息 JSON 数组:[{"role":"user","content":"..."},...]`}},content:{type:`string`,valueHint:`<text>`,description:{"en-US":`Custom content text to memorize`,"zh-CN":`要记忆的自定义内容文本`}},profileSchema:{type:`string`,valueHint:`<id>`,description:{"en-US":`Profile schema ID for user profiling`,"zh-CN":`用于用户画像的 Profile Schema ID`}},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID (isolate memory space)`,"zh-CN":`记忆库 ID(用于隔离记忆空间)`}}},exampleArgs:[{"en-US":`--user-id user1 --content "The user likes Python programming"`,"zh-CN":`--user-id user1 --content "用户喜欢使用 Python 编程"`},{"en-US":`--user-id user1 --messages '[{"role":"user","content":"I like traveling"}]'`,"zh-CN":`--user-id user1 --messages '[{"role":"user","content":"我喜欢旅行"}]'`},{"en-US":`--user-id user1 --content "Lives in Beijing" --profile-schema schema_xxx`,"zh-CN":`--user-id user1 --content "居住在北京" --profile-schema schema_xxx`}],validate:e=>!e.messages&&!e.content?`Provide --messages or --content.`:void 0,async run(e){let{settings:t,flags:n}=e,r={user_id:n.userId};if(n.messages)try{r.messages=JSON.parse(n.messages)}catch{throw new y(`--messages must be valid JSON array`)}n.content&&(r.custom_content=n.content),n.profileSchema&&(r.profile_schema=n.profileSchema),n.memoryLibraryId&&(r.memory_library_id=n.memoryLibraryId);let i=T(t.output);if(t.dryRun){A({endpoint:e.client.url(gt()),request:r},i);return}let a=await e.client.requestJson({path:gt(),method:`POST`,body:r});t.quiet||i===`text`?k(`Memory added. IDs: ${a.memory_ids?.join(`, `)||`none`}`):A(a,i)}}),Js=w({description:{"en-US":`Search memory nodes by query or messages`,"zh-CN":`通过查询文本或消息搜索记忆节点`},auth:`apiKey`,usageArgs:`--user-id <id> [--query <text>] [flags]`,flags:{userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},query:{type:`string`,valueHint:`<text>`,description:{"en-US":`Search query text`,"zh-CN":`搜索查询文本`}},messages:{type:`string`,valueHint:`<json>`,description:{"en-US":`Messages JSON array for context-based search`,"zh-CN":`用于上下文搜索的消息 JSON 数组`}},topK:{type:`number`,valueHint:`<n>`,description:{"en-US":`Number of results to return (default: 10)`,"zh-CN":`返回结果数量(默认:10)`}},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID`,"zh-CN":`记忆库 ID`}}},exampleArgs:[{"en-US":`--user-id user1 --query "programming preferences"`,"zh-CN":`--user-id user1 --query "编程偏好"`},{"en-US":`--user-id user1 --messages '[{"role":"user","content":"recommend a book"}]' --top-k 5`,"zh-CN":`--user-id user1 --messages '[{"role":"user","content":"推荐一本书"}]' --top-k 5`}],validate:e=>!e.query&&!e.messages?`Provide --query or --messages.`:void 0,async run(e){let{settings:t,flags:n}=e,r={user_id:n.userId};if(n.query&&(r.query=n.query),n.messages)try{r.messages=JSON.parse(n.messages)}catch{throw new y(`--messages must be valid JSON array`)}!r.messages&&r.query&&(r.messages=[{role:`user`,content:r.query}]),n.topK!==void 0&&(r.top_k=n.topK),n.memoryLibraryId&&(r.memory_library_id=n.memoryLibraryId);let i=T(t.output);if(t.dryRun){A({endpoint:e.client.url(yt()),request:r},i);return}let a=await e.client.requestJson({path:yt(),method:`POST`,body:r});if(t.quiet||i===`text`)if(!a.memory_nodes||a.memory_nodes.length===0)k(`No memory nodes found.`);else for(let e of a.memory_nodes)k(`[${e.memory_node_id}] ${e.content}`);else A(a,i)}}),Ys=w({description:{"en-US":`List memory nodes for a user`,"zh-CN":`列出用户的记忆节点`},auth:`apiKey`,usageArgs:`--user-id <id> [flags]`,flags:{userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Results per page (default: 10)`,"zh-CN":`每页结果数(默认:10)`}},page:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID`,"zh-CN":`记忆库 ID`}}},exampleArgs:[`--user-id user1`,`--user-id user1 --page-size 20 --page 2`],async run(e){let{settings:t,flags:n}=e,r=n.userId,i=T(t.output),a=new URLSearchParams;a.set(`user_id`,r),n.pageSize!==void 0&&a.set(`page_size`,String(n.pageSize)),n.page!==void 0&&a.set(`page_num`,String(n.page)),n.memoryLibraryId&&a.set(`memory_library_id`,n.memoryLibraryId);let o=`${_t()}?${a.toString()}`;if(t.dryRun){A({endpoint:e.client.url(o),method:`GET`},i);return}let s=await e.client.requestJson({path:o,method:`GET`});if(t.quiet||i===`text`)if(!s.memory_nodes||s.memory_nodes.length===0)k(`No memory nodes found.`);else{for(let e of s.memory_nodes)k(`[${e.memory_node_id}] ${e.content}`);s.total!==void 0&&k(`\nTotal: ${s.total}`)}else A(s,i)}}),Xs=w({description:{"en-US":`Update a memory node content`,"zh-CN":`更新记忆节点内容`},auth:`apiKey`,usageArgs:`--node-id <id> --user-id <id> --content <text>`,flags:{nodeId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory node ID (required)`,"zh-CN":`记忆节点 ID(必填)`},required:!0},userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},content:{type:`string`,valueHint:`<text>`,description:{"en-US":`New content for the memory node (required)`,"zh-CN":`记忆节点的新内容(必填)`},required:!0},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID (non-default library)`,"zh-CN":`记忆库 ID(非默认记忆库)`}}},exampleArgs:[{"en-US":`--node-id node_xxx --user-id user1 --content "updated memory content"`,"zh-CN":`--node-id node_xxx --user-id user1 --content "更新后的记忆内容"`}],async run(e){let{settings:t,flags:n}=e,r=n.nodeId,i={user_id:n.userId,custom_content:n.content};n.memoryLibraryId&&(i.memory_library_id=n.memoryLibraryId);let a=T(t.output);if(t.dryRun){A({endpoint:e.client.url(vt(r)),method:`PATCH`,request:i},a);return}let o=await e.client.requestJson({path:vt(r),method:`PATCH`,body:i});t.quiet||a===`text`?k(`Memory node ${r} updated.`):A(o,a)}}),Zs=w({description:{"en-US":`Delete a memory node`,"zh-CN":`删除记忆节点`},auth:`apiKey`,usageArgs:`--node-id <id> --user-id <id>`,flags:{nodeId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory node ID (required)`,"zh-CN":`记忆节点 ID(必填)`},required:!0},userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID (non-default library)`,"zh-CN":`记忆库 ID(非默认记忆库)`}}},exampleArgs:[`--node-id node_xxx --user-id user1`],async run(e){let{settings:t,flags:n}=e,r=n.nodeId,i=n.userId,a=T(t.output),o=new URLSearchParams({user_id:i});n.memoryLibraryId&&o.set(`memory_library_id`,n.memoryLibraryId);let s=`${vt(r)}?${o.toString()}`;if(t.dryRun){A({endpoint:e.client.url(s),method:`DELETE`},a);return}let c=await e.client.requestJson({path:s,method:`DELETE`});t.quiet||a===`text`?k(`Memory node ${r} deleted.`):A(c,a)}}),Qs=w({description:{"en-US":`Create a user profile schema for memory profiling`,"zh-CN":`创建用于记忆画像的用户 Profile Schema`},auth:`apiKey`,usageArgs:`--name <name> --attributes <json> [flags]`,flags:{name:{type:`string`,valueHint:`<name>`,description:{"en-US":`Schema name (required)`,"zh-CN":`Schema 名称(必填)`},required:!0},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`Schema description`,"zh-CN":`Schema 描述`}},attributes:{type:`string`,valueHint:`<json>`,description:{"en-US":`Attributes JSON array: [{"name":"age","description":"age"}]`,"zh-CN":`属性 JSON 数组:[{"name":"age","description":"age"}]`},required:!0}},exampleArgs:[{"en-US":`--name "user_basic" --attributes '[{"name":"age","description":"age"},{"name":"hobby","description":"hobby"}]'`,"zh-CN":`--name "user_basic" --attributes '[{"name":"age","description":"年龄"},{"name":"hobby","description":"爱好"}]'`}],async run(e){let{settings:t,flags:n}=e,r=n.name,i=n.attributes,a;try{a=JSON.parse(i)}catch{throw new y(`--attributes must be valid JSON array`)}let o={name:r,attributes:a};n.description&&(o.description=n.description);let s=T(t.output);if(t.dryRun){A({endpoint:e.client.url(At()),request:o},s);return}let c=await e.client.requestJson({path:At(),method:`POST`,body:o});t.quiet||s===`text`?k(`Profile schema created: ${c.profile_schema_id}`):A(c,s)}}),$s=w({description:{"en-US":`Get user profile by schema ID and user ID`,"zh-CN":`通过 Schema ID 和用户 ID 获取用户画像`},auth:`apiKey`,usageArgs:`--schema-id <id> --user-id <id>`,flags:{schemaId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Profile schema ID (required)`,"zh-CN":`Profile Schema ID(必填)`},required:!0},userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0}},exampleArgs:[`--schema-id schema_xxx --user-id user1`],async run(e){let{settings:t,flags:n}=e,r=n.schemaId,i=n.userId,a=T(t.output),o=new URLSearchParams({user_id:i}),s=`${on(r)}?${o.toString()}`;if(t.dryRun){A({endpoint:e.client.url(s),method:`GET`},a);return}let c=await e.client.requestJson({path:s,method:`GET`});if(t.quiet||a===`text`)if(c.profile?.attributes)for(let e of c.profile.attributes)k(`${e.name}: ${e.value??`(empty)`}`);else k(`No profile data found.`);else A(c,a)}}),ec=w({description:{"en-US":"Retrieve from a Bailian knowledge base (deprecated, use `search` instead)","zh-CN":"从百炼知识库检索(已废弃,请改用 `search`)"},auth:`apiKey`,usageArgs:`--index-id <id> --query <text> [flags]`,flags:{indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base index ID (required)`,"zh-CN":`知识库索引 ID(必填)`},required:!0},query:{type:`string`,valueHint:`<text>`,description:{"en-US":`Search query (required)`,"zh-CN":`搜索查询(必填)`},required:!0},denseSimilarityTopK:{type:`number`,valueHint:`<n>`,description:{"en-US":`Dense retrieval top K`,"zh-CN":`稠密检索 Top K`}},sparseSimilarityTopK:{type:`number`,valueHint:`<n>`,description:{"en-US":`Sparse retrieval top K`,"zh-CN":`稀疏检索 Top K`}},rerank:{type:`switch`,description:{"en-US":`Enable reranking`,"zh-CN":`启用重排序`}},rerankTopN:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rerank top N results`,"zh-CN":`重排序前 N 个结果`}},rerankModel:{type:`string`,valueHint:`<name>`,description:{"en-US":`Rerank model, e.g. qwen3-rerank-hybrid`,"zh-CN":`重排序模型,例如 qwen3-rerank-hybrid`}},rerankMode:{type:`string`,valueHint:`<mode>`,description:{"en-US":`Rerank mode: qa, similar, or custom`,"zh-CN":`重排序模式:qa、similar 或 custom`}},rerankInstruct:{type:`string`,valueHint:`<text>`,description:{"en-US":`Custom rerank instruction, when mode=custom`,"zh-CN":`自定义重排序指令,仅在 mode=custom 时使用`}},topK:{type:`number`,valueHint:`<n>`,description:{"en-US":`Number of results (deprecated, use --rerank-top-n)`,"zh-CN":`结果数量(已废弃,请使用 --rerank-top-n)`}}},notes:[{"en-US":`--rerank-model requires the target knowledge base to already have a rerank model configured; otherwise every value is rejected.`,"zh-CN":`--rerank-model 要求目标知识库已配置重排序模型,否则任何取值都会被拒绝。`}],exampleArgs:[{"en-US":`--index-id idx_xxx --query "How to use Alibaba Cloud Bailian"`,"zh-CN":`--index-id idx_xxx --query "如何使用阿里云百炼"`},{"en-US":`--index-id idx_xxx --query "RAG retrieval" --rerank --rerank-model qwen3-rerank-hybrid`,"zh-CN":`--index-id idx_xxx --query "RAG 检索" --rerank --rerank-model qwen3-rerank-hybrid`}],async run(e){let{settings:t,flags:n}=e,r=T(t.output);n.topK!==void 0&&n.rerankTopN===void 0&&(process.stderr.write(`Warning: --top-k is deprecated. Use --rerank-top-n instead.
2731
2731
  `),n.rerankTopN=n.topK);let i={index_id:n.indexId,query:n.query,search_filters:[]};if(n.denseSimilarityTopK!==void 0&&(i.dense_similarity_top_k=n.denseSimilarityTopK),n.sparseSimilarityTopK!==void 0&&(i.sparse_similarity_top_k=n.sparseSimilarityTopK),n.rerank&&(i.enable_reranking=!0),n.rerankTopN!==void 0&&(i.rerank_top_n=n.rerankTopN),n.rerankModel){let e={model_name:n.rerankModel};n.rerankMode&&(e.rerank_mode=n.rerankMode),n.rerankInstruct&&(e.rerank_instruct=n.rerankInstruct),i.rerank=[e]}if(t.dryRun){A({endpoint:e.client.url(tt()),request:i},r);return}let a=await e.client.requestJson({path:tt(),method:`POST`,body:i}),o=a.data?.nodes||[];t.quiet||r===`text`?tc(o.map(e=>({text:e.text,score:e.score}))):A(a,r)}});function tc(e){if(e.length===0)k(`No results found.`);else for(let t=0;t<e.length;t++){let n=e[t];k(`[${t+1}] (score: ${n.score.toFixed(4)})`),k(n.text),k(``)}}const U={workspaceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID)`,"zh-CN":`API Endpoint URL 使用的 Workspace ID(也可设置 BAILIAN_WORKSPACE_ID)`}}},nc={pageNumber:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page size per request`,"zh-CN":`每次请求的分页大小`}}};function W(e){let n=e.flags.workspaceId||e.settings.workspaceId;if(!n)throw new t(`Workspace ID is required.`,c.USAGE,`Pass --workspace-id, set BAILIAN_WORKSPACE_ID env, or configure: ${e.identity.binName} config set workspace_id <id>`);return n}function rc(e){if(!process.stdout.isTTY)return e;let t=process.stdout.columns??120;return e.length>t?`${e.slice(0,Math.max(0,t-1))}…`:e}function ic(e){return e.data?.ingestion_status??`UNKNOWN`}function ac(e){return(e.data?.rows??[]).filter(e=>[e.code,e.status].some(e=>typeof e==`string`&&e.includes(`FAILED`)))}function oc(e){let t=e.data?.rows??[];if(t.length===0)return!1;let n=e.data?.total_count;return typeof n==`number`&&t.length<n?!1:t.every(e=>{let t=e.code??e.status??``;return t===`FINISH`||t.includes(`FAILED`)})}function sc(e,t){let n=e.data?.rows??[],r=ac(e),i=new Set(r.map(e=>e.doc_id)),a=n.filter(e=>!i.has(e.doc_id)),o=r.map(e=>`${e.doc_name??e.doc_id??`?`}: ${e.message??e.code??`unknown`}`).join(`; `),s=a.map(e=>e.doc_name??e.doc_id??`?`).join(`, `),c=[];return o&&c.push(`failed: ${o}`),s&&c.push(`succeeded: ${s}`),c.length>0?`${t} (${c.join(`; `)})`:t}function cc(e,t,n){let r=new URL(E(e,p.indexJobStatus));return r.searchParams.set(`index_id`,t),r.searchParams.set(`job_id`,n),r}async function lc(e,t,n){return Pn(e,t,{url:n.statusUrl,intervalSec:n.intervalSec,timeoutSec:t.timeout,isComplete:e=>{let t=e;return ic(t)===`COMPLETED`||oc(t)},isFailed:()=>!1,getStatus:e=>{let t=e,n=ic(t),r=ac(t).length,i=t.data?.total_count;return typeof i==`number`&&i>0?`${n} (${r}/${i} failed)`:r>0?`${n} (${r} failed)`:n}})}function uc(e,n){return!(e instanceof t)||e.hint?e:new t(e.message,e.exitCode,n,{cause:e,api:e.api,rawResponse:e.rawResponse})}function dc(e,t){let n=e.data?.[t];if(typeof n==`string`)return n;let r=e[t];return typeof r==`string`?r:void 0}var fc=w({description:{"en-US":`Search a Bailian knowledge base (RAG semantic retrieval)`,"zh-CN":`搜索百炼知识库(RAG 语义检索)`},auth:`apiKey`,usageArgs:`--query <text> --agent-id <id> [flags]`,flags:{query:{type:`string`,valueHint:`<text>`,description:{"en-US":`Search query text (required, cannot be empty)`,"zh-CN":`搜索查询文本(必填且不能为空)`},required:!0},agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Retrieval service ID (find in console knowledge retrieval page)`,"zh-CN":`检索服务 ID(可在控制台知识库检索页面查看)`},required:!0},...U,agentVersion:{type:`string`,valueHint:`<version>`,description:{"en-US":`Service version to call: beta (draft for debugging) or a published number; default is the latest published version`,"zh-CN":`要调用的服务版本:beta(用于调试的草稿)或已发布版本号;默认使用最新发布版本`}},image:{type:`array`,valueHint:`<url>`,description:{"en-US":`Image URL for multimodal retrieval (repeatable)`,"zh-CN":`多模态检索使用的图片 URL(可重复)`}}},notes:[{"en-US":`Retrieval scope and strategy (multi-index weighting, routing, reranking, etc.) are driven by the agent_id service config. Only query and agent_id are required.`,"zh-CN":`检索范围与策略(多索引权重、路由、重排序等)由 agent_id 服务配置决定。仅 query 和 agent_id 必填。`},{"en-US":`Auth: uses DashScope API Key (Bearer token). Get yours from the console API Key page.`,"zh-CN":`鉴权:使用 DashScope API Key(Bearer Token)。可在控制台 API Key 页面获取。`},{"en-US":"`--workspace-id` can be set via BAILIAN_WORKSPACE_ID env or `kscli config set workspace_id <id>`.","zh-CN":"`--workspace-id` 可通过 BAILIAN_WORKSPACE_ID 环境变量或 `kscli config set workspace_id <id>` 设置。"},{"en-US":"`--agent-version beta` calls the draft config for debugging before it is deployed.","zh-CN":"`--agent-version beta` 会调用尚未部署的草稿配置,便于发布前调试。"}],exampleArgs:[{"en-US":`--query "What is RAG?" --agent-id aid-xxx --workspace-id ws-xxx`,"zh-CN":`--query "什么是 RAG?" --agent-id aid-xxx --workspace-id ws-xxx`},{"en-US":`--api-key $DASHSCOPE_API_KEY --query "test search" --agent-id aid-xxx --workspace-id ws-xxx --image https://example.com/img.jpg`,"zh-CN":`--api-key $DASHSCOPE_API_KEY --query "测试搜索" --agent-id aid-xxx --workspace-id ws-xxx --image https://example.com/img.jpg`}],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={query:n.query,agent_id:n.agentId};n.agentVersion&&(a.agent_version=n.agentVersion),n.image&&n.image.length>0&&(a.images=n.image);let o=nt(r);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.nodes||[];if(t.quiet||i===`text`)if(c.length===0)k(`No results found.`);else for(let e=0;e<c.length;e++){let t=c[e];k(`[${e+1}] (score: ${t.score.toFixed(4)})`),k(t.text),k(``)}else A(s,i)}});const pc={message:{type:`array`,valueHint:`<text>`,description:{"en-US":`Message text (repeatable). Supports role:content prefix to set role (e.g. user:hello), defaults to user. Follows OpenAI message format`,"zh-CN":`消息文本(可重复)。支持使用 role:content 前缀指定角色(例如 user:hello),默认为 user。遵循 OpenAI 消息格式`}},agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Q&A service ID (find in console knowledge Q&A page)`,"zh-CN":`问答服务 ID(可在控制台知识库问答页面查看)`},required:!0},...U,agentVersion:{type:`string`,valueHint:`<version>`,description:{"en-US":`Service version to call: beta (draft for debugging) or a published number; default is the latest published version`,"zh-CN":`要调用的服务版本:beta(用于调试的草稿)或已发布版本号;默认使用最新发布版本`}},image:{type:`array`,valueHint:`<url>`,description:{"en-US":`Image URL (repeatable). Attached to the last user message as multimodal content`,"zh-CN":`图片 URL(可重复)。将作为多模态内容附加到最后一条用户消息`}}};function mc(e){let t=[];if(e.message){let n=new Set([`user`,`assistant`]);for(let r of e.message){if(r.startsWith(`{`))try{let e=JSON.parse(r);if(e.role&&n.has(e.role)&&e.content!==void 0){t.push(e);continue}}catch{}let e=r.indexOf(`:`),i=e===-1?``:r.slice(0,e);n.has(i)?t.push({role:i,content:r.slice(e+1)}):t.push({role:`user`,content:r})}}return t}function hc(e){for(let t of e)if(Array.isArray(t.content)&&t.content.some(e=>e.type===`image_url`))return!0;return!1}function gc(e,t){let n=-1;for(let t=e.length-1;t>=0;t--)if(e[t].role===`user`){n=t;break}n===-1&&(e.push({role:`user`,content:``}),n=e.length-1);let r=e[n],i=[];typeof r.content==`string`?i.push({type:`text`,text:r.content}):i.push(...r.content);for(let e of t)i.push({type:`image_url`,image_url:{url:e}});r.content=i}const _c={tool_calling:`🔍 Retrieving...`,plan_start:`🤔 Planning...`,generation_start:`✍️ Generating...`};var vc=w({description:{"en-US":`Chat with a Bailian knowledge base (RAG Q&A with streaming)`,"zh-CN":`与百炼知识库对话(支持流式输出的 RAG 问答)`},auth:`apiKey`,usageArgs:`--message <text> --agent-id <id> [flags]`,flags:pc,notes:[{"en-US":`Response is returned as SSE stream events. Event lifecycle: tool_calling → tool_return → plan_start → planning → plan_end → generation_start → generating → generation_end. tool_calling → tool_return may loop multiple times.`,"zh-CN":`响应以 SSE 流事件返回。事件生命周期:tool_calling → tool_return → plan_start → planning → plan_end → generation_start → generating → generation_end。tool_calling → tool_return 可能循环多次。`},{"en-US":`Auth: uses DashScope API Key (Bearer token). Get yours from the console API Key page.`,"zh-CN":`鉴权:使用 DashScope API Key(Bearer Token)。可在控制台 API Key 页面获取。`},{"en-US":"`--workspace-id` can be set via BAILIAN_WORKSPACE_ID env or `kscli config set workspace_id <id>`.","zh-CN":"`--workspace-id` 可通过 BAILIAN_WORKSPACE_ID 环境变量或 `kscli config set workspace_id <id>` 设置。"},{"en-US":`Multi-turn: use --message "user:..." and --message "assistant:..." to pass conversation history.`,"zh-CN":`多轮对话:使用 --message "user:..." 和 --message "assistant:..." 传入对话历史。`},{"en-US":"`--agent-version beta` calls the draft config for debugging before it is deployed.","zh-CN":"`--agent-version beta` 会调用尚未部署的草稿配置,便于发布前调试。"}],exampleArgs:[{"en-US":`--message "What is RAG?" --agent-id aid-xxx --workspace-id ws-xxx`,"zh-CN":`--message "什么是 RAG?" --agent-id aid-xxx --workspace-id ws-xxx`},{"en-US":`--message "user:What is RAG?" --message "assistant:RAG is..." --message "How does it work?" --agent-id aid-xxx --workspace-id ws-xxx`,"zh-CN":`--message "user:什么是 RAG?" --message "assistant:RAG 是……" --message "它是如何工作的?" --agent-id aid-xxx --workspace-id ws-xxx`},{"en-US":`--message "Describe these images" --image https://example.com/a.png --image https://example.com/b.png --agent-id aid-xxx --workspace-id ws-xxx`,"zh-CN":`--message "描述这些图片" --image https://example.com/a.png --image https://example.com/b.png --agent-id aid-xxx --workspace-id ws-xxx`}],validate:e=>e.message&&e.message.length>0||e.image&&e.image.length>0?void 0:`Provide --message (or --image for a pure image query).`,async run(e){let{settings:n,flags:r}=e,i=mc(r),a=r.image,o=!!a&&a.length>0;i.length===0&&o&&(i=[{role:`user`,content:``}]);let s=W(e),l=T(n.output),u=l===`text`&&!!process.stdout.isTTY;if(o){if(hc(i))throw new t(`Cannot use --image when messages already contain embedded image_url content parts. Use one approach or the other.`,c.USAGE);gc(i,a)}let d={input:{messages:i},parameters:{agent_options:{agent_id:r.agentId,...r.agentVersion?{agent_version:r.agentVersion}:{}}},stream:!0},f=et(s);if(n.dryRun){A({endpoint:f,request:d},l);return}let p=await e.client.request({path:f,method:`POST`,body:d,stream:!0});if(u){let e=O(process.stdout),r=n.verbose;for await(let n of Et(p)){if(n.data===`[DONE]`)break;if(n.event===`error`){let e=`Chat API error`,r;try{let t=JSON.parse(n.data);e=t.message||e,r=t.code}catch{}throw new t(e,c.GENERAL,r?`API error: ${r}`:void 0)}try{let t=JSON.parse(n.data);for(let n of t.output?.choices??[]){let t=n.message;if(t.extra?.step_change){let n=_c[t.extra.step_change];n&&process.stdout.write(`${e.dim(n)}\n`)}if(r&&t.extra?.step_change&&process.stderr.write(O(process.stderr).dim(`[event] step_change=${t.extra.step_change} step=${t.extra?.step??``} group=${t.extra?.group??``}`)+`
2732
2732
  `),t.content&&process.stdout.write(t.content),n.finish_reason===`stop`)break}}catch{}}process.stdout.write(`
2733
- `)}else{let e=``,r=``;for await(let n of Et(p)){if(n.data===`[DONE]`)break;if(n.event===`error`){let e=`Chat API error`,r;try{let t=JSON.parse(n.data);e=t.message||e,r=t.code}catch{}throw new t(e,c.GENERAL,r?`API error: ${r}`:void 0)}try{let t=JSON.parse(n.data);t.request_id&&(r=t.request_id);for(let n of t.output?.choices??[])if(n.message?.content&&(e+=n.message.content),n.finish_reason===`stop`)break}catch{}}n.quiet||l===`text`?k(e):A({answer:e,request_id:r},l)}}}),yc=w({description:{"en-US":`List knowledge bases in the workspace`,"zh-CN":`列出 Workspace 中的知识库`},auth:`apiKey`,usageArgs:`[flags]`,flags:{name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by knowledge base name (fuzzy match, 1-20 chars)`,"zh-CN":`按知识库名称筛选(模糊匹配,1–20 个字符)`}},...nc,...U},notes:[{"en-US":`Auth: uses DashScope API Key (Bearer token).`,"zh-CN":`鉴权:使用 DashScope API Key(Bearer Token)。`},{"en-US":"`--workspace-id` can be set via BAILIAN_WORKSPACE_ID env or config workspace_id.","zh-CN":"`--workspace-id` 可通过 BAILIAN_WORKSPACE_ID 环境变量或配置项 workspace_id 设置。"},{"en-US":`Use the returned id as --index-id in knowledge base / document management commands.`,"zh-CN":`在知识库/文档管理命令中,将返回的 ID 作为 --index-id 使用。`}],exampleArgs:[`--workspace-id ws-xxx`,`--name demo --page-number 2 --page-size 50`],validate(e){if(e.name!==void 0&&(e.name.length<1||e.name.length>20))return`--name must be 1-20 characters`;if(e.pageSize!==void 0&&(e.pageSize<1||e.pageSize>100))return`--page-size must be between 1 and 100`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a=new URL(E(r,p.indexList));n.name&&a.searchParams.set(`pipeline_name`,n.name),a.searchParams.set(`page_number`,String(n.pageNumber??1)),a.searchParams.set(`page_size`,String(n.pageSize??20));let o=a.toString();if(t.dryRun){A({endpoint:o,request:null},i);return}let s=await e.client.requestJson({path:o,method:`GET`}),c=s.data?.rows??[];if(t.quiet){for(let e of c)k(e.id);return}if(i===`text`){if(c.length===0)k(`No knowledge bases found.`);else for(let e of c)k(rc([e.id,e.name,e.embeddingModelName??`-`,e.chunkSize??`-`,e.description??``].join(` `)));k(`total: ${s.data?.total??c.length}`)}else A(s,i)}});const bc={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},...U};function xc(e,t){let n=new URL(E(e,p.indexList));return n.searchParams.set(`pipeline_id`,t),n.searchParams.set(`page_number`,`1`),n.searchParams.set(`page_size`,`1`),n.toString()}async function Sc(e,n,r){let i=(await e.requestJson({path:xc(n,r),method:`GET`})).data?.rows?.[0];if(!i)throw new t(`Knowledge base not found: ${r}`,c.GENERAL,`Check the id — list knowledge bases in this workspace to verify it.`);return i}function G(e,t){return` ${e}: ${t??`-`}`}var Cc=w({description:{"en-US":`Show knowledge base configuration details`,"zh-CN":`查看知识库配置详情`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:bc,notes:[{"en-US":`Indexing settings are immutable; changing them requires recreating the knowledge base.`,"zh-CN":`索引设置不可修改;如需更改,必须重新创建知识库。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output);if(t.dryRun){A({endpoint:xc(r,n.indexId),request:null},i);return}let a=await Sc(e.client,r,n.indexId);if(t.quiet){k(a.id??``);return}if(i!==`text`){A(a,i);return}k(`Basic:`),k(G(`id`,a.id)),k(G(`name`,a.name)),k(G(`description`,a.description)),k(G(`dataType`,a.dataType)),k(`Indexing: [immutable — recreate required to change]`),k(G(`embeddingModelName`,a.embeddingModelName)),k(G(`embeddingDimension`,a.embeddingDimension)),k(G(`chunkSize`,a.chunkSize)),k(G(`overlapSize`,a.overlapSize)),k(G(`chunkMode`,a.chunkMode)),k(G(`separator`,a.separator)),k(`Retrieval:`),k(G(`rerankModelName`,a.rerankModelName)),k(G(`rerankMinScore`,a.rerankMinScore)),k(G(`rerankTopN`,a.rerankTopN)),k(G(`rerankMode`,a.rerankMode)),k(G(`enableRewrite`,a.enableRewrite)),k(G(`denseSimilarityTopK`,a.denseSimilarityTopK)),k(G(`sparseSimilarityTopK`,a.sparseSimilarityTopK)),k(`Data:`),k(G(`sourceType`,a.sourceType)),k(G(`connectorId`,a.connectorId))}}),wc=w({description:{"en-US":`List documents in a knowledge base with parse/index status`,"zh-CN":`列出知识库文档及其解析/索引状态`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:{indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},...nc,...U},notes:[{"en-US":`Documents with status FAILED are highlighted in text mode — use the import job status command to inspect failures.`,"zh-CN":`文本模式会突出显示状态为 FAILED 的文档——请使用导入任务状态命令检查失败详情。`},{"en-US":`Page size defaults to 10 (server default), max 100.`,"zh-CN":`分页大小默认为 10(服务端默认值),最大为 100。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --page-size 100`],validate(e){if(e.pageSize!==void 0&&(e.pageSize<1||e.pageSize>100))return`--page-size must be between 1 and 100`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a=new URL(E(r,p.indexFiles));a.searchParams.set(`index_id`,n.indexId),a.searchParams.set(`page_num`,String(n.pageNumber??1)),a.searchParams.set(`page_size`,String(n.pageSize??10));let o=a.toString();if(t.dryRun){A({endpoint:o,request:null},i);return}let s=await e.client.requestJson({path:o,method:`GET`}),c=s.data?.rows??[];if(t.quiet){for(let e of c)k(e.doc_id??``);return}if(i===`text`){let e=O(process.stdout);if(c.length===0)k(`No documents found.`);else for(let t of c){let n=rc([t.doc_id,t.status,t.doc_name,t.doc_type??`-`,t.size??`-`].join(` `));k(t.status===`FAILED`?e.red(n):n)}k(`total: ${s.data?.total_count??c.length}`)}else A(s,i)}});const Tc={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},jobId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Import job ID (ingestionId returned by import commands)`,"zh-CN":`导入任务 ID(导入命令返回的 ingestionId)`},required:!0},...nc,wait:{type:`switch`,description:{"en-US":`Poll until the job reaches a terminal state`,"zh-CN":`轮询直到任务进入终态`}},pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 5)`,"zh-CN":`等待时的轮询间隔(默认:5)`}},...U};function Ec(e){let t=O(process.stdout);k(`status: ${e.data?.ingestion_status??`UNKNOWN`}`);for(let n of e.data?.rows??[]){let e=n.code??n.status??`?`,r=` ${n.doc_id??`?`} ${e} ${n.doc_name??``}`;k(e.includes(`FAILED`)?t.red(r):r)}}var Dc=w({description:{"en-US":`Check knowledge base import job status`,"zh-CN":`检查知识库导入任务状态`},auth:`apiKey`,usageArgs:`--index-id <id> --job-id <id> [flags]`,flags:Tc,notes:[{"en-US":`Both --index-id and --job-id are required (passing only one returns SystemError).`,"zh-CN":`--index-id 和 --job-id 均为必填(只传其中一个会返回 SystemError)。`},{"en-US":`If you see a SystemError, the job may not exist — check the ingestion id in the document list output.`,"zh-CN":`如果出现 SystemError,任务可能不存在——请检查文档列表输出中的 ingestion ID。`},{"en-US":`Overall job states are PENDING / RUNNING / COMPLETED; per-document failures (for example PARSE_FAILED) exit non-zero with the error message passed through.`,"zh-CN":`任务整体状态为 PENDING / RUNNING / COMPLETED;单个文档失败(例如 PARSE_FAILED)时会以非零状态退出,并原样透传错误信息。`}],exampleArgs:[`--index-id idx-xxx --job-id job-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --job-id job-xxx --wait --poll-interval 10`],async run(e){let{settings:n,flags:r}=e,i=W(e),a=T(n.output),o=new URL(E(i,p.indexJobStatus));o.searchParams.set(`index_id`,r.indexId),o.searchParams.set(`job_id`,r.jobId),r.pageNumber!==void 0&&o.searchParams.set(`page_number`,String(r.pageNumber)),r.pageSize!==void 0&&o.searchParams.set(`page_size`,String(r.pageSize));let s=o.toString();if(n.dryRun){A({endpoint:s,request:null},a);return}let l;if(l=r.wait?await lc(e.client,n,{statusUrl:s,intervalSec:r.pollInterval??5}):await e.client.requestJson({path:s,method:`GET`}),ac(l).length>0)throw new t(sc(l,`Import job reported document failures.`),c.GENERAL);if(n.quiet){k(l.data?.ingestion_status??`UNKNOWN`);return}a===`text`?Ec(l):A(l,a)}});const K=1024*1024,Oc={".doc":{maxBytes:150*K,enforce:`block`},".docx":{maxBytes:150*K,enforce:`block`},".ppt":{maxBytes:150*K,enforce:`block`},".pptx":{maxBytes:150*K,enforce:`block`},".pdf":{maxBytes:150*K,enforce:`block`},".png":{maxBytes:20*K,enforce:`block`},".jpg":{maxBytes:20*K,enforce:`block`},".jpeg":{maxBytes:20*K,enforce:`block`},".bmp":{maxBytes:20*K,enforce:`block`},".gif":{maxBytes:20*K,enforce:`block`},".xls":{maxBytes:10*K,enforce:`warn`},".xlsx":{maxBytes:10*K,enforce:`warn`},".csv":{maxBytes:10*K,enforce:`warn`},".md":{maxBytes:10*K,enforce:`warn`},".txt":{maxBytes:10*K,enforce:`warn`},".html":{maxBytes:10*K,enforce:`warn`}};function kc(e){return dr(e).toLowerCase()in Oc}const Ac=new Set([`node_modules`,`.git`,`.svn`,`.hg`,`__pycache__`,`.venv`,`venv`,`.env`,`.tox`,`dist`,`build`,`.cache`,`.next`,`.nuxt`]);function jc(e){let n=[],r=[];function i(e){let a;try{a=or(e,{withFileTypes:!0})}catch(n){let r=n.code??`unknown`;throw new t(`Cannot read directory: ${e}`,c.GENERAL,`File system error (${r}) — check the path and permissions.`)}for(let t of a){let a=I(e,t.name);if(t.isDirectory()){Ac.has(t.name)||i(a);continue}t.isFile()&&(kc(t.name)?n.push(a):r.push(a))}}for(let r of e){let e;try{e=sr(r)}catch(e){let n=e.code??`unknown`;throw new t(`Cannot read path: ${r}`,c.GENERAL,`File system error (${n}) — check the path and permissions.`)}e.isDirectory()?i(r):e.isFile()&&n.push(r)}return{files:n,skipped:r}}function Mc(e){let n=dr(e).toLowerCase(),r=Oc[n];if(!r)throw new t(`Unsupported file type: ${n||F(e)}`,c.USAGE,`Supported formats: ${Object.keys(Oc).join(` `)}`);let i;try{i=sr(e).size}catch(n){let r=n.code??`unknown`;throw new t(`Cannot read file: ${e}`,c.GENERAL,`File system error (${r}) — check the path and permissions.`)}if(i>r.maxBytes){let a=r.maxBytes/K;if(r.enforce===`block`)throw new t(`File exceeds the ${a} MB limit for ${n}: ${F(e)}`,c.USAGE);return{sizeBytes:i,warning:`${F(e)} exceeds the recommended 10 MB for ${n}; the server may reject or truncate it.`}}return{sizeBytes:i}}const Nc=new Set([`.doc`,`.docx`,`.ppt`,`.pptx`,`.pdf`,`.xls`,`.xlsx`,`.png`,`.jpg`,`.jpeg`,`.bmp`,`.gif`]);function Pc(e,n){let r;try{r=ar(e)}catch(r){let i=r.code??`unknown`,a=`File system error (${i}) — check the path and permissions.`;throw n&&i===`ENOENT`&&!dr(e)&&!e.includes(`/`)&&!e.includes(`\\`)&&(a+=` If you meant to pass text content directly, use ${n} instead of --content-file.`),new t(`Cannot read file: ${e}`,c.GENERAL,a)}try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(r)}catch{let n=dr(e).toLowerCase(),r=Nc.has(n)?`Document formats cannot be used as chunk content. Upload documents via the document upload command; to edit a chunk, save the text as .md/.txt first.`:`Convert the file to UTF-8 encoding and retry.`;throw new t(`File is not valid UTF-8 plain text: ${F(e)}`,c.USAGE,r)}}var Fc=w({description:{"en-US":`Upload local files or directories to the data center and optionally import into a knowledge base`,"zh-CN":`上传本地文件或目录到数据中心,并可选择导入知识库`},auth:`apiKey`,usageArgs:`--file <path> [flags]`,flags:{file:{type:`array`,valueHint:`<path>`,description:{"en-US":`Local file or directory path (repeatable). Directories are scanned recursively; unsupported formats are skipped`,"zh-CN":`本地文件或目录路径(可重复)。目录会递归扫描,不支持的格式将被跳过`},required:!0},indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Import into this knowledge base after registration (one job for all files)`,"zh-CN":`文件注册后导入该知识库(所有文件共用一个任务)`}},categoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Target data-center category; defaults to the workspace default category`,"zh-CN":`目标数据中心类目;默认为 Workspace 的默认类目`}},tag:{type:`array`,valueHint:`<text>`,description:{"en-US":`File tag (repeatable), applied to every uploaded file`,"zh-CN":`文件标签(可重复),应用于每个上传文件`}},wait:{type:`switch`,description:{"en-US":`Poll the import job to a terminal state (needs --index-id)`,"zh-CN":`轮询导入任务直到进入终态(需要 --index-id)`}},pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 5)`,"zh-CN":`等待时的轮询间隔(默认:5)`}},...U},notes:[{"en-US":`Pipeline: apply upload lease → PUT to OSS → register file → (with --index-id) create import job.`,"zh-CN":`处理流程:申请上传凭证 → PUT 到 OSS → 注册文件 →(传入 --index-id 时)创建导入任务。`},{"en-US":`Without --category-id the workspace default category is resolved automatically.`,"zh-CN":`未传入 --category-id 时,会自动解析 Workspace 的默认类目。`},{"en-US":`Directories are scanned recursively; node_modules, .git, and similar are skipped automatically.`,"zh-CN":`目录会递归扫描;node_modules、.git 等目录会被自动跳过。`},{"en-US":`Multiple files are processed sequentially; on failure, already-registered file ids are listed in the error hint.`,"zh-CN":`多个文件会依次处理;失败时,错误提示会列出已经注册成功的文件 ID。`}],exampleArgs:[`--file ./a.md --workspace-id ws-xxx`,`--file ./a.md --file ./b.pdf --index-id idx-xxx --wait`,`--file ./docs/ --workspace-id ws-xxx`,`--file ./docs/ --dry-run --verbose`],validate(e){if(e.wait&&!e.indexId)return`--wait requires --index-id`},async run(e){let{settings:n,flags:r}=e,i=W(e),a=T(n.output),{files:o,skipped:s}=jc(r.file);if(o.length===0)throw new t(`No supported files found`,c.USAGE,`Supported formats: .pdf .doc .docx .ppt .pptx .xls .xlsx .csv .md .txt .html .png .jpg .jpeg .bmp .gif`);let l=o.map(e=>{let t=Mc(e);return t.warning&&process.stderr.write(`Warning: ${t.warning}\n`),{filePath:e,sizeBytes:t.sizeBytes}});if(n.dryRun){let e=r.categoryId??`default`,t=l.flatMap(t=>[{step:`applyFileUploadLease`,endpoint:E(i,p.applyFileUploadLease),request:{category:e,fileName:F(t.filePath),sizeBytes:String(t.sizeBytes),contentMd5:`<md5-base64>`}},{step:`ossPut`,endpoint:`<lease.param.url>`,request:{method:`PUT`,headers:`<lease.param.headers>`}},{step:`addFile`,endpoint:E(i,p.addFile),request:{leaseId:`<leaseId>`,category:e,parser:`AUTO_SELECT`,...r.tag?.length?{tags:r.tag}:{}}}]);r.indexId&&t.push({step:`createImportJob`,endpoint:E(i,p.indexJobCreate),request:{indexId:r.indexId,sourceType:`DATA_CENTER_FILE`,docIds:[`<fileId>`]}}),A({steps:t,skipped:s},a);return}let u=r.categoryId??`default`,d=[];for(let n of l)try{let a=ar(n.filePath),o=Vn(`md5`).update(a).digest(`base64`),s=await e.client.requestJson({path:E(i,p.applyFileUploadLease),method:`POST`,body:{category:u,fileName:F(n.filePath),sizeBytes:String(n.sizeBytes),contentMd5:o}}),l=s.data?.leaseId,f=s.data?.param;if(!l||!f?.url)throw new t(`Upload lease response missing leaseId/url for ${n.filePath}`,c.GENERAL);let m;try{m=await fetch(f.url,{method:f.method??`PUT`,headers:f.headers,body:a})}catch(e){let r=e.cause?.code;throw new t(`OSS upload failed for ${F(n.filePath)}`,c.NETWORK,r?`Network error (${r}).`:void 0,{cause:e})}if(!m.ok){let e=await m.text().catch(()=>``);throw new t(`OSS upload rejected (HTTP ${m.status}) for ${F(n.filePath)}${e?`: ${e.slice(0,300)}`:``}`,c.GENERAL)}let h=(await e.client.requestJson({path:E(i,p.addFile),method:`POST`,body:{leaseId:l,category:u,parser:`AUTO_SELECT`,...r.tag?.length?{tags:r.tag}:{}}})).data?.fileId;if(!h)throw new t(`addFile response missing fileId for ${n.filePath}`,c.GENERAL);d.push({path:n.filePath,fileId:h})}catch(e){throw d.length>0?uc(e,`Already registered: ${d.map(e=>e.fileId).join(`, `)}`):e}let f,m;if(r.indexId&&(f=(await e.client.requestJson({path:E(i,p.indexJobCreate),method:`POST`,body:{indexId:r.indexId,sourceType:`DATA_CENTER_FILE`,docIds:d.map(e=>e.fileId)}})).data?.ingestionId,r.wait&&f)){let a=await lc(e.client,n,{statusUrl:cc(i,r.indexId,f).toString(),intervalSec:r.pollInterval??5});if(m=ic(a),ac(a).length>0)throw new t(sc(a,`Import job reported document failures.`),c.GENERAL,`Registered file ids: ${d.map(e=>e.fileId).join(`, `)}`)}if(n.quiet){for(let e of d)k(e.fileId);return}if(a===`text`){for(let e of d)k(`${F(e.path)} ${e.fileId} registered`);f&&k(`job: ${f}`),m&&k(`status: ${m}`);let e=[`Uploaded ${d.length} file${d.length===1?``:`s`}`];if(s.length>0&&e.push(`skipped ${s.length} unsupported`),k(`\n${e.join(`, `)}.`),n.verbose&&s.length>0){k(`Skipped files:`);for(let e of s)k(` ${F(e)}`)}return}A({files:d.map(e=>({path:e.path,fileId:e.fileId})),skipped:s,...r.indexId?{index_id:r.indexId}:{},...f?{ingestion_id:f}:{},...m?{final_status:m}:{}},a)}});const Ic={name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Knowledge base name (1-20 chars, unique in workspace)`,"zh-CN":`知识库名称(1–20 个字符,在 Workspace 中唯一)`},required:!0},docId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Data-center file id to import (repeatable); mutually exclusive with --category-id`,"zh-CN":`要导入的数据中心文件 ID(可重复);不能与 --category-id 同时使用`}},categoryId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Import every file under this category (repeatable); mutually exclusive with --doc-id`,"zh-CN":`导入该类目下的所有文件(可重复);不能与 --doc-id 同时使用`}},embeddingModel:{type:`string`,valueHint:`<name>`,description:{"en-US":`Embedding model name (default: text-embedding-v4)`,"zh-CN":`Embedding 模型名称(默认:text-embedding-v4)`}},chunkSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Chunk size in characters (default: 600, recommended 300-800)`,"zh-CN":`Chunk 字符数(默认:600,建议:300–800)`}},wait:{type:`switch`,description:{"en-US":`Poll the initial import job to a terminal state`,"zh-CN":`轮询初始导入任务直到进入终态`}},pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 5)`,"zh-CN":`等待时的轮询间隔(默认:5)`}},...U};function Lc(e){return e.docId?.length?{sourceType:`DATA_CENTER_FILE`,docIds:e.docId,dataSources:[{sourceType:`DATA_CENTER_FILE`}]}:{sourceType:`DATA_CENTER_CATEGORY`,categoryIds:e.categoryId,dataSources:[{sourceType:`DATA_CENTER_CATEGORY`}]}}var Rc=w({description:{"en-US":`Create a knowledge base and import data-center files or categories`,"zh-CN":`创建知识库并导入数据中心文件或类目`},auth:`apiKey`,usageArgs:`--name <text> (--doc-id <id> | --category-id <id>) [flags]`,flags:Ic,notes:[{"en-US":`Structure/sink types are fixed to the default document knowledge base (unstructured, BUILT_IN storage).`,"zh-CN":`结构和存储类型固定为默认文档知识库(unstructured、BUILT_IN 存储)。`},{"en-US":`Returns the knowledge base id (pipelineId) and the initial import job id (ingestionId).`,"zh-CN":`返回知识库 ID(pipelineId)和初始导入任务 ID(ingestionId)。`},{"en-US":`Use the import job status command (or --wait) to track the initial import.`,"zh-CN":`使用导入任务状态命令(或 --wait)跟踪初始导入。`}],exampleArgs:[`--name demo --doc-id file-xxx --workspace-id ws-xxx`,`--name demo --category-id cate-xxx --wait`],validate(e){if(e.name.length<1||e.name.length>20)return`--name must be 1-20 characters`;let t=!!e.docId?.length,n=!!e.categoryId?.length;if(t&&n)return`Use either --doc-id or --category-id, not both`;if(!t&&!n)return`Provide --doc-id or --category-id as the data source`},async run(e){let{settings:n,flags:r}=e,i=W(e),a=T(n.output),o={name:r.name,structureType:`unstructured`,sinkType:`BUILT_IN`,embeddingModelName:r.embeddingModel??`text-embedding-v4`,chunkSize:r.chunkSize??600,...Lc(r)},s=E(i,p.indexCreateV2);if(n.dryRun){A({endpoint:s,request:o},a);return}let l=await e.client.requestJson({path:s,method:`POST`,body:o}),u=l.data?.pipelineId,d=l.data?.ingestionId,f;if(r.wait&&u&&d){let a=await lc(e.client,n,{statusUrl:cc(i,u,d).toString(),intervalSec:r.pollInterval??5});if(f=ic(a),ac(a).length>0)throw new t(sc(a,`Initial import reported document failures.`),c.GENERAL,`Knowledge base created: ${u}`,{api:{requestId:a.request_id}})}if(n.quiet){k(u??``);return}if(a===`text`){k(`index_id: ${u??`-`}`),d&&k(`ingestion_id: ${d}`),f&&k(`status: ${f}`),k(`Next: check the import job status, then search against this knowledge base.`);return}A(f?{...l,final_status:f}:l,a)}}),zc=w({description:{"en-US":`Update knowledge base name, description or rerank threshold`,"zh-CN":`更新知识库名称、描述或 Rerank 阈值`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:{indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`New knowledge base name (1-20 chars)`,"zh-CN":`新的知识库名称(1–20 个字符)`}},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`New knowledge base description`,"zh-CN":`新的知识库描述`}},rerankMinScore:{type:`number`,valueHint:`<score>`,description:{"en-US":`Rerank minimum score threshold, range 0-1 (chunks below are filtered)`,"zh-CN":`Rerank 最低分数阈值,范围 0–1(低于阈值的 Chunk 会被过滤)`}},...U},notes:[{"en-US":`Indexing settings (embedding model, chunk size, etc.) are immutable — recreate the knowledge base to change them.`,"zh-CN":`索引设置(Embedding 模型、Chunk 大小等)不可修改——如需更改,请重新创建知识库。`}],exampleArgs:[{"en-US":`--index-id idx-xxx --description 'product docs v2' --workspace-id ws-xxx`,"zh-CN":`--index-id idx-xxx --description '产品文档 v2' --workspace-id ws-xxx`},`--index-id idx-xxx --rerank-min-score 0.3`],validate(e){if(e.name===void 0&&e.description===void 0&&e.rerankMinScore===void 0)return`Nothing to update — pass --name, --description or --rerank-min-score`;if(e.name!==void 0&&(e.name.length<1||e.name.length>20))return`--name must be 1-20 characters`;if(e.rerankMinScore!==void 0&&(e.rerankMinScore<0||e.rerankMinScore>1))return`--rerank-min-score must be between 0 and 1`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={id:n.indexId,...n.name===void 0?{}:{name:n.name},...n.description===void 0?{}:{description:n.description},...n.rerankMinScore===void 0?{}:{rerankMinScore:n.rerankMinScore}},o=E(r,p.indexUpdate);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){k(`updated: ${n.indexId}`);return}A(s,i)}}});const Bc={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},yes:{type:`switch`,description:{"en-US":`Skip the confirmation prompt`,"zh-CN":`跳过确认提示`}},...U};async function Vc(e,t,n){let r=``,i=``;try{r=` name: ${(await Sc(e.client,t,n)).name}`}catch{}try{let r=new URL(E(t,p.indexFiles));r.searchParams.set(`index_id`,n),r.searchParams.set(`page_num`,`1`),r.searchParams.set(`page_size`,`1`);let a=(await e.client.requestJson({path:r.toString(),method:`GET`})).data?.total_count;typeof a==`number`&&(i=` documents: ${a}`)}catch{}return`Delete knowledge base ${n}${r}${i}\nThis permanently removes the knowledge base with all documents and chunks. It cannot be undone.`}var Hc=w({description:{"en-US":`Delete a knowledge base with all its documents and chunks`,"zh-CN":`删除知识库及其所有文档和 Chunk`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:Bc,notes:[{"en-US":`Irreversible — the knowledge base and all indexed content are permanently removed.`,"zh-CN":`该操作不可撤销——知识库及所有已索引内容将被永久删除。`},{"en-US":`Files in the data center are not affected; only the knowledge base index is deleted.`,"zh-CN":`数据中心中的文件不受影响;仅删除知识库索引。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={index_id:n.indexId},o=E(r,p.indexDelete);if(t.dryRun){A({endpoint:o,request:a},i);return}await yn(n.yes?``:await Vc(e,r,n.indexId),n.yes??!1);let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){k(`deleted: ${n.indexId}`);return}A(s,i)}}});const Uc={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},docId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Document ID to delete (repeatable)`,"zh-CN":`要删除的文档 ID(可重复)`},required:!0},yes:{type:`switch`,description:{"en-US":`Skip the confirmation prompt`,"zh-CN":`跳过确认提示`}},...U};function Wc(e,t){let n=t.length<=5?t.join(`
2733
+ `)}else{let e=``,r=``;for await(let n of Et(p)){if(n.data===`[DONE]`)break;if(n.event===`error`){let e=`Chat API error`,r;try{let t=JSON.parse(n.data);e=t.message||e,r=t.code}catch{}throw new t(e,c.GENERAL,r?`API error: ${r}`:void 0)}try{let t=JSON.parse(n.data);t.request_id&&(r=t.request_id);for(let n of t.output?.choices??[])if(n.message?.content&&(e+=n.message.content),n.finish_reason===`stop`)break}catch{}}n.quiet||l===`text`?k(e):A({answer:e,request_id:r},l)}}}),yc=w({description:{"en-US":`List knowledge bases in the workspace`,"zh-CN":`列出 Workspace 中的知识库`},auth:`apiKey`,usageArgs:`[flags]`,flags:{name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by knowledge base name (fuzzy match, 1-20 chars)`,"zh-CN":`按知识库名称筛选(模糊匹配,1–20 个字符)`}},...nc,...U},notes:[{"en-US":`Auth: uses DashScope API Key (Bearer token).`,"zh-CN":`鉴权:使用 DashScope API Key(Bearer Token)。`},{"en-US":"`--workspace-id` can be set via BAILIAN_WORKSPACE_ID env or config workspace_id.","zh-CN":"`--workspace-id` 可通过 BAILIAN_WORKSPACE_ID 环境变量或配置项 workspace_id 设置。"},{"en-US":`Use the returned id as --index-id in knowledge base / document management commands.`,"zh-CN":`在知识库/文档管理命令中,将返回的 ID 作为 --index-id 使用。`}],exampleArgs:[`--workspace-id ws-xxx`,`--name demo --page-number 2 --page-size 50`],validate(e){if(e.name!==void 0&&(e.name.length<1||e.name.length>20))return`--name must be 1-20 characters`;if(e.pageSize!==void 0&&(e.pageSize<1||e.pageSize>100))return`--page-size must be between 1 and 100`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a=new URL(E(r,p.indexList));n.name&&a.searchParams.set(`pipeline_name`,n.name),a.searchParams.set(`page_number`,String(n.pageNumber??1)),a.searchParams.set(`page_size`,String(n.pageSize??20));let o=a.toString();if(t.dryRun){A({endpoint:o,request:null},i);return}let s=await e.client.requestJson({path:o,method:`GET`}),c=s.data?.rows??[];if(t.quiet){for(let e of c)k(e.id);return}if(i===`text`){if(c.length===0)k(`No knowledge bases found.`);else for(let e of c)k(rc([e.id,e.name,e.embeddingModelName??`-`,e.chunkSize??`-`,e.description??``].join(` `)));k(`total: ${s.data?.total??c.length}`)}else A(s,i)}});const bc={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},...U};function xc(e,t){let n=new URL(E(e,p.indexList));return n.searchParams.set(`pipeline_id`,t),n.searchParams.set(`page_number`,`1`),n.searchParams.set(`page_size`,`1`),n.toString()}async function Sc(e,n,r){let i=(await e.requestJson({path:xc(n,r),method:`GET`})).data?.rows?.[0];if(!i)throw new t(`Knowledge base not found: ${r}`,c.GENERAL,`Check the id — list knowledge bases in this workspace to verify it.`);return i}function G(e,t){return` ${e}: ${t??`-`}`}var Cc=w({description:{"en-US":`Show knowledge base configuration details`,"zh-CN":`查看知识库配置详情`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:bc,notes:[{"en-US":`Indexing settings are immutable; changing them requires recreating the knowledge base.`,"zh-CN":`索引设置不可修改;如需更改,必须重新创建知识库。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output);if(t.dryRun){A({endpoint:xc(r,n.indexId),request:null},i);return}let a=await Sc(e.client,r,n.indexId);if(t.quiet){k(a.id??``);return}if(i!==`text`){A(a,i);return}k(`Basic:`),k(G(`id`,a.id)),k(G(`name`,a.name)),k(G(`description`,a.description)),k(G(`dataType`,a.dataType)),k(`Indexing: [immutable — recreate required to change]`),k(G(`embeddingModelName`,a.embeddingModelName)),k(G(`embeddingDimension`,a.embeddingDimension)),k(G(`chunkSize`,a.chunkSize)),k(G(`overlapSize`,a.overlapSize)),k(G(`chunkMode`,a.chunkMode)),k(G(`separator`,a.separator)),k(`Retrieval:`),k(G(`rerankModelName`,a.rerankModelName)),k(G(`rerankMinScore`,a.rerankMinScore)),k(G(`rerankTopN`,a.rerankTopN)),k(G(`rerankMode`,a.rerankMode)),k(G(`enableRewrite`,a.enableRewrite)),k(G(`denseSimilarityTopK`,a.denseSimilarityTopK)),k(G(`sparseSimilarityTopK`,a.sparseSimilarityTopK)),k(`Data:`),k(G(`sourceType`,a.sourceType)),k(G(`connectorId`,a.connectorId))}}),wc=w({description:{"en-US":`List documents in a knowledge base with parse/index status`,"zh-CN":`列出知识库文档及其解析/索引状态`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:{indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},...nc,...U},notes:[{"en-US":`Documents with status FAILED are highlighted in text mode — use the import job status command to inspect failures.`,"zh-CN":`文本模式会突出显示状态为 FAILED 的文档——请使用导入任务状态命令检查失败详情。`},{"en-US":`Page size defaults to 10 (server default), max 100.`,"zh-CN":`分页大小默认为 10(服务端默认值),最大为 100。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --page-size 100`],validate(e){if(e.pageSize!==void 0&&(e.pageSize<1||e.pageSize>100))return`--page-size must be between 1 and 100`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a=new URL(E(r,p.indexFiles));a.searchParams.set(`index_id`,n.indexId),a.searchParams.set(`page_num`,String(n.pageNumber??1)),a.searchParams.set(`page_size`,String(n.pageSize??10));let o=a.toString();if(t.dryRun){A({endpoint:o,request:null},i);return}let s=await e.client.requestJson({path:o,method:`GET`}),c=s.data?.rows??[];if(t.quiet){for(let e of c)k(e.doc_id??``);return}if(i===`text`){let e=O(process.stdout);if(c.length===0)k(`No documents found.`);else for(let t of c){let n=rc([t.doc_id,t.status,t.doc_name,t.doc_type??`-`,t.size??`-`].join(` `));k(t.status===`FAILED`?e.red(n):n)}k(`total: ${s.data?.total_count??c.length}`)}else A(s,i)}});const Tc={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},jobId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Import job ID (ingestionId returned by import commands)`,"zh-CN":`导入任务 ID(导入命令返回的 ingestionId)`},required:!0},...nc,wait:{type:`switch`,description:{"en-US":`Poll until the job reaches a terminal state`,"zh-CN":`轮询直到任务进入终态`}},pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 5)`,"zh-CN":`等待时的轮询间隔(默认:5)`}},...U};function Ec(e){let t=O(process.stdout);k(`status: ${e.data?.ingestion_status??`UNKNOWN`}`);for(let n of e.data?.rows??[]){let e=n.code??n.status??`?`,r=` ${n.doc_id??`?`} ${e} ${n.doc_name??``}`;k(e.includes(`FAILED`)?t.red(r):r)}}var Dc=w({description:{"en-US":`Check knowledge base import job status`,"zh-CN":`检查知识库导入任务状态`},auth:`apiKey`,usageArgs:`--index-id <id> --job-id <id> [flags]`,flags:Tc,notes:[{"en-US":`Both --index-id and --job-id are required (passing only one returns SystemError).`,"zh-CN":`--index-id 和 --job-id 均为必填(只传其中一个会返回 SystemError)。`},{"en-US":`If you see a SystemError, the job may not exist — check the ingestion id in the document list output.`,"zh-CN":`如果出现 SystemError,任务可能不存在——请检查文档列表输出中的 ingestion ID。`},{"en-US":`Overall job states are PENDING / RUNNING / COMPLETED; per-document failures (for example PARSE_FAILED) exit non-zero with the error message passed through.`,"zh-CN":`任务整体状态为 PENDING / RUNNING / COMPLETED;单个文档失败(例如 PARSE_FAILED)时会以非零状态退出,并原样透传错误信息。`}],exampleArgs:[`--index-id idx-xxx --job-id job-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --job-id job-xxx --wait --poll-interval 10`],async run(e){let{settings:n,flags:r}=e,i=W(e),a=T(n.output),o=new URL(E(i,p.indexJobStatus));o.searchParams.set(`index_id`,r.indexId),o.searchParams.set(`job_id`,r.jobId),r.pageNumber!==void 0&&o.searchParams.set(`page_number`,String(r.pageNumber)),r.pageSize!==void 0&&o.searchParams.set(`page_size`,String(r.pageSize));let s=o.toString();if(n.dryRun){A({endpoint:s,request:null},a);return}let l;if(l=r.wait?await lc(e.client,n,{statusUrl:s,intervalSec:r.pollInterval??5}):await e.client.requestJson({path:s,method:`GET`}),ac(l).length>0)throw new t(sc(l,`Import job reported document failures.`),c.GENERAL);if(n.quiet){k(l.data?.ingestion_status??`UNKNOWN`);return}a===`text`?Ec(l):A(l,a)}});const K=1024*1024,Oc={".doc":{maxBytes:150*K,enforce:`block`},".docx":{maxBytes:150*K,enforce:`block`},".ppt":{maxBytes:150*K,enforce:`block`},".pptx":{maxBytes:150*K,enforce:`block`},".pdf":{maxBytes:150*K,enforce:`block`},".png":{maxBytes:20*K,enforce:`block`},".jpg":{maxBytes:20*K,enforce:`block`},".jpeg":{maxBytes:20*K,enforce:`block`},".bmp":{maxBytes:20*K,enforce:`block`},".gif":{maxBytes:20*K,enforce:`block`},".xls":{maxBytes:10*K,enforce:`warn`},".xlsx":{maxBytes:10*K,enforce:`warn`},".csv":{maxBytes:10*K,enforce:`warn`},".md":{maxBytes:10*K,enforce:`warn`},".txt":{maxBytes:10*K,enforce:`warn`},".html":{maxBytes:10*K,enforce:`warn`}};function kc(e){return dr(e).toLowerCase()in Oc}const Ac=new Set([`node_modules`,`.git`,`.svn`,`.hg`,`__pycache__`,`.venv`,`venv`,`.env`,`.tox`,`dist`,`build`,`.cache`,`.next`,`.nuxt`]);function jc(e){let n=[],r=[];function i(e){let a;try{a=or(e,{withFileTypes:!0})}catch(n){let r=n.code??`unknown`;throw new t(`Cannot read directory: ${e}`,c.GENERAL,`File system error (${r}) — check the path and permissions.`)}for(let t of a){let a=I(e,t.name);if(t.isDirectory()){Ac.has(t.name)||i(a);continue}t.isFile()&&(kc(t.name)?n.push(a):r.push(a))}}for(let r of e){let e;try{e=sr(r)}catch(e){let n=e.code??`unknown`;throw new t(`Cannot read path: ${r}`,c.GENERAL,`File system error (${n}) — check the path and permissions.`)}e.isDirectory()?i(r):e.isFile()&&n.push(r)}return{files:n,skipped:r}}function Mc(e){let n=dr(e).toLowerCase(),r=Oc[n];if(!r)throw new t(`Unsupported file type: ${n||F(e)}`,c.USAGE,`Supported formats: ${Object.keys(Oc).join(` `)}`);let i;try{i=sr(e).size}catch(n){let r=n.code??`unknown`;throw new t(`Cannot read file: ${e}`,c.GENERAL,`File system error (${r}) — check the path and permissions.`)}if(i>r.maxBytes){let a=r.maxBytes/K;if(r.enforce===`block`)throw new t(`File exceeds the ${a} MB limit for ${n}: ${F(e)}`,c.USAGE);return{sizeBytes:i,warning:`${F(e)} exceeds the recommended 10 MB for ${n}; the server may reject or truncate it.`}}return{sizeBytes:i}}const Nc=new Set([`.doc`,`.docx`,`.ppt`,`.pptx`,`.pdf`,`.xls`,`.xlsx`,`.png`,`.jpg`,`.jpeg`,`.bmp`,`.gif`]);function Pc(e,n){let r;try{r=ar(e)}catch(r){let i=r.code??`unknown`,a=`File system error (${i}) — check the path and permissions.`;throw n&&i===`ENOENT`&&!dr(e)&&!e.includes(`/`)&&!e.includes(`\\`)&&(a+=` If you meant to pass text content directly, use ${n} instead of --content-file.`),new t(`Cannot read file: ${e}`,c.GENERAL,a)}try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(r)}catch{let n=dr(e).toLowerCase(),r=Nc.has(n)?`Document formats cannot be used as chunk content. Upload documents via the document upload command; to edit a chunk, save the text as .md/.txt first.`:`Convert the file to UTF-8 encoding and retry.`;throw new t(`File is not valid UTF-8 plain text: ${F(e)}`,c.USAGE,r)}}var Fc=w({description:{"en-US":`Upload local files or directories to the data center and optionally import into a knowledge base`,"zh-CN":`上传本地文件或目录到数据中心,并可选择导入知识库`},auth:`apiKey`,usageArgs:`--file <path> [flags]`,flags:{file:{type:`array`,valueHint:`<path>`,description:{"en-US":`Local file or directory path (repeatable). Directories are scanned recursively; unsupported formats are skipped`,"zh-CN":`本地文件或目录路径(可重复)。目录会递归扫描,不支持的格式将被跳过`},required:!0},indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Import into this knowledge base after registration (one job for all files)`,"zh-CN":`文件注册后导入该知识库(所有文件共用一个任务)`}},categoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Target data-center category; defaults to the workspace default category`,"zh-CN":`目标数据中心类目;默认为 Workspace 的默认类目`}},tag:{type:`array`,valueHint:`<text>`,description:{"en-US":`File tag (repeatable), applied to every uploaded file`,"zh-CN":`文件标签(可重复),应用于每个上传文件`}},wait:{type:`switch`,description:{"en-US":`Poll the import job to a terminal state (needs --index-id)`,"zh-CN":`轮询导入任务直到进入终态(需要 --index-id)`}},pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 5)`,"zh-CN":`等待时的轮询间隔(默认:5)`}},...U},notes:[{"en-US":`Pipeline: apply upload lease → PUT to OSS → register file → (with --index-id) create import job.`,"zh-CN":`处理流程:申请上传凭证 → PUT 到 OSS → 注册文件 →(传入 --index-id 时)创建导入任务。`},{"en-US":`Without --category-id the workspace default category is resolved automatically.`,"zh-CN":`未传入 --category-id 时,会自动解析 Workspace 的默认类目。`},{"en-US":`Directories are scanned recursively; node_modules, .git, and similar are skipped automatically.`,"zh-CN":`目录会递归扫描;node_modules、.git 等目录会被自动跳过。`},{"en-US":`Multiple files are processed sequentially; on failure, already-registered file ids are listed in the error hint.`,"zh-CN":`多个文件会依次处理;失败时,错误提示会列出已经注册成功的文件 ID。`}],exampleArgs:[`--file ./a.md --workspace-id ws-xxx`,`--file ./a.md --file ./b.pdf --index-id idx-xxx --wait`,`--file ./docs/ --workspace-id ws-xxx`,`--file ./docs/ --dry-run --verbose`],validate(e){if(e.wait&&!e.indexId)return`--wait requires --index-id`},async run(e){let{settings:n,flags:r}=e,i=W(e),a=T(n.output),{files:o,skipped:s}=jc(r.file);if(o.length===0)throw new t(`No supported files found`,c.USAGE,`Supported formats: .pdf .doc .docx .ppt .pptx .xls .xlsx .csv .md .txt .html .png .jpg .jpeg .bmp .gif`);let l=o.map(e=>{let t=Mc(e);return t.warning&&process.stderr.write(`Warning: ${t.warning}\n`),{filePath:e,sizeBytes:t.sizeBytes}});if(n.dryRun){let e=r.categoryId??`default`,t=l.flatMap(t=>[{step:`applyFileUploadLease`,endpoint:E(i,p.applyFileUploadLease),request:{category:e,fileName:F(t.filePath),sizeBytes:String(t.sizeBytes),contentMd5:`<md5-base64>`}},{step:`ossPut`,endpoint:`<lease.param.url>`,request:{method:`PUT`,headers:`<lease.param.headers>`}},{step:`addFile`,endpoint:E(i,p.addFile),request:{leaseId:`<leaseId>`,category:e,parser:`AUTO_SELECT`,...r.tag?.length?{tags:r.tag}:{}}}]);r.indexId&&t.push({step:`createImportJob`,endpoint:E(i,p.indexJobCreate),request:{indexId:r.indexId,sourceType:`DATA_CENTER_FILE`,docIds:[`<fileId>`]}}),A({steps:t,skipped:s},a);return}let u=r.categoryId??`default`,d=[];for(let n of l)try{let a=ar(n.filePath),o=Vn(`md5`).update(a).digest(`base64`),s=await e.client.requestJson({path:E(i,p.applyFileUploadLease),method:`POST`,body:{category:u,fileName:F(n.filePath),sizeBytes:String(n.sizeBytes),contentMd5:o}}),l=s.data?.leaseId,f=s.data?.param;if(!l||!f?.url)throw new t(`Upload lease response missing leaseId/url for ${n.filePath}`,c.GENERAL);let m;try{m=await fetch(f.url,{method:f.method??`PUT`,headers:f.headers,body:a})}catch(e){let r=e.cause?.code;throw new t(`OSS upload failed for ${F(n.filePath)}`,c.NETWORK,r?`Network error (${r}).`:void 0,{cause:e})}if(!m.ok){let e=await m.text().catch(()=>``);throw new t(`OSS upload rejected (HTTP ${m.status}) for ${F(n.filePath)}${e?`: ${e.slice(0,300)}`:``}`,c.GENERAL)}let h=(await e.client.requestJson({path:E(i,p.addFile),method:`POST`,body:{leaseId:l,category:u,parser:`AUTO_SELECT`,...r.tag?.length?{tags:r.tag}:{}}})).data?.fileId;if(!h)throw new t(`addFile response missing fileId for ${n.filePath}`,c.GENERAL);d.push({path:n.filePath,fileId:h})}catch(e){throw d.length>0?uc(e,`Already registered: ${d.map(e=>e.fileId).join(`, `)}`):e}let f,m;if(r.indexId&&(f=(await e.client.requestJson({path:E(i,p.indexJobCreate),method:`POST`,body:{indexId:r.indexId,sourceType:`DATA_CENTER_FILE`,docIds:d.map(e=>e.fileId)}})).data?.ingestionId,r.wait&&f)){let a=await lc(e.client,n,{statusUrl:cc(i,r.indexId,f).toString(),intervalSec:r.pollInterval??5});if(m=ic(a),ac(a).length>0)throw new t(sc(a,`Import job reported document failures.`),c.GENERAL,`Registered file ids: ${d.map(e=>e.fileId).join(`, `)}`)}if(n.quiet){for(let e of d)k(e.fileId);return}if(a===`text`){for(let e of d)k(`${F(e.path)} ${e.fileId} registered`);f&&k(`job: ${f}`),m&&k(`status: ${m}`);let e=[`Uploaded ${d.length} file${d.length===1?``:`s`}`];if(s.length>0&&e.push(`skipped ${s.length} unsupported`),k(`\n${e.join(`, `)}.`),n.verbose&&s.length>0){k(`Skipped files:`);for(let e of s)k(` ${F(e)}`)}return}A({files:d.map(e=>({path:e.path,fileId:e.fileId})),skipped:s,...r.indexId?{index_id:r.indexId}:{},...f?{ingestion_id:f}:{},...m?{final_status:m}:{}},a)}});const Ic={name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Knowledge base name (1-20 chars, unique in workspace)`,"zh-CN":`知识库名称(1–20 个字符,在 Workspace 中唯一)`},required:!0},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`What this knowledge base holds and what it is for — tells bases apart in the workspace list (1-500 chars)`,"zh-CN":`知识库装了什么内容、给谁用,用于在 Workspace 列表中区分同类知识库(1–500 个字符)`},required:!0},docId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Data-center file id to import (repeatable); mutually exclusive with --category-id`,"zh-CN":`要导入的数据中心文件 ID(可重复);不能与 --category-id 同时使用`}},categoryId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Import every file under this category (repeatable); mutually exclusive with --doc-id`,"zh-CN":`导入该类目下的所有文件(可重复);不能与 --doc-id 同时使用`}},embeddingModel:{type:`string`,valueHint:`<name>`,description:{"en-US":`Embedding model name (default: text-embedding-v4)`,"zh-CN":`Embedding 模型名称(默认:text-embedding-v4)`}},chunkSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Chunk size in characters (default: 600, recommended 300-800)`,"zh-CN":`Chunk 字符数(默认:600,建议:300–800)`}},wait:{type:`switch`,description:{"en-US":`Poll the initial import job to a terminal state`,"zh-CN":`轮询初始导入任务直到进入终态`}},pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 5)`,"zh-CN":`等待时的轮询间隔(默认:5)`}},...U};function Lc(e){return e.docId?.length?{sourceType:`DATA_CENTER_FILE`,docIds:e.docId,dataSources:[{sourceType:`DATA_CENTER_FILE`}]}:{sourceType:`DATA_CENTER_CATEGORY`,categoryIds:e.categoryId,dataSources:[{sourceType:`DATA_CENTER_CATEGORY`}]}}var Rc=w({description:{"en-US":`Create a knowledge base and import data-center files or categories`,"zh-CN":`创建知识库并导入数据中心文件或类目`},auth:`apiKey`,usageArgs:`--name <text> --description <text> (--doc-id <id> | --category-id <id>) [flags]`,flags:Ic,notes:[{"en-US":`Structure/sink types are fixed to the default document knowledge base (unstructured, BUILT_IN storage).`,"zh-CN":`结构和存储类型固定为默认文档知识库(unstructured、BUILT_IN 存储)。`},{"en-US":`Returns the knowledge base id (pipelineId) and the initial import job id (ingestionId).`,"zh-CN":`返回知识库 ID(pipelineId)和初始导入任务 ID(ingestionId)。`},{"en-US":`Use the import job status command (or --wait) to track the initial import.`,"zh-CN":`使用导入任务状态命令(或 --wait)跟踪初始导入。`}],exampleArgs:[{"en-US":`--name demo --description 'product docs' --doc-id file-xxx --workspace-id ws-xxx`,"zh-CN":`--name demo --description '产品文档' --doc-id file-xxx --workspace-id ws-xxx`},{"en-US":`--name demo --description 'product docs' --category-id cate-xxx --wait`,"zh-CN":`--name demo --description '产品文档' --category-id cate-xxx --wait`}],validate(e){if(e.name.length<1||e.name.length>20)return`--name must be 1-20 characters`;if(e.description.length<1||e.description.length>500)return`--description must be 1-500 characters`;let t=!!e.docId?.length,n=!!e.categoryId?.length;if(t&&n)return`Use either --doc-id or --category-id, not both`;if(!t&&!n)return`Provide --doc-id or --category-id as the data source`},async run(e){let{settings:n,flags:r}=e,i=W(e),a=T(n.output),o={name:r.name,description:r.description,structureType:`unstructured`,sinkType:`BUILT_IN`,embeddingModelName:r.embeddingModel??`text-embedding-v4`,chunkSize:r.chunkSize??600,...Lc(r)},s=E(i,p.indexCreateV2);if(n.dryRun){A({endpoint:s,request:o},a);return}let l=await e.client.requestJson({path:s,method:`POST`,body:o}),u=l.data?.pipelineId,d=l.data?.ingestionId,f;if(r.wait&&u&&d){let a=await lc(e.client,n,{statusUrl:cc(i,u,d).toString(),intervalSec:r.pollInterval??5});if(f=ic(a),ac(a).length>0)throw new t(sc(a,`Initial import reported document failures.`),c.GENERAL,`Knowledge base created: ${u}`,{api:{requestId:a.request_id}})}if(n.quiet){k(u??``);return}if(a===`text`){k(`index_id: ${u??`-`}`),d&&k(`ingestion_id: ${d}`),f&&k(`status: ${f}`),k(`Next: check the import job status, then search against this knowledge base.`);return}A(f?{...l,final_status:f}:l,a)}}),zc=w({description:{"en-US":`Update knowledge base name, description or rerank threshold`,"zh-CN":`更新知识库名称、描述或 Rerank 阈值`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:{indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`New knowledge base name (1-20 chars)`,"zh-CN":`新的知识库名称(1–20 个字符)`}},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`New knowledge base description`,"zh-CN":`新的知识库描述`}},rerankMinScore:{type:`number`,valueHint:`<score>`,description:{"en-US":`Rerank minimum score threshold, range 0-1 (chunks below are filtered)`,"zh-CN":`Rerank 最低分数阈值,范围 0–1(低于阈值的 Chunk 会被过滤)`}},...U},notes:[{"en-US":`Indexing settings (embedding model, chunk size, etc.) are immutable — recreate the knowledge base to change them.`,"zh-CN":`索引设置(Embedding 模型、Chunk 大小等)不可修改——如需更改,请重新创建知识库。`}],exampleArgs:[{"en-US":`--index-id idx-xxx --description 'product docs v2' --workspace-id ws-xxx`,"zh-CN":`--index-id idx-xxx --description '产品文档 v2' --workspace-id ws-xxx`},`--index-id idx-xxx --rerank-min-score 0.3`],validate(e){if(e.name===void 0&&e.description===void 0&&e.rerankMinScore===void 0)return`Nothing to update — pass --name, --description or --rerank-min-score`;if(e.name!==void 0&&(e.name.length<1||e.name.length>20))return`--name must be 1-20 characters`;if(e.rerankMinScore!==void 0&&(e.rerankMinScore<0||e.rerankMinScore>1))return`--rerank-min-score must be between 0 and 1`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={id:n.indexId,...n.name===void 0?{}:{name:n.name},...n.description===void 0?{}:{description:n.description},...n.rerankMinScore===void 0?{}:{rerankMinScore:n.rerankMinScore}},o=E(r,p.indexUpdate);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){k(`updated: ${n.indexId}`);return}A(s,i)}}});const Bc={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},yes:{type:`switch`,description:{"en-US":`Skip the confirmation prompt`,"zh-CN":`跳过确认提示`}},...U};async function Vc(e,t,n){let r=``,i=``;try{r=` name: ${(await Sc(e.client,t,n)).name}`}catch{}try{let r=new URL(E(t,p.indexFiles));r.searchParams.set(`index_id`,n),r.searchParams.set(`page_num`,`1`),r.searchParams.set(`page_size`,`1`);let a=(await e.client.requestJson({path:r.toString(),method:`GET`})).data?.total_count;typeof a==`number`&&(i=` documents: ${a}`)}catch{}return`Delete knowledge base ${n}${r}${i}\nThis permanently removes the knowledge base with all documents and chunks. It cannot be undone.`}var Hc=w({description:{"en-US":`Delete a knowledge base with all its documents and chunks`,"zh-CN":`删除知识库及其所有文档和 Chunk`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:Bc,notes:[{"en-US":`Irreversible — the knowledge base and all indexed content are permanently removed.`,"zh-CN":`该操作不可撤销——知识库及所有已索引内容将被永久删除。`},{"en-US":`Files in the data center are not affected; only the knowledge base index is deleted.`,"zh-CN":`数据中心中的文件不受影响;仅删除知识库索引。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={index_id:n.indexId},o=E(r,p.indexDelete);if(t.dryRun){A({endpoint:o,request:a},i);return}await yn(n.yes?``:await Vc(e,r,n.indexId),n.yes??!1);let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){k(`deleted: ${n.indexId}`);return}A(s,i)}}});const Uc={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},docId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Document ID to delete (repeatable)`,"zh-CN":`要删除的文档 ID(可重复)`},required:!0},yes:{type:`switch`,description:{"en-US":`Skip the confirmation prompt`,"zh-CN":`跳过确认提示`}},...U};function Wc(e,t){let n=t.length<=5?t.join(`
2734
2734
  `):`${t.slice(0,5).join(`
2735
- `)}\n ... (${t.length} documents total)`;return`Delete ${t.length} document(s) from knowledge base ${e}:\n ${n}\nDocuments and all their chunks are permanently removed from the index. This cannot be undone.`}var Gc=w({description:{"en-US":`Delete documents and their chunks from a knowledge base`,"zh-CN":`从知识库中删除文档及其 Chunk`},auth:`apiKey`,usageArgs:`--index-id <id> --doc-id <id> [flags]`,flags:Uc,notes:[{"en-US":`Removes documents from the knowledge base index only; the source files remain in the data center.`,"zh-CN":`仅从知识库索引中移除文档;源文件仍保留在数据中心。`},{"en-US":"Use the doc_id from `knowledge doc list --quiet`, not the fileId from `knowledge doc upload`. For documents created via `knowledge create --doc-id`, the doc_id equals the fileId; for documents imported via `knowledge doc upload --index-id`, the doc_id may include a workspace suffix.","zh-CN":"请使用 `knowledge doc list --quiet` 返回的 doc_id,而不是 `knowledge doc upload` 返回的 fileId。通过 `knowledge create --doc-id` 创建的文档,其 doc_id 等于 fileId;通过 `knowledge doc upload --index-id` 导入的文档,其 doc_id 可能带有 Workspace 后缀。"},{"en-US":`Deletion may take up to ~30s to propagate — the document may still appear in the doc list briefly.`,"zh-CN":`删除结果最多可能需要约 30 秒才会生效——文档可能会短暂地继续出现在列表中。`},{"en-US":`The output lists the ids actually deleted.`,"zh-CN":`输出会列出实际删除的 ID。`}],exampleArgs:[`--index-id idx-xxx --doc-id file-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --doc-id file-a --doc-id file-b --yes`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={index_id:n.indexId,doc_ids:n.docId},o=E(r,p.indexDeleteFile);if(t.dryRun){A({endpoint:o,request:a},i);return}await yn(Wc(n.indexId,n.docId),n.yes??!1);let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.deleted??[];if(t.quiet){for(let e of c)k(e);return}if(i===`text`){k(`deleted: ${c.length} document(s)`);for(let e of c)k(` ${e}`);c.length!==n.docId.length&&process.stderr.write(`Warning: requested ${n.docId.length} deletion(s) but the server reported ${c.length}.\n`);return}A(s,i)}}),Kc=w({description:{"en-US":`Batch update tags on data-center files`,"zh-CN":`批量更新数据中心文件标签`},auth:`apiKey`,usageArgs:`--doc-id <id> --tag <text> [flags]`,flags:{docId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Data-center file ID to tag (repeatable, 1-20 per call)`,"zh-CN":`要添加标签的数据中心文件 ID(可重复,每次调用 1–20 个)`},required:!0},tag:{type:`array`,valueHint:`<text>`,description:{"en-US":`Tag applied to every --doc-id (repeatable, each up to 32 chars)`,"zh-CN":`应用于每个 --doc-id 的标签(可重复,每个最多 32 个字符)`},required:!0},mode:{type:`string`,valueHint:`<mode>`,description:{"en-US":`Update mode: append (default) or overwrite`,"zh-CN":`更新模式:append(默认)或 overwrite`}},...U},notes:[{"en-US":`The same tag set is applied to every --doc-id; run the command multiple times for different tag sets.`,"zh-CN":`同一组标签会应用于每个 --doc-id;若需应用不同标签组,请多次运行该命令。`},{"en-US":`Server limits: up to 100 tags per file, total tag length up to 700 chars, tag up to 32 chars.`,"zh-CN":`服务端限制:每个文件最多 100 个标签,标签总长度最多 700 个字符,单个标签最多 32 个字符。`}],exampleArgs:[`--doc-id file-xxx --tag project-a --tag draft --workspace-id ws-xxx`,`--doc-id file-a --doc-id file-b --tag final --mode overwrite`],validate(e){if(e.docId.length>20)return`--doc-id accepts at most 20 ids per call`;if(e.mode!==void 0&&e.mode!==`append`&&e.mode!==`overwrite`)return`--mode must be append or overwrite`;if(e.tag.length>100)return`At most 100 tags per file`;let t=e.tag.find(e=>e.length>32);if(t)return`Tag exceeds 32 characters: ${t}`;if(e.tag.reduce((e,t)=>e+t.length,0)>700)return`Total tag length exceeds 700 characters`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={fileInfos:n.docId.map(e=>({fileId:e,tags:n.tag})),updateMode:(n.mode??`append`).toUpperCase()},o=E(r,p.batchUpdateFileTag);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){k(`tagged: ${n.docId.length} file(s) with [${n.tag.join(`, `)}]`);return}A(s,i)}}});const qc={scene:{type:`string`,valueHint:`<scene>`,description:{"en-US":`Service scene: chat (Q&A) or search (retrieval). Required by the server`,"zh-CN":`服务场景:chat(问答)或 search(检索),服务端必填`},required:!0},status:{type:`string`,valueHint:`<status>`,description:{"en-US":`Filter by status: draft, deployed (includes edited) or deleted`,"zh-CN":`按状态筛选:draft、deployed(包含 edited)或 deleted`}},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by service name (fuzzy match)`,"zh-CN":`按服务名称模糊筛选`}},agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by exact agent ID`,"zh-CN":`按 Agent ID 精确筛选`}},indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by exact linked knowledge base (pipeline) ID`,"zh-CN":`按关联的知识库(Pipeline)ID 精确筛选`}},...nc,...U},Jc=[`chat`,`search`],Yc=[`draft`,`deployed`,`deleted`];var Xc=w({description:{"en-US":`List retrieval / Q&A services (agents) in the workspace`,"zh-CN":`列出 Workspace 中的检索/问答服务(Agent)`},auth:`apiKey`,usageArgs:`--scene <chat|search> [flags]`,flags:qc,notes:[{"en-US":`A scene (chat or search) is required — run once per scene to see both.`,"zh-CN":`必须指定场景(chat 或 search)——要查看两类服务,请分别运行一次。`},{"en-US":`Use the returned agent_id with the search or chat commands, or with service management commands.`,"zh-CN":`将返回的 agent_id 用于 search/chat 命令或服务管理命令。`}],exampleArgs:[`--scene chat --workspace-id ws-xxx`,`--scene search --status deployed`],validate(e){if(!Jc.includes(e.scene))return`--scene must be chat or search`;if(e.status!==void 0&&!Yc.includes(e.status))return`--status must be draft, deployed or deleted`;if(e.pageSize!==void 0&&(e.pageSize<1||e.pageSize>100))return`--page-size must be between 1 and 100`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={agent_scene:n.scene,...n.status?{agent_status:n.status}:{},...n.name?{agent_name:n.name}:{},...n.agentId?{agent_id:n.agentId}:{},...n.indexId?{pipeline_id:n.indexId}:{},page_number:n.pageNumber??1,page_size:n.pageSize??10},o=E(r,p.agentList);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.rows??[];if(t.quiet){for(let e of c)k(e.agent_id??``);return}if(i===`text`){if(c.length===0)k(`No services found.`);else for(let e of c){let t=(e.pipeline_list??[]).map(e=>e.pipeline_name).filter(Boolean).join(`,`);k(rc([e.agent_id,e.agent_status,e.agent_version,e.agent_name,t?`(kb: ${t})`:``].filter(Boolean).join(` `)))}k(`total: ${s.data?.total_count??c.length}`),k(n.scene===`search`?`Use an agent_id above with the knowledge search command.`:`Use an agent_id above with the knowledge chat command.`)}else A(s,i)}});const Zc={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Service (agent) ID`,"zh-CN":`服务(Agent)ID`},required:!0},agentVersion:{type:`string`,valueHint:`<version>`,description:{"en-US":`Specific version to inspect (beta or a published number); omit for all versions`,"zh-CN":`要查看的指定版本(beta 或已发布版本号);省略则返回全部版本`}},...U};function Qc(e){k(`Version ${e.agent_version??`?`}:`),e.agent_version_desc&&k(` desc: ${e.agent_version_desc}`),e.publish_time!==void 0&&k(` published: ${e.publish_time}`);let t=e.agent_config;if(t){t.agent_policy&&k(` policy: ${t.agent_policy}`),t.agent_model&&k(` model: ${t.agent_model}`),t.temperature!==void 0&&k(` temperature: ${t.temperature}`);for(let e of t.kb_search_configs??[])k(` kb: ${typeof e.id==`string`?e.id:`?`}${typeof e.name==`string`?` (${e.name})`:``}`)}}var $c=w({description:{"en-US":`Show service (agent) details including per-version configuration`,"zh-CN":`查看服务(Agent)详情及各版本配置`},auth:`apiKey`,usageArgs:`--agent-id <id> [flags]`,flags:Zc,notes:[{"en-US":`Without --agent-version all versions are returned (beta draft plus published numbers).`,"zh-CN":`未传入 --agent-version 时,会返回所有版本(beta 草稿和已发布版本号)。`},{"en-US":`The version value is passed through as-is; the valid set is server-side state.`,"zh-CN":`版本值将原样传递;有效版本集合由服务端状态决定。`}],exampleArgs:[`--agent-id aid-xxx --workspace-id ws-xxx`,`--agent-id aid-xxx --agent-version beta`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={agent_id:n.agentId,...n.agentVersion?{agent_version:n.agentVersion}:{}},o=E(r,p.agentGet);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data;if(t.quiet){k(c?.agent_id??``);return}if(i!==`text`){A(s,i);return}k(`Basic:`),k(` id: ${c?.agent_id??`-`}`),k(` name: ${c?.agent_name??`-`}`),k(` desc: ${c?.agent_desc??`-`}`),k(` scene: ${c?.agent_scene??`-`}`),k(` status: ${c?.agent_status??`-`}`);for(let e of c?.agent_details??[])Qc(e)}}),el=w({description:{"en-US":`Create a retrieval / Q&A service (initial status: draft, version: beta)`,"zh-CN":`创建检索/问答服务(初始状态:draft,版本:beta)`},auth:`apiKey`,usageArgs:`--name <text> --scene <chat|search> [flags]`,flags:{name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Service name (up to 200 chars, unique per scene in the workspace)`,"zh-CN":`服务名称(最多 200 个字符,在 Workspace 的同一场景中唯一)`},required:!0},scene:{type:`string`,valueHint:`<scene>`,description:{"en-US":`Service scene: chat (Q&A) or search (retrieval)`,"zh-CN":`服务场景:chat(问答)或 search(检索)`},required:!0},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`Service description (up to 1000 chars)`,"zh-CN":`服务描述(最多 1000 个字符)`}},indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Bind this knowledge base; other settings use server defaults`,"zh-CN":`绑定该知识库;其他设置使用服务端默认值`}},...U},notes:[{"en-US":`Without an explicit configuration the server applies its default agent settings.`,"zh-CN":`未显式提供配置时,服务端会应用默认 Agent 设置。`},{"en-US":`The draft (beta) version can be tested via --agent-version beta on search/chat before deploying.`,"zh-CN":`部署前,可在 search/chat 命令中使用 --agent-version beta 测试草稿(beta)版本。`},{"en-US":`Requires the knowledge-base create permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库创建权限。`}],exampleArgs:[`--name my-qa --scene chat --workspace-id ws-xxx`,`--name my-search --scene search --index-id idx-xxx`],validate(e){if(e.name.length>200)return`--name must be at most 200 characters`;if(e.scene!==`chat`&&e.scene!==`search`)return`--scene must be chat or search`;if(e.description!==void 0&&e.description.length>1e3)return`--description must be at most 1000 characters`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={agent_name:n.name,agent_scene:n.scene,...n.description?{agent_desc:n.description}:{},...n.indexId?{agent_config:{kb_search_configs:[{id:n.indexId}]}}:{}},o=E(r,p.agentCreate);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=dc(s,`agent_id`);if(t.quiet){k(c??``);return}if(i===`text`){k(`created: ${c??`-`} (status: ${dc(s,`agent_status`)??`draft`}, version: ${dc(s,`agent_version`)??`beta`})`),k(`Test the draft with --agent-version beta on search/chat, then deploy it to publish.`);return}A(s,i)}});const tl=[`true`,`false`],nl={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Service (agent) ID`,"zh-CN":`服务(Agent)ID`},required:!0},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`New service name (up to 200 chars)`,"zh-CN":`新服务名称(最多 200 个字符)`}},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`New service description (up to 1000 chars)`,"zh-CN":`新服务描述(最多 1000 个字符)`}},agentVersion:{type:`string`,valueHint:`<version>`,description:{"en-US":`Target version (default: beta draft). Published versions only accept --version-desc`,"zh-CN":`目标版本(默认:beta 草稿)。已发布版本只接受 --version-desc`}},versionDesc:{type:`string`,valueHint:`<text>`,description:{"en-US":`Version description`,"zh-CN":`版本描述`}},policy:{type:`string`,valueHint:`<policy>`,description:{"en-US":`Agent policy: turbo (fast) or agentic (multi-turn)`,"zh-CN":`Agent 策略:turbo(快速)或 agentic(多轮)`}},model:{type:`string`,valueHint:`<name>`,description:{"en-US":`Generation model code (must be in the platform allowlist)`,"zh-CN":`生成模型代码(必须在平台白名单中)`}},temperature:{type:`number`,valueHint:`<n>`,description:{"en-US":`Sampling temperature, range 0-2`,"zh-CN":`采样温度,范围 0–2`}},maxLlmCalls:{type:`number`,valueHint:`<n>`,description:{"en-US":`Max LLM calls per request, range 1-30`,"zh-CN":`每次请求最大 LLM 调用次数,范围 1–30`}},enableSessionFile:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable session files: true or false`,"zh-CN":`启用会话文件:true 或 false`}},enableRefusal:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable refusal answers: true or false`,"zh-CN":`启用拒答:true 或 false`}},enableAntiLeak:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable anti prompt-leak: true or false`,"zh-CN":`启用防提示词泄露:true 或 false`}},enableRichText:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable rich text output: true or false`,"zh-CN":`启用富文本输出:true 或 false`}},enableCitation:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable citations: true or false`,"zh-CN":`启用引用:true 或 false`}},configFile:{type:`string`,valueHint:`<path>`,description:{"en-US":`JSON file replacing the whole agent_config (for nested settings like kb_search_configs); mutually exclusive with scalar config flags`,"zh-CN":`替换整个 agent_config 的 JSON 文件(用于 kb_search_configs 等嵌套设置);不能与标量配置选项同时使用`}},...U};function rl(e){let t={};return e.policy!==void 0&&(t.agent_policy=e.policy),e.model!==void 0&&(t.agent_model=e.model),e.temperature!==void 0&&(t.temperature=e.temperature),e.maxLlmCalls!==void 0&&(t.max_num_llm_calls=e.maxLlmCalls),e.enableSessionFile!==void 0&&(t.enable_session_file=e.enableSessionFile),e.enableRefusal!==void 0&&(t.enable_refusal=e.enableRefusal),e.enableAntiLeak!==void 0&&(t.enable_anti_leak=e.enableAntiLeak),e.enableRichText!==void 0&&(t.enable_rich_text=e.enableRichText),e.enableCitation!==void 0&&(t.enable_citation=e.enableCitation),t}function il(e){let n;try{n=ar(e,`utf-8`)}catch(n){let r=n.code??`unknown`;throw new t(`Cannot read config file: ${e}`,c.GENERAL,`File system error (${r}) — check the path and permissions.`)}let r;try{r=JSON.parse(n)}catch{throw new t(`--config-file must contain valid JSON.`,c.USAGE)}if(typeof r!=`object`||!r||Array.isArray(r))throw new t(`--config-file must contain a JSON object.`,c.USAGE);let i=r;return ol(i),i}const al=new Set([`agent_policy`,`agent_model`,`enable_session_file`,`enable_refusal`,`enable_anti_leak`,`enable_rich_text`,`enable_citation`,`temperature`,`max_num_llm_calls`,`max_completion_tokens`,`session_file_max_parse_length`,`enable_kb_router`,`kb_router_model`,`rerank_top_n`,`hybrid_rerank`,`kb_search_configs`]);function ol(e){if(e.agent_policy!==void 0&&![`turbo`,`agentic`].includes(e.agent_policy))throw new t(`agent_policy must be turbo or agentic`,c.USAGE);if(e.temperature!==void 0&&(e.temperature<0||e.temperature>2))throw new t(`temperature must be between 0 and 2`,c.USAGE);if(e.max_num_llm_calls!==void 0&&(e.max_num_llm_calls<1||e.max_num_llm_calls>30))throw new t(`max_num_llm_calls must be between 1 and 30`,c.USAGE);if(e.rerank_top_n!==void 0&&(e.rerank_top_n<1||e.rerank_top_n>20))throw new t(`rerank_top_n must be between 1 and 20`,c.USAGE);for(let t of e.kb_search_configs??[]){let e=t.rerank;e?.rerank_instruct&&e.rerank_mode!==`custom`&&process.stderr.write(`Warning: rerank_instruct is only effective with rerank_mode=custom; the server clears it otherwise.
2735
+ `)}\n ... (${t.length} documents total)`;return`Delete ${t.length} document(s) from knowledge base ${e}:\n ${n}\nDocuments and all their chunks are permanently removed from the index. This cannot be undone.`}var Gc=w({description:{"en-US":`Delete documents and their chunks from a knowledge base`,"zh-CN":`从知识库中删除文档及其 Chunk`},auth:`apiKey`,usageArgs:`--index-id <id> --doc-id <id> [flags]`,flags:Uc,notes:[{"en-US":`Removes documents from the knowledge base index only; the source files remain in the data center.`,"zh-CN":`仅从知识库索引中移除文档;源文件仍保留在数据中心。`},{"en-US":"Use the doc_id from `knowledge doc list --quiet`, not the fileId from `knowledge doc upload`. For documents created via `knowledge create --doc-id`, the doc_id equals the fileId; for documents imported via `knowledge doc upload --index-id`, the doc_id may include a workspace suffix.","zh-CN":"请使用 `knowledge doc list --quiet` 返回的 doc_id,而不是 `knowledge doc upload` 返回的 fileId。通过 `knowledge create --doc-id` 创建的文档,其 doc_id 等于 fileId;通过 `knowledge doc upload --index-id` 导入的文档,其 doc_id 可能带有 Workspace 后缀。"},{"en-US":`Deletion may take up to ~30s to propagate — the document may still appear in the doc list briefly.`,"zh-CN":`删除结果最多可能需要约 30 秒才会生效——文档可能会短暂地继续出现在列表中。`},{"en-US":`The output lists the ids actually deleted.`,"zh-CN":`输出会列出实际删除的 ID。`}],exampleArgs:[`--index-id idx-xxx --doc-id file-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --doc-id file-a --doc-id file-b --yes`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={index_id:n.indexId,doc_ids:n.docId},o=E(r,p.indexDeleteFile);if(t.dryRun){A({endpoint:o,request:a},i);return}await yn(Wc(n.indexId,n.docId),n.yes??!1);let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.deleted??[];if(t.quiet){for(let e of c)k(e);return}if(i===`text`){k(`deleted: ${c.length} document(s)`);for(let e of c)k(` ${e}`);c.length!==n.docId.length&&process.stderr.write(`Warning: requested ${n.docId.length} deletion(s) but the server reported ${c.length}.\n`);return}A(s,i)}}),Kc=w({description:{"en-US":`Batch update tags on data-center files`,"zh-CN":`批量更新数据中心文件标签`},auth:`apiKey`,usageArgs:`--doc-id <id> --tag <text> [flags]`,flags:{docId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Data-center file ID to tag (repeatable, 1-20 per call)`,"zh-CN":`要添加标签的数据中心文件 ID(可重复,每次调用 1–20 个)`},required:!0},tag:{type:`array`,valueHint:`<text>`,description:{"en-US":`Tag applied to every --doc-id (repeatable, each up to 32 chars)`,"zh-CN":`应用于每个 --doc-id 的标签(可重复,每个最多 32 个字符)`},required:!0},mode:{type:`string`,valueHint:`<mode>`,description:{"en-US":`Update mode: append (default) or overwrite`,"zh-CN":`更新模式:append(默认)或 overwrite`}},...U},notes:[{"en-US":`The same tag set is applied to every --doc-id; run the command multiple times for different tag sets.`,"zh-CN":`同一组标签会应用于每个 --doc-id;若需应用不同标签组,请多次运行该命令。`},{"en-US":`Server limits: up to 100 tags per file, total tag length up to 700 chars, tag up to 32 chars.`,"zh-CN":`服务端限制:每个文件最多 100 个标签,标签总长度最多 700 个字符,单个标签最多 32 个字符。`}],exampleArgs:[`--doc-id file-xxx --tag project-a --tag draft --workspace-id ws-xxx`,`--doc-id file-a --doc-id file-b --tag final --mode overwrite`],validate(e){if(e.docId.length>20)return`--doc-id accepts at most 20 ids per call`;if(e.mode!==void 0&&e.mode!==`append`&&e.mode!==`overwrite`)return`--mode must be append or overwrite`;if(e.tag.length>100)return`At most 100 tags per file`;let t=e.tag.find(e=>e.length>32);if(t)return`Tag exceeds 32 characters: ${t}`;if(e.tag.reduce((e,t)=>e+t.length,0)>700)return`Total tag length exceeds 700 characters`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={fileInfos:n.docId.map(e=>({fileId:e,tags:n.tag})),updateMode:(n.mode??`append`).toUpperCase()},o=E(r,p.batchUpdateFileTag);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){k(`tagged: ${n.docId.length} file(s) with [${n.tag.join(`, `)}]`);return}A(s,i)}}});const qc={scene:{type:`string`,valueHint:`<scene>`,description:{"en-US":`Service scene: chat (Q&A) or search (retrieval)`,"zh-CN":`服务场景:chat(问答)或 search(检索)`},required:!0},status:{type:`string`,valueHint:`<status>`,description:{"en-US":`Filter by status: draft, deployed (includes edited) or deleted`,"zh-CN":`按状态筛选:draft、deployed(包含 edited)或 deleted`}},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by service name (fuzzy match)`,"zh-CN":`按服务名称模糊筛选`}},agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by exact agent ID`,"zh-CN":`按 Agent ID 精确筛选`}},indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by exact linked knowledge base (pipeline) ID`,"zh-CN":`按关联的知识库(Pipeline)ID 精确筛选`}},...nc,...U},Jc=[`chat`,`search`],Yc=[`draft`,`deployed`,`deleted`];var Xc=w({description:{"en-US":`List retrieval / Q&A services (agents) in the workspace`,"zh-CN":`列出 Workspace 中的检索/问答服务(Agent)`},auth:`apiKey`,usageArgs:`--scene <chat|search> [flags]`,flags:qc,notes:[{"en-US":`A scene (chat or search) is required — run once per scene to see both.`,"zh-CN":`必须指定场景(chat 或 search)——要查看两类服务,请分别运行一次。`},{"en-US":`Use the returned agent_id with the search or chat commands, or with service management commands.`,"zh-CN":`将返回的 agent_id 用于 search/chat 命令或服务管理命令。`}],exampleArgs:[`--scene chat --workspace-id ws-xxx`,`--scene search --status deployed`],validate(e){if(!Jc.includes(e.scene))return`--scene must be chat or search`;if(e.status!==void 0&&!Yc.includes(e.status))return`--status must be draft, deployed or deleted`;if(e.pageSize!==void 0&&(e.pageSize<1||e.pageSize>100))return`--page-size must be between 1 and 100`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={agent_scene:n.scene,...n.status?{agent_status:n.status}:{},...n.name?{agent_name:n.name}:{},...n.agentId?{agent_id:n.agentId}:{},...n.indexId?{pipeline_id:n.indexId}:{},page_number:n.pageNumber??1,page_size:n.pageSize??10},o=E(r,p.agentList);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.rows??[];if(t.quiet){for(let e of c)k(e.agent_id??``);return}if(i===`text`){if(c.length===0)k(`No services found.`);else for(let e of c){let t=(e.pipeline_list??[]).map(e=>e.pipeline_name).filter(Boolean).join(`,`);k(rc([e.agent_id,e.agent_status,e.agent_version,e.agent_name,t?`(kb: ${t})`:``].filter(Boolean).join(` `)))}k(`total: ${s.data?.total_count??c.length}`),k(n.scene===`search`?`Use an agent_id above with the knowledge search command.`:`Use an agent_id above with the knowledge chat command.`)}else A(s,i)}});const Zc={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Service (agent) ID`,"zh-CN":`服务(Agent)ID`},required:!0},agentVersion:{type:`string`,valueHint:`<version>`,description:{"en-US":`Specific version to inspect (beta or a published number); omit for all versions`,"zh-CN":`要查看的指定版本(beta 或已发布版本号);省略则返回全部版本`}},...U};function Qc(e){k(`Version ${e.agent_version??`?`}:`),e.agent_version_desc&&k(` desc: ${e.agent_version_desc}`),e.publish_time!==void 0&&k(` published: ${e.publish_time}`);let t=e.agent_config;if(t){t.agent_policy&&k(` policy: ${t.agent_policy}`),t.agent_model&&k(` model: ${t.agent_model}`),t.temperature!==void 0&&k(` temperature: ${t.temperature}`);for(let e of t.kb_search_configs??[])k(` kb: ${typeof e.id==`string`?e.id:`?`}${typeof e.name==`string`?` (${e.name})`:``}`)}}var $c=w({description:{"en-US":`Show service (agent) details including per-version configuration`,"zh-CN":`查看服务(Agent)详情及各版本配置`},auth:`apiKey`,usageArgs:`--agent-id <id> [flags]`,flags:Zc,notes:[{"en-US":`Without --agent-version all versions are returned (beta draft plus published numbers).`,"zh-CN":`未传入 --agent-version 时,会返回所有版本(beta 草稿和已发布版本号)。`},{"en-US":`The version value is passed through as-is; the valid set is server-side state.`,"zh-CN":`版本值将原样传递;有效版本集合由服务端状态决定。`}],exampleArgs:[`--agent-id aid-xxx --workspace-id ws-xxx`,`--agent-id aid-xxx --agent-version beta`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={agent_id:n.agentId,...n.agentVersion?{agent_version:n.agentVersion}:{}},o=E(r,p.agentGet);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data;if(t.quiet){k(c?.agent_id??``);return}if(i!==`text`){A(s,i);return}k(`Basic:`),k(` id: ${c?.agent_id??`-`}`),k(` name: ${c?.agent_name??`-`}`),k(` desc: ${c?.agent_desc??`-`}`),k(` scene: ${c?.agent_scene??`-`}`),k(` status: ${c?.agent_status??`-`}`);for(let e of c?.agent_details??[])Qc(e)}}),el=w({description:{"en-US":`Create a retrieval / Q&A service (initial status: draft, version: beta)`,"zh-CN":`创建检索/问答服务(初始状态:draft,版本:beta)`},auth:`apiKey`,usageArgs:`--name <text> --scene <chat|search> [flags]`,flags:{name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Service name (up to 200 chars, unique per scene in the workspace)`,"zh-CN":`服务名称(最多 200 个字符,在 Workspace 的同一场景中唯一)`},required:!0},scene:{type:`string`,valueHint:`<scene>`,description:{"en-US":`Service scene: chat (Q&A) or search (retrieval)`,"zh-CN":`服务场景:chat(问答)或 search(检索)`},required:!0},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`What this service answers and who it serves — recommended: agents read it to pick the right service (up to 1000 chars)`,"zh-CN":`这个服务能回答什么、给谁用 —— 建议填写:agent 靠它判断该调用哪个服务(最多 1000 个字符)`}},indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Bind this knowledge base; other settings use server defaults`,"zh-CN":`绑定该知识库;其他设置使用服务端默认值`}},...U},notes:[{"en-US":`Without an explicit configuration the server applies its default agent settings.`,"zh-CN":`未显式提供配置时,服务端会应用默认 Agent 设置。`},{"en-US":`The draft (beta) version can be tested via --agent-version beta on search/chat before deploying.`,"zh-CN":`部署前,可在 search/chat 命令中使用 --agent-version beta 测试草稿(beta)版本。`},{"en-US":`Requires the knowledge-base create permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库创建权限。`}],exampleArgs:[{"en-US":`--name my-qa --scene chat --description 'answers product FAQs' --workspace-id ws-xxx`,"zh-CN":`--name my-qa --scene chat --description '回答产品常见问题' --workspace-id ws-xxx`},`--name my-search --scene search --index-id idx-xxx`],validate(e){if(e.name.length>200)return`--name must be at most 200 characters`;if(e.scene!==`chat`&&e.scene!==`search`)return`--scene must be chat or search`;if(e.description!==void 0&&e.description.length>1e3)return`--description must be at most 1000 characters`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={agent_name:n.name,agent_scene:n.scene,...n.description?{agent_desc:n.description}:{},...n.indexId?{agent_config:{kb_search_configs:[{id:n.indexId}]}}:{}},o=E(r,p.agentCreate);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=dc(s,`agent_id`);if(t.quiet){k(c??``);return}if(i===`text`){k(`created: ${c??`-`} (status: ${dc(s,`agent_status`)??`draft`}, version: ${dc(s,`agent_version`)??`beta`})`),k(`Test the draft with --agent-version beta on search/chat, then deploy it to publish.`);return}A(s,i)}});const tl=[`true`,`false`],nl={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Service (agent) ID`,"zh-CN":`服务(Agent)ID`},required:!0},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`New service name (up to 200 chars)`,"zh-CN":`新服务名称(最多 200 个字符)`}},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`New service description (up to 1000 chars)`,"zh-CN":`新服务描述(最多 1000 个字符)`}},agentVersion:{type:`string`,valueHint:`<version>`,description:{"en-US":`Target version (default: beta draft). Published versions only accept --version-desc`,"zh-CN":`目标版本(默认:beta 草稿)。已发布版本只接受 --version-desc`}},versionDesc:{type:`string`,valueHint:`<text>`,description:{"en-US":`Version description`,"zh-CN":`版本描述`}},policy:{type:`string`,valueHint:`<policy>`,description:{"en-US":`Agent policy: turbo (fast) or agentic (multi-turn)`,"zh-CN":`Agent 策略:turbo(快速)或 agentic(多轮)`}},model:{type:`string`,valueHint:`<name>`,description:{"en-US":`Generation model code (must be in the platform allowlist)`,"zh-CN":`生成模型代码(必须在平台白名单中)`}},temperature:{type:`number`,valueHint:`<n>`,description:{"en-US":`Sampling temperature, range 0-2`,"zh-CN":`采样温度,范围 0–2`}},maxLlmCalls:{type:`number`,valueHint:`<n>`,description:{"en-US":`Max LLM calls per request, range 1-30`,"zh-CN":`每次请求最大 LLM 调用次数,范围 1–30`}},enableSessionFile:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable session files: true or false`,"zh-CN":`启用会话文件:true 或 false`}},enableRefusal:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable refusal answers: true or false`,"zh-CN":`启用拒答:true 或 false`}},enableAntiLeak:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable anti prompt-leak: true or false`,"zh-CN":`启用防提示词泄露:true 或 false`}},enableRichText:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable rich text output: true or false`,"zh-CN":`启用富文本输出:true 或 false`}},enableCitation:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable citations: true or false`,"zh-CN":`启用引用:true 或 false`}},configFile:{type:`string`,valueHint:`<path>`,description:{"en-US":`JSON file replacing the whole agent_config (for nested settings like kb_search_configs); mutually exclusive with scalar config flags`,"zh-CN":`替换整个 agent_config 的 JSON 文件(用于 kb_search_configs 等嵌套设置);不能与标量配置选项同时使用`}},...U};function rl(e){let t={};return e.policy!==void 0&&(t.agent_policy=e.policy),e.model!==void 0&&(t.agent_model=e.model),e.temperature!==void 0&&(t.temperature=e.temperature),e.maxLlmCalls!==void 0&&(t.max_num_llm_calls=e.maxLlmCalls),e.enableSessionFile!==void 0&&(t.enable_session_file=e.enableSessionFile),e.enableRefusal!==void 0&&(t.enable_refusal=e.enableRefusal),e.enableAntiLeak!==void 0&&(t.enable_anti_leak=e.enableAntiLeak),e.enableRichText!==void 0&&(t.enable_rich_text=e.enableRichText),e.enableCitation!==void 0&&(t.enable_citation=e.enableCitation),t}function il(e){let n;try{n=ar(e,`utf-8`)}catch(n){let r=n.code??`unknown`;throw new t(`Cannot read config file: ${e}`,c.GENERAL,`File system error (${r}) — check the path and permissions.`)}let r;try{r=JSON.parse(n)}catch{throw new t(`--config-file must contain valid JSON.`,c.USAGE)}if(typeof r!=`object`||!r||Array.isArray(r))throw new t(`--config-file must contain a JSON object.`,c.USAGE);let i=r;return ol(i),i}const al=new Set([`agent_policy`,`agent_model`,`enable_session_file`,`enable_refusal`,`enable_anti_leak`,`enable_rich_text`,`enable_citation`,`temperature`,`max_num_llm_calls`,`max_completion_tokens`,`session_file_max_parse_length`,`enable_kb_router`,`kb_router_model`,`user_system_prompt`,`anti_leak_prompt`,`refusal_prompt`,`credibility_prompt`,`enable_thinking`,`enable_temperature`,`enable_credibility`,`enable_max_completion_tokens`,`session_file_parse_mode`,`rerank_top_n`,`hybrid_rerank`,`kb_search_configs`]);function ol(e){if(e.agent_policy!==void 0&&![`turbo`,`agentic`].includes(e.agent_policy))throw new t(`agent_policy must be turbo or agentic`,c.USAGE);if(e.temperature!==void 0&&(e.temperature<0||e.temperature>2))throw new t(`temperature must be between 0 and 2`,c.USAGE);if(e.max_num_llm_calls!==void 0&&(e.max_num_llm_calls<1||e.max_num_llm_calls>30))throw new t(`max_num_llm_calls must be between 1 and 30`,c.USAGE);if(e.rerank_top_n!==void 0&&(e.rerank_top_n<1||e.rerank_top_n>20))throw new t(`rerank_top_n must be between 1 and 20`,c.USAGE);for(let t of e.kb_search_configs??[]){let e=t.rerank;e?.rerank_instruct&&e.rerank_mode!==`custom`&&process.stderr.write(`Warning: rerank_instruct is only effective with rerank_mode=custom; the server clears it otherwise.
2736
2736
  `)}for(let t of Object.keys(e))al.has(t)||process.stderr.write(`Warning: unknown agent_config field passed through: ${t}\n`)}async function sl(e,t,n){return((await e.requestJson({path:E(t,p.agentGet),method:`POST`,body:{agent_id:n,agent_version:`beta`}})).data?.agent_details??[]).find(e=>e.agent_version===`beta`)?.agent_config??{}}var cl=w({description:{"en-US":`Update service name, description or draft configuration`,"zh-CN":`更新服务名称、描述或草稿配置`},auth:`apiKey`,usageArgs:`--agent-id <id> [flags]`,flags:nl,notes:[{"en-US":`Configuration changes only apply to the beta draft; published versions accept --version-desc only.`,"zh-CN":`配置修改只应用于 beta 草稿;已发布版本只接受 --version-desc。`},{"en-US":`To change the configuration of a published version, first update the beta draft (this command without --agent-version or with --agent-version beta), then run service deploy to publish a new version.`,"zh-CN":`要修改已发布版本的配置,请先更新 beta 草稿(不传 --agent-version,或传 --agent-version beta),然后运行 service deploy 发布新版本。`},{"en-US":`Scalar config flags merge into the current draft config (read-merge-write); --config-file replaces the whole config and is mutually exclusive with them.`,"zh-CN":`标量配置选项会合并到当前草稿配置(读取-合并-写入);--config-file 会替换整个配置,且不能与标量配置选项同时使用。`},{"en-US":`After updating the draft, verify with --agent-version beta on search/chat, then deploy.`,"zh-CN":`更新草稿后,先在 search/chat 命令中使用 --agent-version beta 验证,再部署。`},{"en-US":`Requires the knowledge-base modify permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库修改权限。`}],exampleArgs:[`--agent-id aid-xxx --temperature 0.7 --workspace-id ws-xxx`,`--agent-id aid-xxx --config-file ./agent-config.json`,{"en-US":`--agent-id aid-xxx --agent-version 1 --version-desc 'first stable release'`,"zh-CN":`--agent-id aid-xxx --agent-version 1 --version-desc '首个稳定版本'`}],validate(e){let t=Object.keys(rl(e)).length>0;if(!(e.name!==void 0||e.description!==void 0||e.versionDesc!==void 0||e.configFile!==void 0||t))return`Nothing to update — pass a name/description/version-desc or config flags`;if(e.configFile!==void 0&&t)return`--config-file is mutually exclusive with scalar config flags`;if(e.agentVersion!==void 0&&e.agentVersion!==`beta`&&(t||e.configFile!==void 0))return`Published versions only accept --version-desc; update the beta draft to change config`;if(e.name!==void 0&&e.name.length>200)return`--name must be at most 200 characters`;if(e.description!==void 0&&e.description.length>1e3)return`--description must be at most 1000 characters`;if(e.policy!==void 0&&![`turbo`,`agentic`].includes(e.policy))return`--policy must be turbo or agentic`;if(e.temperature!==void 0&&(e.temperature<0||e.temperature>2))return`--temperature must be between 0 and 2`;if(e.maxLlmCalls!==void 0&&(e.maxLlmCalls<1||e.maxLlmCalls>30))return`--max-llm-calls must be between 1 and 30`;for(let[t,n]of[[`--enable-session-file`,e.enableSessionFile],[`--enable-refusal`,e.enableRefusal],[`--enable-anti-leak`,e.enableAntiLeak],[`--enable-rich-text`,e.enableRichText],[`--enable-citation`,e.enableCitation]])if(n!==void 0&&!tl.includes(n))return`${t} must be true or false`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a=rl(n),o=n.configFile!==void 0||Object.keys(a).length>0,s;n.configFile===void 0?Object.keys(a).length>0&&(t.dryRun?s={...a}:(s={...await sl(e.client,r,n.agentId),...a},ol(s))):s=il(n.configFile);let c={agent_id:n.agentId,...n.name===void 0?{}:{agent_name:n.name},...n.description===void 0?{}:{agent_desc:n.description},...n.agentVersion===void 0?{}:{agent_version:n.agentVersion},...n.versionDesc===void 0?{}:{agent_version_desc:n.versionDesc},...s===void 0?{}:{agent_config:s}},l=E(r,p.agentUpdate);if(t.dryRun){A({endpoint:l,request:c,...o&&n.configFile===void 0?{note:`scalar config flags are merged into the current beta config at run time`}:{}},i);return}let u=await e.client.requestJson({path:l,method:`POST`,body:c});if(!t.quiet){if(i===`text`){k(`updated: ${n.agentId}`),o&&k(`Draft config changed — verify with --agent-version beta, then deploy.`);return}A(u,i)}}});const ll={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Service (agent) ID`,"zh-CN":`服务(Agent)ID`},required:!0},versionDesc:{type:`string`,valueHint:`<text>`,description:{"en-US":`Description for the newly published version`,"zh-CN":`新发布版本的描述`}},yes:{type:`switch`,description:{"en-US":`Skip the confirmation prompt`,"zh-CN":`跳过确认提示`}},...U};async function ul(e,t,n){let r=``,i=``;try{let a=await e.requestJson({path:E(t,p.agentGet),method:`POST`,body:{agent_id:n}}),o=a.data?.agent_name,s=a.data?.agent_status;o&&(r+=` name: ${o}`),s&&(r+=` status: ${s}`,s===`edited`&&(i=`
2737
2737
  WARNING: a published version is live — deploying replaces its behavior with the current draft.`))}catch{}return`Deploy service ${n}${r}${i}\nPublishing changes what live callers get from this service.`}var dl=w({description:{"en-US":`Publish the beta draft of a service as a new version`,"zh-CN":`将服务的 beta 草稿发布为新版本`},auth:`apiKey`,usageArgs:`--agent-id <id> [flags]`,flags:ll,notes:[{"en-US":`The version number auto-increments; status becomes deployed.`,"zh-CN":`版本号会自动递增;状态将变为 deployed。`},{"en-US":`Publishing affects live callers — the confirmation prompt guards against accidents.`,"zh-CN":`发布会影响线上调用方——确认提示用于避免误操作。`},{"en-US":`Requires the knowledge-base modify permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库修改权限。`}],exampleArgs:[`--agent-id aid-xxx --workspace-id ws-xxx`,{"en-US":`--agent-id aid-xxx --version-desc 'tuned rerank params' --yes`,"zh-CN":`--agent-id aid-xxx --version-desc '已调优 Rerank 参数' --yes`}],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={agent_id:n.agentId,...n.versionDesc?{agent_version_desc:n.versionDesc}:{}},o=E(r,p.agentDeploy);if(t.dryRun){A({endpoint:o,request:a},i);return}await yn(n.yes?``:await ul(e.client,r,n.agentId),n.yes??!1);let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=dc(s,`agent_version`);if(t.quiet){k(c??``);return}if(i===`text`){k(`deployed: ${n.agentId} version ${c??`-`}`);return}A(s,i)}});const fl={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Service (agent) ID`,"zh-CN":`服务(Agent)ID`},required:!0},yes:{type:`switch`,description:{"en-US":`Skip the confirmation prompt`,"zh-CN":`跳过确认提示`}},...U};async function pl(e,t,n){let r=``,i=``;try{let a=await e.requestJson({path:E(t,p.agentGet),method:`POST`,body:{agent_id:n}}),o=a.data?.agent_name,s=a.data?.agent_status;o&&(r+=` name: ${o}`),s&&(r+=` status: ${s}`,(s===`deployed`||s===`edited`)&&(i=`
2738
- WARNING: this service is LIVE — deleting it breaks existing callers.`))}catch{}return`Delete service ${n}${r}${i}\nDeletion cannot be undone; the agent_id can no longer be used for search or chat calls.`}var ml=w({description:{"en-US":`Delete a retrieval / Q&A service (soft delete, idempotent)`,"zh-CN":`删除检索/问答服务(软删除,幂等)`},auth:`apiKey`,usageArgs:`--agent-id <id> [flags]`,flags:fl,notes:[{"en-US":`Deletion cannot be undone; the agent_id becomes unusable for search and chat calls.`,"zh-CN":`删除无法撤销;该 agent_id 将不能再用于 search 和 chat 调用。`},{"en-US":`Idempotent — deleting an already-deleted service does not fail.`,"zh-CN":`该操作具有幂等性——重复删除已删除的服务不会失败。`},{"en-US":`Requires the knowledge-base delete permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库删除权限。`}],exampleArgs:[`--agent-id aid-xxx --workspace-id ws-xxx`,`--agent-id aid-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={agent_id:n.agentId},o=E(r,p.agentDelete);if(t.dryRun){A({endpoint:o,request:a},i);return}await yn(n.yes?``:await pl(e.client,r,n.agentId),n.yes??!1);let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){k(`deleted: ${n.agentId} (status: ${dc(s,`agent_status`)??`deleted`})`);return}A(s,i)}}}),hl=w({description:{"en-US":`Copy a service into a new draft (name gets a copy_ prefix)`,"zh-CN":`将服务复制为新草稿(名称会添加 copy_ 前缀)`},auth:`apiKey`,usageArgs:`--agent-id <id> [flags]`,flags:{agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Source service (agent) ID to copy`,"zh-CN":`要复制的源服务(Agent)ID`},required:!0},...U},notes:[{"en-US":`The copy starts as a beta draft; test it with --agent-version beta, then deploy to publish.`,"zh-CN":`副本初始为 beta 草稿;请使用 --agent-version beta 测试,然后部署发布。`},{"en-US":`Requires the knowledge-base create permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库创建权限。`}],exampleArgs:[`--agent-id aid-xxx --workspace-id ws-xxx`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={agent_id:n.agentId},o=E(r,p.agentCopy);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=dc(s,`agent_id`);if(t.quiet){k(c??``);return}if(i===`text`){k(`new agent_id: ${c??`-`} (name: ${dc(s,`agent_name`)??`-`}, status: ${dc(s,`agent_status`)??`draft`})`),k(`Test the draft with --agent-version beta on search/chat, then deploy it to publish.`);return}A(s,i)}});const gl={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},docId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Owning document ID from the doc list command; required in practice for all knowledge base types`,"zh-CN":`来自文档列表命令的所属文档 ID;实际使用时所有知识库类型都需要提供`}},content:{type:`string`,valueHint:`<text>`,description:{"en-US":`Chunk body text, up to 6000 chars (document-type); alternative to --content-file`,"zh-CN":`Chunk 正文,最多 6000 个字符(文档型);与 --content-file 二选一`}},contentFile:{type:`string`,valueHint:`<path>`,description:{"en-US":`Read chunk body from a UTF-8 plain text file (.md/.txt etc.)`,"zh-CN":`从 UTF-8 纯文本文件(.md/.txt 等)读取 Chunk 正文`}},title:{type:`string`,valueHint:`<text>`,description:{"en-US":`Chunk title, up to 50 chars (document-type)`,"zh-CN":`Chunk 标题,最多 50 个字符(文档型)`}},imageUrl:{type:`array`,valueHint:`<url>`,description:{"en-US":`Chunk image URL (repeatable, up to 10; document-type)`,"zh-CN":`Chunk 图片 URL(可重复,最多 10 个;文档型)`}},field:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Arbitrary field entry (repeatable) for table/image knowledge bases where keys are Excel column headers; mutually exclusive with content/title/image flags`,"zh-CN":`表格/图片知识库的自定义字段(可重复),键为 Excel 列标题;不能与 content/title/image 相关选项同时使用`}},...U};function _l(e){let n={};for(let r of e){let e=r.indexOf(`=`);if(e<=0)throw new t(`--field must be key=value, got: ${r}`,c.USAGE);n[r.slice(0,e)]=r.slice(e+1)}return n}var vl=w({description:{"en-US":`Add a chunk directly to a knowledge base`,"zh-CN":`直接向知识库添加 Chunk`},auth:`apiKey`,usageArgs:`--index-id <id> (--content <text> | --field <k=v>) [flags]`,flags:gl,notes:[{"en-US":`Document / table / image knowledge bases are supported; audio-video ones are not.`,"zh-CN":`支持文档、表格和图片知识库;不支持音视频知识库。`},{"en-US":`--doc-id is required in practice for all knowledge base types. Use the document-level id from the doc list command; the per-row doc_id in chunk list output is not accepted.`,"zh-CN":`实际使用时,所有知识库类型都需要 --doc-id。请使用文档列表命令返回的文档级 ID;Chunk 列表每行返回的 doc_id 不被接受。`},{"en-US":`Image-type documents do not support text chunks. Target a text-type document (docx/pdf/txt) instead.`,"zh-CN":`图片型文档不支持文本 Chunk;请改为操作文本型文档(docx/pdf/txt)。`},{"en-US":`The API is idempotent but rate-limited to 10 calls per second — throttle batch scripts.`,"zh-CN":`该 API 具有幂等性,但限流为每秒 10 次调用——批处理脚本需要控制速率。`},{"en-US":`The response carries no chunk id; list chunks afterwards to find the new one.`,"zh-CN":`响应不包含 Chunk ID;添加后请列出 Chunk 以查找新条目。`},{"en-US":`For table/image knowledge bases use --field with Excel column headers as keys; values are passed through as strings.`,"zh-CN":`表格/图片知识库请使用 --field,并以 Excel 列标题作为键;值将按字符串原样传递。`}],exampleArgs:[{"en-US":`--index-id idx-xxx --content "chunk text" --title intro --workspace-id ws-xxx`,"zh-CN":`--index-id idx-xxx --content "Chunk 文本" --title 简介 --workspace-id ws-xxx`},{"en-US":`--index-id idx-xxx --field columnA=v1 --field columnB=v2`,"zh-CN":`--index-id idx-xxx --field 列A=v1 --field 列B=v2`}],validate(e){let t=e.content!==void 0||e.contentFile!==void 0||e.title!==void 0||!!e.imageUrl?.length,n=!!e.field?.length;if(t&&n)return`--field is mutually exclusive with --content/--content-file/--title/--image-url`;if(!t&&!n)return`Provide chunk content via --content/--content-file or --field entries`;if(e.content!==void 0&&e.contentFile!==void 0)return`Use either --content or --content-file, not both`;if(e.content!==void 0&&e.content.length>6e3)return`--content must be at most 6000 characters`;if(e.title!==void 0&&e.title.length>50)return`--title must be at most 50 characters`;if(e.imageUrl!==void 0&&e.imageUrl.length>10)return`--image-url accepts at most 10 entries`},async run(e){let{settings:n,flags:r}=e,i=W(e),a=T(n.output),o;if(r.field?.length)o=_l(r.field);else{let e=r.contentFile===void 0?r.content:Pc(r.contentFile,`--content`);if(typeof e==`string`&&e.length>6e3)throw new t(`Chunk content must be at most 6000 characters`,c.USAGE);o={...e===void 0?{}:{content:e},...r.title===void 0?{}:{title:r.title},...r.imageUrl?.length?{image_urls:r.imageUrl}:{}}}let s={pipelineId:r.indexId,...r.docId?{dataId:r.docId}:{},field:o},l=E(i,p.chunkCreate);if(n.dryRun){A({endpoint:l,request:s},a);return}let u=await e.client.requestJson({path:l,method:`POST`,body:s});if(!n.quiet){if(a===`text`){k(`chunk created (pipeline: ${r.indexId})`),k(`List chunks to find the new chunk id.`);return}A(u,a)}}}),yl=w({description:{"en-US":`List chunks in a knowledge base with content and status`,"zh-CN":`列出知识库中的 Chunk 及其内容和状态`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:{indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},docId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Only show chunks belonging to this document`,"zh-CN":`仅显示属于该文档的 Chunk`}},...nc,...U},notes:[{"en-US":`Use metadata._id as the chunk id and metadata.doc_id as the document id in chunk update/delete commands.`,"zh-CN":`在 Chunk 更新/删除命令中,使用 metadata._id 作为 Chunk ID,使用 metadata.doc_id 作为文档 ID。`},{"en-US":`Page size defaults to 20 (server default), max 100.`,"zh-CN":`分页大小默认为 20(服务端默认值),最大为 100。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --doc-id file-xxx --page-size 50`],validate(e){if(e.pageSize!==void 0&&(e.pageSize<1||e.pageSize>100))return`--page-size must be between 1 and 100`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={indexId:n.indexId,pageNum:n.pageNumber??1,pageSize:n.pageSize??20,...n.docId?{docId:n.docId}:{}},o=E(r,p.chunkList);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.nodes??[];if(t.quiet){for(let e of c)k(e.metadata?._id??``);return}if(i===`text`){if(c.length===0)k(`No chunks found.`);else for(let e of c){let t=e.metadata??{},n=t._chunk_status_message?` status: ${t._chunk_status_message}`:``,r=t.is_displayed_chunk_content===!1?` [excluded from retrieval]`:``;k(`[chunk] ${t._id??`?`} (doc: ${t.doc_name??`?`}, doc_id: ${t.doc_id??`?`})${n}${r}`);let i=t.content??e.text??``;k(` ${i.length>200?`${i.slice(0,200)}…`:i}`)}k(`total: ${s.data?.total??c.length}`)}else A(s,i)}});const bl={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},chunkId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Chunk ID (metadata._id from the chunk list output)`,"zh-CN":`Chunk ID(来自 Chunk 列表输出的 metadata._id)`},required:!0},docId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Document ID owning the chunk (metadata.doc_id from the chunk list output)`,"zh-CN":`Chunk 所属文档 ID(来自 Chunk 列表输出的 metadata.doc_id)`},required:!0},content:{type:`string`,valueHint:`<text>`,description:{"en-US":`New chunk content, 10-6000 chars; alternative to --content-file`,"zh-CN":`新的 Chunk 内容,10–6000 个字符;与 --content-file 二选一`}},contentFile:{type:`string`,valueHint:`<path>`,description:{"en-US":`Read new content from a UTF-8 plain text file (.md/.txt etc.)`,"zh-CN":`从 UTF-8 纯文本文件(.md/.txt 等)读取新内容`}},title:{type:`string`,valueHint:`<text>`,description:{"en-US":`Chunk title, 0-50 chars (empty string clears it; omit to keep unchanged)`,"zh-CN":`Chunk 标题,0–50 个字符(空字符串表示清除;省略则保持不变)`}},exclude:{type:`switch`,description:{"en-US":`Exclude this chunk from retrieval`,"zh-CN":`在检索中排除该 Chunk`}},include:{type:`switch`,description:{"en-US":`Include this chunk in retrieval (default)`,"zh-CN":`在检索中包含该 Chunk(默认)`}},...U};async function xl(e,n,r,i,a){for(let t=1;t<=10;t++){let o=(await e.requestJson({path:E(n,p.chunkList),method:`POST`,body:{indexId:r,docId:a,pageNum:t,pageSize:100}})).data?.nodes??[],s=o.find(e=>e.metadata?._id===i),c=s?.metadata?.content??s?.text;if(typeof c==`string`)return c;if(o.length<100)break}throw new t(`Chunk not found: ${i}`,c.GENERAL,`Check the chunk id via the chunk list command.`)}var Sl=w({description:{"en-US":`Update chunk content or toggle its retrieval visibility`,"zh-CN":`更新 Chunk 内容或切换其检索可见性`},auth:`apiKey`,usageArgs:`--index-id <id> --chunk-id <id> --doc-id <id> [flags]`,flags:bl,notes:[{"en-US":`Content must be 10-6000 characters and within the knowledge base's max chunk size.`,"zh-CN":`内容必须为 10–6000 个字符,且不能超过知识库的最大 Chunk 大小。`},{"en-US":`--content-file expects a UTF-8 plain text file; document formats (.docx/.pdf) are not parsed here.`,"zh-CN":`--content-file 需要 UTF-8 纯文本文件;此处不会解析 .docx/.pdf 等文档格式。`},{"en-US":`Toggling --exclude/--include without new content re-submits the existing content automatically.`,"zh-CN":`仅切换 --exclude/--include 而不提供新内容时,会自动重新提交现有内容。`}],exampleArgs:[{"en-US":`--index-id idx-xxx --chunk-id chunk-xxx --doc-id file-xxx --content "corrected text"`,"zh-CN":`--index-id idx-xxx --chunk-id chunk-xxx --doc-id file-xxx --content "修正后的文本"`},`--index-id idx-xxx --chunk-id chunk-xxx --doc-id file-xxx --exclude`],validate(e){if(e.content!==void 0&&e.contentFile!==void 0)return`Use either --content or --content-file, not both`;if(e.exclude&&e.include)return`--exclude and --include are mutually exclusive`;if(!(e.content!==void 0||e.contentFile!==void 0)&&!e.exclude&&!e.include&&e.title===void 0)return`Nothing to update — pass --content/--content-file, --title, --exclude or --include`;if(e.content!==void 0&&(e.content.length<10||e.content.length>6e3))return`--content must be 10-6000 characters`;if(e.title!==void 0&&e.title.length>50)return`--title must be at most 50 characters`},async run(e){let{settings:n,flags:r}=e,i=W(e),a=T(n.output),o=r.contentFile===void 0?r.content:Pc(r.contentFile,`--content`);if(o!==void 0&&(o.length<10||o.length>6e3))throw new t(`Chunk content must be 10-6000 characters`,c.USAGE);o===void 0&&(o=n.dryRun?`<current-content (fetched at run time)>`:await xl(e.client,i,r.indexId,r.chunkId,r.docId));let s={pipelineId:r.indexId,chunkId:r.chunkId,dataId:r.docId,content:o,isDisplayedChunkContent:!r.exclude,...r.title===void 0?{}:{title:r.title}},l=E(i,p.chunkUpdate);if(n.dryRun){A({endpoint:l,request:s},a);return}let u=await e.client.requestJson({path:l,method:`POST`,body:s});if(!n.quiet){if(a===`text`){k(`updated: ${r.chunkId}`);return}A(u,a)}}});const Cl={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},chunkId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Chunk ID to delete (repeatable; batches of 10 are sent automatically)`,"zh-CN":`要删除的 Chunk ID(可重复;每 10 个自动分批发送)`},required:!0},yes:{type:`switch`,description:{"en-US":`Skip the confirmation prompt`,"zh-CN":`跳过确认提示`}},...U};function wl(e,t=10){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}var Tl=w({description:{"en-US":`Delete chunks from a knowledge base (irreversible)`,"zh-CN":`从知识库中删除 Chunk(不可撤销)`},auth:`apiKey`,usageArgs:`--index-id <id> --chunk-id <id> [flags]`,flags:Cl,notes:[{"en-US":`Accepts at most 10 chunk ids per call; larger sets are batched automatically.`,"zh-CN":`每次调用最多接受 10 个 Chunk ID;更多 ID 会自动分批处理。`}],exampleArgs:[`--index-id idx-xxx --chunk-id chunk-a --chunk-id chunk-b --workspace-id ws-xxx`,`--index-id idx-xxx --chunk-id chunk-a --yes`],async run(e){let{settings:n,flags:r}=e,i=W(e),a=T(n.output),o=wl(r.chunkId),s=E(i,p.chunkDelete);if(n.dryRun){A({endpoint:s,batches:o.map(e=>({request:{pipelineId:r.indexId,chunkIds:e}}))},a);return}await yn(`Delete ${r.chunkId.length} chunk(s) from knowledge base ${r.indexId} in ${o.length} batch(es).\nChunks are permanently removed. This cannot be undone.`,r.yes??!1);let c=0;for(let n of o)try{await e.client.requestJson({path:s,method:`POST`,body:{pipelineId:r.indexId,chunkIds:n}}),c+=n.length}catch(e){throw c>0&&e instanceof t&&!e.hint?new t(e.message,e.exitCode,`${c} chunk(s) in earlier batches were already deleted.`,{cause:e,api:e.api,rawResponse:e.rawResponse}):e}if(!n.quiet){if(a===`text`){k(`deleted: ${c} chunk(s) in ${o.length} batch(es)`);return}A({deleted_count:c,batches:o.length},a)}}});const El={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},start:{type:`string`,valueHint:`<time>`,description:{"en-US":`Range start: Unix seconds or ISO date, must be in the past (default: 24 hours ago)`,"zh-CN":`范围开始时间:Unix 秒或 ISO 日期,必须是过去时间(默认:24 小时前)`}},end:{type:`string`,valueHint:`<time>`,description:{"en-US":`Range end: Unix seconds or ISO date, must be in the past (default: now)`,"zh-CN":`范围结束时间:Unix 秒或 ISO 日期,必须是过去时间(默认:当前时间)`}},...U};function Dl(e){if(/^\d+$/.test(e))return e.length>=13?String(Math.floor(Number(e)/1e3)):e;let n=/^\d{4}-\d{2}-\d{2}([T ].*)?$/.test(e)?Date.parse(e):NaN;if(Number.isNaN(n))throw new t(`Invalid time value: ${e}`,c.USAGE,`Pass Unix seconds (e.g. 1780900000) or an ISO date (e.g. 2026-07-30T00:00:00Z).`);return String(Math.floor(n/1e3))}var Ol=w({description:{"en-US":`Show knowledge base storage and QPS monitoring data`,"zh-CN":`查看知识库存储和 QPS 监控数据`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:El,notes:[{"en-US":`Defaults to the last 24 hours when --start/--end are omitted.`,"zh-CN":`省略 --start/--end 时,默认查询最近 24 小时。`},{"en-US":`Timestamps are normalized to epoch seconds as required by the server.`,"zh-CN":`时间戳会按服务端要求归一化为 Epoch 秒。`},{"en-US":`Future timestamps are rejected for --start and clamped to now for --end, since the monitor API only returns past data.`,"zh-CN":`监控 API 只返回历史数据,因此未来的 --start 会被拒绝,未来的 --end 会被截断为当前时间。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --start 2026-07-30 --end 2026-07-31`],async run(e){let{settings:n,flags:r}=e,i=W(e),a=T(n.output),o=Math.floor(Date.now()/1e3),s=r.start?Dl(r.start):String(o-24*3600),l=r.end?Dl(r.end):String(o);if(Number(s)>o)throw new t(`Start time is in the future; the monitor API only accepts past or current timestamps.`,c.USAGE,`Use a start date/time at or before now, or omit --start to default to 24 hours ago.`);let u=Number(l)>o;u&&(l=String(o));let d={indexId:r.indexId,startTimestamp:s,endTimestamp:l},f=E(i,p.indexMonitor);if(n.dryRun){A({endpoint:f,request:d},a);return}let m=await e.client.requestJson({path:f,method:`POST`,body:d});if(a!==`text`){A(m,a);return}u&&k(`note: end time was in the future, clamped to now.`);let h=m.data?.storageMonitorData,g=m.data?.qpsMonitorData;k(`plan: ${m.data?.pipelineCommercialType??`-`}`),k(`storage: ${h?.indexStorageUsage??`-`} / ${h?.indexStorageLimit??`-`}`),k(`peak qps: ${g?.peakQps??`-`}`),k(`qps windows: ${g?.monitorData?.length??0} data point(s)`)}}),kl=w({description:{"en-US":`List data-center categories`,"zh-CN":`列出数据中心类目`},auth:`apiKey`,usageArgs:`[flags]`,flags:{collectionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by exact collection ID`,"zh-CN":`按数据集合 ID 精确筛选`}},parentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`List sub-categories of this exact parent category`,"zh-CN":`列出该父类目下的子类目`}},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by category name (exact match, unlike the knowledge base list)`,"zh-CN":`按类目名称筛选(精确匹配,与知识库列表不同)`}},nextToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Cursor for the next page (from previous output)`,"zh-CN":`下一页游标(来自上一次输出)`}},maxResult:{type:`number`,valueHint:`<n>`,description:{"en-US":`Items per page (default: 20)`,"zh-CN":`每页条目数(默认:20)`}},...U},notes:[{"en-US":`Categories marked [default] are where files land when no category is specified.`,"zh-CN":`未指定类目时,文件会进入标记为 [default] 的类目。`},{"en-US":`Pagination is cursor-based: reuse the printed next token to continue.`,"zh-CN":`分页使用游标:复用输出中的 next token 继续查询。`}],exampleArgs:[`--workspace-id ws-xxx`,`--name my-category`,`--next-token <token>`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={type:`UNSTRUCTURED`,...n.collectionId?{connectorId:n.collectionId}:{},...n.parentId?{parentId:n.parentId}:{},...n.name?{categoryName:n.name}:{},...n.nextToken?{nextToken:n.nextToken}:{},...n.maxResult===void 0?{}:{maxResult:n.maxResult}},o=E(r,p.listCategory);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.categoryList??[];if(t.quiet){for(let e of c)k(e.categoryId??``);return}if(i===`text`){if(c.length===0)k(`No categories found.`);else for(let e of c){let t=e.isDefault?` [default]`:``;k(rc(`${e.categoryId} ${e.categoryName}${t}`))}let e=s.data?.nextToken;e&&k(`next: --next-token ${e}`)}else A(s,i)}}),Al=w({description:{"en-US":`Create a data-center category`,"zh-CN":`创建数据中心类目`},auth:`apiKey`,usageArgs:`--name <text> [flags]`,flags:{name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Category name (1-20 chars)`,"zh-CN":`类目名称(1–20 个字符)`},required:!0},parentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Create as a sub-category of this category`,"zh-CN":`创建为该类目的子类目`}},collectionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Create under this collection (defaults to the platform collection)`,"zh-CN":`在该数据集合下创建(默认为平台数据集合)`}},...U},notes:[{"en-US":`Use categories to organize data-center files by business domain.`,"zh-CN":`使用类目按业务领域组织数据中心文件。`}],exampleArgs:[`--name product-docs --workspace-id ws-xxx`,`--name sub --parent-id cate-xxx`],validate(e){if(e.name.length<1||e.name.length>20)return`--name must be 1-20 characters`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={categoryName:n.name,categoryType:`UNSTRUCTURED`,...n.parentId?{parentCategoryId:n.parentId}:{},...n.collectionId?{connectorId:n.collectionId}:{}},o=E(r,p.addCategory);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.categoryId;if(t.quiet){k(c??``);return}if(i===`text`){k(`created: ${c??`-`} (${n.name})`);return}A(s,i)}}),jl=w({description:{"en-US":`Delete a data-center category`,"zh-CN":`删除数据中心类目`},auth:`apiKey`,usageArgs:`--category-id <id> [flags]`,flags:{categoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Category ID to delete`,"zh-CN":`要删除的类目 ID`},required:!0},yes:{type:`switch`,description:{"en-US":`Skip the confirmation prompt`,"zh-CN":`跳过确认提示`}},...U},notes:[{"en-US":`Behavior for categories containing files or sub-categories is server-defined — the server error is passed through as-is.`,"zh-CN":`包含文件或子类目时的处理行为由服务端定义——服务端返回的错误将原样透传。`}],exampleArgs:[`--category-id cate-xxx --workspace-id ws-xxx`,`--category-id cate-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={categoryId:n.categoryId},o=E(r,p.deleteCategory);if(t.dryRun){A({endpoint:o,request:a},i);return}await yn(`Delete category ${n.categoryId}\nThis cannot be undone.`,n.yes??!1);let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){k(`deleted: ${n.categoryId}`);return}A(s,i)}}}),Ml=w({description:{"en-US":`List files in a data-center category`,"zh-CN":`列出数据中心类目中的文件`},auth:`apiKey`,usageArgs:`--category-id <id> [flags]`,flags:{categoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Category to list (find ids via the category list command); exact match`,"zh-CN":`要列出文件的类目(通过类目列表命令查找 ID);精确匹配`},required:!0},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by exact file name without its extension (a.md → pass a)`,"zh-CN":`按不含扩展名的文件名精确筛选(a.md 应传入 a)`}},fileId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Filter by exact file ID (repeatable)`,"zh-CN":`按文件 ID 精确筛选(可重复)`}},nextToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Cursor for the next page (from previous output)`,"zh-CN":`下一页游标(来自上一次输出)`}},maxResult:{type:`number`,valueHint:`<n>`,description:{"en-US":`Items per page`,"zh-CN":`每页条目数`}},...U},notes:[{"en-US":`A real category id is required — the default value is not resolved here. Find the id via the category list command.`,"zh-CN":`必须提供真实的类目 ID——此处不会解析 default 值。请通过类目列表命令查找 ID。`},{"en-US":`--name matches the exact file name without its extension (for a.md pass a); partial keywords return no results.`,"zh-CN":`--name 精确匹配不含扩展名的文件名(a.md 应传入 a);部分关键字不会返回结果。`},{"en-US":`Pagination is cursor-based: reuse the printed next token to continue.`,"zh-CN":`分页使用游标:复用输出中的 next token 继续查询。`}],exampleArgs:[`--category-id cate-xxx --workspace-id ws-xxx`,{"en-US":`--category-id cate-xxx --name report`,"zh-CN":`--category-id cate-xxx --name 报告`}],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={categoryId:n.categoryId,...n.name?{fileName:n.name}:{},...n.fileId?.length?{fileIds:n.fileId}:{},...n.nextToken?{nextToken:n.nextToken}:{},...n.maxResult===void 0?{}:{maxResult:n.maxResult}},o=E(r,p.listFile);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.fileList??[];if(t.quiet){for(let e of c)k(e.fileId??``);return}if(i===`text`){if(c.length===0)k(`No files found.`);else for(let e of c)k(rc([e.fileId,e.status??`-`,e.fileName,e.sizeBytes??`-`].join(` `)));let e=s.data?.nextToken;e&&k(`next: --next-token ${e}`)}else A(s,i)}}),Nl=w({description:{"en-US":`Show data-center file details (size, MD5, tags, timestamps)`,"zh-CN":`查看数据中心文件详情(大小、MD5、标签、时间戳)`},auth:`apiKey`,usageArgs:`--file-id <id> [flags]`,flags:{fileId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Data-center file ID`,"zh-CN":`数据中心文件 ID`},required:!0},...U},exampleArgs:[`--file-id file-xxx --workspace-id ws-xxx`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={fileId:n.fileId},o=E(r,p.describeFile);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data;if(t.quiet){k(c?.fileId??``);return}if(i!==`text`){A(s,i);return}k(`id: ${c?.fileId??`-`}`),k(`name: ${c?.fileName??`-`}`),k(`type: ${c?.fileType??`-`}`),k(`size: ${c?.sizeBytes??`-`}`),k(`status: ${c?.status??`-`}`),k(`parser: ${c?.parser??`-`}`),k(`category: ${c?.category??`-`}`),k(`uploaded: ${c?.uploadTime??`-`}`),k(`tags: ${(Array.isArray(c?.tags)?c.tags.join(`, `):c?.tags??`-`)||`-`}`)}});const Pl={fileId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Data-center file ID to delete`,"zh-CN":`要删除的数据中心文件 ID`},required:!0},yes:{type:`switch`,description:{"en-US":`Skip the confirmation prompt`,"zh-CN":`跳过确认提示`}},...U};async function Fl(e,t,n){let r=``;try{let i=await e.requestJson({path:E(t,p.describeFile),method:`POST`,body:{fileId:n}});i.data?.fileName&&(r=` name: ${i.data.fileName}`)}catch{}return`Delete data-center file ${n}${r}\nPERMANENT: if the file is referenced by knowledge bases, their document indexes break too. This differs from removing a document from one knowledge base.`}var Il=w({description:{"en-US":`Permanently delete a file from the data center`,"zh-CN":`从数据中心永久删除文件`},auth:`apiKey`,usageArgs:`--file-id <id> [flags]`,flags:Pl,notes:[{"en-US":`Irreversible. If knowledge bases reference this file, their related document indexes become invalid.`,"zh-CN":`该操作不可撤销。如果知识库引用了此文件,其相关文档索引将失效。`},{"en-US":`To remove a document from a single knowledge base only, use the document delete command instead.`,"zh-CN":`如果只需从单个知识库中移除文档,请改用文档删除命令。`}],exampleArgs:[`--file-id file-xxx --workspace-id ws-xxx`,`--file-id file-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={fileId:n.fileId},o=E(r,p.deleteFile);if(t.dryRun){A({endpoint:o,request:a},i);return}await yn(n.yes?``:await Fl(e.client,r,n.fileId),n.yes??!1);let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){k(`deleted: ${n.fileId}`);return}A(s,i)}}}),Ll=w({description:{"en-US":`Create a FILE data collection`,"zh-CN":`创建 FILE 数据集合`},auth:`apiKey`,usageArgs:`--name <text> --description <text> [flags]`,flags:{name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Collection name`,"zh-CN":`数据集合名称`},required:!0},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`Collection description (required by the server)`,"zh-CN":`数据集合描述(服务端必填)`},required:!0},storeType:{type:`string`,valueHint:`<type>`,description:{"en-US":`Storage: platform (managed) or custom (your own OSS bucket)`,"zh-CN":`存储类型:platform(托管)或 custom(自有 OSS Bucket)`}},ossRegion:{type:`string`,valueHint:`<id>`,description:{"en-US":`OSS region id (required with --store-type custom)`,"zh-CN":`OSS Region ID(使用 --store-type custom 时必填)`}},ossBucket:{type:`string`,valueHint:`<name>`,description:{"en-US":`OSS bucket name (required with --store-type custom)`,"zh-CN":`OSS Bucket 名称(使用 --store-type custom 时必填)`}},...U},notes:[{"en-US":`Store type defaults to platform (managed storage); custom uses your authorized OSS bucket.`,"zh-CN":`存储类型默认为 platform(托管存储);custom 使用已授权的自有 OSS Bucket。`},{"en-US":`Custom buckets must carry the bucket tag bailian-connector-access=ReadAndWrite (Bailian's tag-based access control); without it the server rejects creation with a misleading 'setBucketCORS failed' error.`,"zh-CN":`自定义 Bucket 必须带有 bailian-connector-access=ReadAndWrite 标签(百炼基于标签的访问控制);缺少该标签时,服务端会以容易误解的 'setBucketCORS failed' 错误拒绝创建。`},{"en-US":`There is no collection delete API — create collections deliberately.`,"zh-CN":`目前没有删除数据集合的 API——请谨慎创建。`}],exampleArgs:[{"en-US":`--name my-collection --description 'team docs' --workspace-id ws-xxx`,"zh-CN":`--name my-collection --description '团队文档' --workspace-id ws-xxx`},{"en-US":`--name oss-coll --description 'own bucket' --store-type custom --oss-region cn-beijing --oss-bucket my-bucket`,"zh-CN":`--name oss-coll --description '自有 Bucket' --store-type custom --oss-region cn-beijing --oss-bucket my-bucket`}],validate(e){if(e.name.length<1||e.name.length>20)return`--name must be 1-20 characters`;let t=e.storeType??`platform`;if(t!==`platform`&&t!==`custom`)return`--store-type must be platform or custom`;if(t===`custom`&&(!e.ossRegion||!e.ossBucket))return`--store-type custom requires --oss-region and --oss-bucket`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a=(n.storeType??`platform`).toUpperCase(),o={connectorType:`FILE`,connectorName:n.name,description:n.description,fileConnectorConfig:{storeType:a,...a===`CUSTOM`?{regionId:n.ossRegion,bucketName:n.ossBucket}:{}}},s=E(r,p.addConnector);if(t.dryRun){A({endpoint:s,request:o},i);return}let c=await e.client.requestJson({path:s,method:`POST`,body:o}),l=c.data?.connectorId;if(t.quiet){k(l??``);return}if(i===`text`){k(`created: ${l??`-`} (${n.name}, ${a})`);return}A(c,i)}}),Rl=w({description:{"en-US":`Show data collection details`,"zh-CN":`查看数据集合详情`},auth:`apiKey`,usageArgs:`(--collection-id <id> | --name <text>) [flags]`,flags:{collectionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Collection ID; alternative to --name`,"zh-CN":`数据集合 ID;与 --name 二选一`}},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Collection name; alternative to --collection-id`,"zh-CN":`数据集合名称;与 --collection-id 二选一`}},...U},exampleArgs:[`--collection-id conn-xxx --workspace-id ws-xxx`,`--name my-collection`],validate(e){if(!e.collectionId&&!e.name)return`Pass --collection-id or --name`;if(e.collectionId&&e.name)return`Use either --collection-id or --name, not both`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={...n.collectionId?{connectorId:n.collectionId}:{},...n.name?{connectorName:n.name}:{}},o=E(r,p.getConnector);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data;if(t.quiet){k(c?.connectorId??``);return}if(i===`text`){k(`id: ${c?.connectorId??`-`}`),k(`name: ${c?.connectorName??`-`}`),k(`description: ${c?.description??`-`}`);return}A(s,i)}}),zl=w({description:{"en-US":`Batch import files from an authorized OSS bucket into the data center`,"zh-CN":`从已授权的 OSS Bucket 批量导入文件到数据中心`},auth:`apiKey`,usageArgs:`--bucket <name> --region <id> --oss-key <key> [flags]`,flags:{bucket:{type:`string`,valueHint:`<name>`,description:{"en-US":`Authorized OSS bucket name`,"zh-CN":`已授权的 OSS Bucket 名称`},required:!0},region:{type:`string`,valueHint:`<id>`,description:{"en-US":`OSS region id (e.g. cn-beijing)`,"zh-CN":`OSS Region ID(例如 cn-beijing)`},required:!0},ossKey:{type:`array`,valueHint:`<key>`,description:{"en-US":`OSS object key to import (repeatable, 1-10 per call)`,"zh-CN":`要导入的 OSS Object Key(可重复,每次调用 1–10 个)`},required:!0},categoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Target data-center category (default: the default category)`,"zh-CN":`目标数据中心类目(默认:默认类目)`}},tag:{type:`array`,valueHint:`<text>`,description:{"en-US":`File tag applied to every imported file (repeatable, up to 10)`,"zh-CN":`应用于每个导入文件的标签(可重复,最多 10 个)`}},overwrite:{type:`switch`,description:{"en-US":`Overwrite files previously imported from the same OSS keys`,"zh-CN":`覆盖此前从相同 OSS Key 导入的文件`}},...U},notes:[{"en-US":`The bucket must be authorized to the platform service role beforehand; permission errors from the server are passed through with a pointer to check AliyunServiceRoleForBailian in the RAM console.`,"zh-CN":`必须预先将 Bucket 授权给平台服务角色;服务端权限错误将原样透传,并提示在 RAM 控制台检查 AliyunServiceRoleForBailian。`},{"en-US":`File names are derived from the OSS key basename.`,"zh-CN":`文件名取自 OSS Key 的 basename。`},{"en-US":`--overwrite replaces the previously imported file and issues a NEW fileId (the old one becomes invalid) — verified live.`,"zh-CN":`--overwrite 会替换此前导入的文件并生成新的 fileId(旧 fileId 将失效)——已通过真实环境验证。`}],exampleArgs:[`--bucket my-bucket --region cn-beijing --oss-key docs/a.pdf --workspace-id ws-xxx`,`--bucket my-bucket --region cn-beijing --oss-key docs/a.pdf --oss-key docs/b.docx --overwrite`],validate(e){if(e.ossKey.length>10)return`--oss-key accepts at most 10 entries per call`;if(e.tag!==void 0&&e.tag.length>10)return`--tag accepts at most 10 entries`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={categoryId:n.categoryId??`default`,categoryType:`UNSTRUCTURED`,ossBucket:n.bucket,ossRegionId:n.region,fileDetails:n.ossKey.map(e=>({fileName:F(e),ossKey:e})),...n.tag?.length?{tags:n.tag}:{},...n.overwrite?{overWriteFileByOssKey:!0}:{}},o=E(r,p.addFilesFromAuthorizedOss);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.addFileResultList??[],l=c.map(e=>e.fileId).filter(e=>!!e);if(t.quiet){for(let e of l)k(e);return}if(i===`text`){k(`imported: ${l.length} file(s)`);for(let e of c)k(` ${e.fileId??`-`} ${e.status??`-`} ${e.ossKey??``}`);return}A(s,i)}});function Bl(e){if(!(e instanceof t))return!1;let n=e.message;return/^MCP request failed:\s*404\b/i.test(n)?/未开通|MCP不存在|MCP_IS_INVALID/i.test(n):!1}function Vl(e){let t=[`Activate (or re-activate) the ${e} MCP in the Bailian MCP marketplace, then retry.`];return e===`WebSearch`&&t.push(`If it was previously on SSE, cancel and activate again to upgrade to Streamable HTTP.`),t.push(`Open: ${jn(e)}`),t.join(`
2738
+ WARNING: this service is LIVE — deleting it breaks existing callers.`))}catch{}return`Delete service ${n}${r}${i}\nDeletion cannot be undone; the agent_id can no longer be used for search or chat calls.`}var ml=w({description:{"en-US":`Delete a retrieval / Q&A service (soft delete, idempotent)`,"zh-CN":`删除检索/问答服务(软删除,幂等)`},auth:`apiKey`,usageArgs:`--agent-id <id> [flags]`,flags:fl,notes:[{"en-US":`Deletion cannot be undone; the agent_id becomes unusable for search and chat calls.`,"zh-CN":`删除无法撤销;该 agent_id 将不能再用于 search 和 chat 调用。`},{"en-US":`Idempotent — deleting an already-deleted service does not fail.`,"zh-CN":`该操作具有幂等性——重复删除已删除的服务不会失败。`},{"en-US":`Requires the knowledge-base delete permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库删除权限。`}],exampleArgs:[`--agent-id aid-xxx --workspace-id ws-xxx`,`--agent-id aid-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={agent_id:n.agentId},o=E(r,p.agentDelete);if(t.dryRun){A({endpoint:o,request:a},i);return}await yn(n.yes?``:await pl(e.client,r,n.agentId),n.yes??!1);let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){k(`deleted: ${n.agentId} (status: ${dc(s,`agent_status`)??`deleted`})`);return}A(s,i)}}}),hl=w({description:{"en-US":`Copy a service into a new draft (name gets a copy_ prefix)`,"zh-CN":`将服务复制为新草稿(名称会添加 copy_ 前缀)`},auth:`apiKey`,usageArgs:`--agent-id <id> [flags]`,flags:{agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Source service (agent) ID to copy`,"zh-CN":`要复制的源服务(Agent)ID`},required:!0},...U},notes:[{"en-US":`The copy starts as a beta draft; test it with --agent-version beta, then deploy to publish.`,"zh-CN":`副本初始为 beta 草稿;请使用 --agent-version beta 测试,然后部署发布。`},{"en-US":`Requires the knowledge-base create permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库创建权限。`}],exampleArgs:[`--agent-id aid-xxx --workspace-id ws-xxx`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={agent_id:n.agentId},o=E(r,p.agentCopy);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=dc(s,`agent_id`);if(t.quiet){k(c??``);return}if(i===`text`){k(`new agent_id: ${c??`-`} (name: ${dc(s,`agent_name`)??`-`}, status: ${dc(s,`agent_status`)??`draft`})`),k(`Test the draft with --agent-version beta on search/chat, then deploy it to publish.`);return}A(s,i)}});const gl={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},docId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Owning document ID from the doc list command; required in practice for all knowledge base types`,"zh-CN":`来自文档列表命令的所属文档 ID;实际使用时所有知识库类型都需要提供`}},content:{type:`string`,valueHint:`<text>`,description:{"en-US":`Chunk body text, up to 6000 chars (document-type); alternative to --content-file`,"zh-CN":`Chunk 正文,最多 6000 个字符(文档型);与 --content-file 二选一`}},contentFile:{type:`string`,valueHint:`<path>`,description:{"en-US":`Read chunk body from a UTF-8 plain text file (.md/.txt etc.)`,"zh-CN":`从 UTF-8 纯文本文件(.md/.txt 等)读取 Chunk 正文`}},title:{type:`string`,valueHint:`<text>`,description:{"en-US":`Chunk title, up to 50 chars (document-type)`,"zh-CN":`Chunk 标题,最多 50 个字符(文档型)`}},imageUrl:{type:`array`,valueHint:`<url>`,description:{"en-US":`Chunk image URL (repeatable, up to 10; document-type)`,"zh-CN":`Chunk 图片 URL(可重复,最多 10 个;文档型)`}},field:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Arbitrary field entry (repeatable) for table/image knowledge bases where keys are Excel column headers; mutually exclusive with content/title/image flags`,"zh-CN":`表格/图片知识库的自定义字段(可重复),键为 Excel 列标题;不能与 content/title/image 相关选项同时使用`}},...U};function _l(e){let n={};for(let r of e){let e=r.indexOf(`=`);if(e<=0)throw new t(`--field must be key=value, got: ${r}`,c.USAGE);n[r.slice(0,e)]=r.slice(e+1)}return n}var vl=w({description:{"en-US":`Add a chunk directly to a knowledge base`,"zh-CN":`直接向知识库添加 Chunk`},auth:`apiKey`,usageArgs:`--index-id <id> (--content <text> | --field <k=v>) [flags]`,flags:gl,notes:[{"en-US":`Document / table / image knowledge bases are supported; audio-video ones are not.`,"zh-CN":`支持文档、表格和图片知识库;不支持音视频知识库。`},{"en-US":`--doc-id is required in practice for all knowledge base types. Use the document-level id from the doc list command; the per-row doc_id in chunk list output is not accepted.`,"zh-CN":`实际使用时,所有知识库类型都需要 --doc-id。请使用文档列表命令返回的文档级 ID;Chunk 列表每行返回的 doc_id 不被接受。`},{"en-US":`Image-type documents do not support text chunks. Target a text-type document (docx/pdf/txt) instead.`,"zh-CN":`图片型文档不支持文本 Chunk;请改为操作文本型文档(docx/pdf/txt)。`},{"en-US":`The API is idempotent but rate-limited to 10 calls per second — throttle batch scripts.`,"zh-CN":`该 API 具有幂等性,但限流为每秒 10 次调用——批处理脚本需要控制速率。`},{"en-US":`The response carries no chunk id; list chunks afterwards to find the new one.`,"zh-CN":`响应不包含 Chunk ID;添加后请列出 Chunk 以查找新条目。`},{"en-US":`For table/image knowledge bases use --field with Excel column headers as keys; values are passed through as strings.`,"zh-CN":`表格/图片知识库请使用 --field,并以 Excel 列标题作为键;值将按字符串原样传递。`}],exampleArgs:[{"en-US":`--index-id idx-xxx --content "chunk text" --title intro --workspace-id ws-xxx`,"zh-CN":`--index-id idx-xxx --content "Chunk 文本" --title 简介 --workspace-id ws-xxx`},{"en-US":`--index-id idx-xxx --field columnA=v1 --field columnB=v2`,"zh-CN":`--index-id idx-xxx --field 列A=v1 --field 列B=v2`}],validate(e){let t=e.content!==void 0||e.contentFile!==void 0||e.title!==void 0||!!e.imageUrl?.length,n=!!e.field?.length;if(t&&n)return`--field is mutually exclusive with --content/--content-file/--title/--image-url`;if(!t&&!n)return`Provide chunk content via --content/--content-file or --field entries`;if(e.content!==void 0&&e.contentFile!==void 0)return`Use either --content or --content-file, not both`;if(e.content!==void 0&&e.content.length>6e3)return`--content must be at most 6000 characters`;if(e.title!==void 0&&e.title.length>50)return`--title must be at most 50 characters`;if(e.imageUrl!==void 0&&e.imageUrl.length>10)return`--image-url accepts at most 10 entries`},async run(e){let{settings:n,flags:r}=e,i=W(e),a=T(n.output),o;if(r.field?.length)o=_l(r.field);else{let e=r.contentFile===void 0?r.content:Pc(r.contentFile,`--content`);if(typeof e==`string`&&e.length>6e3)throw new t(`Chunk content must be at most 6000 characters`,c.USAGE);o={...e===void 0?{}:{content:e},...r.title===void 0?{}:{title:r.title},...r.imageUrl?.length?{image_urls:r.imageUrl}:{}}}let s={pipelineId:r.indexId,...r.docId?{dataId:r.docId}:{},field:o},l=E(i,p.chunkCreate);if(n.dryRun){A({endpoint:l,request:s},a);return}let u=await e.client.requestJson({path:l,method:`POST`,body:s});if(!n.quiet){if(a===`text`){k(`chunk created (pipeline: ${r.indexId})`),k(`List chunks to find the new chunk id.`);return}A(u,a)}}}),yl=w({description:{"en-US":`List chunks in a knowledge base with content and status`,"zh-CN":`列出知识库中的 Chunk 及其内容和状态`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:{indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},docId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Only show chunks belonging to this document`,"zh-CN":`仅显示属于该文档的 Chunk`}},...nc,...U},notes:[{"en-US":`Use metadata._id as the chunk id and metadata.doc_id as the document id in chunk update/delete commands.`,"zh-CN":`在 Chunk 更新/删除命令中,使用 metadata._id 作为 Chunk ID,使用 metadata.doc_id 作为文档 ID。`},{"en-US":`Page size defaults to 20 (server default), max 100.`,"zh-CN":`分页大小默认为 20(服务端默认值),最大为 100。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --doc-id file-xxx --page-size 50`],validate(e){if(e.pageSize!==void 0&&(e.pageSize<1||e.pageSize>100))return`--page-size must be between 1 and 100`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={indexId:n.indexId,pageNum:n.pageNumber??1,pageSize:n.pageSize??20,...n.docId?{docId:n.docId}:{}},o=E(r,p.chunkList);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.nodes??[];if(t.quiet){for(let e of c)k(e.metadata?._id??``);return}if(i===`text`){if(c.length===0)k(`No chunks found.`);else for(let e of c){let t=e.metadata??{},n=t._chunk_status_message?` status: ${t._chunk_status_message}`:``,r=t.is_displayed_chunk_content===!1?` [excluded from retrieval]`:``;k(`[chunk] ${t._id??`?`} (doc: ${t.doc_name??`?`}, doc_id: ${t.doc_id??`?`})${n}${r}`);let i=t.content??e.text??``;k(` ${i.length>200?`${i.slice(0,200)}…`:i}`)}k(`total: ${s.data?.total??c.length}`)}else A(s,i)}});const bl={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},chunkId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Chunk ID (metadata._id from the chunk list output)`,"zh-CN":`Chunk ID(来自 Chunk 列表输出的 metadata._id)`},required:!0},docId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Document ID owning the chunk (metadata.doc_id from the chunk list output)`,"zh-CN":`Chunk 所属文档 ID(来自 Chunk 列表输出的 metadata.doc_id)`},required:!0},content:{type:`string`,valueHint:`<text>`,description:{"en-US":`New chunk content, 10-6000 chars; alternative to --content-file`,"zh-CN":`新的 Chunk 内容,10–6000 个字符;与 --content-file 二选一`}},contentFile:{type:`string`,valueHint:`<path>`,description:{"en-US":`Read new content from a UTF-8 plain text file (.md/.txt etc.)`,"zh-CN":`从 UTF-8 纯文本文件(.md/.txt 等)读取新内容`}},title:{type:`string`,valueHint:`<text>`,description:{"en-US":`Chunk title, 0-50 chars (empty string clears it; omit to keep unchanged)`,"zh-CN":`Chunk 标题,0–50 个字符(空字符串表示清除;省略则保持不变)`}},exclude:{type:`switch`,description:{"en-US":`Exclude this chunk from retrieval`,"zh-CN":`在检索中排除该 Chunk`}},include:{type:`switch`,description:{"en-US":`Include this chunk in retrieval (default)`,"zh-CN":`在检索中包含该 Chunk(默认)`}},...U};async function xl(e,n,r,i,a){for(let t=1;t<=10;t++){let o=(await e.requestJson({path:E(n,p.chunkList),method:`POST`,body:{indexId:r,docId:a,pageNum:t,pageSize:100}})).data?.nodes??[],s=o.find(e=>e.metadata?._id===i),c=s?.metadata?.content??s?.text;if(typeof c==`string`)return c;if(o.length<100)break}throw new t(`Chunk not found: ${i}`,c.GENERAL,`Check the chunk id via the chunk list command.`)}var Sl=w({description:{"en-US":`Update chunk content or toggle its retrieval visibility`,"zh-CN":`更新 Chunk 内容或切换其检索可见性`},auth:`apiKey`,usageArgs:`--index-id <id> --chunk-id <id> --doc-id <id> [flags]`,flags:bl,notes:[{"en-US":`Content must be 10-6000 characters and within the knowledge base's max chunk size.`,"zh-CN":`内容必须为 10–6000 个字符,且不能超过知识库的最大 Chunk 大小。`},{"en-US":`--content-file expects a UTF-8 plain text file; document formats (.docx/.pdf) are not parsed here.`,"zh-CN":`--content-file 需要 UTF-8 纯文本文件;此处不会解析 .docx/.pdf 等文档格式。`},{"en-US":`Toggling --exclude/--include without new content re-submits the existing content automatically.`,"zh-CN":`仅切换 --exclude/--include 而不提供新内容时,会自动重新提交现有内容。`}],exampleArgs:[{"en-US":`--index-id idx-xxx --chunk-id chunk-xxx --doc-id file-xxx --content "corrected text"`,"zh-CN":`--index-id idx-xxx --chunk-id chunk-xxx --doc-id file-xxx --content "修正后的文本"`},`--index-id idx-xxx --chunk-id chunk-xxx --doc-id file-xxx --exclude`],validate(e){if(e.content!==void 0&&e.contentFile!==void 0)return`Use either --content or --content-file, not both`;if(e.exclude&&e.include)return`--exclude and --include are mutually exclusive`;if(!(e.content!==void 0||e.contentFile!==void 0)&&!e.exclude&&!e.include&&e.title===void 0)return`Nothing to update — pass --content/--content-file, --title, --exclude or --include`;if(e.content!==void 0&&(e.content.length<10||e.content.length>6e3))return`--content must be 10-6000 characters`;if(e.title!==void 0&&e.title.length>50)return`--title must be at most 50 characters`},async run(e){let{settings:n,flags:r}=e,i=W(e),a=T(n.output),o=r.contentFile===void 0?r.content:Pc(r.contentFile,`--content`);if(o!==void 0&&(o.length<10||o.length>6e3))throw new t(`Chunk content must be 10-6000 characters`,c.USAGE);o===void 0&&(o=n.dryRun?`<current-content (fetched at run time)>`:await xl(e.client,i,r.indexId,r.chunkId,r.docId));let s={pipelineId:r.indexId,chunkId:r.chunkId,dataId:r.docId,content:o,isDisplayedChunkContent:!r.exclude,...r.title===void 0?{}:{title:r.title}},l=E(i,p.chunkUpdate);if(n.dryRun){A({endpoint:l,request:s},a);return}let u=await e.client.requestJson({path:l,method:`POST`,body:s});if(!n.quiet){if(a===`text`){k(`updated: ${r.chunkId}`);return}A(u,a)}}});const Cl={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},chunkId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Chunk ID to delete (repeatable; batches of 10 are sent automatically)`,"zh-CN":`要删除的 Chunk ID(可重复;每 10 个自动分批发送)`},required:!0},yes:{type:`switch`,description:{"en-US":`Skip the confirmation prompt`,"zh-CN":`跳过确认提示`}},...U};function wl(e,t=10){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}var Tl=w({description:{"en-US":`Delete chunks from a knowledge base (irreversible)`,"zh-CN":`从知识库中删除 Chunk(不可撤销)`},auth:`apiKey`,usageArgs:`--index-id <id> --chunk-id <id> [flags]`,flags:Cl,notes:[{"en-US":`Accepts at most 10 chunk ids per call; larger sets are batched automatically.`,"zh-CN":`每次调用最多接受 10 个 Chunk ID;更多 ID 会自动分批处理。`}],exampleArgs:[`--index-id idx-xxx --chunk-id chunk-a --chunk-id chunk-b --workspace-id ws-xxx`,`--index-id idx-xxx --chunk-id chunk-a --yes`],async run(e){let{settings:n,flags:r}=e,i=W(e),a=T(n.output),o=wl(r.chunkId),s=E(i,p.chunkDelete);if(n.dryRun){A({endpoint:s,batches:o.map(e=>({request:{pipelineId:r.indexId,chunkIds:e}}))},a);return}await yn(`Delete ${r.chunkId.length} chunk(s) from knowledge base ${r.indexId} in ${o.length} batch(es).\nChunks are permanently removed. This cannot be undone.`,r.yes??!1);let c=0;for(let n of o)try{await e.client.requestJson({path:s,method:`POST`,body:{pipelineId:r.indexId,chunkIds:n}}),c+=n.length}catch(e){throw c>0&&e instanceof t&&!e.hint?new t(e.message,e.exitCode,`${c} chunk(s) in earlier batches were already deleted.`,{cause:e,api:e.api,rawResponse:e.rawResponse}):e}if(!n.quiet){if(a===`text`){k(`deleted: ${c} chunk(s) in ${o.length} batch(es)`);return}A({deleted_count:c,batches:o.length},a)}}});const El={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},start:{type:`string`,valueHint:`<time>`,description:{"en-US":`Range start: Unix seconds or ISO date, must be in the past (default: 24 hours ago)`,"zh-CN":`范围开始时间:Unix 秒或 ISO 日期,必须是过去时间(默认:24 小时前)`}},end:{type:`string`,valueHint:`<time>`,description:{"en-US":`Range end: Unix seconds or ISO date, must be in the past (default: now)`,"zh-CN":`范围结束时间:Unix 秒或 ISO 日期,必须是过去时间(默认:当前时间)`}},...U};function Dl(e){if(/^\d+$/.test(e))return e.length>=13?String(Math.floor(Number(e)/1e3)):e;let n=/^\d{4}-\d{2}-\d{2}([T ].*)?$/.test(e)?Date.parse(e):NaN;if(Number.isNaN(n))throw new t(`Invalid time value: ${e}`,c.USAGE,`Pass Unix seconds (e.g. 1780900000) or an ISO date (e.g. 2026-07-30T00:00:00Z).`);return String(Math.floor(n/1e3))}var Ol=w({description:{"en-US":`Show knowledge base storage and QPS monitoring data`,"zh-CN":`查看知识库存储和 QPS 监控数据`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:El,notes:[{"en-US":`Defaults to the last 24 hours when --start/--end are omitted.`,"zh-CN":`省略 --start/--end 时,默认查询最近 24 小时。`},{"en-US":`Timestamps are normalized to epoch seconds as required by the server.`,"zh-CN":`时间戳会按服务端要求归一化为 Epoch 秒。`},{"en-US":`Future timestamps are rejected for --start and clamped to now for --end, since the monitor API only returns past data.`,"zh-CN":`监控 API 只返回历史数据,因此未来的 --start 会被拒绝,未来的 --end 会被截断为当前时间。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --start 2026-07-30 --end 2026-07-31`],async run(e){let{settings:n,flags:r}=e,i=W(e),a=T(n.output),o=Math.floor(Date.now()/1e3),s=r.start?Dl(r.start):String(o-24*3600),l=r.end?Dl(r.end):String(o);if(Number(s)>o)throw new t(`Start time is in the future; the monitor API only accepts past or current timestamps.`,c.USAGE,`Use a start date/time at or before now, or omit --start to default to 24 hours ago.`);let u=Number(l)>o;u&&(l=String(o));let d={indexId:r.indexId,startTimestamp:s,endTimestamp:l},f=E(i,p.indexMonitor);if(n.dryRun){A({endpoint:f,request:d},a);return}let m=await e.client.requestJson({path:f,method:`POST`,body:d});if(a!==`text`){A(m,a);return}u&&k(`note: end time was in the future, clamped to now.`);let h=m.data?.storageMonitorData,g=m.data?.qpsMonitorData;k(`plan: ${m.data?.pipelineCommercialType??`-`}`),k(`storage: ${h?.indexStorageUsage??`-`} / ${h?.indexStorageLimit??`-`}`),k(`peak qps: ${g?.peakQps??`-`}`),k(`qps windows: ${g?.monitorData?.length??0} data point(s)`)}}),kl=w({description:{"en-US":`List data-center categories`,"zh-CN":`列出数据中心类目`},auth:`apiKey`,usageArgs:`[flags]`,flags:{collectionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by exact collection ID`,"zh-CN":`按数据集合 ID 精确筛选`}},parentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`List sub-categories of this exact parent category`,"zh-CN":`列出该父类目下的子类目`}},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by category name (exact match, unlike the knowledge base list)`,"zh-CN":`按类目名称筛选(精确匹配,与知识库列表不同)`}},nextToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Cursor for the next page (from previous output)`,"zh-CN":`下一页游标(来自上一次输出)`}},maxResult:{type:`number`,valueHint:`<n>`,description:{"en-US":`Items per page (default: 20)`,"zh-CN":`每页条目数(默认:20)`}},...U},notes:[{"en-US":`Categories marked [default] are where files land when no category is specified.`,"zh-CN":`未指定类目时,文件会进入标记为 [default] 的类目。`},{"en-US":`Pagination is cursor-based: reuse the printed next token to continue.`,"zh-CN":`分页使用游标:复用输出中的 next token 继续查询。`}],exampleArgs:[`--workspace-id ws-xxx`,`--name my-category`,`--next-token <token>`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={type:`UNSTRUCTURED`,...n.collectionId?{connectorId:n.collectionId}:{},...n.parentId?{parentId:n.parentId}:{},...n.name?{categoryName:n.name}:{},...n.nextToken?{nextToken:n.nextToken}:{},...n.maxResult===void 0?{}:{maxResult:n.maxResult}},o=E(r,p.listCategory);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.categoryList??[];if(t.quiet){for(let e of c)k(e.categoryId??``);return}if(i===`text`){if(c.length===0)k(`No categories found.`);else for(let e of c){let t=e.isDefault?` [default]`:``;k(rc(`${e.categoryId} ${e.categoryName}${t}`))}let e=s.data?.nextToken;e&&k(`next: --next-token ${e}`)}else A(s,i)}}),Al=w({description:{"en-US":`Create a data-center category`,"zh-CN":`创建数据中心类目`},auth:`apiKey`,usageArgs:`--name <text> [flags]`,flags:{name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Category name (1-20 chars)`,"zh-CN":`类目名称(1–20 个字符)`},required:!0},parentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Create as a sub-category of this category`,"zh-CN":`创建为该类目的子类目`}},collectionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Create under this collection (defaults to the platform collection)`,"zh-CN":`在该数据集合下创建(默认为平台数据集合)`}},...U},notes:[{"en-US":`Use categories to organize data-center files by business domain.`,"zh-CN":`使用类目按业务领域组织数据中心文件。`}],exampleArgs:[`--name product-docs --workspace-id ws-xxx`,`--name sub --parent-id cate-xxx`],validate(e){if(e.name.length<1||e.name.length>20)return`--name must be 1-20 characters`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={categoryName:n.name,categoryType:`UNSTRUCTURED`,...n.parentId?{parentCategoryId:n.parentId}:{},...n.collectionId?{connectorId:n.collectionId}:{}},o=E(r,p.addCategory);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.categoryId;if(t.quiet){k(c??``);return}if(i===`text`){k(`created: ${c??`-`} (${n.name})`);return}A(s,i)}}),jl=w({description:{"en-US":`Delete a data-center category`,"zh-CN":`删除数据中心类目`},auth:`apiKey`,usageArgs:`--category-id <id> [flags]`,flags:{categoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Category ID to delete`,"zh-CN":`要删除的类目 ID`},required:!0},yes:{type:`switch`,description:{"en-US":`Skip the confirmation prompt`,"zh-CN":`跳过确认提示`}},...U},notes:[{"en-US":`Behavior for categories containing files or sub-categories is server-defined — the server error is passed through as-is.`,"zh-CN":`包含文件或子类目时的处理行为由服务端定义——服务端返回的错误将原样透传。`}],exampleArgs:[`--category-id cate-xxx --workspace-id ws-xxx`,`--category-id cate-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={categoryId:n.categoryId},o=E(r,p.deleteCategory);if(t.dryRun){A({endpoint:o,request:a},i);return}await yn(`Delete category ${n.categoryId}\nThis cannot be undone.`,n.yes??!1);let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){k(`deleted: ${n.categoryId}`);return}A(s,i)}}}),Ml=w({description:{"en-US":`List files in a data-center category`,"zh-CN":`列出数据中心类目中的文件`},auth:`apiKey`,usageArgs:`--category-id <id> [flags]`,flags:{categoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Category to list (find ids via the category list command); exact match`,"zh-CN":`要列出文件的类目(通过类目列表命令查找 ID);精确匹配`},required:!0},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by exact file name without its extension (a.md → pass a)`,"zh-CN":`按不含扩展名的文件名精确筛选(a.md 应传入 a)`}},fileId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Filter by exact file ID (repeatable)`,"zh-CN":`按文件 ID 精确筛选(可重复)`}},nextToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Cursor for the next page (from previous output)`,"zh-CN":`下一页游标(来自上一次输出)`}},maxResult:{type:`number`,valueHint:`<n>`,description:{"en-US":`Items per page`,"zh-CN":`每页条目数`}},...U},notes:[{"en-US":`A real category id is required — the default value is not resolved here. Find the id via the category list command.`,"zh-CN":`必须提供真实的类目 ID——此处不会解析 default 值。请通过类目列表命令查找 ID。`},{"en-US":`--name matches the exact file name without its extension (for a.md pass a); partial keywords return no results.`,"zh-CN":`--name 精确匹配不含扩展名的文件名(a.md 应传入 a);部分关键字不会返回结果。`},{"en-US":`Pagination is cursor-based: reuse the printed next token to continue.`,"zh-CN":`分页使用游标:复用输出中的 next token 继续查询。`}],exampleArgs:[`--category-id cate-xxx --workspace-id ws-xxx`,{"en-US":`--category-id cate-xxx --name report`,"zh-CN":`--category-id cate-xxx --name 报告`}],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={categoryId:n.categoryId,...n.name?{fileName:n.name}:{},...n.fileId?.length?{fileIds:n.fileId}:{},...n.nextToken?{nextToken:n.nextToken}:{},...n.maxResult===void 0?{}:{maxResult:n.maxResult}},o=E(r,p.listFile);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.fileList??[];if(t.quiet){for(let e of c)k(e.fileId??``);return}if(i===`text`){if(c.length===0)k(`No files found.`);else for(let e of c)k(rc([e.fileId,e.status??`-`,e.fileName,e.sizeBytes??`-`].join(` `)));let e=s.data?.nextToken;e&&k(`next: --next-token ${e}`)}else A(s,i)}}),Nl=w({description:{"en-US":`Show data-center file details (size, MD5, tags, timestamps)`,"zh-CN":`查看数据中心文件详情(大小、MD5、标签、时间戳)`},auth:`apiKey`,usageArgs:`--file-id <id> [flags]`,flags:{fileId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Data-center file ID`,"zh-CN":`数据中心文件 ID`},required:!0},...U},exampleArgs:[`--file-id file-xxx --workspace-id ws-xxx`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={fileId:n.fileId},o=E(r,p.describeFile);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data;if(t.quiet){k(c?.fileId??``);return}if(i!==`text`){A(s,i);return}k(`id: ${c?.fileId??`-`}`),k(`name: ${c?.fileName??`-`}`),k(`type: ${c?.fileType??`-`}`),k(`size: ${c?.sizeBytes??`-`}`),k(`status: ${c?.status??`-`}`),k(`parser: ${c?.parser??`-`}`),k(`category: ${c?.category??`-`}`),k(`uploaded: ${c?.uploadTime??`-`}`),k(`tags: ${(Array.isArray(c?.tags)?c.tags.join(`, `):c?.tags??`-`)||`-`}`)}});const Pl={fileId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Data-center file ID to delete`,"zh-CN":`要删除的数据中心文件 ID`},required:!0},yes:{type:`switch`,description:{"en-US":`Skip the confirmation prompt`,"zh-CN":`跳过确认提示`}},...U};async function Fl(e,t,n){let r=``;try{let i=await e.requestJson({path:E(t,p.describeFile),method:`POST`,body:{fileId:n}});i.data?.fileName&&(r=` name: ${i.data.fileName}`)}catch{}return`Delete data-center file ${n}${r}\nPERMANENT: if the file is referenced by knowledge bases, their document indexes break too. This differs from removing a document from one knowledge base.`}var Il=w({description:{"en-US":`Permanently delete a file from the data center`,"zh-CN":`从数据中心永久删除文件`},auth:`apiKey`,usageArgs:`--file-id <id> [flags]`,flags:Pl,notes:[{"en-US":`Irreversible. If knowledge bases reference this file, their related document indexes become invalid.`,"zh-CN":`该操作不可撤销。如果知识库引用了此文件,其相关文档索引将失效。`},{"en-US":`To remove a document from a single knowledge base only, use the document delete command instead.`,"zh-CN":`如果只需从单个知识库中移除文档,请改用文档删除命令。`}],exampleArgs:[`--file-id file-xxx --workspace-id ws-xxx`,`--file-id file-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={fileId:n.fileId},o=E(r,p.deleteFile);if(t.dryRun){A({endpoint:o,request:a},i);return}await yn(n.yes?``:await Fl(e.client,r,n.fileId),n.yes??!1);let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){k(`deleted: ${n.fileId}`);return}A(s,i)}}}),Ll=w({description:{"en-US":`Create a FILE data collection`,"zh-CN":`创建 FILE 数据集合`},auth:`apiKey`,usageArgs:`--name <text> --description <text> [flags]`,flags:{name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Collection name`,"zh-CN":`数据集合名称`},required:!0},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`What this collection holds and what it is for — tells collections apart in the list`,"zh-CN":`数据集合装了什么内容、给谁用,用于在列表中区分同类集合`},required:!0},storeType:{type:`string`,valueHint:`<type>`,description:{"en-US":`Storage: platform (managed) or custom (your own OSS bucket)`,"zh-CN":`存储类型:platform(托管)或 custom(自有 OSS Bucket)`}},ossRegion:{type:`string`,valueHint:`<id>`,description:{"en-US":`OSS region id (required with --store-type custom)`,"zh-CN":`OSS Region ID(使用 --store-type custom 时必填)`}},ossBucket:{type:`string`,valueHint:`<name>`,description:{"en-US":`OSS bucket name (required with --store-type custom)`,"zh-CN":`OSS Bucket 名称(使用 --store-type custom 时必填)`}},...U},notes:[{"en-US":`Store type defaults to platform (managed storage); custom uses your authorized OSS bucket.`,"zh-CN":`存储类型默认为 platform(托管存储);custom 使用已授权的自有 OSS Bucket。`},{"en-US":`Custom buckets must carry the bucket tag bailian-connector-access=ReadAndWrite (Bailian's tag-based access control); without it the server rejects creation with a misleading 'setBucketCORS failed' error.`,"zh-CN":`自定义 Bucket 必须带有 bailian-connector-access=ReadAndWrite 标签(百炼基于标签的访问控制);缺少该标签时,服务端会以容易误解的 'setBucketCORS failed' 错误拒绝创建。`},{"en-US":`There is no collection delete API — create collections deliberately.`,"zh-CN":`目前没有删除数据集合的 API——请谨慎创建。`}],exampleArgs:[{"en-US":`--name my-collection --description 'team docs' --workspace-id ws-xxx`,"zh-CN":`--name my-collection --description '团队文档' --workspace-id ws-xxx`},{"en-US":`--name oss-coll --description 'own bucket' --store-type custom --oss-region cn-beijing --oss-bucket my-bucket`,"zh-CN":`--name oss-coll --description '自有 Bucket' --store-type custom --oss-region cn-beijing --oss-bucket my-bucket`}],validate(e){if(e.name.length<1||e.name.length>20)return`--name must be 1-20 characters`;let t=e.storeType??`platform`;if(t!==`platform`&&t!==`custom`)return`--store-type must be platform or custom`;if(t===`custom`&&(!e.ossRegion||!e.ossBucket))return`--store-type custom requires --oss-region and --oss-bucket`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a=(n.storeType??`platform`).toUpperCase(),o={connectorType:`FILE`,connectorName:n.name,description:n.description,fileConnectorConfig:{storeType:a,...a===`CUSTOM`?{regionId:n.ossRegion,bucketName:n.ossBucket}:{}}},s=E(r,p.addConnector);if(t.dryRun){A({endpoint:s,request:o},i);return}let c=await e.client.requestJson({path:s,method:`POST`,body:o}),l=c.data?.connectorId;if(t.quiet){k(l??``);return}if(i===`text`){k(`created: ${l??`-`} (${n.name}, ${a})`);return}A(c,i)}}),Rl=w({description:{"en-US":`Show data collection details`,"zh-CN":`查看数据集合详情`},auth:`apiKey`,usageArgs:`(--collection-id <id> | --name <text>) [flags]`,flags:{collectionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Collection ID; alternative to --name`,"zh-CN":`数据集合 ID;与 --name 二选一`}},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Collection name; alternative to --collection-id`,"zh-CN":`数据集合名称;与 --collection-id 二选一`}},...U},exampleArgs:[`--collection-id conn-xxx --workspace-id ws-xxx`,`--name my-collection`],validate(e){if(!e.collectionId&&!e.name)return`Pass --collection-id or --name`;if(e.collectionId&&e.name)return`Use either --collection-id or --name, not both`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={...n.collectionId?{connectorId:n.collectionId}:{},...n.name?{connectorName:n.name}:{}},o=E(r,p.getConnector);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data;if(t.quiet){k(c?.connectorId??``);return}if(i===`text`){k(`id: ${c?.connectorId??`-`}`),k(`name: ${c?.connectorName??`-`}`),k(`description: ${c?.description??`-`}`);return}A(s,i)}}),zl=w({description:{"en-US":`Batch import files from an authorized OSS bucket into the data center`,"zh-CN":`从已授权的 OSS Bucket 批量导入文件到数据中心`},auth:`apiKey`,usageArgs:`--bucket <name> --region <id> --oss-key <key> [flags]`,flags:{bucket:{type:`string`,valueHint:`<name>`,description:{"en-US":`Authorized OSS bucket name`,"zh-CN":`已授权的 OSS Bucket 名称`},required:!0},region:{type:`string`,valueHint:`<id>`,description:{"en-US":`OSS region id (e.g. cn-beijing)`,"zh-CN":`OSS Region ID(例如 cn-beijing)`},required:!0},ossKey:{type:`array`,valueHint:`<key>`,description:{"en-US":`OSS object key to import (repeatable, 1-10 per call)`,"zh-CN":`要导入的 OSS Object Key(可重复,每次调用 1–10 个)`},required:!0},categoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Target data-center category (default: the default category)`,"zh-CN":`目标数据中心类目(默认:默认类目)`}},tag:{type:`array`,valueHint:`<text>`,description:{"en-US":`File tag applied to every imported file (repeatable, up to 10)`,"zh-CN":`应用于每个导入文件的标签(可重复,最多 10 个)`}},overwrite:{type:`switch`,description:{"en-US":`Overwrite files previously imported from the same OSS keys`,"zh-CN":`覆盖此前从相同 OSS Key 导入的文件`}},...U},notes:[{"en-US":`The bucket must be authorized to the platform service role beforehand; permission errors from the server are passed through with a pointer to check AliyunServiceRoleForBailian in the RAM console.`,"zh-CN":`必须预先将 Bucket 授权给平台服务角色;服务端权限错误将原样透传,并提示在 RAM 控制台检查 AliyunServiceRoleForBailian。`},{"en-US":`File names are derived from the OSS key basename.`,"zh-CN":`文件名取自 OSS Key 的 basename。`},{"en-US":`--overwrite replaces the previously imported file and issues a NEW fileId (the old one becomes invalid) — verified live.`,"zh-CN":`--overwrite 会替换此前导入的文件并生成新的 fileId(旧 fileId 将失效)——已通过真实环境验证。`}],exampleArgs:[`--bucket my-bucket --region cn-beijing --oss-key docs/a.pdf --workspace-id ws-xxx`,`--bucket my-bucket --region cn-beijing --oss-key docs/a.pdf --oss-key docs/b.docx --overwrite`],validate(e){if(e.ossKey.length>10)return`--oss-key accepts at most 10 entries per call`;if(e.tag!==void 0&&e.tag.length>10)return`--tag accepts at most 10 entries`},async run(e){let{settings:t,flags:n}=e,r=W(e),i=T(t.output),a={categoryId:n.categoryId??`default`,categoryType:`UNSTRUCTURED`,ossBucket:n.bucket,ossRegionId:n.region,fileDetails:n.ossKey.map(e=>({fileName:F(e),ossKey:e})),...n.tag?.length?{tags:n.tag}:{},...n.overwrite?{overWriteFileByOssKey:!0}:{}},o=E(r,p.addFilesFromAuthorizedOss);if(t.dryRun){A({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.addFileResultList??[],l=c.map(e=>e.fileId).filter(e=>!!e);if(t.quiet){for(let e of l)k(e);return}if(i===`text`){k(`imported: ${l.length} file(s)`);for(let e of c)k(` ${e.fileId??`-`} ${e.status??`-`} ${e.ossKey??``}`);return}A(s,i)}});function Bl(e){if(!(e instanceof t))return!1;let n=e.message;return/^MCP request failed:\s*404\b/i.test(n)?/未开通|MCP不存在|MCP_IS_INVALID/i.test(n):!1}function Vl(e){let t=[`Activate (or re-activate) the ${e} MCP in the Bailian MCP marketplace, then retry.`];return e===`WebSearch`&&t.push(`If it was previously on SSE, cancel and activate again to upgrade to Streamable HTTP.`),t.push(`Open: ${jn(e)}`),t.join(`
2739
2739
  `)}function Hl(e,n){throw!(e instanceof t)||e.hint?e:Bl(e)||n===`WebSearch`&&Qe(e)?new t(e.message,e.exitCode,Vl(n),{cause:e,api:e.api,rawResponse:e.rawResponse}):e}const Ul={target:{type:`string`,valueHint:`<server.tool>`,description:{"en-US":`Server code and tool name joined by a dot, e.g. market-cmapi00073529.SmartStockSelection`,"zh-CN":`由点号连接的 Server Code 和工具名称,例如 market-cmapi00073529.SmartStockSelection`},required:!0},arg:{type:`array`,valueHint:`<kv>`,description:{"en-US":`Tool argument (repeatable). Values parsed as JSON if possible, else string.`,"zh-CN":`工具参数(可重复)。值会优先按 JSON 解析,否则作为字符串。`}},json:{type:`string`,valueHint:`<obj>`,description:{"en-US":`Full arguments object as JSON; merged with --arg (arg wins).`,"zh-CN":`完整的 JSON 参数对象;与 --arg 合并(--arg 优先)。`}},query:{type:`string`,valueHint:`<text>`,description:{"en-US":`Shortcut for --arg query=<text> (mirrors many DashScope MCP tools).`,"zh-CN":`--arg query=<text> 的快捷方式(与许多 DashScope MCP 工具一致)。`}},url:{type:`string`,valueHint:`<url>`,description:{"en-US":`Override the MCP endpoint URL (non-Bailian). Tries Streamable HTTP first, then classic SSE on the same URL.`,"zh-CN":`覆盖 MCP Endpoint URL(非百炼)。先尝试 Streamable HTTP,再在同一 URL 上回退到传统 SSE。`}}};function Wl(e){let t=e.indexOf(`.`);if(t<=0||t===e.length-1)throw new y(`target must be <server-code>.<tool>, got "${e}".`);return{serverCode:e.slice(0,t),toolName:e.slice(t+1)}}function Gl(e){let t={};for(let n of e){let e=n.indexOf(`=`);if(e<=0)throw new y(`--arg must be in K=V form, got: ${n}`);let r=n.slice(0,e).trim(),i=n.slice(e+1);try{t[r]=JSON.parse(i)}catch{t[r]=i}}return t}function Kl(e){let t;try{t=JSON.parse(e)}catch(e){throw new y(`--json is not valid JSON — ${e.message}`)}if(!t||typeof t!=`object`||Array.isArray(t))throw new y(`--json must decode to an object.`);return t}function ql(e){let t=e.json?Kl(e.json):{};return Object.assign(t,Gl(e.arg??[])),e.query!==void 0&&(t.query=e.query),t}function Jl(e){try{Wl(e.target),ql(e)}catch(e){if(e instanceof y)return e.message;throw e}}var Yl=w({description:{"en-US":`Call a tool on an MCP server (tools/call)`,"zh-CN":`调用 MCP 服务器上的工具(tools/call)`},auth:`apiKey`,usageArgs:`--target <server.tool> [--arg k=v ...] [--json '{...}'] [--url <url>]`,flags:Ul,exampleArgs:[{"en-US":`--target market-cmapi00073529.SmartStockSelection --query "Screen consumer stocks with ROE > 15%"`,"zh-CN":`--target market-cmapi00073529.SmartStockSelection --query "筛选 ROE 大于 15% 的消费股"`},{"en-US":`--target market-cmapi00073529.FinQuery --json '{"q":"Guizhou Maotai","limit":5}'`,"zh-CN":`--target market-cmapi00073529.FinQuery --json '{"q":"贵州茅台","limit":5}'`},`--target market-cmapi00073529.SmartFundSelection --arg riskLevel=R3 --arg minScale=10`],validate:Jl,async run(e){let{settings:n,flags:r}=e,{serverCode:i,toolName:a}=Wl(r.target),o=ql(r),s=r.url||e.client.url(C(i)),c=T(n.output);if(n.dryRun){A({server:i,url:s,tool:a,arguments:o},c);return}let l;try{let n=await e.client.connectBailianMcp(i,r.url);l=n.client;let s=await n.client.callTool(a,o);if(s.isError)throw new t(`Tool error: ${s.content.map(e=>e.text||``).join(`
2740
2740
  `)}`);A(s,c)}catch(e){throw r.url||Hl(e,i),e}finally{l?.close?.()}}});const Xl=`zeldaEasy.broadscope-bailian.mcp-server.PageList`;var Zl=w({description:{"en-US":`List MCP servers activated under your Bailian account`,"zh-CN":`列出百炼账号下已激活的 MCP 服务器`},auth:`console`,usageArgs:`[flags]`,flags:{name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by server name (substring match)`,"zh-CN":`按服务器名称筛选(子字符串匹配)`}},type:{type:`string`,valueHint:`<type>`,description:{"en-US":`Server type: OFFICIAL | PRIVATE (default: OFFICIAL)`,"zh-CN":`服务器类型:OFFICIAL | PRIVATE(默认:OFFICIAL)`}},page:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Results per page (default: 30)`,"zh-CN":`每页结果数(默认:30)`}}},exampleArgs:[``,`--name finance`,`--output json`],async run(e){let{settings:n,identity:r,flags:i}=e,a=i.name||``,o=i.type||`OFFICIAL`,s=i.page||1,l=i.pageSize||30,u=T(n.output),d={reqDTO:{type:o,displayTools:!1,activated:1,pageNo:s,pageSize:l,serverName:a}};if(n.dryRun){A({api:Xl,data:d,...be(n)},u);return}let f=(await e.client.console(Xl,d))?.data??{};if(f.success===!1){let e=f.errorCode??`UnknownError`,n=f.errorMsg??e,i=e===`BailianGateway.Login.NotLogined`?`Run \`${r.binName} auth login --console\` to refresh your console session.`:void 0;throw new t(`Console gateway: ${n}`,c.AUTH,i)}let p=(f.DataV2??{}).data?.data??{},m=p.mcpServerDetailList??[];A({total:p.total??0,servers:m.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}))},u)}}),Ql=w({description:{"en-US":`List tools exposed by an MCP server (tools/list)`,"zh-CN":`列出 MCP 服务器提供的工具(tools/list)`},auth:`apiKey`,usageArgs:`--server <code> [--url <url>]`,flags:{server:{type:`string`,valueHint:`<code>`,description:{"en-US":"Server code from `mcp list` (e.g. market-cmapi00073529)","zh-CN":"来自 `mcp list` 的 Server Code(例如 market-cmapi00073529)"},required:!0},url:{type:`string`,valueHint:`<url>`,description:{"en-US":`Override the MCP endpoint URL (non-Bailian). Tries Streamable HTTP first, then classic SSE on the same URL.`,"zh-CN":`覆盖 MCP Endpoint URL(非百炼)。先尝试 Streamable HTTP,再在同一 URL 上回退到传统 SSE。`}}},exampleArgs:[`--server market-cmapi00073529`,`--server market-cmapi00073529 --output json`,`--server my-server --url https://example.com/mcp`],async run(e){let{settings:t,flags:n}=e,r=n.server,i=n.url||e.client.url(C(r)),a=T(t.output);if(t.dryRun){A({server:r,url:i,action:`tools/list`},a);return}let o;try{let t=await e.client.connectBailianMcp(r,n.url);o=t.client;let i=await t.client.listTools();A({server:r,url:t.url,tools:i},a)}catch(e){throw n.url||Hl(e,r),e}finally{o?.close?.()}}});function $l(e){Hl(e,`WebSearch`)}var eu=w({description:{"en-US":`Search the web using DashScope MCP WebSearch service`,"zh-CN":`使用 DashScope MCP WebSearch 服务搜索互联网`},auth:`apiKey`,usageArgs:`--query <text> [flags]`,flags:{query:{type:`string`,valueHint:`<text>`,description:{"en-US":`Search query text`,"zh-CN":`搜索查询文本`}},count:{type:`number`,valueHint:`<n>`,description:{"en-US":`Number of search results (default: 10)`,"zh-CN":`搜索结果数量(默认:10)`}},listTools:{type:`switch`,description:{"en-US":`List available MCP tools and exit`,"zh-CN":`列出可用的 MCP 工具并退出`}}},exampleArgs:[{"en-US":`--query "Alibaba Cloud Bailian latest features"`,"zh-CN":`--query "阿里云百炼最新功能"`},{"en-US":`--query "TypeScript 5.9 new features" --count 5`,"zh-CN":`--query "TypeScript 5.9 新功能" --count 5`},{"en-US":`--query "Today's news"`,"zh-CN":`--query "今日新闻"`},`--list-tools`],validate:e=>!e.listTools&&!e.query?`Missing required flag: --query`:void 0,async run(e){let{settings:n,flags:r}=e,i=T(n.output);if(r.listTools){if(n.dryRun){A({endpoint:e.client.url(ht()),action:`tools/list`},i);return}try{let t=e.client.mcp(ht());await t.initialize(),A({tools:await t.listTools()},i)}catch(e){$l(e)}return}let a=r.query;if(n.dryRun){A({endpoint:e.client.url(ht()),action:`tools/call`,tool:`bailian_web_search`,arguments:{query:a,count:r.count||void 0}},i);return}let o=e.client.mcp(ht()),s=bn(`Initializing search...`);n.quiet||s.start();try{await o.initialize(),n.quiet||s.update(`Searching...`);let e={query:a};r.count&&(e.count=r.count);let c=await o.callTool(`bailian_web_search`,e);if(c.isError)throw new t(`Search error: ${c.content.map(e=>e.text||``).join(`
2741
2741
  `)}`);if(n.quiet||s.stop(`Done.`),i===`json`)A(c,i);else for(let e of c.content)if(e.type===`text`&&e.text)try{let t=JSON.parse(e.text);t.pages&&Array.isArray(t.pages)?A({pages:t.pages,total:t.pages.length},i):A(t,i)}catch{A({text:e.text},i)}}catch(e){s.stop(`Failed.`),$l(e)}}});const tu=`${s.cn}/cosyvoice-clone-design-api`,nu=[{voice:`longanyang`,name:`龙安洋`,desc:`阳光大男孩`,lang:`中文/英文`},{voice:`longanhuan_v3`,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:`印尼语`}],ru={"cosyvoice-v3-flash":nu,"cosyvoice-v3-plus":nu,"cosyvoice-v3.5-flash":[],"cosyvoice-v3.5-plus":[],"cosyvoice-v2":[]};function iu(e){let t=ru[e];if(!t){process.stdout.write(`No built-in voice list available for model: ${e}\n`),process.stdout.write(`Browse voices in the console: ${gn}\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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bailian-cli-commands",
3
- "version": "1.17.0",
3
+ "version": "1.17.1",
4
4
  "description": "Command library for bailian-cli products (knowledge, memory, media, …). See https://www.npmjs.com/package/bailian-cli for usage.",
5
5
  "homepage": "https://bailian.console.aliyun.com/cli",
6
6
  "bugs": {
@@ -32,8 +32,8 @@
32
32
  "chalk": "^5.6.2",
33
33
  "smol-toml": "^1.4.2",
34
34
  "yaml": "^2.8.3",
35
- "bailian-cli-core": "1.17.0",
36
- "bailian-cli-runtime": "1.17.0"
35
+ "bailian-cli-core": "1.17.1",
36
+ "bailian-cli-runtime": "1.17.1"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@types/node": "^24",