bailian-cli-commands 1.24.0 → 1.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +30 -17
- package/dist/index.mjs +7 -6
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -2794,7 +2794,8 @@ Hint: Add --diarization flag to enable speaker separation.`,l.USAGE);let s=r.mod
|
|
|
2794
2794
|
`)}}),Dm=C({description:{"en-US":`Publish a checkpoint as a deployable model`,"zh-CN":`将 Checkpoint 发布为可部署模型`},auth:`apiKey`,usageArgs:`--job-id <id> --checkpoint <name> --model-name <name>`,flags:{jobId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Fine-tune job ID (required)`,"zh-CN":`微调任务 ID(必填)`},required:!0},checkpoint:{type:`string`,valueHint:`<name>`,description:{"en-US":"Checkpoint identifier from `finetune checkpoints` (required)","zh-CN":"来自 `finetune checkpoints` 的 Checkpoint 标识(必填)"},required:!0},modelName:{type:`string`,valueHint:`<name>`,description:{"en-US":`Deployable model name (required)`,"zh-CN":`可部署模型名称(必填)`},required:!0}},exampleArgs:[`--job-id ft-xxx --checkpoint ckpt-3 --model-name my-qwen-sft`],notes:[{"en-US":"Required before `deploy <modality> create` can target a checkpoint. The platform may auto-export the best checkpoint when a job reaches SUCCEEDED — explicit export is the canonical path for non-best checkpoints.","zh-CN":"必须先执行此操作,`deploy <modality> create` 才能使用 Checkpoint。任务达到 SUCCEEDED 后,平台可能自动导出最佳 Checkpoint;对于非最佳 Checkpoint,显式导出是标准方式。"}],async run(e){let{settings:t,flags:n}=e,r=n.jobId,i=n.checkpoint,a=n.modelName;if(t.dryRun){D({action:`finetune.export`,job_id:r,checkpoint:i,model_name:a},`json`);return}let o=await je(e.client,r,i,a),s=(o.output??o.data)?.model_name??a;t.quiet?E(s):D(o,`json`)}});const Om=new Set([`SUCCEEDED`,`FAILED`,`CANCELED`]);function km(){let e=new Date,t=e=>String(e).padStart(2,`0`);return`${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}`}function Am(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;return n===0?`${r}s`:`${n}m ${r}s`}function jm(e,t){return new Promise((n,r)=>{if(t.aborted){r(Error(`aborted`));return}let i=()=>{clearTimeout(a),r(Error(`aborted`))},a=setTimeout(()=>{t.removeEventListener(`abort`,i),n()},e);t.addEventListener(`abort`,i,{once:!0})})}var Mm=C({description:{"en-US":`Probe a fine-tune job's status (default: single non-blocking fetch). Pass --follow to poll until terminal.`,"zh-CN":`查询微调任务状态(默认:单次非阻塞获取)。使用 --follow 持续轮询至终态。`},auth:`apiKey`,usageArgs:`--job-id <id> [--follow] [--interval <sec>] [--poll-timeout <sec>]`,flags:{jobId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Fine-tune job ID (required)`,"zh-CN":`微调任务 ID(必填)`},required:!0},follow:{type:`switch`,description:{"en-US":`Block and poll until a terminal state (the legacy behavior). Without it, a single status probe is performed and the command returns immediately.`,"zh-CN":`阻塞并轮询至终态(旧版行为)。不使用时仅查询一次状态并立即返回。`}},interval:{type:`number`,valueHint:`<sec>`,description:{"en-US":`Seconds between polls with --follow (default: 10, min: 1). Ignored without --follow.`,"zh-CN":`使用 --follow 时的轮询间隔秒数(默认:10,最小:1)。未使用 --follow 时忽略。`}},pollTimeout:{type:`number`,valueHint:`<sec>`,description:{"en-US":`With --follow, stop polling after this many seconds (default: no limit). Ignored without --follow.`,"zh-CN":`使用 --follow 时,在指定秒数后停止轮询(默认:无限制)。未使用 --follow 时忽略。`}}},exampleArgs:[{"en-US":`--job-id ft-xxx # single probe, returns immediately`,"zh-CN":`--job-id ft-xxx # 单次查询,立即返回`},{"en-US":`--job-id ft-xxx --output json # status probe for agents`,"zh-CN":`--job-id ft-xxx --output json # 供智能体查询状态`},{"en-US":`--job-id ft-xxx --follow # block until terminal`,"zh-CN":`--job-id ft-xxx --follow # 阻塞等待至终态`},`--job-id ft-xxx --follow --interval 5`,`--job-id ft-xxx --follow --poll-timeout 3600`],notes:[{"en-US":`Default (no --follow) is a NON-BLOCKING single status probe: one fetch, then return immediately. This is the mode meant for agents / scripts — the caller owns the polling cadence, so the CLI never holds the terminal.`,"zh-CN":`默认不使用 --follow,执行非阻塞的单次状态查询:获取一次后立即返回。该模式适用于 Agent / 脚本,由调用方控制轮询节奏,CLI 不会持续占用终端。`},{"en-US":`A terminal FAILED/CANCELED status raises a normal CLI error (non-zero exit); a SUCCEEDED or still-running status returns 0. With --follow, exceeding --poll-timeout raises a timeout error.`,"zh-CN":`终态 FAILED/CANCELED 会触发普通 CLI 错误(非零退出码);SUCCEEDED 或仍在运行时返回 0。使用 --follow 时,超过 --poll-timeout 会触发超时错误。`},{"en-US":`Use --follow for the blocking, human-terminal-follow experience; use the default mode when driving the loop yourself (e.g. from an agent).`,"zh-CN":`需要在人工终端中阻塞跟踪时使用 --follow;自行驱动轮询(例如通过 Agent)时使用默认模式。`},{"en-US":"For per-step training output (not status), use `finetune logs`.","zh-CN":"要查看逐步骤训练输出(而非状态),请使用 `finetune logs`。"}],async run(e){let{settings:t,flags:r}=e,i=r.jobId,a=r.follow,o=Math.max(1,r.interval??10),s=r.pollTimeout;if(t.dryRun){D({action:`finetune.watch`,job_id:i,follow:a,interval:o,timeout:s},`json`);return}if(!a){let r=await Ye(e.client,i),a=r.output??r.data,o=String(a?.status??``).toUpperCase(),s=Om.has(o);if(t.quiet)E(o||`UNKNOWN`);else{let e={job_id:i,status:o||`UNKNOWN`,terminal:s,request_id:r.request_id},n=typeof a?.usage==`number`?a.usage:void 0;if(s&&n&&n>0&&a?.model){e.usage_tokens=n;let r=await vm(t,a.model,n);r&&(e.training_cost=r.cost,e.cost_basis=`${r.unitPrice} 元/${r.priceUnit}`)}D(e,`json`)}if(s&&o!==`SUCCEEDED`)throw new n(`Fine-tune job ${i} ended in status ${o}.`,l.GENERAL);return}let c=new AbortController,u=()=>c.abort();process.on(`SIGINT`,u);try{let r=``,a=Date.now();for(;;){let u=await Ye(e.client,i,c.signal),d=u.output??u.data,f=String(d?.status??``).toUpperCase();if(!t.quiet&&f!==r&&(process.stderr.write(`${km()} ${i} ${f||`UNKNOWN`}\n`),r=f),Om.has(f)){let e=Date.now()-a;if(t.quiet)E(f||`UNKNOWN`);else{let e=typeof d?.usage==`number`?d.usage:void 0,n={...u};if(e&&e>0&&d?.model){let r=await vm(t,d.model,e);r&&(n.training_cost=r.cost,n.usage_tokens=e,n.cost_basis=`${r.unitPrice} 元/${r.priceUnit}`)}D(n,`json`)}if(f!==`SUCCEEDED`)throw new n(`Fine-tune job ${i} ended in status ${f} (elapsed ${Am(e)}).`,l.GENERAL);return}if(s!==void 0&&(Date.now()-a)/1e3>=s)throw new n(`Watching fine-tune job ${i} timed out after ${Am(Date.now()-a)} (last status: ${f||`UNKNOWN`}).`,l.TIMEOUT);await jm(o*1e3,c.signal)}}catch(e){if(c.signal.aborted){process.stderr.write(`
|
|
2795
2795
|
Interrupted.
|
|
2796
2796
|
`);return}throw e}finally{process.off(`SIGINT`,u)}}});async function Nm(e){return await Le(te(e))}var Pm=C({description:{"en-US":`Query fine-tune training capability — by model (which training types it supports) or by training type (which models support it)`,"zh-CN":`查询微调训练能力:按模型查询其支持的训练类型,或按训练类型查询支持它的模型`},auth:`none`,usageArgs:`--base-model <m> | --training-type <t>`,flags:{baseModel:{type:`string`,valueHint:`<m>`,description:{"en-US":`List training types supported by this base model.`,"zh-CN":`列出该基础模型支持的训练类型。`}},trainingType:{type:`string`,valueHint:`<t>`,description:{"en-US":`List models supporting this training type: ${b.join(` | `)}.`,"zh-CN":`列出支持该训练类型的模型:${b.join(` | `)}。`}}},exampleArgs:[`--base-model qwen3-8b`,`--training-type sft-lora`,`--training-type cpt --output json`,`--training-type sft --quiet`],notes:[{"en-US":`Exactly one of --base-model / --training-type is required.`,"zh-CN":`--base-model 和 --training-type 必须且只能指定一个。`},{"en-US":"Training-type values use the `<method>` / `<method>-lora` convention: sft | sft-lora | dpo | dpo-lora | cpt. (cpt has no -lora variant server-side.)","zh-CN":"训练类型遵循 `<method>` / `<method>-lora` 命名约定:sft | sft-lora | dpo | dpo-lora | cpt。(服务端没有 cpt-lora 变体。)"},{"en-US":`Queries listFoundationModels, a public API — no console login needed.`,"zh-CN":`查询公开 API listFoundationModels,无需登录控制台。`}],validate:e=>{if(e.baseModel&&e.trainingType)return`--base-model and --training-type are mutually exclusive; pass one.`;if(!e.baseModel&&!e.trainingType)return`one of --base-model / --training-type is required.`},async run(e){let{settings:t,flags:n}=e,r=n.baseModel||void 0,i=n.trainingType||void 0;if(t.dryRun){D({action:`finetune.capability`,model:r,training_type:i},`json`);return}if(r){let e=await Pe(t,r);if(!e){D({model:r,error:`No foundation model found matching "${r}".`},`json`);return}let n=bt(e);if(t.quiet){for(let e of n)E(e);return}D({model:e.model??r,supported:n,supports:e.supports,trainingTypes:e.trainingTypes},`json`);return}if(!i||!ct(i))throw new x(`--training-type "${i}" is not supported. Valid: ${b.join(`, `)}.`);let{method:a,variant:o}=Sn(i),s=(await Nm(t)).filter(e=>At(e,i)).map(e=>({model:e.model,name:e.name??e.model})).filter(e=>!!e.model).sort((e,t)=>e.model.localeCompare(t.model));if(t.quiet){for(let e of s)E(e.model);return}D({training_type:i,method:a,variant:o,count:s.length,models:s},`json`)}});const Fm={baseModel:{type:`string`,valueHint:`<model>`,description:{"en-US":`Base model to fine-tune (e.g. qwen3-8b; not the output model name)`,"zh-CN":`待微调的基座模型(例如 qwen3-8b;不是输出模型名称)`},required:!0},datasets:{type:`string`,valueHint:`<ids>`,description:{"en-US":`Training dataset file IDs, comma-separated (required)`,"zh-CN":`训练数据集文件 ID,多个以逗号分隔(必填)`},required:!0},trainingType:{type:`string`,valueHint:`<type>`,description:{"en-US":`Training type: sft | dpo | cpt (default: sft)`,"zh-CN":`训练类型:sft | dpo | cpt(默认:sft)`}},nEpochs:{type:`number`,valueHint:`<n>`,description:{"en-US":`Number of training epochs (default: 3)`,"zh-CN":`训练轮数(默认:3)`}}},Im=[`sft`,`dpo`,`cpt`];var Lm=C({description:{"en-US":`Estimate the training cost for a fine-tune job (token billing)`,"zh-CN":`估算微调任务的训练费用(按 Token 计费)`},auth:`console`,usageArgs:`--base-model <model> --datasets <ids> [--training-type <type>] [--n-epochs <n>]`,flags:Fm,exampleArgs:[`--base-model qwen3-8b --datasets file-ft-xxx`,`--base-model qwen3-8b --datasets file-ft-xxx,file-ft-yyy --n-epochs 2`,`--base-model qwen3-8b --datasets file-ft-xxx --training-type cpt`],notes:[{"en-US":`Estimate only — the server computes token usage from the datasets; final cost is subject to the bill.`,"zh-CN":`该结果仅为估算值——服务端根据数据集计算 Token 用量,最终费用以账单为准。`},{"en-US":`Covers token billing for sft / dpo / cpt. Training-unit (MTU) billing is not supported by this command.`,"zh-CN":`支持估算 sft / dpo / cpt 的 Token 计费;此命令不支持训练单元(MTU)计费估算。`},{"en-US":`Hyper-parameters other than --n-epochs are fixed at representative defaults for estimation.`,"zh-CN":`除 --n-epochs 外,其他超参数会使用具有代表性的固定默认值进行估算。`}],async run(e){let{settings:t,flags:r}=e,i=r.baseModel,a=r.datasets.split(`,`).map(e=>e.trim()).filter(Boolean),o=(r.trainingType??`sft`).toLowerCase(),s=r.nEpochs??3;if(!Im.includes(o))throw new n(`Unsupported training type "${o}". Supported: ${Im.join(`, `)}.`,l.USAGE);if(a.length===0)throw new n(`--datasets must contain at least one file ID.`,l.USAGE);if(t.dryRun){D({action:`finetune.price`,model:i,datasets:a,trainingType:o,nEpochs:s},`json`);return}let c=await Be(e.client,i),u=Number(c.price);if(!Number.isFinite(u))throw new n(`No training price found for model "${i}".`,l.GENERAL,void 0,{rawResponse:JSON.stringify(c)});let d=o===`cpt`?await ke(e.client,i,a.join(`,`),s):await Ae(e.client,a,{nEpochs:s,batchSize:16,maxLength:8192}),f=d.estimatedDatasetConsumedTokensMinPerEpoch??0,p=d.estimatedDatasetConsumedTokensMaxPerEpoch??0,m=d.estimatedMixedConsumedTokensMinPerEpoch??0,h=d.estimatedMixedConsumedTokensMaxPerEpoch??0,g=(f+m)*s,_=(p+h)*s,v=g/1e3*u,y=_/1e3*u;D({model:i,training_type:o,n_epochs:s,unit_price:u,price_unit:c.priceUnit??`千Token`,estimated_tokens:{min:g,max:_},estimated_fee_yuan:{min:Number(v.toFixed(4)),max:Number(y.toFixed(4))},disclaimer:`Server-side estimate; final cost is subject to the bill.`},`json`)}});const Rm={modelName:{type:`string`,valueHint:`<model_name>`,description:{"en-US":`Model to deploy — fine-tuned output name or catalog model (required)`,"zh-CN":`要部署的模型:微调输出模型名称或模型目录中的模型(必填)`},required:!0},displayName:{type:`string`,valueHint:`<display_name>`,description:{"en-US":`Console display name for the deployment (required)`,"zh-CN":`部署在控制台中的显示名称(必填)`},required:!0},plan:{type:`string`,valueHint:`<plan>`,description:{"en-US":`Billing plan: lora (default, Token-billed) | ptu (Token-billed) | mu`,"zh-CN":`计费方案:lora(默认,按 Token 计费)| ptu(按 Token 计费)| mu`}},deploySpec:{type:`string`,valueHint:`<id>`,description:{"en-US":`Deploy spec (only used by plan=mu; auto-picked if omitted)`,"zh-CN":`部署规格(仅 plan=mu 使用;省略时自动选择)`}},capacity:{type:`number`,valueHint:`<n>`,description:{"en-US":`Resource units (plan=mu only; required by API; defaults to the template's unit)`,"zh-CN":`资源单元数(仅 plan=mu;API 必填;默认为模板的单元数)`}},billingMethod:{type:`string`,valueHint:`<m>`,description:{"en-US":`Billing method (plan=mu only; default "POST_PAY", the only supported value)`,"zh-CN":`计费方式(仅 plan=mu;默认且仅支持 "POST_PAY")`}},inputTpm:{type:`number`,valueHint:`<n>`,description:{"en-US":`PTU max input tokens/min (required for plan=ptu)`,"zh-CN":`PTU 每分钟最大输入 Token 数(plan=ptu 时必填)`}},outputTpm:{type:`number`,valueHint:`<n>`,description:{"en-US":`PTU max output tokens/min (required for plan=ptu)`,"zh-CN":`PTU 每分钟最大输出 Token 数(plan=ptu 时必填)`}},thinkingOutputTpm:{type:`number`,valueHint:`<n>`,description:{"en-US":`PTU max thinking-output tokens/min (optional, some models)`,"zh-CN":`PTU 每分钟最大思考输出 Token 数(部分模型可选)`}}},zm=`--model-name <model_name> --display-name <display_name> [--plan <plan>] [--deploy-spec <id>] [--capacity <n>] [--billing-method <m>] [--input-tpm <n>] [--output-tpm <n>] [--thinking-output-tpm <n>]`,Bm=[{"en-US":"Plan defaults to `lora` (Token-billed) for text/image and `mu` (model-unit-billed) for audio (CosyVoice TTS). Pass --plan to override.","zh-CN":"文本和图片部署默认使用 `lora`(按 Token 计费),音频(CosyVoice TTS)默认使用 `mu`(按模型单元计费)。可通过 --plan 覆盖。"},{"en-US":`For plan=ptu (Token-billed, provisioned throughput), --input-tpm and --output-tpm are required (the platform rejects creation without an explicit ptu_capacity despite the doc listing defaults).`,"zh-CN":`plan=ptu(按 Token 计费的预置吞吐)时,--input-tpm 和 --output-tpm 必填;即使文档列出了默认值,未显式传入 ptu_capacity 时平台也会拒绝创建。`},{"en-US":"For plan=mu, `capacity`, `billing_method` and `deploy_spec` are required. billing_method defaults to POST_PAY (only supported value); deploy_spec and capacity are auto-picked from GET /deployments/models when omitted.","zh-CN":"plan=mu 时,`capacity`、`billing_method` 和 `deploy_spec` 必填。billing_method 默认且仅支持 POST_PAY;省略 deploy_spec 和 capacity 时,会从 GET /deployments/models 自动选择。"},{"en-US":"Use `bl deploy models --source base` to inspect available templates.","zh-CN":"使用 `bl deploy models --source base` 查看可用模板。"},{"en-US":`After creation, status starts at PENDING and transitions to RUNNING. Invoke the deployed model with: bl text chat --model <deployed_model>`,"zh-CN":`创建后状态从 PENDING 开始,随后转为 RUNNING。调用已部署模型:bl text chat --model <deployed_model>`},{"en-US":"NOTE: --model-name is the model being deployed (e.g. `qwen3-8b-ft-...`). The create response also returns a `deployed_model` field — the deployment instance id (e.g. `qwen3-8b-5ecb5f068d79`). Use that id for inference (`bl text chat --model <deployed_model>`) and lifecycle commands (`deploy get/scale/pause/resume/delete --deployed-model <id>`).","zh-CN":"注意:--model-name 是要部署的模型(例如 `qwen3-8b-ft-...`)。创建响应中的 `deployed_model` 是部署实例 ID(例如 `qwen3-8b-5ecb5f068d79`),用于推理(`bl text chat --model <deployed_model>`)及生命周期命令(`deploy get/scale/pause/resume/delete --deployed-model <id>`)。"}];function Vm(e,t){let n=t.plan||be(e),r=v[n];return r?r.validateFlags(t):`Unsupported plan "${n}". Supported plans: ${Object.keys(v).join(`, `)}.`}async function Hm(e,t){let{identity:n,settings:r,flags:i}=t,a=i.modelName,o=i.displayName,s=i.plan||be(e),c={model_name:a,name:o,plan:s,...(await Vt(s).resolve({client:t.client,dryRun:r.dryRun,binName:n.binName,flags:i,model:a,name:o})).body};if(r.dryRun){D({action:`deploy.create`,body:c},`json`);return}let l=await ge(t.client,c),u=l.output??l.data;r.quiet?E(u?.deployed_model??``):D(l,`json`)}const Um=C({description:{"en-US":`Create a text model deployment`,"zh-CN":`创建文本模型部署`},auth:`apiKey`,usageArgs:zm,flags:Rm,exampleArgs:[`--model-name my-qwen-sft --display-name my-sft-test`,`--model-name qwen3.6-flash-2026-04-16 --display-name my-flash --plan ptu --input-tpm 10000 --output-tpm 1000`,`--model-name qwen3-8b --display-name my-qwen3-mu --plan mu`,`--model-name qwen3-8b --display-name my-qwen3 --plan mu --deploy-spec MU1 --capacity 2`],notes:Bm,validate:e=>Vm(`text`,e),run:e=>Hm(`text`,e)}),Wm=C({description:{"en-US":`Create an audio (TTS) model deployment`,"zh-CN":`创建音频(TTS)模型部署`},auth:`apiKey`,usageArgs:zm,flags:Rm,exampleArgs:[`--model-name my-cosyvoice-ft --display-name my-tts`,`--model-name my-cosyvoice-ft --display-name my-tts --deploy-spec dps-xxxx --capacity 1`,`--model-name my-cosyvoice-ft --display-name my-tts --dry-run`],notes:Bm,validate:e=>Vm(`audio`,e),run:e=>Hm(`audio`,e)}),Gm=C({description:{"en-US":`Create an image generation model deployment`,"zh-CN":`创建图片生成模型部署`},auth:`apiKey`,usageArgs:zm,flags:Rm,exampleArgs:[`--model-name my-wan-ft --display-name my-wan`,`--model-name my-wan-ft --display-name my-wan-mu --plan mu`,`--model-name my-wan-ft --display-name my-wan --dry-run`],notes:Bm,validate:e=>Vm(`image`,e),run:e=>Hm(`image`,e)});var Km=C({description:{"en-US":`List model deployments`,"zh-CN":`列出模型部署`},auth:`apiKey`,usageArgs:`[--page <n>] [--page-size <n>] [--status <s>]`,flags:{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: 10, max 100)`,"zh-CN":`每页结果数(默认:10,最多:100)`}},status:{type:`string`,valueHint:`<s>`,description:{"en-US":`Filter by status (PENDING / RUNNING / STOPPED / FAILED)`,"zh-CN":`按状态筛选(PENDING / RUNNING / STOPPED / FAILED)`}}},exampleArgs:[``,`--status RUNNING`,`--page-size 20 --output json`],async run(e){let{settings:t,flags:n}=e,r=n.status||void 0;if(t.dryRun){D({action:`deploy.list`,page:n.page,page_size:n.pageSize,status:r},`json`);return}let i=await gt(e.client,{pageNo:n.page,pageSize:n.pageSize,status:r}),a=i.output??i.data,o=a?.deployments??[],s=a?.total;D({items:o.map(e=>({deployed_model:e.deployed_model??``,model_name:e.model_name??``,status:e.status??``,plan:e.plan??``,capacity:e.capacity===void 0?``:String(e.capacity),created_at:e.gmt_create??``})),total:s,request_id:i.request_id},`json`)}}),qm=C({description:{"en-US":`Get details of a single model deployment`,"zh-CN":`获取单个模型部署的详情`},auth:`apiKey`,usageArgs:`--deployed-model <id>`,flags:{deployedModel:{type:`string`,valueHint:`<id>`,description:{"en-US":`Deployed model identifier (required)`,"zh-CN":`已部署模型标识(必填)`},required:!0}},exampleArgs:[`--deployed-model qwen-plus-2025-12-01-b6d61c71`,`--deployed-model qwen-plus-2025-12-01-b6d61c71 --output json`],async run(e){let{settings:t,flags:n}=e,r=n.deployedModel;if(t.dryRun){D({action:`deploy.get`,deployed_model:r},`json`);return}let i=await Je(e.client,r),a=i.output??i.data;if(!a){D({deployed_model:r,request_id:i.request_id},`json`);return}let o={deployed_model:a.deployed_model??r,deployed_name:a.name??``,model_name:a.model_name??``,base_model:a.base_model??``,status:a.status??``,plan:a.plan??``};a.model_unit_spec&&(o.model_unit_spec=a.model_unit_spec),a.charge_type&&(o.charge_type=a.charge_type),a.capacity!==void 0&&(o.capacity=a.capacity),a.base_capacity!==void 0&&(o.base_capacity=a.base_capacity),a.ready_capacity!==void 0&&(o.ready_capacity=a.ready_capacity),a.rpm_limit!==void 0&&(o.rpm_limit=a.rpm_limit),a.tpm_limit!==void 0&&(o.tpm_limit=a.tpm_limit),a.input_tpm!==void 0&&(o.input_tpm=a.input_tpm),a.output_tpm!==void 0&&(o.output_tpm=a.output_tpm),a.gmt_create&&(o.created_at=a.gmt_create),a.gmt_modified&&(o.updated_at=a.gmt_modified),D({...o,request_id:i.request_id},`json`)}}),Jm=C({description:{"en-US":`List models available for deployment`,"zh-CN":`列出可部署的模型`},auth:`apiKey`,usageArgs:`[--page <n>] [--page-size <n>] [--catalog-version <v>] [--source <custom|public>]`,flags:{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: 100)`,"zh-CN":`每页结果数(默认:100)`}},catalogVersion:{type:`string`,valueHint:`<v>`,description:{"en-US":`Catalog version filter (default: v1.0; required for new catalog models)`,"zh-CN":`模型目录版本筛选(默认:v1.0;新目录模型必填)`}},source:{type:`string`,valueHint:`<s>`,description:{"en-US":`Model source filter: custom (fine-tuned) | base (catalog) | public`,"zh-CN":`模型来源筛选:custom(微调模型)| base(模型目录)| public`}}},exampleArgs:[``,`--source base`,`--source custom --page-size 50`,`--catalog-version v1.0 --output json`],async run(e){let{settings:t,flags:n}=e,r=n.catalogVersion===``?void 0:n.catalogVersion??`v1.0`,i=n.source||void 0;if(t.dryRun){D({action:`deploy.models`,page:n.page,page_size:n.pageSize,version:r,model_source:i},`json`);return}let a=await ht(e.client,{pageNo:n.page,pageSize:n.pageSize,version:r,modelSource:i}),o=a.output??a.data,s=o?.models??[],c=o?.total;D({items:s.map(e=>{let t={model_name:e.model_name??``};return e.base_model&&(t.base_model=e.base_model),e.model_source&&(t.model_source=e.model_source),e.supported_plans&&e.supported_plans.length>0&&(t.supported_plans=e.supported_plans),e.plans&&e.plans.length>0&&(t.plans=e.plans.map(e=>{let t={plan:e.plan??``};return e.cu_specs&&e.cu_specs.length>0&&(t.cu_specs=e.cu_specs),e.templates&&e.templates.length>0&&(t.templates=e.templates.map(e=>{let t={};e.template_id&&(t.template_id=e.template_id),e.template_name&&(t.template_name=e.template_name),e.charge_type&&(t.charge_type=e.charge_type);let n=e.roles?.unified;return n?.model_unit_spec&&(t.model_unit_spec=n.model_unit_spec),n?.capacity_unit_per_instance!==void 0&&(t.capacity_unit_per_instance=n.capacity_unit_per_instance),(e.roles?.prefill||e.roles?.decode)&&(t.roles={prefill:e.roles?.prefill,decode:e.roles?.decode}),e.template_desc&&(t.template_desc=e.template_desc),t})),t})),t}),total:c,request_id:a.request_id},`json`)}}),Ym=C({description:{"en-US":`Scale a deployment's capacity`,"zh-CN":`调整部署容量`},auth:`apiKey`,usageArgs:`--deployed-model <id> --capacity <n> [--input-tpm <n>] [--output-tpm <n>]`,flags:{deployedModel:{type:`string`,valueHint:`<id>`,description:{"en-US":`Deployed model identifier (required)`,"zh-CN":`已部署模型标识(必填)`},required:!0},capacity:{type:`number`,valueHint:`<n>`,description:{"en-US":`New capacity in plan units (must be a multiple of base_capacity)`,"zh-CN":`以方案单元表示的新容量(必须是 base_capacity 的整数倍)`}},inputTpm:{type:`number`,valueHint:`<n>`,description:{"en-US":`PTU only — input tokens per minute`,"zh-CN":`仅 PTU:每分钟输入 Token 数`}},outputTpm:{type:`number`,valueHint:`<n>`,description:{"en-US":`PTU only — output tokens per minute`,"zh-CN":`仅 PTU:每分钟输出 Token 数`}}},exampleArgs:[`--deployed-model qwen-plus-...-b6d61c71 --capacity 8`,`--deployed-model dep-... --capacity 2`],validate:e=>e.capacity===void 0&&e.inputTpm===void 0&&e.outputTpm===void 0?`Provide at least one of --capacity / --input-tpm / --output-tpm.`:void 0,async run(e){let{settings:t,flags:n}=e,r=n.deployedModel,i={};if(n.capacity!==void 0&&(i.capacity=n.capacity),n.inputTpm!==void 0&&(i.input_tpm=n.inputTpm),n.outputTpm!==void 0&&(i.output_tpm=n.outputTpm),t.dryRun){D({action:`deploy.scale`,deployed_model:r,body:i},`json`);return}let a=await mn(e.client,r,i);t.quiet?E(r):D(a,`json`)}}),Xm=C({description:{"en-US":`Update a deployment's rate limits (rpm_limit / tpm_limit)`,"zh-CN":`更新部署的限流配置(rpm_limit / tpm_limit)`},auth:`apiKey`,usageArgs:`--deployed-model <id> [--rpm-limit <n>] [--tpm-limit <n>]`,flags:{deployedModel:{type:`string`,valueHint:`<id>`,description:{"en-US":`Deployed model identifier (required)`,"zh-CN":`已部署模型标识(必填)`},required:!0},rpmLimit:{type:`number`,valueHint:`<n>`,description:{"en-US":`Requests per minute`,"zh-CN":`每分钟请求数`}},tpmLimit:{type:`number`,valueHint:`<n>`,description:{"en-US":`Tokens per minute`,"zh-CN":`每分钟 Token 数`}}},exampleArgs:[`--deployed-model dep-... --rpm-limit 1000`,`--deployed-model dep-... --rpm-limit 1000 --tpm-limit 200000`],notes:[{"en-US":`At least one of --rpm-limit / --tpm-limit must be provided.`,"zh-CN":`--rpm-limit / --tpm-limit 至少需要提供一个。`}],validate:e=>e.rpmLimit===void 0&&e.tpmLimit===void 0?`Provide at least one of --rpm-limit / --tpm-limit.`:void 0,async run(e){let{settings:t,flags:n}=e,r=n.deployedModel,i={};if(n.rpmLimit!==void 0&&(i.rpm_limit=n.rpmLimit),n.tpmLimit!==void 0&&(i.tpm_limit=n.tpmLimit),t.dryRun){D({action:`deploy.update`,deployed_model:r,body:i},`json`);return}let a=await Tn(e.client,r,i);t.quiet?E(r):D(a,`json`)}}),Zm=C({description:{"en-US":`Delete a model deployment (must be STOPPED or FAILED)`,"zh-CN":`删除模型部署(状态必须为 STOPPED 或 FAILED)`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the specified model deployment and cannot be undone.`,"zh-CN":`该操作会永久删除指定的模型部署,且无法撤销。`}},usageArgs:`--deployed-model <id> [--skip-precheck]`,flags:{deployedModel:{type:`string`,valueHint:`<id>`,description:{"en-US":`Deployed model identifier (required)`,"zh-CN":`已部署模型标识(必填)`},required:!0},skipPrecheck:{type:`switch`,description:{"en-US":`Skip the local STOPPED/FAILED status precheck`,"zh-CN":`跳过本地 STOPPED/FAILED 状态预检查`}}},exampleArgs:[`--deployed-model dep-...`,`--deployed-model dep-... --dry-run`,`--deployed-model dep-... --yes`],async run(e){let{settings:t,flags:r}=e,i=r.deployedModel;if(t.dryRun){D({action:`deploy.delete`,deployed_model:i},`json`);return}if(!r.skipPrecheck)try{let t=await Je(e.client,i),r=((t.output??t.data)?.status??``).toUpperCase();if(r&&r!==`STOPPED`&&r!==`FAILED`)throw new n(`Deployment ${i} is ${r}. Only STOPPED / FAILED deployments can be deleted. Run \`bl deploy pause --deployed-model ${i}\` to pause it first, or pass --skip-precheck to attempt deletion anyway.`,l.USAGE)}catch(e){if(e instanceof n)throw e}let a=await Ce(e.client,i);t.quiet?E(i):D(a,`json`)}}),Qm=C({description:{"en-US":`Pause a running model deployment (stops billing for mu/ptu)`,"zh-CN":`暂停运行中的模型部署(mu/ptu 方案将停止计费)`},auth:`console`,usageArgs:`--deployed-model <id> [--skip-precheck]`,flags:{deployedModel:{type:`string`,valueHint:`<id>`,description:{"en-US":`Deployed model identifier (required)`,"zh-CN":`已部署模型标识(必填)`},required:!0},skipPrecheck:{type:`switch`,description:{"en-US":`Skip the local RUNNING/PENDING status precheck`,"zh-CN":`跳过本地 RUNNING/PENDING 状态预检查`}}},exampleArgs:[`--deployed-model dep-...`,`--deployed-model dep-... --skip-precheck`,`--deployed-model dep-... --dry-run`],notes:[{"en-US":"While paused, billing ceases for mu/ptu plans. Use `deploy resume` to bring it back online or `deploy delete` to remove.","zh-CN":"暂停期间,mu/ptu 方案将停止计费。使用 `deploy resume` 恢复服务,或使用 `deploy delete` 删除部署。"},{"en-US":`Precheck verifies status is RUNNING/PENDING before issuing the pause; pass --skip-precheck to bypass.`,"zh-CN":`发起暂停前会预检查部署状态是否为 RUNNING/PENDING;可传入 --skip-precheck 跳过检查。`}],async run(e){let{settings:t,flags:r}=e,i=r.deployedModel;if(t.dryRun){D({action:`deploy.pause`,deployed_model:i},`json`);return}if(!r.skipPrecheck)try{let t=Ve(await vt(e.client),i);if(t){let e=(t.status??``).toUpperCase();if(e&&e!==`RUNNING`&&e!==`PENDING`)throw new n(`Deployment ${i} is ${e}. Only RUNNING / PENDING deployments can be paused. Pass --skip-precheck to attempt the pause anyway.`,l.USAGE)}}catch(e){if(e instanceof n)throw e}let a=await yn(e.client,i);t.quiet?E(i):D({deployed_model:i,action:`pause`,...a},`json`)}}),$m=C({description:{"en-US":`Resume a paused model deployment (brings service back online)`,"zh-CN":`恢复已暂停的模型部署(使服务重新上线)`},auth:`console`,usageArgs:`--deployed-model <id> [--skip-precheck]`,flags:{deployedModel:{type:`string`,valueHint:`<id>`,description:{"en-US":`Deployed model identifier (required)`,"zh-CN":`已部署模型标识(必填)`},required:!0},skipPrecheck:{type:`switch`,description:{"en-US":`Skip the local STOPPED status precheck`,"zh-CN":`跳过本地 STOPPED 状态预检查`}}},exampleArgs:[`--deployed-model dep-...`,`--deployed-model dep-... --skip-precheck`,`--deployed-model dep-... --dry-run`],notes:[{"en-US":`Precheck verifies status is STOPPED before issuing the resume; pass --skip-precheck to bypass.`,"zh-CN":`发起恢复前会预检查部署状态是否为 STOPPED;可传入 --skip-precheck 跳过检查。`},{"en-US":`For mu/ptu plans, billing resumes once the service is back online.`,"zh-CN":`对于 mu/ptu 方案,服务重新上线后将恢复计费。`}],async run(e){let{settings:t,flags:r}=e,i=r.deployedModel;if(t.dryRun){D({action:`deploy.resume`,deployed_model:i},`json`);return}if(!r.skipPrecheck)try{let t=Ve(await vt(e.client),i);if(t){let e=(t.status??``).toUpperCase();if(e&&e!==`STOPPED`)throw new n(`Deployment ${i} is ${e}. Only STOPPED deployments can be resumed. Pass --skip-precheck to attempt the resume anyway.`,l.USAGE)}}catch(e){if(e instanceof n)throw e}let a=await vn(e.client,i);t.quiet?E(i):D({deployed_model:i,action:`resume`,...a},`json`)}});const eh={callerUacAccountId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Caller UAC account ID`,"zh-CN":`调用方 UAC 账号 ID`}},namespaceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Product namespace ID (Token Plan default: namespace-1)`,"zh-CN":`产品 Namespace ID(Token Plan 默认:namespace-1)`}}},th={workspaceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Workspace ID (env: BAILIAN_WORKSPACE_ID, config: workspace_id)`,"zh-CN":`Workspace ID(环境变量:BAILIAN_WORKSPACE_ID,配置项:workspace_id)`}}},nh={cn:`modelstudio.cn-beijing.aliyuncs.com`,intl:`modelstudio.ap-southeast-1.aliyuncs.com`};function rh(e){for(let[t,n]of Object.entries(h))if(e===n||e.startsWith(`${n}/`))return t;return`cn`}function ih(e){return nh[rh(e)]??nh.cn}function ah(e,t,r){let i=t.workspaceId||e.workspaceId;if(!i)throw new n(`Missing workspace ID.
|
|
2797
|
-
Set via: --workspace-id flag, env: BAILIAN_WORKSPACE_ID, or config: ${r} config set workspace_id <id>`,l.USAGE);return i}function oh(e,t){t.callerUacAccountId&&(e.CallerUacAccountId=t.callerUacAccountId),t.namespaceId&&(e.NamespaceId=t.namespaceId)}function sh(e,t,n){let r=ie(n),i=ih(e);return{host:i,endpoint:`https://${i}${t}${r?`?${r}`:``}`,queryString:r,queryParams:n}}async function ch(e){let{client:t,baseUrl:n,action:r,path:i,method:a,queryParams:o}=e,{host:s}=sh(n,i,o);return t.openApiQueryJson({host:s,path:i,action:r,version:`2026-02-10`,method:a,queryParams:o})}const lh=`/tokenplan/subscription/seat-detail`;var uh=C({description:{"en-US":`List Token Plan subscription seat details`,"zh-CN":`列出 Token Plan 订阅席位详情`},auth:`openapi`,usageArgs:`[flags]`,flags:{pageNo:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page size (default: 10)`,"zh-CN":`每页数量(默认:10)`}},...eh,status:{type:`array`,valueHint:`<status>`,description:{"en-US":`Seat status filter (repeatable): CREATING, NORMAL, LIMIT, RELEASE, STOP, REFUNDED`,"zh-CN":`席位状态筛选(可重复):CREATING、NORMAL、LIMIT、RELEASE、STOP、REFUNDED`}},statusListStr:{type:`string`,valueHint:`<json>`,description:{"en-US":`StatusList as JSON string, e.g. '["NORMAL"]'`,"zh-CN":`JSON 字符串格式的 StatusList,例如 '["NORMAL"]'`}},seatId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by seat ID`,"zh-CN":`按席位 ID 筛选`}},seatType:{type:`string`,valueHint:`<type>`,description:{"en-US":`Seat tier: standard, pro, or max`,"zh-CN":`席位档位:standard、pro 或 max`}},queryAssigned:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Filter by assignment: true=assigned, false=unassigned`,"zh-CN":`按分配状态筛选:true=已分配,false=未分配`}}},exampleArgs:[``,`--page-size 20 --status NORMAL`,`--query-assigned true --seat-type standard`],async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=dh(n);if(t.dryRun){let{endpoint:t,queryParams:n}=sh(e.client.baseUrl,lh,i);D({endpoint:t,query:n},r);return}let a=await ch({client:e.client,baseUrl:e.client.baseUrl,action:`GetSubscriptionSeatDetails`,path:lh,method:`GET`,queryParams:i}),o=a.Data?.Items??[];t.quiet||r===`text`?fh(o,a.Data?.Total,a.Data?.PageNo,a.Data?.PageSize):D(a,r)}});function dh(e){let t={};if(e.pageNo!==void 0&&(t.PageNo=String(e.pageNo)),e.pageSize!==void 0&&(t.PageSize=String(e.pageSize)),oh(t,e),e.statusListStr&&(t.StatusListStr=e.statusListStr),e.status&&e.status.length>0&&(t.StatusList=e.status),e.seatId&&(t.SeatId=e.seatId),e.seatType&&(t.SeatType=e.seatType),typeof e.queryAssigned==`string`&&e.queryAssigned.length>0){let r=e.queryAssigned.toLowerCase();if(r!==`true`&&r!==`false`)throw new n(`--query-assigned must be 'true' or 'false'.`,l.USAGE);t.QueryAssigned=r}return t}function fh(e,t,n,r){if(e.length===0){E(`No seats found.`);return}let i=[O(`SeatId`,18),O(`Type`,10),O(`Status`,10),O(`Assigned`,12),O(`Account`,20)].join(` `);E(i),E(`-`.repeat(i.length));for(let t of e)E([O(t.SeatId??`-`,18),O(t.SpecType??`-`,10),O(t.Status??`-`,10),O(t.AssignedStatus??`-`,12),O(t.AccountName??t.AccountId??`-`,20)].join(` `));t!==void 0&&(E(``),E(`Total: ${t}${n===void 0?``:` | Page: ${n}`}${r===void 0?``:` | PageSize: ${r}`}`))}const ph=`/tokenplan/api-keys`;var mh=C({description:{"en-US":`Create a Token Plan API key for a seat`,"zh-CN":`为席位创建 Token Plan API Key`},auth:`openapi`,usageArgs:`--account-id <id> --workspace-id <id> [flags]`,flags:{accountId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Target member account ID`,"zh-CN":`目标成员账号 ID`},required:!0},...th,description:{type:`string`,valueHint:`<text>`,description:{"en-US":`API key description`,"zh-CN":`API Key 描述`}},...eh},exampleArgs:[`--account-id acc_123 --workspace-id ws_456`,{"en-US":`--account-id acc_123 --workspace-id ws_456 --description 'Dev key'`,"zh-CN":`--account-id acc_123 --workspace-id ws_456 --description '开发密钥'`}],async run(e){let{identity:t,settings:n,flags:r}=e,i=w(n.output),a=ah(n,r,t.binName),o=hh(r,{accountId:r.accountId,workspaceId:a});if(n.dryRun){let{endpoint:t,queryParams:n}=sh(e.client.baseUrl,ph,o);D({endpoint:t,query:n},i);return}let s=await ch({client:e.client,baseUrl:e.client.baseUrl,action:`CreateTokenPlanKey`,path:ph,method:`POST`,queryParams:o});n.quiet||i===`text`?gh(s):D(s,i)}});function hh(e,t){let n={};return n.AccountId=t.accountId,n.WorkspaceId=t.workspaceId,e.description&&(n.Description=e.description),oh(n,e),n}function gh(e){let t=e.Data;if(!t){E(`API key created.`);return}E(`${O(`ApiKeyId`,14)} ${t.ApiKeyId??`-`}`),E(`${O(`MaskedApiKey`,14)} ${t.MaskedApiKey??`-`}`),t.Description&&E(`${O(`Description`,14)} ${t.Description}`),t.PlainApiKey&&(E(``),E(`PlainApiKey (shown once): ${t.PlainApiKey}`))}const _h=`/tokenplan/subscription/seat-assignments`;var vh=C({description:{"en-US":`Batch assign Token Plan seats to members`,"zh-CN":`批量向成员分配 Token Plan 席位`},auth:`openapi`,usageArgs:`--workspace-id <id> --seat-type <type> --account-id <id> [flags]`,flags:{...th,seatType:{type:`string`,valueHint:`<type>`,description:{"en-US":`Seat tier: standard, pro, or max`,"zh-CN":`席位档位:standard、pro 或 max`},required:!0},accountId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Target member account ID (repeatable)`,"zh-CN":`目标成员账号 ID(可重复)`}},...eh,locale:{type:`string`,valueHint:`<locale>`,description:{"en-US":`Language: zh-CN or en-US`,"zh-CN":`语言:zh-CN 或 en-US`}}},exampleArgs:[`--workspace-id ws_456 --seat-type standard --account-id acc_123`,`--workspace-id ws_456 --seat-type pro --account-id acc_1 --account-id acc_2`],validate:e=>e.accountId&&e.accountId.length>0?void 0:`Missing required flag: --account-id`,async run(e){let{identity:t,settings:n,flags:r}=e,i=w(n.output),a=yh(r,ah(n,r,t.binName));if(n.dryRun){let{endpoint:t,queryParams:n}=sh(e.client.baseUrl,_h,a);D({endpoint:t,query:n},i);return}let o=await ch({client:e.client,baseUrl:e.client.baseUrl,action:`BatchAssignSeats`,path:_h,method:`POST`,queryParams:a});n.quiet||i===`text`?E(`Seats assigned successfully.`):D(o,i)}});function yh(e,t){let n={};return n.WorkspaceId=t,e.seatType&&(n.SeatType=e.seatType),oh(n,e),e.locale&&(n.Locale=e.locale),e.accountId&&e.accountId.length>0&&(n.AccountIds=e.accountId),n}const bh=`/tokenplan/organization/member-additions`;var xh=C({description:{"en-US":`Add a member to a Token Plan organization`,"zh-CN":`向 Token Plan 组织添加成员`},auth:`openapi`,usageArgs:`--account-name <name> --org-id <id> [flags]`,flags:{accountName:{type:`string`,valueHint:`<name>`,description:{"en-US":`Member display name`,"zh-CN":`成员显示名称`},required:!0},orgId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Organization ID`,"zh-CN":`组织 ID`},required:!0},orgRoleCode:{type:`string`,valueHint:`<code>`,description:{"en-US":`Organization role: ORG_ADMIN or ORG_MEMBER (default: ORG_MEMBER)`,"zh-CN":`组织角色:ORG_ADMIN 或 ORG_MEMBER(默认:ORG_MEMBER)`}},specType:{type:`string`,valueHint:`<type>`,description:{"en-US":`Seat tier to assign on creation: standard, pro, or max`,"zh-CN":`创建时分配的席位档位:standard、pro 或 max`}},...eh},exampleArgs:[`--account-name dev_user --org-id org_123`,`--account-name admin_user --org-id org_123 --org-role-code ORG_ADMIN`,`--account-name member1 --org-id org_123 --spec-type standard`],async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=Sh(n);if(t.dryRun){let{endpoint:t,queryParams:n}=sh(e.client.baseUrl,bh,i);D({endpoint:t,query:n},r);return}let a=await ch({client:e.client,baseUrl:e.client.baseUrl,action:`AddOrganizationMember`,path:bh,method:`POST`,queryParams:i});t.quiet||r===`text`?Ch(a):D(a,r)}});function Sh(e){let t={};return e.accountName&&(t.AccountName=e.accountName),e.orgId&&(t.OrgId=e.orgId),t.OrgRoleCode=e.orgRoleCode||`ORG_MEMBER`,e.specType&&(t.SpecType=e.specType),oh(t,e),t}function Ch(e){let t=e.Data;if(!t){E(`Member added.`);return}E(`${O(`AccountId`,14)} ${t.AccountId??`-`}`),E(`${O(`SeatAssigned`,14)} ${String(t.SeatAssigned??`-`)}`)}function wh(e){return`version: "1"
|
|
2797
|
+
Set via: --workspace-id flag, env: BAILIAN_WORKSPACE_ID, or config: ${r} config set workspace_id <id>`,l.USAGE);return i}function oh(e,t){t.callerUacAccountId&&(e.CallerUacAccountId=t.callerUacAccountId),t.namespaceId&&(e.NamespaceId=t.namespaceId)}function sh(e,t,n){let r=ie(n),i=ih(e);return{host:i,endpoint:`https://${i}${t}${r?`?${r}`:``}`,queryString:r,queryParams:n}}async function ch(e){let{client:t,baseUrl:n,action:r,path:i,method:a,queryParams:o}=e,{host:s}=sh(n,i,o);return t.openApiQueryJson({host:s,path:i,action:r,version:`2026-02-10`,method:a,queryParams:o})}const lh=`/tokenplan/subscription/seat-detail`;var uh=C({description:{"en-US":`List Token Plan subscription seat details`,"zh-CN":`列出 Token Plan 订阅席位详情`},auth:`openapi`,usageArgs:`[flags]`,flags:{pageNo:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page size (default: 10)`,"zh-CN":`每页数量(默认:10)`}},...eh,status:{type:`array`,valueHint:`<status>`,description:{"en-US":`Seat status filter (repeatable): CREATING, NORMAL, LIMIT, RELEASE, STOP, REFUNDED`,"zh-CN":`席位状态筛选(可重复):CREATING、NORMAL、LIMIT、RELEASE、STOP、REFUNDED`}},statusListStr:{type:`string`,valueHint:`<json>`,description:{"en-US":`StatusList as JSON string, e.g. '["NORMAL"]'`,"zh-CN":`JSON 字符串格式的 StatusList,例如 '["NORMAL"]'`}},seatId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by seat ID`,"zh-CN":`按席位 ID 筛选`}},seatType:{type:`string`,valueHint:`<type>`,description:{"en-US":`Seat tier: standard, pro, or max`,"zh-CN":`席位档位:standard、pro 或 max`}},queryAssigned:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Filter by assignment: true=assigned, false=unassigned`,"zh-CN":`按分配状态筛选:true=已分配,false=未分配`}}},exampleArgs:[``,`--page-size 20 --status NORMAL`,`--query-assigned true --seat-type standard`],async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=dh(n);if(t.dryRun){let{endpoint:t,queryParams:n}=sh(e.client.baseUrl,lh,i);D({endpoint:t,query:n},r);return}let a=await ch({client:e.client,baseUrl:e.client.baseUrl,action:`GetSubscriptionSeatDetails`,path:lh,method:`GET`,queryParams:i}),o=a.Data?.Items??[];t.quiet||r===`text`?fh(o,a.Data?.Total,a.Data?.PageNo,a.Data?.PageSize):D(a,r)}});function dh(e){let t={};if(e.pageNo!==void 0&&(t.PageNo=String(e.pageNo)),e.pageSize!==void 0&&(t.PageSize=String(e.pageSize)),oh(t,e),e.statusListStr&&(t.StatusListStr=e.statusListStr),e.status&&e.status.length>0&&(t.StatusList=e.status),e.seatId&&(t.SeatId=e.seatId),e.seatType&&(t.SeatType=e.seatType),typeof e.queryAssigned==`string`&&e.queryAssigned.length>0){let r=e.queryAssigned.toLowerCase();if(r!==`true`&&r!==`false`)throw new n(`--query-assigned must be 'true' or 'false'.`,l.USAGE);t.QueryAssigned=r}return t}function fh(e,t,n,r){if(e.length===0){E(`No seats found.`);return}let i=[O(`SeatId`,18),O(`Type`,10),O(`Status`,10),O(`Assigned`,12),O(`Account`,20)].join(` `);E(i),E(`-`.repeat(i.length));for(let t of e)E([O(t.SeatId??`-`,18),O(t.SpecType??`-`,10),O(t.Status??`-`,10),O(t.AssignedStatus??`-`,12),O(t.AccountName??t.AccountId??`-`,20)].join(` `));t!==void 0&&(E(``),E(`Total: ${t}${n===void 0?``:` | Page: ${n}`}${r===void 0?``:` | PageSize: ${r}`}`))}const ph=`/tokenplan/api-keys`;var mh=C({description:{"en-US":`Create a Token Plan API key for a seat`,"zh-CN":`为席位创建 Token Plan API Key`},auth:`openapi`,usageArgs:`--account-id <id> --workspace-id <id> [flags]`,flags:{accountId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Target member account ID`,"zh-CN":`目标成员账号 ID`},required:!0},...th,description:{type:`string`,valueHint:`<text>`,description:{"en-US":`API key description`,"zh-CN":`API Key 描述`}},...eh},exampleArgs:[`--account-id acc_123 --workspace-id ws_456`,{"en-US":`--account-id acc_123 --workspace-id ws_456 --description 'Dev key'`,"zh-CN":`--account-id acc_123 --workspace-id ws_456 --description '开发密钥'`}],async run(e){let{identity:t,settings:n,flags:r}=e,i=w(n.output),a=ah(n,r,t.binName),o=hh(r,{accountId:r.accountId,workspaceId:a});if(n.dryRun){let{endpoint:t,queryParams:n}=sh(e.client.baseUrl,ph,o);D({endpoint:t,query:n},i);return}let s=await ch({client:e.client,baseUrl:e.client.baseUrl,action:`CreateTokenPlanKey`,path:ph,method:`POST`,queryParams:o});n.quiet||i===`text`?gh(s):D(s,i)}});function hh(e,t){let n={};return n.AccountId=t.accountId,n.WorkspaceId=t.workspaceId,e.description&&(n.Description=e.description),oh(n,e),n}function gh(e){let t=e.Data;if(!t){E(`API key created.`);return}E(`${O(`ApiKeyId`,14)} ${t.ApiKeyId??`-`}`),E(`${O(`MaskedApiKey`,14)} ${t.MaskedApiKey??`-`}`),t.Description&&E(`${O(`Description`,14)} ${t.Description}`),t.PlainApiKey&&(E(``),E(`PlainApiKey (shown once): ${t.PlainApiKey}`))}const _h=`/tokenplan/subscription/seat-assignments`;var vh=C({description:{"en-US":`Batch assign Token Plan seats to members`,"zh-CN":`批量向成员分配 Token Plan 席位`},auth:`openapi`,usageArgs:`--workspace-id <id> --seat-type <type> --account-id <id> [flags]`,flags:{...th,seatType:{type:`string`,valueHint:`<type>`,description:{"en-US":`Seat tier: standard, pro, or max`,"zh-CN":`席位档位:standard、pro 或 max`},required:!0},accountId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Target member account ID (repeatable)`,"zh-CN":`目标成员账号 ID(可重复)`}},...eh,locale:{type:`string`,valueHint:`<locale>`,description:{"en-US":`Language: zh-CN or en-US`,"zh-CN":`语言:zh-CN 或 en-US`}}},exampleArgs:[`--workspace-id ws_456 --seat-type standard --account-id acc_123`,`--workspace-id ws_456 --seat-type pro --account-id acc_1 --account-id acc_2`],validate:e=>e.accountId&&e.accountId.length>0?void 0:`Missing required flag: --account-id`,async run(e){let{identity:t,settings:n,flags:r}=e,i=w(n.output),a=yh(r,ah(n,r,t.binName));if(n.dryRun){let{endpoint:t,queryParams:n}=sh(e.client.baseUrl,_h,a);D({endpoint:t,query:n},i);return}let o=await ch({client:e.client,baseUrl:e.client.baseUrl,action:`BatchAssignSeats`,path:_h,method:`POST`,queryParams:a});n.quiet||i===`text`?E(`Seats assigned successfully.`):D(o,i)}});function yh(e,t){let n={};return n.WorkspaceId=t,e.seatType&&(n.SeatType=e.seatType),oh(n,e),e.locale&&(n.Locale=e.locale),e.accountId&&e.accountId.length>0&&(n.AccountIds=e.accountId),n}const bh=`/tokenplan/organization/member-additions`;var xh=C({description:{"en-US":`Add a member to a Token Plan organization`,"zh-CN":`向 Token Plan 组织添加成员`},auth:`openapi`,usageArgs:`--account-name <name> --org-id <id> [flags]`,flags:{accountName:{type:`string`,valueHint:`<name>`,description:{"en-US":`Member display name`,"zh-CN":`成员显示名称`},required:!0},orgId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Organization ID`,"zh-CN":`组织 ID`},required:!0},orgRoleCode:{type:`string`,valueHint:`<code>`,description:{"en-US":`Organization role: ORG_ADMIN or ORG_MEMBER (default: ORG_MEMBER)`,"zh-CN":`组织角色:ORG_ADMIN 或 ORG_MEMBER(默认:ORG_MEMBER)`}},specType:{type:`string`,valueHint:`<type>`,description:{"en-US":`Seat tier to assign on creation: standard, pro, or max`,"zh-CN":`创建时分配的席位档位:standard、pro 或 max`}},...eh},exampleArgs:[`--account-name dev_user --org-id org_123`,`--account-name admin_user --org-id org_123 --org-role-code ORG_ADMIN`,`--account-name member1 --org-id org_123 --spec-type standard`],async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=Sh(n);if(t.dryRun){let{endpoint:t,queryParams:n}=sh(e.client.baseUrl,bh,i);D({endpoint:t,query:n},r);return}let a=await ch({client:e.client,baseUrl:e.client.baseUrl,action:`AddOrganizationMember`,path:bh,method:`POST`,queryParams:i});t.quiet||r===`text`?Ch(a):D(a,r)}});function Sh(e){let t={};return e.accountName&&(t.AccountName=e.accountName),e.orgId&&(t.OrgId=e.orgId),t.OrgRoleCode=e.orgRoleCode||`ORG_MEMBER`,e.specType&&(t.SpecType=e.specType),oh(t,e),t}function Ch(e){let t=e.Data;if(!t){E(`Member added.`);return}E(`${O(`AccountId`,14)} ${t.AccountId??`-`}`),E(`${O(`SeatAssigned`,14)} ${String(t.SeatAssigned??`-`)}`)}const wh=`zeldaEasy.broadscope-bailian.token-plan.detail`,Th=`zeldaEasy.bailian-commerce.tokenPlan.queryTokenPlanEquityInfo`;function Eh(e,t){let n=wn(e)[t];return Array.isArray(n)?n:[]}function Dh(e,t){let n=[];for(let r of e){if(r.hasResourcePack!==!0)continue;let e=r.planCodes??[],i=t.find(t=>t.equityType&&e.includes(t.equityType)),a=i?.equityType??e[0]??``,o={planCode:a,title:r.title??a,type:r.type??``,status:i?`issued`:`issuing`,quotaUnit:r.quotaUnit??r.priceInfo?.unit??``};if(!i){n.push(o);continue}i.instanceId&&(o.instanceId=i.instanceId);let s=gf(i.totalQuota);s!==void 0&&(o.totalQuota=s);let c=gf(i.availableQuota);c!==void 0&&(o.availableQuota=c),s!==void 0&&c!==void 0&&(o.usedQuota=Math.max(s-c,0),s>0&&(o.usedPercent=Math.round(o.usedQuota/s*1e3)/10));let l=gf(i.instanceStartTime);l!==void 0&&(o.instanceStartTime=l);let u=gf(i.instanceEndTime);u!==void 0&&(o.instanceEndTime=u),n.push(o)}return n}function Oh(e){let t={label:`${e.title} (${e.planCode})`,emptyMessage:e.status===`issuing`?`Quota is being issued; issuance can take up to 5 minutes.`:`No positive quota total reported; check the Bailian Token Plan console.`};if(e.status===`issuing`)return t;if(e.totalQuota!==void 0&&e.usedQuota!==void 0){let n=e.quotaUnit?` ${e.quotaUnit}`:``;t.detail=`Used: ${V(e.usedQuota)} / ${V(e.totalQuota)}${n}`,e.totalQuota>0&&(t.percentage=e.usedQuota/e.totalQuota)}return e.instanceEndTime!==void 0&&(t.resetTime=e.instanceEndTime),t}var kh=C({description:{"en-US":`Show Token Plan harness entitlement quota usage`,"zh-CN":`查看 Token Plan harness 权益额度用量`},auth:`console`,usageArgs:`[flags]`,flags:{type:{type:`string`,valueHint:`<type>`,choices:[`official_tool`,`infrastructure`],description:{"en-US":`Filter harness list by type: official_tool, infrastructure`,"zh-CN":`按类型筛选 harness 列表:official_tool、infrastructure`}}},exampleArgs:[``,`--type official_tool`,`--output json`],async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=n.type?{type:n.type}:{},a={queryTokenPlanEquityInfoRequest:{requestId:fr()}};if(t.dryRun){D({requests:[{api:wh,data:i},{api:Th,data:a}]},r);return}let[o,s]=await Promise.all([e.client.console(wh,i),e.client.console(Th,a)]),c=Dh(Eh(o,`items`),Eh(s,`tokenPlanEquityInfos`));if(r===`json`){D({generatedAt:Date.now(),items:c},r);return}if(c.length===0){process.stdout.write(`No harness with entitlement quota found.
|
|
2798
|
+
`);return}yf(`Token Plan Harness Quota`,c.map(Oh),Date.now())}});function Ah(e){return`version: "1"
|
|
2798
2799
|
|
|
2799
2800
|
providers:
|
|
2800
2801
|
bailian:
|
|
@@ -2821,7 +2822,7 @@ agents:
|
|
|
2821
2822
|
environment: dev
|
|
2822
2823
|
tools:
|
|
2823
2824
|
builtin: [bash, read, glob, grep]
|
|
2824
|
-
`}var
|
|
2825
|
+
`}var jh=C({description:{"en-US":`Create an agents.yaml template`,"zh-CN":`创建 agents.yaml 模板`},auth:`none`,usageArgs:`[--agent-name <name>] [--file <path>] [--force]`,flags:{agentName:{type:`string`,valueHint:`<name>`,description:{"en-US":`Name of the first agent (default: assistant)`,"zh-CN":`第一个 Agent 的名称(默认:assistant)`}},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Output config path (default: agents.yaml)`,"zh-CN":`输出配置路径(默认:agents.yaml)`}},force:{type:`switch`,description:{"en-US":`Overwrite an existing config file`,"zh-CN":`覆盖已有配置文件`}}},exampleArgs:[``,`--agent-name assistant`],async run(e){let{settings:t,flags:r}=e,i=w(t.output),a=r.agentName??`assistant`,o=r.file??`agents.yaml`;if(k(o)&&!r.force)throw new n(`${M(o)} already exists.`,l.USAGE,`Pass --force to overwrite.`);let s=`.gitignore`;if(t.dryRun){let e=!0;k(s)&&(e=!(await Zr(s,`utf8`)).includes(`agents.state.json`)),D({would_create:o,provider:`bailian`,agent:a,would_update_gitignore:e},i);return}if(await ti(o,Ah({agentName:a}),`utf8`),k(s)){let e=await Zr(s,`utf8`);e.includes(`agents.state.json`)||await ti(s,e+`
|
|
2825
2826
|
# agents
|
|
2826
2827
|
agents.state.json
|
|
2827
2828
|
.openagentpack/versions/
|
|
@@ -2830,9 +2831,9 @@ agents.state.json
|
|
|
2830
2831
|
agents.state.json
|
|
2831
2832
|
.openagentpack/versions/
|
|
2832
2833
|
.env
|
|
2833
|
-
`,`utf8`);i===`json`?D({created:o,provider:`bailian`,agent:a},i):(E(`Created ${M(o)}`),E("Credentials: run `bl auth login --api-key <key> --base-url <url>`, or set DASHSCOPE_API_KEY / BAILIAN_BASE_URL."),E("Next: edit agents.yaml, then run `bl managed-agent plan`."))}});const
|
|
2834
|
+
`,`utf8`);i===`json`?D({created:o,provider:`bailian`,agent:a},i):(E(`Created ${M(o)}`),E("Credentials: run `bl auth login --api-key <key> --base-url <url>`, or set DASHSCOPE_API_KEY / BAILIAN_BASE_URL."),E("Next: edit agents.yaml, then run `bl managed-agent plan`."))}});const Mh=`/api/v1/agentstudio`,Nh=[...new Set([...Object.values(oi).flatMap(e=>e.map(e=>e.key)),`BAILIAN_API_KEY`,`BAILIAN_BASE_URL`,`CLAUDE_API_KEY`,`QODER_API_KEY`])],Ph={bailian:"Run `bl auth login --api-key <key>`, pass --api-key, or set DASHSCOPE_API_KEY.",claude:`Set ANTHROPIC_API_KEY (or CLAUDE_API_KEY) in your shell or .env.`,ark:`Set ARK_API_KEY in your shell or .env.`,qoder:`Set QODER_PAT (or QODER_API_KEY) in your shell or .env.`},Fh={"en-US":`bl managed-agent supports the Bailian provider only; configurations containing other providers are rejected.`,"zh-CN":`bl managed-agent 仅支持百炼 Provider;包含其他 Provider 的配置会被拒绝。`},U=[Fh,{"en-US":"Bailian credentials come from bl's auth chain: --api-key > DASHSCOPE_API_KEY > `bl auth login` (active config profile).","zh-CN":"百炼凭证来自 bl 鉴权链:--api-key > DASHSCOPE_API_KEY > `bl auth login`(当前激活的配置 Profile)。"},{"en-US":`Resolved credentials are injected into the SDK in-memory and cleared from the environment; they never persist in process env.`,"zh-CN":`解析后的凭证仅在内存中注入 SDK,并从环境中清除;不会持久保留在进程环境变量中。`}],Ih=[Fh,{"en-US":`Runs fully offline against local files: no login or provider credentials required.`,"zh-CN":`完全离线处理本地文件:无需登录或提供 Provider 凭证。`}];function Lh(){fi();for(let e of Nh)process.env[e]===void 0&&(process.env[e]=``)}function Rh(e,t,n={}){let r=e.bailian;if(!r||typeof r!=`object`)return;let i=r,a=t.client.exportApiCredential();if(a&&(i.api_key=a.token),`base_url`in i&&(n.overrideBaseUrl||!i.base_url)){let e=t.client.baseUrl.replace(/\/+$/,``);i.base_url=e.endsWith(Mh)?e:`${e}${Mh}`}`workspace_id`in i&&!i.workspace_id&&t.settings.workspaceId&&(i.workspace_id=t.settings.workspaceId)}function zh(){for(let e of Nh)delete process.env[e]}function Bh(e){for(let t of Object.values(e)){if(!t||typeof t!=`object`)continue;let e=t;for(let[t,n]of Object.entries(e))n===null&&(e[t]=``)}}function Vh(e,t){for(let[r,i]of Object.entries(e)){if(t&&!t.includes(r)||!i||typeof i!=`object`)continue;let e=i;if(!(`api_key`in e))continue;let a=e.api_key;if(!(typeof a==`string`&&a.trim()))throw new n(`Provider '${r}' is configured but its API key is empty.`,l.AUTH,Ph[r]??`Provide credentials for provider '${r}'.`)}}function Hh(e,t){let n=M(e);return{projectId:t??A(Ir(n))}}async function Uh(e,t,n){let r=M(e),i=new si({configPath:r,statePath:t}).getStatePath(Hh(r,n));return li.load(i)}let Wh=!1;function Gh(e){if(Wh)return;let t=ai.setDefaultFetch;typeof t==`function`&&(t(ve(e)),Wh=!0)}const Kh=`bailian`;async function qh(e,t,n={}){Lh();let r=await Zi(t,n);return Bh(r.config.providers),Rh(r.config.providers,e,{overrideBaseUrl:n.overrideBailianBaseUrl}),zh(),Jh(r.config.providers),(n.credentials??`all`)!==`none`&&Vh(r.config.providers),r}async function W(e,t,n={}){Gh(e);let{config:r,configPath:i,projectName:a}=await qh(e,t,n);return{...mi({projectName:a,config:r,state:await Uh(i,n.statePath,a),configPath:i,providers:r.providers}),configPath:i}}function Jh(e){let t=Object.keys(e).filter(e=>e!==Kh);if(t.length>0){let e=t.join(`, `);throw new n(`bl managed-agent only supports provider '${Kh}'; remove unsupported providers: ${e}. / bl managed-agent 仅支持 Provider '${Kh}';请移除不支持的 Provider:${e}。`,l.USAGE)}if(!(`bailian`in e))throw new n(`bl managed-agent requires a '${Kh}' provider configuration. / bl managed-agent 需要配置 Provider '${Kh}'。`,l.USAGE)}function Yh(e){let t=e;return typeof t.statusCode==`number`&&typeof t.responseBody==`string`}function Xh(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`)return t}catch{}return{message:e.trim()||void 0}}function Zh(e){return/did not complete within the timeout/i.test(e.message)}function Qh(e,t){let n=e.filter(e=>e.severity===`error`),r=n[0];if(!r)return t;let i=r.code?.trim()?`[${r.code}] `:``,a=n.length-1,o=a>0?` (+${a} more errors)`:``;return`${i}${r.message}${o}`}function $h(e,t,r){return e instanceof n?new n(e.message,e.exitCode,t,{api:e.api,rawResponse:e.rawResponse,cause:e.cause}):e instanceof Error?new n(e.message,l.GENERAL,t,{cause:e}):new n(typeof e==`string`&&e.trim()?e:r,l.GENERAL,t)}async function G(e){try{return await e()}catch(e){throw e instanceof n?e:e instanceof ui?Zh(e)?new n(e.message,l.TIMEOUT,"The session may still be running — check `bl managed-agent session get --session-id <id>` or `session events`."):new n(e.message,l.USAGE):e instanceof Error&&Yh(e)?St(e.statusCode,Xh(e.responseBody)):e instanceof TypeError&&e.message===`fetch failed`?e:e instanceof Error?new n(e.message,l.GENERAL):e}}var eg=C({description:{"en-US":`Validate an agents.yaml configuration (offline)`,"zh-CN":`离线验证 agents.yaml 配置`},auth:`none`,usageArgs:`[--file <path>]`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}},exampleArgs:[``,`--file agents.yaml`],notes:Ih,async run(e){let{settings:t,flags:r}=e,i=w(t.output),a=r.file??`agents.yaml`,o=await G(async()=>{let{config:t}=await qh(e,a,{credentials:`none`});return ua(t)}),s=o.filter(e=>e.severity===`error`).length;if(i===`json`)D({valid:s===0,diagnostics:o},i);else{for(let e of o){let t=e.resource?` (${e.resource.type}.${e.resource.name})`:``;E(`[${e.severity}] ${e.message}${t}`)}s===0&&E(`Configuration is valid.`)}if(s>0)throw new n(Qh(o,`Validation failed with ${s} error(s).`),l.GENERAL)}});function tg(e){return`${e.type}.${e.name} (${e.provider})`}async function K(e){let t=console.log,n=console.info,r=(...e)=>{process.stderr.write(`${e.map(e=>String(e)).join(` `)}\n`)};console.log=r,console.info=r;try{return await e()}finally{console.log=t,console.info=n}}function ng(e){process.stderr.write(`${e.message}\n`)}var rg=C({description:{"en-US":`Show what changes would be applied to agent infrastructure`,"zh-CN":`显示将应用到 Agent 基础设施的变更`},auth:`apiKey`,usageArgs:`[--file <path>] [--no-refresh] [--refresh-only]`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},noRefresh:{type:`switch`,description:{"en-US":`Skip refreshing state from remote before planning`,"zh-CN":`规划前跳过从远端刷新状态`}},refreshOnly:{type:`switch`,description:{"en-US":`Refresh state and show drift without planning remote mutations`,"zh-CN":`刷新状态并显示漂移,不规划远端变更`}}},exampleArgs:[``,`--no-refresh`],notes:[...U,{"en-US":`--no-refresh and --dry-run plan offline from local config and state: no remote requests, no state writes, provider keys are not checked.`,"zh-CN":`--no-refresh 和 --dry-run 基于本地配置与 State 离线规划:不发送远端请求、不写入 State,也不检查 Provider Key。`}],async run(e){let{settings:t,flags:r}=e,i=w(t.output),a=r.file??`agents.yaml`,o=!!r.noRefresh||t.dryRun,s=(await G(()=>K(async()=>Ji(await W(e,a,{credentials:o?`none`:`all`}),{provider:`bailian`,refresh:!o,quiet:i===`json`,onFeedback:i===`json`?void 0:ng})))).plan,c=s.diagnostics.some(e=>e.severity===`error`),u=Qh(s.diagnostics,`Plan contains errors.`);if(i===`json`){if(D(s,i),c)throw new n(u,l.GENERAL);return}for(let e of s.diagnostics)E(`[${e.severity}] ${e.code}: ${e.message}`);if(c)throw new n(u,l.GENERAL);let d=s.actions.filter(e=>e.action===`create`),f=s.actions.filter(e=>e.action===`update`),p=s.actions.filter(e=>e.action===`delete`);if(d.length+f.length+p.length===0){E(`No changes. Infrastructure is up-to-date.`),r.refreshOnly&&E(`Refresh-only mode: no remote mutations were performed.`);return}E(`
|
|
2834
2835
|
Planned actions:
|
|
2835
|
-
`);for(let e of d)E(` + ${Yh(e.address)}`);for(let e of f)E(` ~ ${Yh(e.address)}`),e.reason&&E(` ${e.reason}`);for(let e of p)E(` - ${Yh(e.address)}`);E(`\nPlan: ${d.length} to create, ${f.length} to update, ${p.length} to destroy.`),r.refreshOnly&&E(`Refresh-only mode: no remote mutations will be performed.`)}}),Qh=C({description:{"en-US":`Apply planned changes to create/update/delete agent resources`,"zh-CN":`应用规划的变更,创建、更新或删除 Agent 资源`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This applies the current plan and may create, update, or delete remote managed Agent resources.`,"zh-CN":`该操作会应用当前计划,可能创建、更新或删除远端托管 Agent 资源。`}},usageArgs:`[--file <path>] [--concurrency <n>]`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},noRefresh:{type:`switch`,description:{"en-US":`Skip refreshing state from remote before planning`,"zh-CN":`规划前跳过从远端刷新状态`}},concurrency:{type:`number`,valueHint:`<n>`,description:{"en-US":`Max independent resources to apply in parallel (default 6, max 10)`,"zh-CN":`最大并行应用资源数(默认:6,最多:10)`}}},exampleArgs:[`--yes`],notes:U,async run(e){let{settings:t,flags:r}=e,i=w(t.output),a=r.file??`agents.yaml`;if(t.dryRun){D({would_apply:{provider:`bailian`,refresh:!r.noRefresh,concurrency:r.concurrency},config_file:a,hint:"Run `managed-agent plan` to preview the exact resource changes."},i);return}let o=await G(()=>K(async()=>Ji(await W(e,a),{provider:`bailian`,refresh:!r.noRefresh,quiet:!0,onFeedback:Xh}))),s=o.plan,c=e=>{i===`json`?process.stderr.write(`${e}\n`):E(e)},u=s.diagnostics.filter(e=>e.severity===`error`);if(u.length>0){for(let e of u)c(`[error] ${e.code}: ${e.message}`);throw new n(Kh(u,`Cannot apply: resolve the errors above first.`),l.GENERAL)}let d=s.actions.filter(e=>e.action!==`no-op`);if(d.length===0){i===`json`?D({succeeded:0,failed:0,skipped:0,results:[]},i):E(`No changes. Infrastructure is up-to-date.`);return}for(let e of d)c(` ${e.action===`create`?`+`:e.action===`update`?`~`:`-`} ${Yh(e.address)}`);let f=await G(()=>K(()=>Si(o,{onFeedback:Xh,policy:`force`,concurrency:r.concurrency}))),p=f.results.filter(e=>e.status===`success`).length,m=f.results.filter(e=>e.status===`failed`),h=m.length,g=f.results.filter(e=>e.status===`skipped`).length;if(i===`json`?D({succeeded:p,failed:h,skipped:g,results:f.results},i):E(`\nApply finished: ${p} succeeded, ${h} failed, ${g} skipped.`),h>0)throw new n(m.find(e=>e.error)?.error??`Apply failed.`,l.GENERAL)}}),$h=C({description:{"en-US":`Destroy all managed agent resources tracked in state`,"zh-CN":`销毁 State 中跟踪的全部托管 Agent 资源`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This deletes every managed Agent resource tracked in state; --cascade may also delete dependent resources.`,"zh-CN":`该操作会删除 State 中跟踪的全部托管 Agent 资源;--cascade 还可能删除依赖资源。`}},usageArgs:`[--file <path>] [--cascade]`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},cascade:{type:`switch`,description:{"en-US":`Auto-delete dependent resources (e.g. sessions referencing an environment)`,"zh-CN":`自动删除依赖资源(例如引用某个环境的 Session)`}}},exampleArgs:[`--yes`,`--yes --cascade`],notes:U,async run(e){let{settings:t,flags:r}=e,i=w(t.output),a=r.file??`agents.yaml`;if(t.dryRun){D({would_destroy:{cascade:!!r.cascade},config_file:a,hint:"Run `managed-agent state list` to see the resources tracked in state."},i);return}let o=await G(()=>K(async()=>{let t=qi(await W(e,a));return{...t,resources:t.resources.filter(e=>e.address.provider===`bailian`),defaultMemoryStores:(t.defaultMemoryStores??[]).filter(e=>e.provider===`bailian`)}})),s=o.resources;if(s.length===0){i===`json`?D({destroyed:0,total:0},i):E(`No resources in state. Nothing to destroy.`);return}for(let e of s){let t=` - ${Yh(e.address)} [${e.remote_id}]`;i===`json`?process.stderr.write(`${t}\n`):E(t)}let c=await G(()=>K(()=>yi(o,{cascade:r.cascade,onCascadeRequired:async()=>!!r.cascade,onResourceResult:e=>{let t=Yh(e.resource.address);process.stderr.write(` ${e.status===`success`?`✓`:`✗`} ${t}\n`)}})));if(i===`json`?D({destroyed:c.destroyed,total:c.resources.length},i):E(`\n${c.partial?`Destroy incomplete`:`Destroy complete`}. ${c.destroyed}/${c.resources.length} resources removed.`),c.partial)throw new n(c.results.find(e=>e.status!==`success`)?.error||`Destroy incomplete: ${c.destroyed}/${c.resources.length} resources removed.`,l.GENERAL)}});const eg=`@openagentpack/playground`,tg=da(hr),ng=/running at http:\/\/localhost:(\d+)/i;async function rg(e){ag();let t=e.port??4848;if(!Number.isInteger(t)||t<=0||t>65535)throw new n(`Invalid --port '${t}'.`,l.USAGE);let r=M(e.surface===`workbench`?e.project??`.`:e.file??`agents.yaml`),i=ur(`sha256`).update(r).digest(`hex`).slice(0,16),a=await og(),o=await fg(t);if(o){if(o.projectId===i&&(a.version===void 0||o.version===a.version)){E(`Workbench already running at http://localhost:${t} (pid ${o.pid}).`),await mg(t,e.surface,e.agent,e.open);return}if(!await pg(o,t))throw new n(`Could not stop the existing Workbench process (pid ${o.pid}) on port ${t}.`,l.GENERAL,`Stop it manually or choose another --port.`)}let s=ug(e,t,r);a.fetched&&E(`Fetching ${eg} (first run may take a moment)...`);let c=gr(a.command,a.args,{env:s,stdio:[`inherit`,`pipe`,`inherit`]}),u=_g(c);try{let r=await dg(c,t,3e4,i);if(r===null)throw new n(`Workbench did not become ready in time. Check the logs above, then open http://localhost:${t}.`,l.GENERAL);E(`Workbench ready at http://localhost:${r}`),await mg(r,e.surface,e.agent,e.open);let a=await vg(c);if(a!==0)throw new n(`Workbench exited with code ${a}.`,l.GENERAL)}finally{u()}}function ig(e,t,n){if(t.status!==`valid`)return{url:e};let r=(t.agents??[]).map(e=>e.agent?.id?.trim()).filter(e=>!!e),i=n?.trim();return i?r.includes(i)?{url:`${e}/agents/${encodeURIComponent(i)}/preview`}:{url:e,warning:`Agent '${i}' was not found. Opening the project Workbench instead.`}:r.length===1?{url:`${e}/agents/${encodeURIComponent(r[0])}/preview`}:r.length>1?{url:e,warning:`This project declares multiple Agents. Opening the Workbench; rerun with --agent <id> for Preview.`}:{url:e}}function ag(){let e=Number(process.versions.node.split(`.`)[0]);if(!(Number.isFinite(e)&&e>=22))throw new n(`Managed Agent Workbench requires Node.js 22 or later.`,l.USAGE,`Upgrade Node.js for Workbench; other Bailian CLI commands continue to support Node.js 18.17+.`)}async function og(){let e=process.env.BAILIAN_MANAGED_AGENT_PLAYGROUND_BIN?.trim()||process.env.AGENTS_PLAYGROUND_BIN?.trim();if(e){if(!k(e))throw new n(`Configured Workbench binary does not exist: ${e}`,l.USAGE);return{command:process.execPath,args:[e],fetched:!1}}let{stdout:t}=await tg(`npm`,[`view`,`${eg}@${process.env.BAILIAN_MANAGED_AGENT_PLAYGROUND_VERSION?.trim()||`latest`}`,`version`,`--json`,`--prefer-online`,`--fetch-retries=0`,`--fetch-timeout=10000`],{timeout:15e3,maxBuffer:1024*1024}),r;try{r=JSON.parse(t)}catch{r=void 0}if(typeof r!=`string`||!/^\d+\.\d+\.\d+(?:-[\da-zA-Z.-]+)?(?:\+[\da-zA-Z.-]+)?$/.test(r))throw new n(`npm did not return a single valid Playground version. Specify an exact version or dist-tag. / npm 未返回唯一有效的 Playground 版本号。请指定精确版本或 dist-tag。`,l.GENERAL);let i=cg();if(i?.version===r)return i;let a=lg(process.cwd());return a&&sg(M(Ir(a),`../../package.json`))===r?{command:process.execPath,args:[a],version:r,fetched:!1}:{command:`npx`,args:[`-y`,`${eg}@${r}`],version:r,fetched:!0}}function sg(e){try{return JSON.parse(jr(e,`utf8`)).version}catch{return}}function cg(){try{let t=e(import.meta.url).resolve(`${eg}/package.json`),n=JSON.parse(jr(t,`utf8`)),r=typeof n.bin==`string`?n.bin:n.bin?.[`agents-playground`];if(!r)return;let i=M(Ir(t),r);return k(i)?{command:process.execPath,args:[i],version:n.version,fetched:!1}:void 0}catch{return}}function lg(e){let t=e;for(let e=0;e<10;e+=1){let e=M(t,`packages/playground/dist/bin/playground.js`);if(k(e))return e;let n=Ir(t);if(n===t)break;t=n}}function ug(e,t,n){let r=e.client.exportApiCredential(),i={...process.env,PORT:String(t),AGENTS_PLAYGROUND_TOKEN:dr(32).toString(`hex`)};e.surface===`workbench`?(delete i.AGENTS_CONFIG_PATH,i.AGENTS_PROJECT_ROOT=n):(delete i.AGENTS_PROJECT_ROOT,i.AGENTS_CONFIG_PATH=n),r&&(i.DASHSCOPE_API_KEY=r.token);let a=e.client.baseUrl.replace(/\/+$/,``);return i.BAILIAN_BASE_URL=a.endsWith(`/api/v1/agentstudio`)?a:`${a}/api/v1/agentstudio`,e.settings.workspaceId&&(i.BAILIAN_WORKSPACE_ID=e.settings.workspaceId),i}async function dg(e,t,n,r){let i=t,a=``;e.stdout?.on(`data`,e=>{process.stdout.write(e),a+=e.toString();let t=a.match(ng);t?.[1]&&(i=Number(t[1]))});let o=Date.now()+n;for(;Date.now()<=o;){if(e.exitCode!==null)return null;try{let e=await fetch(`http://localhost:${i}/health`,{signal:AbortSignal.timeout(1e3)});if((e.ok?await e.json():void 0)?.playground?.project_id===r)return i}catch{}await new Promise(e=>setTimeout(e,300))}return null}async function fg(e){try{let t=await fetch(`http://localhost:${e}/health`,{signal:AbortSignal.timeout(2e3)});if(!t.ok)return null;let n=await t.json();return n.playground?.pid?{version:n.playground.version??`unknown`,pid:n.playground.pid,projectId:n.playground.project_id}:null}catch{return null}}async function pg(e,t){E(`Replacing Workbench v${e.version} (pid ${e.pid}) on port ${t}...`);try{process.kill(e.pid,`SIGTERM`)}catch{return!0}for(let e=0;e<30;e+=1)if(await new Promise(e=>setTimeout(e,100)),!await fg(t))return!0;return!1}async function mg(e,t,n,r){if(!r)return;let i=t===`workbench`?{url:`http://localhost:${e}`}:await hg(e,n);i.warning&&E(`Warning: ${i.warning}`),gg(i.url)}async function hg(e,t){let n=`http://localhost:${e}`;try{let e=await fetch(`${n}/api/project`,{signal:AbortSignal.timeout(3e3)});return e.ok?ig(n,await e.json(),t):{url:n}}catch{return{url:n}}}function gg(e){let t=process.platform===`darwin`?`open`:process.platform===`win32`?`start`:`xdg-open`,n=process.platform===`win32`?[``,e]:[e];try{gr(t,n,{stdio:`ignore`,detached:!0,shell:process.platform===`win32`}).unref()}catch{E(`Could not open a browser automatically. Visit ${e}`)}}function _g(e){let t=()=>e.kill(`SIGINT`),n=()=>e.kill(`SIGTERM`);return process.on(`SIGINT`,t),process.on(`SIGTERM`,n),()=>{process.off(`SIGINT`,t),process.off(`SIGTERM`,n)}}function vg(e){return e.exitCode===null?new Promise((t,n)=>{e.once(`exit`,e=>t(e??0)),e.once(`error`,n)}):Promise.resolve(e.exitCode)}const yg=C({description:{"en-US":`Launch a Session Preview for an agents.yaml Agent`,"zh-CN":`为 agents.yaml 中的 Agent 启动会话预览`},auth:`apiKey`,usageArgs:`[--file <path>] [--agent <id>] [--port <n>] [--no-open]`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},port:{type:`number`,valueHint:`<n>`,description:{"en-US":`Local port (default: 4848)`,"zh-CN":`本地端口(默认:4848)`}},noOpen:{type:`switch`,description:{"en-US":`Do not open a browser automatically`,"zh-CN":`不自动打开浏览器`}},agent:{type:`string`,valueHint:`<id>`,description:{"en-US":`Agent to preview (required when the project declares multiple Agents)`,"zh-CN":`要预览的 Agent(项目包含多个 Agent 时需要指定)`}}},exampleArgs:[``,`--agent assistant`,`--file agents.yaml --no-open`],notes:[...U,{"en-US":`Session Preview requires Node.js 22+ and keeps using an agents.yaml source. Directory Workbench is available under managed-agent project workbench.`,"zh-CN":`会话预览需要 Node.js 22+,并继续使用 agents.yaml;目录 Workbench 位于 managed-agent project workbench。`}],async run(e){let t=e.flags.file??`agents.yaml`,n=e.flags.port??4848;if(e.settings.dryRun){D({would_launch:`playground`,config_file:t,agent:e.flags.agent,port:n,open_browser:!e.flags.noOpen},w(e.settings.output));return}await rg({file:t,agent:e.flags.agent,port:n,open:!e.flags.noOpen,surface:`preview`,client:e.client,settings:e.settings})}}),bg={project:{type:`string`,valueHint:`<directory>`,description:{"en-US":`Directory project root (default: current directory)`,"zh-CN":`目录项目根路径(默认:当前目录)`}}},xg=C({description:{"en-US":`Create a directory project or convert the local agents.yaml`,"zh-CN":`创建目录项目,或转换当前 agents.yaml`},auth:`none`,usageArgs:`[--project <directory>]`,flags:{project:{...bg.project,description:{"en-US":`Directory project root (default: ./managed-agent under the current directory)`,"zh-CN":`目录项目根路径(默认:当前目录下的 ./managed-agent)`}}},exampleArgs:[``,`--project ./my-agent`,`--project .`],notes:[{"en-US":`Without --project, creates a managed-agent/ subdirectory. Enter it before running other project commands. Use --project . to initialize in place or convert the current agents.yaml; existing project files are not overwritten.`,"zh-CN":`不传 --project 时创建 managed-agent/ 子目录;后续项目操作请先进入该目录。使用 --project . 可在当前目录初始化或转换 agents.yaml;不会覆盖已有项目文件。`},{"en-US":`New projects include Skill, File, Vault, and Environment examples under each resource directory's _examples/. They are not referenced by agent.json and are excluded from Build/Publish. Copy an example outside _examples/ to enable it, then configure its Agent reference.`,"zh-CN":`新项目在四类资源目录的 _examples/ 下生成配置示例,不写入 agent.json 引用,也不参与 Build/Publish。需要使用时,将示例复制到 _examples/ 外,再配置 Agent 引用。`}],async run(e){let t=e.flags.project??`./managed-agent`;if(e.settings.dryRun){D({would_initialize_project:t},w(e.settings.output));return}D(await ha({projectRoot:t}),w(e.settings.output))}}),Sg=C({description:{"en-US":`Validate a directory Agent project`,"zh-CN":`校验目录式 Agent 项目`},auth:`none`,usageArgs:`[--project <directory>]`,flags:bg,exampleArgs:[``,`--project ./my-agent`],async run(e){let t=await ya(e.flags.project??`.`),r=w(e.settings.output);if(r===`json`)D(Pg(t),r);else{for(let e of[...t.diagnostics,...t.warnings])E(`${e.severity}: ${e.code}: ${e.message}`);t.diagnostics.some(e=>e.severity===`error`)||E(`Project is valid (${t.project_revision.slice(0,12)}).`)}if(t.diagnostics.some(e=>e.severity===`error`))throw new n(`Directory project validation failed.`,l.GENERAL)}}),Cg=C({description:{"en-US":`Organize directory source and generate the immutable Publish Build`,"zh-CN":`整理目录源文件并生成不可变的发布 Build`},auth:`none`,notes:[{"en-US":`Build writes local project files without confirmation, including inferred resource associations and migration of plaintext Vault secrets into .env. Use --dry-run to preview without writing. Publish still requires explicit confirmation before remote changes.`,"zh-CN":`Build 无需确认即可写入本地项目文件,包括推断的资源关联及将 Vault 明文密钥移入 .env。使用 --dry-run 可只预览不写入。Publish 变更远端资源前仍需显式确认。`}],usageArgs:`[--project <directory>]`,flags:bg,exampleArgs:[``,`--dry-run`,`--project ./my-agent`],async validate(e){await G(async()=>{let t=await va(e.project??`.`);if(!(await $r(j(t,`project.json`)).catch(e=>{if(e.code===`ENOENT`)return null;throw e}))?.isFile())throw new n(`Not a project root: ${t} (project.json is missing).`,l.USAGE,`Run from the directory containing project.json, or pass --project <directory>.`)})},async run(e){let t=e.flags.project??`.`,r=await _a(t),i=w(e.settings.output);if(e.settings.dryRun){D(Pg(r),i);return}if(!r.can_build)throw new n(r.diagnostics.find(e=>e.severity===`error`)?.message??`Directory project is invalid and cannot be built.`,l.GENERAL);D({manifest:(await fa({projectRoot:t,baseRevision:r.project_revision})).manifest,organization_moves:r.organization_moves},i)}}),wg=C({description:{"en-US":`Publish the current directory-project Build and record a version`,"zh-CN":`发布当前目录项目 Build 并记录版本`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This publishes the current directory-project Build and may create, update, or delete remote managed Agent resources.`,"zh-CN":`该操作会发布当前目录项目 Build,可能创建、更新或删除远端托管 Agent 资源。`}},usageArgs:`[--project <directory>] [--no-refresh] [--concurrency <n>]`,flags:{...bg,noRefresh:{type:`switch`,description:{"en-US":`Skip remote refresh before planning`,"zh-CN":`规划前跳过远端刷新`}},concurrency:{type:`number`,valueHint:`<n>`,description:{"en-US":`Maximum parallel resource operations`,"zh-CN":`最大并行资源操作数`}}},exampleArgs:[`--yes`,`--project ./my-agent --yes`],notes:U,async run(e){zh(e);let t=e.flags.project??`.`,n=async(t,n)=>await Vh(e,t,{environment:n?.environment,overrideBailianBaseUrl:!0}),r=await G(()=>K(()=>ga(t,{provider:`bailian`,refresh:!e.flags.noRefresh,quiet:!0,onFeedback:Xh,resolveBuild:n}))),i=r.planned.plan.actions.filter(e=>e.action!==`no-op`);if(e.settings.dryRun){D({project_revision:r.project_revision,build_manifest:r.build_manifest,plan:r.planned.plan},w(e.settings.output));return}for(let e of i)E(`${e.action===`create`?`+`:e.action===`update`?`~`:`-`} ${Yh(e.address)}`);D(await G(()=>K(()=>ma({projectRoot:r.project_root,expectedProjectRevision:r.project_revision,expectedYamlHash:r.build_manifest.yaml_hash,expectedPlanFingerprint:r.plan_fingerprint,provider:`bailian`,refresh:!e.flags.noRefresh,concurrency:e.flags.concurrency,policy:`force`,onFeedback:Xh,resolveBuild:n}))),w(e.settings.output))}}),Tg=C({description:{"en-US":`Launch the directory project Workbench`,"zh-CN":`启动目录项目 Workbench`},auth:`apiKey`,usageArgs:`[--project <directory>] [--port <n>] [--no-open]`,flags:{...bg,port:{type:`number`,valueHint:`<n>`,description:{"en-US":`Local port (default: 4848)`,"zh-CN":`本地端口(默认:4848)`}},noOpen:{type:`switch`,description:{"en-US":`Do not open a browser`,"zh-CN":`不自动打开浏览器`}}},exampleArgs:[``,`--project ./my-agent --no-open`],notes:U,async run(e){let t=e.flags.project??`.`;if(e.settings.dryRun){D({would_launch:`workbench`,project_root:t,port:e.flags.port??4848},w(e.settings.output));return}await rg({project:t,port:e.flags.port??4848,open:!e.flags.noOpen,surface:`workbench`,client:e.client,settings:e.settings})}}),Eg=Og(!0),Dg=Og(!1);function Og(e){return C({description:e?{"en-US":`Enable directory project versions`,"zh-CN":`启用目录项目版本管理`}:{"en-US":`Disable directory project versions`,"zh-CN":`关闭目录项目版本管理`},auth:`none`,usageArgs:`[--project <directory>]`,flags:bg,exampleArgs:[``,`--project ./my-agent`],async run(t){let n=pa(t.flags.project??`.`);if(t.settings.dryRun){D({would_set_enabled:e,status:await n.status()},w(t.settings.output));return}D(e?await n.enable(`Enable project versions`):await n.disable(),w(t.settings.output))}})}const kg=C({description:{"en-US":`Show directory project version status`,"zh-CN":`显示目录项目版本状态`},auth:`none`,usageArgs:`[--project <directory>]`,flags:bg,exampleArgs:[``,`--project ./my-agent --output json`],async run(e){D(await pa(e.flags.project??`.`).status(),w(e.settings.output))}}),Ag=C({description:{"en-US":`List directory project versions`,"zh-CN":`列出目录项目版本`},auth:`none`,usageArgs:`[--project <directory>] [--limit <n>] [--cursor <cursor>]`,flags:{...bg,limit:{type:`number`,valueHint:`<n>`,description:{"en-US":`Maximum versions to return`,"zh-CN":`最多返回的版本数`}},cursor:{type:`string`,valueHint:`<cursor>`,description:{"en-US":`Pagination cursor`,"zh-CN":`分页游标`}}},exampleArgs:[``,`--limit 20 --output json`],async run(e){D(await pa(e.flags.project??`.`).listVersions({limit:e.flags.limit,cursor:e.flags.cursor}),w(e.settings.output))}}),jg={versionId:{type:`string`,valueHint:`<full-version>`,required:!0,description:{"en-US":`Full project version ID`,"zh-CN":`完整的项目版本 ID`}}},Mg=C({description:{"en-US":`Preview a directory project version`,"zh-CN":`预览目录项目历史版本`},auth:`none`,usageArgs:`--version-id <full-version> [--project <directory>]`,flags:{...bg,...jg},exampleArgs:[`--version-id <full-version>`],async run(e){D(await pa(e.flags.project??`.`).previewVersion(e.flags.versionId),w(e.settings.output))}}),Ng=C({description:{"en-US":`Restore a version to the project working directory`,"zh-CN":`将历史版本恢复到项目工作目录`},auth:`none`,risk:{level:`high`,message:{"en-US":`This restores the full directory source to the working tree. Version history and remote State will not move.`,"zh-CN":`该操作会将完整目录源文件恢复到工作区;版本历史和远端 State 不会移动。`}},usageArgs:`--version-id <full-version> [--project <directory>]`,flags:{...bg,...jg},exampleArgs:[`--version-id <full-version>`,`--version-id <full-version> --yes`],async run(e){let t=pa(e.flags.project??`.`),r=await t.previewVersion(e.flags.versionId);if(!r.can_restore)throw new n(r.blockers[0]??r.diagnostics[0]?.message??`Version cannot be restored.`,l.GENERAL);if(e.settings.dryRun){D({would_restore:e.flags.versionId,preview:r},w(e.settings.output));return}D(await t.restoreVersion(e.flags.versionId,{headVersion:r.base_head_version,projectRevision:r.base_project_revision}),w(e.settings.output))}});function Pg(e){return{project_root:e.project_root,project_revision:e.project_revision,source_manifest_hash:e.source_manifest_hash,yaml_hash:e.yaml_hash,diagnostics:e.diagnostics,warnings:e.warnings,organization_moves:e.organization_moves,before_yaml:`before_yaml`in e?e.before_yaml:void 0,after_yaml:e.canonical_yaml,can_build:`can_build`in e?e.can_build:void 0}}var Fg=C({description:{"en-US":`List resources tracked in agents state`,"zh-CN":`列出 Agent State 中跟踪的资源`},auth:`none`,usageArgs:`[--file <path>]`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}},exampleArgs:[``,`--file agents.yaml`],notes:Ah,async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=n.file??`agents.yaml`,a=await G(()=>K(async()=>(await W(e,i,{credentials:`none`})).state.listResources()));if(r===`json`){D({resources:a},r);return}if(a.length===0){E(`No resources tracked in state.`);return}let o=[`TYPE`,`NAME`,`PROVIDER`,`REMOTE ID`],s=a.map(e=>[e.address.type,e.address.name,e.address.provider,e.remote_id??`(local)`]);for(let e of Xn(o,s))E(e);E(`\nTotal: ${a.length}`)}}),Ig=C({description:{"en-US":`Show details of a resource in agents state`,"zh-CN":`显示 Agent State 中资源的详情`},auth:`none`,usageArgs:`--address <provider.type.name> [--file <path>]`,flags:{address:{type:`string`,valueHint:`<provider.type.name>`,description:{"en-US":`Resource state address (required)`,"zh-CN":`资源 State 地址(必填)`},required:!0},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}},exampleArgs:[`--address bailian.agent.assistant`],notes:Ah,async run(e){let{settings:t,flags:r}=e,i=w(t.output),a=r.file??`agents.yaml`,o=await G(()=>K(async()=>{let t=await W(e,a,{credentials:`none`}),n=Ki(r.address,{requireProvider:!1});return t.state.findResource(n)}));if(!o)throw new n(`Resource not found: ${r.address}`,l.GENERAL);i===`json`?D(o,i):E(JSON.stringify(o,null,2))}}),Lg=C({description:{"en-US":`Remove a resource from state without destroying it remotely`,"zh-CN":`从 State 中移除资源,但不销毁远端资源`},auth:`none`,risk:{level:`high`,message:{"en-US":`This removes the resource from local state without deleting it remotely, so this project will no longer track it.`,"zh-CN":`该操作会从本地 State 中移除资源但不会删除远端资源,此项目将不再跟踪该资源。`}},usageArgs:`--address <provider.type.name> [--file <path>]`,flags:{address:{type:`string`,valueHint:`<provider.type.name>`,description:{"en-US":`Resource state address (required)`,"zh-CN":`资源 State 地址(必填)`},required:!0},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}},exampleArgs:[`--address bailian.agent.assistant --yes`],notes:Ah,async run(e){let{settings:t,flags:r}=e,i=w(t.output),a=r.file??`agents.yaml`;if(t.dryRun){await G(async()=>{Ki(r.address,{requireProvider:!1})}),D({would_remove:r.address,config_file:a},i);return}await G(()=>K(async()=>{let t=await W(e,a,{credentials:`none`}),i=Ki(r.address,{requireProvider:!1}),o=t.state.findResource(i);if(!o)throw new n(`Resource not found: ${r.address}`,l.GENERAL);t.state.removeResource(o.address),await t.state.save()}));let o=`Removed ${r.address} from state (remote resource not deleted).`;i===`json`?D({removed:r.address},i):E(o)}});const Rg={address:{type:`string`,valueHint:`<bailian.type.name>`,description:{"en-US":`Resource state address (required)`,"zh-CN":`资源 State 地址(必填)`},required:!0},remoteId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Existing remote resource ID to import (required)`,"zh-CN":`要导入的已有远端资源 ID(必填)`},required:!0},resourceVersion:{type:`number`,valueHint:`<n>`,description:{"en-US":`Resource version (for versioned resources like agents)`,"zh-CN":`资源版本(用于 Agent 等带版本的资源)`}},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}};function zg(e){let t=Ki(e,{requireProvider:!0});if(t.provider!==`bailian`)throw new n(`bl managed-agent can import only Bailian resources; address provider was '${t.provider}'. / bl managed-agent 只能导入百炼资源;地址中的 Provider 为 '${t.provider}'。`,l.USAGE);return t}var Bg=C({description:{"en-US":`Import an existing remote resource into agents state`,"zh-CN":`将已有远端资源导入 Agent State`},auth:`apiKey`,usageArgs:`--address <bailian.type.name> --remote-id <id> [--resource-version <n>] [--file <path>]`,flags:Rg,exampleArgs:[`--address bailian.agent.assistant --remote-id agent-abc123`],notes:U,async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=n.file??`agents.yaml`;if(t.dryRun){await G(async()=>{zg(n.address)}),D({would_import:n.address,remote_id:n.remoteId,resource_version:n.resourceVersion,config_file:i},r);return}await G(()=>K(async()=>{let t=zg(n.address);await Mi(await W(e,i),t,n.remoteId,{resourceVersion:n.resourceVersion})})),r===`json`?D({imported:n.address,remote_id:n.remoteId},r):E(`Imported ${n.address} (remote_id: ${n.remoteId}) into state.`)}});function Vg(e){return e.type!==`thinking`&&!(e.type===`message`&&e.role===`user`)}function Hg(e,t){t||process.stderr.write(`\n[session ${e}]\n`)}function Ug(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n?.type===`error`&&n.content?.trim())return n.content}}function Wg(e,t){if(e===`failed`)throw new n(t??`Session failed.`,l.GENERAL)}async function Gg(e,t,n={}){let r=[],i,a;for await(let n of e)if(t?r.push(n):Kg(n),n.type===`error`&&n.content?.trim()&&(a=n.content),n.type===`status`&&Pi(n.status)){i=n.status,Hg(n.status??``,t);break}t&&process.stdout.write(`${JSON.stringify({...n,events:ba(r)},null,2)}\n`),Wg(i,a)}function Kg(e){if(Vg(e))if(e.type===`message`&&e.content)process.stdout.write(e.content);else if(e.type===`tool_use`)process.stderr.write(`\n[tool] ${e.tool_name}\n`);else if(e.type===`tool_result`&&e.content){let t=e.content.length>200?`${e.content.slice(0,200)}...`:e.content;process.stderr.write(`${t}\n`)}else e.type===`status`?e.status===`running`&&process.stderr.write(`
|
|
2836
|
+
`);for(let e of d)E(` + ${tg(e.address)}`);for(let e of f)E(` ~ ${tg(e.address)}`),e.reason&&E(` ${e.reason}`);for(let e of p)E(` - ${tg(e.address)}`);E(`\nPlan: ${d.length} to create, ${f.length} to update, ${p.length} to destroy.`),r.refreshOnly&&E(`Refresh-only mode: no remote mutations will be performed.`)}}),ig=C({description:{"en-US":`Apply planned changes to create/update/delete agent resources`,"zh-CN":`应用规划的变更,创建、更新或删除 Agent 资源`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This applies the current plan and may create, update, or delete remote managed Agent resources.`,"zh-CN":`该操作会应用当前计划,可能创建、更新或删除远端托管 Agent 资源。`}},usageArgs:`[--file <path>] [--concurrency <n>]`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},noRefresh:{type:`switch`,description:{"en-US":`Skip refreshing state from remote before planning`,"zh-CN":`规划前跳过从远端刷新状态`}},concurrency:{type:`number`,valueHint:`<n>`,description:{"en-US":`Max independent resources to apply in parallel (default 6, max 10)`,"zh-CN":`最大并行应用资源数(默认:6,最多:10)`}}},exampleArgs:[`--yes`],notes:U,async run(e){let{settings:t,flags:r}=e,i=w(t.output),a=r.file??`agents.yaml`;if(t.dryRun){D({would_apply:{provider:`bailian`,refresh:!r.noRefresh,concurrency:r.concurrency},config_file:a,hint:"Run `managed-agent plan` to preview the exact resource changes."},i);return}let o=await G(()=>K(async()=>Ji(await W(e,a),{provider:`bailian`,refresh:!r.noRefresh,quiet:!0,onFeedback:ng}))),s=o.plan,c=e=>{i===`json`?process.stderr.write(`${e}\n`):E(e)},u=s.diagnostics.filter(e=>e.severity===`error`);if(u.length>0){for(let e of u)c(`[error] ${e.code}: ${e.message}`);throw new n(Qh(u,`Cannot apply: resolve the errors above first.`),l.GENERAL)}let d=s.actions.filter(e=>e.action!==`no-op`);if(d.length===0){i===`json`?D({succeeded:0,failed:0,skipped:0,results:[]},i):E(`No changes. Infrastructure is up-to-date.`);return}for(let e of d)c(` ${e.action===`create`?`+`:e.action===`update`?`~`:`-`} ${tg(e.address)}`);let f=await G(()=>K(()=>Si(o,{onFeedback:ng,policy:`force`,concurrency:r.concurrency}))),p=f.results.filter(e=>e.status===`success`).length,m=f.results.filter(e=>e.status===`failed`),h=m.length,g=f.results.filter(e=>e.status===`skipped`).length;if(i===`json`?D({succeeded:p,failed:h,skipped:g,results:f.results},i):E(`\nApply finished: ${p} succeeded, ${h} failed, ${g} skipped.`),h>0)throw new n(m.find(e=>e.error)?.error??`Apply failed.`,l.GENERAL)}}),ag=C({description:{"en-US":`Destroy all managed agent resources tracked in state`,"zh-CN":`销毁 State 中跟踪的全部托管 Agent 资源`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This deletes every managed Agent resource tracked in state; --cascade may also delete dependent resources.`,"zh-CN":`该操作会删除 State 中跟踪的全部托管 Agent 资源;--cascade 还可能删除依赖资源。`}},usageArgs:`[--file <path>] [--cascade]`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},cascade:{type:`switch`,description:{"en-US":`Auto-delete dependent resources (e.g. sessions referencing an environment)`,"zh-CN":`自动删除依赖资源(例如引用某个环境的 Session)`}}},exampleArgs:[`--yes`,`--yes --cascade`],notes:U,async run(e){let{settings:t,flags:r}=e,i=w(t.output),a=r.file??`agents.yaml`;if(t.dryRun){D({would_destroy:{cascade:!!r.cascade},config_file:a,hint:"Run `managed-agent state list` to see the resources tracked in state."},i);return}let o=await G(()=>K(async()=>{let t=qi(await W(e,a));return{...t,resources:t.resources.filter(e=>e.address.provider===`bailian`),defaultMemoryStores:(t.defaultMemoryStores??[]).filter(e=>e.provider===`bailian`)}})),s=o.resources;if(s.length===0){i===`json`?D({destroyed:0,total:0},i):E(`No resources in state. Nothing to destroy.`);return}for(let e of s){let t=` - ${tg(e.address)} [${e.remote_id}]`;i===`json`?process.stderr.write(`${t}\n`):E(t)}let c=await G(()=>K(()=>yi(o,{cascade:r.cascade,onCascadeRequired:async()=>!!r.cascade,onResourceResult:e=>{let t=tg(e.resource.address);process.stderr.write(` ${e.status===`success`?`✓`:`✗`} ${t}\n`)}})));if(i===`json`?D({destroyed:c.destroyed,total:c.resources.length},i):E(`\n${c.partial?`Destroy incomplete`:`Destroy complete`}. ${c.destroyed}/${c.resources.length} resources removed.`),c.partial)throw new n(c.results.find(e=>e.status!==`success`)?.error||`Destroy incomplete: ${c.destroyed}/${c.resources.length} resources removed.`,l.GENERAL)}});const og=`@openagentpack/playground`,sg=da(hr),cg=/running at http:\/\/localhost:(\d+)/i;async function lg(e){dg();let t=e.port??4848;if(!Number.isInteger(t)||t<=0||t>65535)throw new n(`Invalid --port '${t}'.`,l.USAGE);let r=M(e.surface===`workbench`?e.project??`.`:e.file??`agents.yaml`),i=ur(`sha256`).update(r).digest(`hex`).slice(0,16),a=await fg(),o=await vg(t);if(o){if(o.projectId===i&&(a.version===void 0||o.version===a.version)){E(`Workbench already running at http://localhost:${t} (pid ${o.pid}).`),await bg(t,e.surface,e.agent,e.open);return}if(!await yg(o,t))throw new n(`Could not stop the existing Workbench process (pid ${o.pid}) on port ${t}.`,l.GENERAL,`Stop it manually or choose another --port.`)}let s=gg(e,t,r);a.fetched&&E(`Fetching ${og} (first run may take a moment)...`);let c=gr(a.command,a.args,{env:s,stdio:[`inherit`,`pipe`,`inherit`]}),u=Cg(c);try{let r=await _g(c,t,3e4,i);if(r===null)throw new n(`Workbench did not become ready in time. Check the logs above, then open http://localhost:${t}.`,l.GENERAL);E(`Workbench ready at http://localhost:${r}`),await bg(r,e.surface,e.agent,e.open);let a=await wg(c);if(a!==0)throw new n(`Workbench exited with code ${a}.`,l.GENERAL)}finally{u()}}function ug(e,t,n){if(t.status!==`valid`)return{url:e};let r=(t.agents??[]).map(e=>e.agent?.id?.trim()).filter(e=>!!e),i=n?.trim();return i?r.includes(i)?{url:`${e}/agents/${encodeURIComponent(i)}/preview`}:{url:e,warning:`Agent '${i}' was not found. Opening the project Workbench instead.`}:r.length===1?{url:`${e}/agents/${encodeURIComponent(r[0])}/preview`}:r.length>1?{url:e,warning:`This project declares multiple Agents. Opening the Workbench; rerun with --agent <id> for Preview.`}:{url:e}}function dg(){let e=Number(process.versions.node.split(`.`)[0]);if(!(Number.isFinite(e)&&e>=22))throw new n(`Managed Agent Workbench requires Node.js 22 or later.`,l.USAGE,`Upgrade Node.js for Workbench; other Bailian CLI commands continue to support Node.js 18.17+.`)}async function fg(){let e=process.env.BAILIAN_MANAGED_AGENT_PLAYGROUND_BIN?.trim()||process.env.AGENTS_PLAYGROUND_BIN?.trim();if(e){if(!k(e))throw new n(`Configured Workbench binary does not exist: ${e}`,l.USAGE);return{command:process.execPath,args:[e],fetched:!1}}let{stdout:t}=await sg(`npm`,[`view`,`${og}@${process.env.BAILIAN_MANAGED_AGENT_PLAYGROUND_VERSION?.trim()||`latest`}`,`version`,`--json`,`--prefer-online`,`--fetch-retries=0`,`--fetch-timeout=10000`],{timeout:15e3,maxBuffer:1024*1024}),r;try{r=JSON.parse(t)}catch{r=void 0}if(typeof r!=`string`||!/^\d+\.\d+\.\d+(?:-[\da-zA-Z.-]+)?(?:\+[\da-zA-Z.-]+)?$/.test(r))throw new n(`npm did not return a single valid Playground version. Specify an exact version or dist-tag. / npm 未返回唯一有效的 Playground 版本号。请指定精确版本或 dist-tag。`,l.GENERAL);let i=mg();if(i?.version===r)return i;let a=hg(process.cwd());return a&&pg(M(Ir(a),`../../package.json`))===r?{command:process.execPath,args:[a],version:r,fetched:!1}:{command:`npx`,args:[`-y`,`${og}@${r}`],version:r,fetched:!0}}function pg(e){try{return JSON.parse(jr(e,`utf8`)).version}catch{return}}function mg(){try{let t=e(import.meta.url).resolve(`${og}/package.json`),n=JSON.parse(jr(t,`utf8`)),r=typeof n.bin==`string`?n.bin:n.bin?.[`agents-playground`];if(!r)return;let i=M(Ir(t),r);return k(i)?{command:process.execPath,args:[i],version:n.version,fetched:!1}:void 0}catch{return}}function hg(e){let t=e;for(let e=0;e<10;e+=1){let e=M(t,`packages/playground/dist/bin/playground.js`);if(k(e))return e;let n=Ir(t);if(n===t)break;t=n}}function gg(e,t,n){let r=e.client.exportApiCredential(),i={...process.env,PORT:String(t),AGENTS_PLAYGROUND_TOKEN:dr(32).toString(`hex`)};e.surface===`workbench`?(delete i.AGENTS_CONFIG_PATH,i.AGENTS_PROJECT_ROOT=n):(delete i.AGENTS_PROJECT_ROOT,i.AGENTS_CONFIG_PATH=n),r&&(i.DASHSCOPE_API_KEY=r.token);let a=e.client.baseUrl.replace(/\/+$/,``);return i.BAILIAN_BASE_URL=a.endsWith(`/api/v1/agentstudio`)?a:`${a}/api/v1/agentstudio`,e.settings.workspaceId&&(i.BAILIAN_WORKSPACE_ID=e.settings.workspaceId),i}async function _g(e,t,n,r){let i=t,a=``;e.stdout?.on(`data`,e=>{process.stdout.write(e),a+=e.toString();let t=a.match(cg);t?.[1]&&(i=Number(t[1]))});let o=Date.now()+n;for(;Date.now()<=o;){if(e.exitCode!==null)return null;try{let e=await fetch(`http://localhost:${i}/health`,{signal:AbortSignal.timeout(1e3)});if((e.ok?await e.json():void 0)?.playground?.project_id===r)return i}catch{}await new Promise(e=>setTimeout(e,300))}return null}async function vg(e){try{let t=await fetch(`http://localhost:${e}/health`,{signal:AbortSignal.timeout(2e3)});if(!t.ok)return null;let n=await t.json();return n.playground?.pid?{version:n.playground.version??`unknown`,pid:n.playground.pid,projectId:n.playground.project_id}:null}catch{return null}}async function yg(e,t){E(`Replacing Workbench v${e.version} (pid ${e.pid}) on port ${t}...`);try{process.kill(e.pid,`SIGTERM`)}catch{return!0}for(let e=0;e<30;e+=1)if(await new Promise(e=>setTimeout(e,100)),!await vg(t))return!0;return!1}async function bg(e,t,n,r){if(!r)return;let i=t===`workbench`?{url:`http://localhost:${e}`}:await xg(e,n);i.warning&&E(`Warning: ${i.warning}`),Sg(i.url)}async function xg(e,t){let n=`http://localhost:${e}`;try{let e=await fetch(`${n}/api/project`,{signal:AbortSignal.timeout(3e3)});return e.ok?ug(n,await e.json(),t):{url:n}}catch{return{url:n}}}function Sg(e){let t=process.platform===`darwin`?`open`:process.platform===`win32`?`start`:`xdg-open`,n=process.platform===`win32`?[``,e]:[e];try{gr(t,n,{stdio:`ignore`,detached:!0,shell:process.platform===`win32`}).unref()}catch{E(`Could not open a browser automatically. Visit ${e}`)}}function Cg(e){let t=()=>e.kill(`SIGINT`),n=()=>e.kill(`SIGTERM`);return process.on(`SIGINT`,t),process.on(`SIGTERM`,n),()=>{process.off(`SIGINT`,t),process.off(`SIGTERM`,n)}}function wg(e){return e.exitCode===null?new Promise((t,n)=>{e.once(`exit`,e=>t(e??0)),e.once(`error`,n)}):Promise.resolve(e.exitCode)}const Tg=C({description:{"en-US":`Launch a Session Preview for an agents.yaml Agent`,"zh-CN":`为 agents.yaml 中的 Agent 启动会话预览`},auth:`apiKey`,usageArgs:`[--file <path>] [--agent <id>] [--port <n>] [--no-open]`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},port:{type:`number`,valueHint:`<n>`,description:{"en-US":`Local port (default: 4848)`,"zh-CN":`本地端口(默认:4848)`}},noOpen:{type:`switch`,description:{"en-US":`Do not open a browser automatically`,"zh-CN":`不自动打开浏览器`}},agent:{type:`string`,valueHint:`<id>`,description:{"en-US":`Agent to preview (required when the project declares multiple Agents)`,"zh-CN":`要预览的 Agent(项目包含多个 Agent 时需要指定)`}}},exampleArgs:[``,`--agent assistant`,`--file agents.yaml --no-open`],notes:[...U,{"en-US":`Session Preview requires Node.js 22+ and keeps using an agents.yaml source. Directory Workbench is available under managed-agent project workbench.`,"zh-CN":`会话预览需要 Node.js 22+,并继续使用 agents.yaml;目录 Workbench 位于 managed-agent project workbench。`}],async run(e){let t=e.flags.file??`agents.yaml`,n=e.flags.port??4848;if(e.settings.dryRun){D({would_launch:`playground`,config_file:t,agent:e.flags.agent,port:n,open_browser:!e.flags.noOpen},w(e.settings.output));return}await lg({file:t,agent:e.flags.agent,port:n,open:!e.flags.noOpen,surface:`preview`,client:e.client,settings:e.settings})}}),Eg={project:{type:`string`,valueHint:`<directory>`,description:{"en-US":`Directory project root (default: current directory)`,"zh-CN":`目录项目根路径(默认:当前目录)`}}},Dg=C({description:{"en-US":`Create a directory project or convert the local agents.yaml`,"zh-CN":`创建目录项目,或转换当前 agents.yaml`},auth:`none`,usageArgs:`[--project <directory>]`,flags:{project:{...Eg.project,description:{"en-US":`Directory project root (default: ./managed-agent under the current directory)`,"zh-CN":`目录项目根路径(默认:当前目录下的 ./managed-agent)`}}},exampleArgs:[``,`--project ./my-agent`,`--project .`],notes:[{"en-US":`Without --project, creates a managed-agent/ subdirectory. Enter it before running other project commands. Use --project . to initialize in place or convert the current agents.yaml; existing project files are not overwritten.`,"zh-CN":`不传 --project 时创建 managed-agent/ 子目录;后续项目操作请先进入该目录。使用 --project . 可在当前目录初始化或转换 agents.yaml;不会覆盖已有项目文件。`},{"en-US":`New projects include Skill, File, Vault, and Environment examples under each resource directory's _examples/. They are not referenced by agent.json and are excluded from Build/Publish. Copy an example outside _examples/ to enable it, then configure its Agent reference.`,"zh-CN":`新项目在四类资源目录的 _examples/ 下生成配置示例,不写入 agent.json 引用,也不参与 Build/Publish。需要使用时,将示例复制到 _examples/ 外,再配置 Agent 引用。`}],async run(e){let t=e.flags.project??`./managed-agent`;if(e.settings.dryRun){D({would_initialize_project:t},w(e.settings.output));return}D(await ha({projectRoot:t}),w(e.settings.output))}}),Og=C({description:{"en-US":`Validate a directory Agent project`,"zh-CN":`校验目录式 Agent 项目`},auth:`none`,usageArgs:`[--project <directory>]`,flags:Eg,exampleArgs:[``,`--project ./my-agent`],async run(e){let t=await ya(e.flags.project??`.`),r=w(e.settings.output);if(r===`json`)D(Bg(t),r);else{for(let e of[...t.diagnostics,...t.warnings])E(`${e.severity}: ${e.code}: ${e.message}`);t.diagnostics.some(e=>e.severity===`error`)||E(`Project is valid (${t.project_revision.slice(0,12)}).`)}if(t.diagnostics.some(e=>e.severity===`error`))throw new n(`Directory project validation failed.`,l.GENERAL)}}),kg=C({description:{"en-US":`Organize directory source and generate the immutable Publish Build`,"zh-CN":`整理目录源文件并生成不可变的发布 Build`},auth:`none`,notes:[{"en-US":`Build writes local project files without confirmation, including inferred resource associations and migration of plaintext Vault secrets into .env. Use --dry-run to preview without writing. Publish still requires explicit confirmation before remote changes.`,"zh-CN":`Build 无需确认即可写入本地项目文件,包括推断的资源关联及将 Vault 明文密钥移入 .env。使用 --dry-run 可只预览不写入。Publish 变更远端资源前仍需显式确认。`}],usageArgs:`[--project <directory>]`,flags:Eg,exampleArgs:[``,`--dry-run`,`--project ./my-agent`],async validate(e){await G(async()=>{let t=await va(e.project??`.`);if(!(await $r(j(t,`project.json`)).catch(e=>{if(e.code===`ENOENT`)return null;throw e}))?.isFile())throw new n(`Not a project root: ${t} (project.json is missing).`,l.USAGE,`Run from the directory containing project.json, or pass --project <directory>.`)})},async run(e){let t=e.flags.project??`.`,r=await _a(t),i=w(e.settings.output);if(e.settings.dryRun){D(Bg(r),i);return}if(!r.can_build)throw new n(r.diagnostics.find(e=>e.severity===`error`)?.message??`Directory project is invalid and cannot be built.`,l.GENERAL);D({manifest:(await fa({projectRoot:t,baseRevision:r.project_revision})).manifest,organization_moves:r.organization_moves},i)}}),Ag=C({description:{"en-US":`Publish the current directory-project Build and record a version`,"zh-CN":`发布当前目录项目 Build 并记录版本`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This publishes the current directory-project Build and may create, update, or delete remote managed Agent resources.`,"zh-CN":`该操作会发布当前目录项目 Build,可能创建、更新或删除远端托管 Agent 资源。`}},usageArgs:`[--project <directory>] [--no-refresh] [--concurrency <n>]`,flags:{...Eg,noRefresh:{type:`switch`,description:{"en-US":`Skip remote refresh before planning`,"zh-CN":`规划前跳过远端刷新`}},concurrency:{type:`number`,valueHint:`<n>`,description:{"en-US":`Maximum parallel resource operations`,"zh-CN":`最大并行资源操作数`}}},exampleArgs:[`--yes`,`--project ./my-agent --yes`],notes:U,async run(e){Gh(e);let t=e.flags.project??`.`,n=async(t,n)=>await qh(e,t,{environment:n?.environment,overrideBailianBaseUrl:!0}),r=await G(()=>K(()=>ga(t,{provider:`bailian`,refresh:!e.flags.noRefresh,quiet:!0,onFeedback:ng,resolveBuild:n}))),i=r.planned.plan.actions.filter(e=>e.action!==`no-op`);if(e.settings.dryRun){D({project_revision:r.project_revision,build_manifest:r.build_manifest,plan:r.planned.plan},w(e.settings.output));return}for(let e of i)E(`${e.action===`create`?`+`:e.action===`update`?`~`:`-`} ${tg(e.address)}`);D(await G(()=>K(()=>ma({projectRoot:r.project_root,expectedProjectRevision:r.project_revision,expectedYamlHash:r.build_manifest.yaml_hash,expectedPlanFingerprint:r.plan_fingerprint,provider:`bailian`,refresh:!e.flags.noRefresh,concurrency:e.flags.concurrency,policy:`force`,onFeedback:ng,resolveBuild:n}))),w(e.settings.output))}}),jg=C({description:{"en-US":`Launch the directory project Workbench`,"zh-CN":`启动目录项目 Workbench`},auth:`apiKey`,usageArgs:`[--project <directory>] [--port <n>] [--no-open]`,flags:{...Eg,port:{type:`number`,valueHint:`<n>`,description:{"en-US":`Local port (default: 4848)`,"zh-CN":`本地端口(默认:4848)`}},noOpen:{type:`switch`,description:{"en-US":`Do not open a browser`,"zh-CN":`不自动打开浏览器`}}},exampleArgs:[``,`--project ./my-agent --no-open`],notes:U,async run(e){let t=e.flags.project??`.`;if(e.settings.dryRun){D({would_launch:`workbench`,project_root:t,port:e.flags.port??4848},w(e.settings.output));return}await lg({project:t,port:e.flags.port??4848,open:!e.flags.noOpen,surface:`workbench`,client:e.client,settings:e.settings})}}),Mg=Pg(!0),Ng=Pg(!1);function Pg(e){return C({description:e?{"en-US":`Enable directory project versions`,"zh-CN":`启用目录项目版本管理`}:{"en-US":`Disable directory project versions`,"zh-CN":`关闭目录项目版本管理`},auth:`none`,usageArgs:`[--project <directory>]`,flags:Eg,exampleArgs:[``,`--project ./my-agent`],async run(t){let n=pa(t.flags.project??`.`);if(t.settings.dryRun){D({would_set_enabled:e,status:await n.status()},w(t.settings.output));return}D(e?await n.enable(`Enable project versions`):await n.disable(),w(t.settings.output))}})}const Fg=C({description:{"en-US":`Show directory project version status`,"zh-CN":`显示目录项目版本状态`},auth:`none`,usageArgs:`[--project <directory>]`,flags:Eg,exampleArgs:[``,`--project ./my-agent --output json`],async run(e){D(await pa(e.flags.project??`.`).status(),w(e.settings.output))}}),Ig=C({description:{"en-US":`List directory project versions`,"zh-CN":`列出目录项目版本`},auth:`none`,usageArgs:`[--project <directory>] [--limit <n>] [--cursor <cursor>]`,flags:{...Eg,limit:{type:`number`,valueHint:`<n>`,description:{"en-US":`Maximum versions to return`,"zh-CN":`最多返回的版本数`}},cursor:{type:`string`,valueHint:`<cursor>`,description:{"en-US":`Pagination cursor`,"zh-CN":`分页游标`}}},exampleArgs:[``,`--limit 20 --output json`],async run(e){D(await pa(e.flags.project??`.`).listVersions({limit:e.flags.limit,cursor:e.flags.cursor}),w(e.settings.output))}}),Lg={versionId:{type:`string`,valueHint:`<full-version>`,required:!0,description:{"en-US":`Full project version ID`,"zh-CN":`完整的项目版本 ID`}}},Rg=C({description:{"en-US":`Preview a directory project version`,"zh-CN":`预览目录项目历史版本`},auth:`none`,usageArgs:`--version-id <full-version> [--project <directory>]`,flags:{...Eg,...Lg},exampleArgs:[`--version-id <full-version>`],async run(e){D(await pa(e.flags.project??`.`).previewVersion(e.flags.versionId),w(e.settings.output))}}),zg=C({description:{"en-US":`Restore a version to the project working directory`,"zh-CN":`将历史版本恢复到项目工作目录`},auth:`none`,risk:{level:`high`,message:{"en-US":`This restores the full directory source to the working tree. Version history and remote State will not move.`,"zh-CN":`该操作会将完整目录源文件恢复到工作区;版本历史和远端 State 不会移动。`}},usageArgs:`--version-id <full-version> [--project <directory>]`,flags:{...Eg,...Lg},exampleArgs:[`--version-id <full-version>`,`--version-id <full-version> --yes`],async run(e){let t=pa(e.flags.project??`.`),r=await t.previewVersion(e.flags.versionId);if(!r.can_restore)throw new n(r.blockers[0]??r.diagnostics[0]?.message??`Version cannot be restored.`,l.GENERAL);if(e.settings.dryRun){D({would_restore:e.flags.versionId,preview:r},w(e.settings.output));return}D(await t.restoreVersion(e.flags.versionId,{headVersion:r.base_head_version,projectRevision:r.base_project_revision}),w(e.settings.output))}});function Bg(e){return{project_root:e.project_root,project_revision:e.project_revision,source_manifest_hash:e.source_manifest_hash,yaml_hash:e.yaml_hash,diagnostics:e.diagnostics,warnings:e.warnings,organization_moves:e.organization_moves,before_yaml:`before_yaml`in e?e.before_yaml:void 0,after_yaml:e.canonical_yaml,can_build:`can_build`in e?e.can_build:void 0}}var Vg=C({description:{"en-US":`List resources tracked in agents state`,"zh-CN":`列出 Agent State 中跟踪的资源`},auth:`none`,usageArgs:`[--file <path>]`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}},exampleArgs:[``,`--file agents.yaml`],notes:Ih,async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=n.file??`agents.yaml`,a=await G(()=>K(async()=>(await W(e,i,{credentials:`none`})).state.listResources()));if(r===`json`){D({resources:a},r);return}if(a.length===0){E(`No resources tracked in state.`);return}let o=[`TYPE`,`NAME`,`PROVIDER`,`REMOTE ID`],s=a.map(e=>[e.address.type,e.address.name,e.address.provider,e.remote_id??`(local)`]);for(let e of Xn(o,s))E(e);E(`\nTotal: ${a.length}`)}}),Hg=C({description:{"en-US":`Show details of a resource in agents state`,"zh-CN":`显示 Agent State 中资源的详情`},auth:`none`,usageArgs:`--address <provider.type.name> [--file <path>]`,flags:{address:{type:`string`,valueHint:`<provider.type.name>`,description:{"en-US":`Resource state address (required)`,"zh-CN":`资源 State 地址(必填)`},required:!0},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}},exampleArgs:[`--address bailian.agent.assistant`],notes:Ih,async run(e){let{settings:t,flags:r}=e,i=w(t.output),a=r.file??`agents.yaml`,o=await G(()=>K(async()=>{let t=await W(e,a,{credentials:`none`}),n=Ki(r.address,{requireProvider:!1});return t.state.findResource(n)}));if(!o)throw new n(`Resource not found: ${r.address}`,l.GENERAL);i===`json`?D(o,i):E(JSON.stringify(o,null,2))}}),Ug=C({description:{"en-US":`Remove a resource from state without destroying it remotely`,"zh-CN":`从 State 中移除资源,但不销毁远端资源`},auth:`none`,risk:{level:`high`,message:{"en-US":`This removes the resource from local state without deleting it remotely, so this project will no longer track it.`,"zh-CN":`该操作会从本地 State 中移除资源但不会删除远端资源,此项目将不再跟踪该资源。`}},usageArgs:`--address <provider.type.name> [--file <path>]`,flags:{address:{type:`string`,valueHint:`<provider.type.name>`,description:{"en-US":`Resource state address (required)`,"zh-CN":`资源 State 地址(必填)`},required:!0},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}},exampleArgs:[`--address bailian.agent.assistant --yes`],notes:Ih,async run(e){let{settings:t,flags:r}=e,i=w(t.output),a=r.file??`agents.yaml`;if(t.dryRun){await G(async()=>{Ki(r.address,{requireProvider:!1})}),D({would_remove:r.address,config_file:a},i);return}await G(()=>K(async()=>{let t=await W(e,a,{credentials:`none`}),i=Ki(r.address,{requireProvider:!1}),o=t.state.findResource(i);if(!o)throw new n(`Resource not found: ${r.address}`,l.GENERAL);t.state.removeResource(o.address),await t.state.save()}));let o=`Removed ${r.address} from state (remote resource not deleted).`;i===`json`?D({removed:r.address},i):E(o)}});const Wg={address:{type:`string`,valueHint:`<bailian.type.name>`,description:{"en-US":`Resource state address (required)`,"zh-CN":`资源 State 地址(必填)`},required:!0},remoteId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Existing remote resource ID to import (required)`,"zh-CN":`要导入的已有远端资源 ID(必填)`},required:!0},resourceVersion:{type:`number`,valueHint:`<n>`,description:{"en-US":`Resource version (for versioned resources like agents)`,"zh-CN":`资源版本(用于 Agent 等带版本的资源)`}},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}};function Gg(e){let t=Ki(e,{requireProvider:!0});if(t.provider!==`bailian`)throw new n(`bl managed-agent can import only Bailian resources; address provider was '${t.provider}'. / bl managed-agent 只能导入百炼资源;地址中的 Provider 为 '${t.provider}'。`,l.USAGE);return t}var Kg=C({description:{"en-US":`Import an existing remote resource into agents state`,"zh-CN":`将已有远端资源导入 Agent State`},auth:`apiKey`,usageArgs:`--address <bailian.type.name> --remote-id <id> [--resource-version <n>] [--file <path>]`,flags:Wg,exampleArgs:[`--address bailian.agent.assistant --remote-id agent-abc123`],notes:U,async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=n.file??`agents.yaml`;if(t.dryRun){await G(async()=>{Gg(n.address)}),D({would_import:n.address,remote_id:n.remoteId,resource_version:n.resourceVersion,config_file:i},r);return}await G(()=>K(async()=>{let t=Gg(n.address);await Mi(await W(e,i),t,n.remoteId,{resourceVersion:n.resourceVersion})})),r===`json`?D({imported:n.address,remote_id:n.remoteId},r):E(`Imported ${n.address} (remote_id: ${n.remoteId}) into state.`)}});function qg(e){return e.type!==`thinking`&&!(e.type===`message`&&e.role===`user`)}function Jg(e,t){t||process.stderr.write(`\n[session ${e}]\n`)}function Yg(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n?.type===`error`&&n.content?.trim())return n.content}}function Xg(e,t){if(e===`failed`)throw new n(t??`Session failed.`,l.GENERAL)}async function Zg(e,t,n={}){let r=[],i,a;for await(let n of e)if(t?r.push(n):Qg(n),n.type===`error`&&n.content?.trim()&&(a=n.content),n.type===`status`&&Pi(n.status)){i=n.status,Jg(n.status??``,t);break}t&&process.stdout.write(`${JSON.stringify({...n,events:ba(r)},null,2)}\n`),Xg(i,a)}function Qg(e){if(qg(e))if(e.type===`message`&&e.content)process.stdout.write(e.content);else if(e.type===`tool_use`)process.stderr.write(`\n[tool] ${e.tool_name}\n`);else if(e.type===`tool_result`&&e.content){let t=e.content.length>200?`${e.content.slice(0,200)}...`:e.content;process.stderr.write(`${t}\n`)}else e.type===`status`?e.status===`running`&&process.stderr.write(`
|
|
2836
2837
|
[session running]
|
|
2837
|
-
`):e.type===`error`&&process.stderr.write(`\n[error] ${e.content??`unknown error`}\n`)}function qg(e,t,n={}){if(t)process.stdout.write(`${JSON.stringify({...n,events:ba(e.result.events),has_more:e.result.has_more,next_page:e.result.next_page},null,2)}\n`);else{for(let t of e.result.events)Kg(t);Hg(e.terminalStatus,t)}Wg(e.terminalStatus,Ug(e.result.events))}function Jg(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean):void 0}var Yg=C({description:{"en-US":`Create a new session for an agent`,"zh-CN":`为 Agent 创建新 Session`},auth:`apiKey`,usageArgs:`[--agent <name>] [--environment <name>] [--title <title>] [--file <path>]`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},agent:{type:`string`,valueHint:`<name>`,description:{"en-US":`Agent name (auto-detected when only one agent is configured)`,"zh-CN":`Agent 名称(仅配置一个 Agent 时自动识别)`}},environment:{type:`string`,valueHint:`<name>`,description:{"en-US":`Override agent's declared environment`,"zh-CN":`覆盖 Agent 声明的环境`}},vault:{type:`string`,valueHint:`<name>`,description:{"en-US":`Override agent's declared vault`,"zh-CN":`覆盖 Agent 声明的 Vault`}},memoryStores:{type:`string`,valueHint:`<names>`,description:{"en-US":`Override agent's memory stores (comma-separated)`,"zh-CN":`覆盖 Agent 的 Memory Store(以逗号分隔)`}},title:{type:`string`,valueHint:`<title>`,description:{"en-US":`Session title`,"zh-CN":`Session 标题`}}},exampleArgs:[``,`--agent assistant`,{"en-US":`--agent assistant --title 'debug run'`,"zh-CN":`--agent assistant --title '调试运行'`}],notes:U,async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=n.file??`agents.yaml`;if(t.dryRun){D({would_create_session:{agent:n.agent??`auto`,provider:`bailian`,environment:n.environment,vault:n.vault,memory_stores:Jg(n.memoryStores),title:n.title},config_file:i},r);return}let{agentName:a,session:o}=await G(()=>K(async()=>hi(await W(e,i),{agent:n.agent,provider:`bailian`,environment:n.environment,vault:n.vault,memoryStores:Jg(n.memoryStores),title:n.title})));if(r===`json`){D({agent:a,session:o},r);return}E(`Session created: ${o.id}`),E(` Agent: ${a}`),E(` Environment: ${o.environment_id}`),E(` Status: ${o.status}`),o.vault_ids.length&&E(` Vaults: ${o.vault_ids.join(`, `)}`),o.memory_store_ids.length&&E(` Memory: ${o.memory_store_ids.join(`, `)}`)}});async function Xg(e,t,n){let r=await e(n),i=[...r.items],a=r.hasMore,o=r.nextPage;for(;t&&o;){let t=await e(o);i.push(...t.items),a=t.hasMore,o=t.nextPage}return{items:i,hasMore:a,nextPage:o}}const q={file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}},J={limit:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page size (1-100)`,"zh-CN":`单页数量(1-100)`}},page:{type:`string`,valueHint:`<cursor>`,description:{"en-US":`Opaque page cursor returned by a previous request`,"zh-CN":`上一次请求返回的不透明分页 Cursor`}},all:{type:`switch`,description:{"en-US":`Fetch all pages by following opaque cursors`,"zh-CN":`跟随不透明 Cursor 获取全部分页`}}},Zg={query:{type:`string`,valueHint:`<text>`,required:!0,description:{"en-US":`Case-insensitive text to find in IDs, names, and descriptions`,"zh-CN":`在 ID、名称和描述中进行不区分大小写的文本搜索`}},pageLimit:{type:`number`,valueHint:`<n>`,description:{"en-US":`Maximum pages to scan for client-side search (default: 10)`,"zh-CN":`客户端搜索最多扫描的页数(默认:10)`}}},Qg={includeArchived:{type:`switch`,description:{"en-US":`Include archived resources`,"zh-CN":`包含已归档资源`}}};function Y(e){if(e.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>100))return`--limit must be an integer between 1 and 100.`;if(e.pageLimit!==void 0&&(!Number.isInteger(e.pageLimit)||e.pageLimit<1||e.pageLimit>100))return`--page-limit must be an integer between 1 and 100.`}function $g(e){if(!e)return;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t.length>0?t:void 0}function e_(e,...t){let n=e.trim().toLocaleLowerCase();return n?t.some(e=>e==null?!1:(typeof e==`string`?e:JSON.stringify(e)).toLocaleLowerCase().includes(n)):!0}async function t_(e,t,n=10){let r=[],i,a=!1,o,s=0;do{let n=await e(i);s+=1,r.push(...n.items.filter(t)),a=n.hasMore,o=n.nextPage,i=n.nextPage}while(a&&i&&s<n);return{items:r,hasMore:a,nextPage:o,scannedPages:s,truncated:!!(a&&o)}}function X(e){let{format:t,key:n,items:r,headers:i,rows:a,hasMore:o=!1,nextPage:s,truncated:c,scannedPages:l,emptyMessage:u=`No resources found.`}=e;if(t===`json`){D({[n]:r,has_more:o,next_page:s,...c===void 0?{}:{truncated:c},...l===void 0?{}:{scanned_pages:l}},t);return}if(r.length===0){E(u);return}for(let e of Xn(i,a))E(e);E(`\nTotal: ${r.length}`),c?E(`Search stopped at --page-limit; more pages remain.`):o&&E(`More results are available.${s?` Next page: ${s}`:``}`)}function Z(e,t=40){if(e==null||e===``)return`-`;let n=typeof e==`string`?e:JSON.stringify(e);return n.length>t?`${n.slice(0,t-3)}...`:n}var n_=C({description:{"en-US":`List sessions from the provider`,"zh-CN":`列出 Provider 中的 Session`},auth:`apiKey`,usageArgs:`[--agent <name>] [--statuses <statuses>] [--limit <n>] [--page <cursor>] [--all]`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},agent:{type:`string`,valueHint:`<name>`,description:{"en-US":`Filter by agent name`,"zh-CN":`按 Agent 名称筛选`}},all:{type:`switch`,description:{"en-US":`Fetch all pages by following the cursor`,"zh-CN":`跟随 Cursor 获取全部分页`}},limit:J.limit,page:J.page,statuses:{type:`string`,valueHint:`<statuses>`,description:{"en-US":`Comma-separated session statuses`,"zh-CN":`Session 状态,多个以逗号分隔`}},createdAtGte:{type:`string`,valueHint:`<timestamp>`,description:{"en-US":`Created at or after this RFC 3339 timestamp`,"zh-CN":`创建时间不早于该 RFC 3339 时间戳`}},createdAtLte:{type:`string`,valueHint:`<timestamp>`,description:{"en-US":`Created at or before this RFC 3339 timestamp`,"zh-CN":`创建时间不晚于该 RFC 3339 时间戳`}}},exampleArgs:[``,`--agent assistant`,`--all`],notes:U,validate:Y,async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=n.file??`agents.yaml`,{items:a,hasMore:o,nextPage:s}=await G(()=>K(async()=>{let t=await W(e,i);return Xg(async e=>{let r=await Gi(t,{agent:n.agent,provider:`bailian`,filter:{page:e,limit:n.limit,statuses:$g(n.statuses),created_at_gte:n.createdAtGte,created_at_lte:n.createdAtLte}});return{items:r.summaries,hasMore:r.hasMore,nextPage:r.nextPage}},n.all,n.page)})),c=a.map(e=>e.session);if(r===`json`){D({sessions:c,has_more:o,next_page:s},r);return}if(c.length===0){E(`No sessions found.`);return}let l=new Map(a.filter(e=>e.agentName).map(e=>[e.session.id,e.agentName])),u=[`ID`,`TITLE`,`AGENT`,`STATUS`,`CREATED`],d=c.map(e=>[e.id,(e.title??``).slice(0,20),l.get(e.id)??e.agent_id.slice(0,12),e.status,e.created_at]);for(let e of Xn(u,d))E(e);E(`\nTotal: ${c.length}`),o&&E(`More sessions available. Use --all to fetch all.`)}}),r_=C({description:{"en-US":`Get details of a session`,"zh-CN":`获取 Session 详情`},auth:`apiKey`,usageArgs:`--session-id <id> [--file <path>]`,flags:{sessionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Session ID (required)`,"zh-CN":`Session ID(必填)`},required:!0},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}},exampleArgs:[`--session-id sess_abc123`],notes:U,async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=n.file??`agents.yaml`,a=await G(()=>K(async()=>ji(await W(e,i),n.sessionId,`bailian`)));if(r===`json`){D(a,r);return}E(` ID: ${a.id}`),E(` Agent: ${a.agent_id}`),E(` Environment: ${a.environment_id}`),E(` Status: ${a.status}`),a.title&&E(` Title: ${a.title}`),E(` Created: ${a.created_at}`),E(` Updated: ${a.updated_at}`)}}),i_=C({description:{"en-US":`Delete a session`,"zh-CN":`删除 Session`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This deletes the specified remote managed Agent Session.`,"zh-CN":`该操作会删除指定的远端托管 Agent Session。`}},usageArgs:`--session-id <id> [--file <path>]`,flags:{sessionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Session ID (required)`,"zh-CN":`Session ID(必填)`},required:!0},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}},exampleArgs:[`--session-id sess_abc123 --yes`],notes:U,async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=n.file??`agents.yaml`;if(t.dryRun){D({would_delete_session:n.sessionId,provider:`bailian`,config_file:i},r);return}await G(()=>K(async()=>{await vi(await W(e,i),n.sessionId,`bailian`)})),r===`json`?D({deleted:n.sessionId},r):E(`Session ${n.sessionId} deleted.`)}}),a_=C({description:{"en-US":`Create a session, send a message, and stream the response`,"zh-CN":`创建 Session、发送消息并流式输出响应`},auth:`apiKey`,usageArgs:`--prompt <text> [--agent <name>] [--no-stream] [--file <path>]`,flags:{prompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Prompt to send (required)`,"zh-CN":`要发送的 Prompt(必填)`},required:!0},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},agent:{type:`string`,valueHint:`<name>`,description:{"en-US":`Agent name (auto-detected when only one agent is configured)`,"zh-CN":`Agent 名称(仅配置一个 Agent 时自动识别)`}},environment:{type:`string`,valueHint:`<name>`,description:{"en-US":`Override agent's declared environment`,"zh-CN":`覆盖 Agent 声明的环境`}},vault:{type:`string`,valueHint:`<name>`,description:{"en-US":`Override agent's declared vault`,"zh-CN":`覆盖 Agent 声明的 Vault`}},memoryStores:{type:`string`,valueHint:`<names>`,description:{"en-US":`Override agent's memory stores (comma-separated)`,"zh-CN":`覆盖 Agent 的 Memory Store(以逗号分隔)`}},title:{type:`string`,valueHint:`<title>`,description:{"en-US":`Session title`,"zh-CN":`Session 标题`}},noStream:{type:`switch`,description:{"en-US":`Use polling instead of SSE streaming`,"zh-CN":`使用轮询代替 SSE 流式传输`}}},exampleArgs:[{"en-US":`--prompt "hello"`,"zh-CN":`--prompt "你好"`},{"en-US":`--agent assistant --prompt "summarize this repo"`,"zh-CN":`--agent assistant --prompt "总结这个代码仓库"`}],notes:[...U,{"en-US":"--output json emits one envelope: { session_id, provider, agent, events } — read session_id to chain `session send/get/events/delete`.","zh-CN":"--output json 输出一个 Envelope:{ session_id, provider, agent, events }。读取 session_id 后可串联调用 `session send/get/events/delete`。"}],async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=n.file??`agents.yaml`,a=r===`json`,o={agent:n.agent,provider:`bailian`,environment:n.environment,vault:n.vault,memoryStores:Jg(n.memoryStores),title:n.title};if(t.dryRun){D({would_run:{prompt:n.prompt,agent:n.agent??`auto`,provider:`bailian`,environment:n.environment,vault:n.vault,memory_stores:o.memoryStores,title:n.title,mode:n.noStream?`polling`:`streaming`},config_file:i},r);return}await G(()=>K(async()=>{let t=await W(e,i);if(n.noStream){let e=await aa(t,n.prompt,o);a||process.stderr.write(`Session created: ${e.session.id}\n`),qg(e,a,{session_id:e.session.id,provider:e.provider,agent:e.agentName})}else{let e=await ia(t,n.prompt,o);a||process.stderr.write(`Session created: ${e.session.id}\n`),await Gg(e.events,a,{session_id:e.session.id,provider:e.provider,agent:e.agentName})}}))}}),o_=C({description:{"en-US":`Send a message to an existing session and stream the response`,"zh-CN":`向已有 Session 发送消息并流式输出响应`},auth:`apiKey`,usageArgs:`--session-id <id> --message <text> [--no-stream] [--file <path>]`,flags:{sessionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Session ID (required)`,"zh-CN":`Session ID(必填)`},required:!0},message:{type:`string`,valueHint:`<text>`,description:{"en-US":`Message to send (required)`,"zh-CN":`要发送的消息(必填)`},required:!0},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},noStream:{type:`switch`,description:{"en-US":`Use polling instead of SSE streaming`,"zh-CN":`使用轮询代替 SSE 流式传输`}}},exampleArgs:[{"en-US":`--session-id sess_abc123 --message "continue"`,"zh-CN":`--session-id sess_abc123 --message "继续"`}],notes:U,async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=n.file??`agents.yaml`,a=r===`json`;if(t.dryRun){D({would_send:{session_id:n.sessionId,message:n.message,provider:`bailian`,mode:n.noStream?`polling`:`streaming`},config_file:i},r);return}await G(()=>K(async()=>{let t=await W(e,i);n.noStream?qg(await ta(t,n.sessionId,n.message,{provider:`bailian`}),a,{session_id:n.sessionId}):await Gg(await na(t,n.sessionId,n.message,{provider:`bailian`}),a,{session_id:n.sessionId})}))}});async function s_(e){return new Uint8Array(await Zr(M(e)))}async function c_(e){let t=e.startsWith(`@`)?await Zr(M(e.slice(1)),`utf8`):e;try{return JSON.parse(t)}catch(e){throw new n(`Invalid JSON input: ${e instanceof Error?e.message:String(e)}`,l.USAGE)}}async function l_(e,t,r=!1){let i=M(e);await Xr(Ir(i),{recursive:!0});let a=`${i}.${fr()}.tmp`;await ti(a,t,{flag:`wx`});try{if(r)await Qr(a,i);else{try{await Yr(a,i)}catch(e){throw e.code===`EEXIST`?new n(`Output file already exists: ${i}`,l.USAGE,`Choose another --output-file path or re-run with --force.`):e}await ei(a)}return i}catch(e){throw await ei(a).catch(()=>void 0),e}}function u_(e){let t=A(e).toLocaleLowerCase();return t.endsWith(`.json`)?`application/json`:t.endsWith(`.md`)?`text/markdown`:t.endsWith(`.txt`)?`text/plain`:t.endsWith(`.pdf`)?`application/pdf`:t.endsWith(`.png`)?`image/png`:t.endsWith(`.jpg`)||t.endsWith(`.jpeg`)?`image/jpeg`:t.endsWith(`.zip`)?`application/zip`:`application/octet-stream`}const d_={sessionId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Session ID`,"zh-CN":`Session ID`}}},f_={...q,...d_,...J,order:{type:`string`,valueHint:`<order>`,choices:[`asc`,`desc`],description:{"en-US":`Event order: asc or desc`,"zh-CN":`事件顺序:asc 或 desc`}},types:{type:`string`,valueHint:`<types>`,description:{"en-US":`Comma-separated raw event types`,"zh-CN":`原始事件类型,多个以逗号分隔`}},createdAtGte:{type:`string`,valueHint:`<timestamp>`,description:{"en-US":`Created at or after this timestamp`,"zh-CN":`创建时间不早于该时间戳`}},createdAtLte:{type:`string`,valueHint:`<timestamp>`,description:{"en-US":`Created at or before this timestamp`,"zh-CN":`创建时间不晚于该时间戳`}}},p_={...q,...d_,event:{type:`string`,valueHint:`<json|@path>`,required:!0,description:{"en-US":`Raw event object/array as JSON or @event.json`,"zh-CN":`原始事件对象/数组 JSON,或 @event.json`}}},m_={...q,...d_,afterId:{type:`string`,valueHint:`<event-id>`,description:{"en-US":`Resume after this event ID`,"zh-CN":`从该 Event ID 之后继续`}}};function h_(e){return e.map(e=>[Z(e.id),e.raw_type,Z(e.session_thread_id),Z(e.content??e.status??e.tool_name,70)])}function g_(e){let t=Array.isArray(e)?e:[e];if(t.length===0||t.some(e=>!e||typeof e!=`object`||Array.isArray(e)))throw new n(`Event input must be a JSON object or a non-empty array of objects.`,l.USAGE);for(let[e,r]of t.entries()){let t=ci.safeParse(r);if(t.success)continue;let i=t.error.issues[0];throw new n(`Invalid event at index ${e}${i?.path.length?` at ${i.path.join(`.`)}`:``}: ${i?.message??`does not match the Session event schema`}.`,l.USAGE)}return t}const __=C({description:{"en-US":`List events for a Managed Agent session`,"zh-CN":`列出托管 Agent Session 事件`},auth:`apiKey`,usageArgs:`--session-id <id> [--types <types>] [--order asc|desc] [--limit <n>] [--page <cursor>] [--all]`,flags:f_,exampleArgs:[`--session-id sess_abc`,`--session-id sess_abc --all --output json`],notes:[...U,{"en-US":`--types is applied client-side to each page returned by the provider.`,"zh-CN":`--types 会在客户端对 Provider 返回的每一页结果进行过滤。`}],validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return Xg(async n=>{let r=await Wi(t,e.flags.sessionId,{provider:`bailian`,limit:e.flags.limit,page_token:n,order:e.flags.order,types:$g(e.flags.types),created_at_gte:e.flags.createdAtGte,created_at_lte:e.flags.createdAtLte});return{items:r.events,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`events`,items:ba(n.items),headers:[`ID`,`TYPE`,`THREAD`,`CONTENT`],rows:h_(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No events found.`})}}),v_=C({description:{"en-US":`Send raw events to a Managed Agent session`,"zh-CN":`向托管 Agent Session 发送原始事件`},auth:`apiKey`,usageArgs:`--session-id <id> --event <json|@path>`,flags:p_,exampleArgs:[`--session-id sess_abc --event '{"type":"message","role":"user","content":[{"type":"text","text":"hello"}]}'`,`--session-id sess_abc --event @event.json`],notes:U,async run(e){let t=w(e.settings.output),n=g_(await c_(e.flags.event));if(e.settings.dryRun){D({would_send_events:n,session_id:e.flags.sessionId},t);return}let r=await G(()=>K(async()=>ea(await W(e,e.flags.file??`agents.yaml`),e.flags.sessionId,n,{provider:`bailian`})));t===`json`?D({session_id:e.flags.sessionId,...r},t):E(`Sent ${n.length} event(s): ${r.event_ids.join(`, `)}`)}}),y_=C({description:{"en-US":`Stream events from a Managed Agent session`,"zh-CN":`流式读取托管 Agent Session 事件`},auth:`apiKey`,usageArgs:`--session-id <id> [--after-id <event-id>]`,flags:m_,exampleArgs:[`--session-id sess_abc`,`--session-id sess_abc --after-id evt_123 --output json`],notes:[...U,{"en-US":`When the provider has no native event cursor, --after-id resumes through paginated history polling and event ID de-duplication.`,"zh-CN":`当 Provider 不支持原生事件 Cursor 时,--after-id 会通过分页历史轮询和 Event ID 去重实现续传。`}],async run(e){let t=w(e.settings.output);await G(()=>K(async()=>{let n=await W(e,e.flags.file??`agents.yaml`),r=[];for await(let i of oa(n,e.flags.sessionId,{provider:`bailian`,after_id:e.flags.afterId}))if(r.push(i),t!==`json`&&E(JSON.stringify(ba([i])[0])),i.type===`status`&&Pi(i.status))break;t===`json`&&D({session_id:e.flags.sessionId,events:ba(r)},t)}))}}),b_={source:{type:`string`,valueHint:`<source>`,choices:[`custom`,`official`,`all`],description:{"en-US":`Skill catalog: custom (default), official, or all`,"zh-CN":`Skill Catalog:custom(默认)、official 或 all`}}},x_={...q,...J,...b_},S_={...q,limit:J.limit,...Zg,...b_},C_={...q,skillId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Skill ID`,"zh-CN":`Skill ID`}}},w_={...C_,...J},T_={...C_,skillVersion:{type:`string`,valueHint:`<version>`,required:!0,description:{"en-US":`Skill version`,"zh-CN":`Skill 版本`}},outputFile:{type:`string`,valueHint:`<path>`,required:!0,description:{"en-US":`Destination ZIP path`,"zh-CN":`目标 ZIP 路径`}},force:{type:`switch`,description:{"en-US":`Overwrite an existing output file`,"zh-CN":`覆盖已存在的输出文件`}}};function E_(e){return e.map(e=>[e.id,Z(e.name),e.source,e.status,Z(e.latest_version),Z(e.updated_at??e.created_at)])}function D_(e){return e.map(e=>[Z(e.version),Z(e.name),Z(e.type),Z(e.status),Z(e.updated_at??e.created_at)])}function O_(e,t){return{source:e,skills:t.items,has_more:t.hasMore,next_page:t.nextPage}}async function k_(e,t,n){return Xg(async r=>{let i=await Hi(e,{provider:`bailian`,source:t,limit:n.limit,page:r});return{items:i.data,hasMore:i.has_more,nextPage:i.next_page}},n.all,n.page)}var A_=C({description:{"en-US":`List Managed Agent skills`,"zh-CN":`列出托管 Agent Skill`},auth:`apiKey`,usageArgs:`[--source custom|official|all] [--limit <n>] [--page <cursor>] [--all]`,flags:x_,exampleArgs:[``,`--source official`,`--source all --all --output json`],notes:[...U,{"en-US":`--source all combines one page from each catalog, or every page with --all; it does not accept --page.`,"zh-CN":`--source all 默认合并两个 Catalog 的各一页,传入 --all 时获取全部分页;该模式不接受 --page。`}],validate:e=>Y(e)??(e.source===`all`&&e.page?`--source all cannot be combined with --page.`:void 0),async run(e){let t=w(e.settings.output),n=e.flags.source??`custom`,r=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);if(n!==`all`)return k_(t,n,{limit:e.flags.limit,page:e.flags.page,all:e.flags.all});let[r,i]=await Promise.all([k_(t,`custom`,{limit:e.flags.limit,all:e.flags.all}),k_(t,`official`,{limit:e.flags.limit,all:e.flags.all})]);return{items:[...r.items,...i.items],hasMore:r.hasMore||i.hasMore,nextPage:void 0}}));if(t===`json`){D(O_(n,r),t);return}X({format:t,key:`skills`,items:r.items,headers:[`ID`,`NAME`,`SOURCE`,`STATUS`,`VERSION`,`UPDATED`],rows:E_(r.items),hasMore:r.hasMore,nextPage:r.nextPage,emptyMessage:`No skills found.`})}});const j_=[{"en-US":`Without --yes, this command only previews. --dry-run is fully offline. The scoped flow checks only the target resource and its transitive dependencies; unrelated resources are not refreshed or drift-checked.`,"zh-CN":`不带 --yes 时仅预览;--dry-run 完全离线。定向流程只检查目标资源及其传递依赖,不刷新或检测无关资源的 Drift。`}];function M_(e){let t=e=>Array.isArray(e)?e.map(t):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,n])=>[e,t(n)]));return JSON.stringify(t(e))}function N_(e,t=`resource`){return e.normalize(`NFKC`).trim().toLowerCase().replace(/[^\p{L}\p{N}]+/gu,`-`).replace(/^-+|-+$/g,``)||t}function P_(e){let t=new Set(e.state.listResources().filter(t=>t.address.provider===e.provider&&e.resourceTypes.includes(t.address.type)).map(e=>e.address.name)),n=M_(e.candidate);for(let[r,i]of Object.entries(e.declarations))if(!(e.effectiveName(r,i)!==e.displayName||t.has(r))&&M_(i)===n)return{key:r,reusedPending:!0};let r=N_(e.displayName,e.fallbackKey);if(!(r in e.declarations))return{key:r,reusedPending:!1};let i=2;for(;`${r}-${i}`in e.declarations;)i+=1;return{key:`${r}-${i}`,reusedPending:!1}}async function F_(e,t){let r=await Zr(M(t),`utf8`).catch(e=>{throw e.code===`ENOENT`?new n(`Config file not found: ${t}`,l.USAGE,"Run `bl managed-agent init` first."):e}),i=await G(()=>Vh(e,t,{credentials:`none`})),a=await Zr(i.configPath,`utf8`);if(a!==r)throw new n(`${t} changed while it was being loaded.`,l.GENERAL,`Re-run the command against the latest file.`);let o=`bailian`;e.settings.dryRun||Fh(i.config.providers,[o]),zh(e);let s=new si({configPath:i.configPath});return{...i,source:a,provider:o,stateBackend:s,stateScope:Ih(i.configPath,i.projectName)}}async function I_(e){let t=`__bailian_cli_create_candidate__`,n=structuredClone(e.project.config),r=n[e.group]??{};return n[e.group]={...r,[t]:e.rawDeclaration},(await G(()=>Qi(n,{projectName:e.project.projectName,basePath:Ir(e.project.configPath)}))).config[e.group]?.[t]??e.rawDeclaration}async function L_(e){let{project:t,host:r}=e,i=w(r.settings.output),a=await t.stateBackend.read(t.stateScope,n=>P_({displayName:e.displayName,provider:t.provider,resourceTypes:[e.resourceType],declarations:e.existingDeclarations,candidate:e.resolvedDeclaration,effectiveName:e.effectiveName,fallbackKey:e.fallbackKey,state:n})),o=a.key,s=structuredClone(t.config),c=s[e.group]??{};s[e.group]={...c,[o]:e.resolvedDeclaration},s._resolved=!0;let u=Ur(t.source);if(u.errors.length>0)throw new n(`YAML parse error: ${u.errors.map(e=>e.message).join(`; `)}`,l.USAGE);u.setIn([e.group,o],e.rawDeclaration);let d=u.toString(),f={type:e.resourceType,name:o,provider:t.provider},p={projectName:t.projectName,config:s,configPath:t.configPath,providers:{[t.provider]:t.config.providers[t.provider]},stateBackend:t.stateBackend,stateScope:t.stateScope};if(r.settings.dryRun||!e.yes){let n=await G(()=>K(()=>Yi(p,{provider:t.provider,scope:{roots:[f]},mode:`create-only`,refresh:!r.settings.dryRun,quiet:i===`json`}))),s=!n.plan.diagnostics.some(e=>e.severity===`error`),c={resource:{type:e.resourceType,key:o,name:e.displayName,provider:t.provider},config_file:t.configPath,yaml_written:!1,reused_pending:a.reusedPending,requires_confirmation:!r.settings.dryRun,ready_to_create:s,actions:n.plan.actions,diagnostics:n.plan.diagnostics};i===`json`?D(c,i):(E(`Generated YAML key: ${o}`),V_(n.plan.actions,n.plan.diagnostics),E(r.settings.dryRun?`Dry run: YAML, State, and remote resources were not changed.`:`Preview only: re-run with --yes to write YAML and create this resource.`));return}await R_(t.configPath,t.source,d);let m;try{m=await G(()=>K(()=>sa(p,{provider:t.provider,scope:{roots:[f]},mode:`create-only`,refresh:!0,quiet:i===`json`,policy:`block`})))}catch(t){throw qh(t,`The YAML declaration was kept. Fix the related dependency or provider error, then re-run the same create command.`,`Scoped ${e.resourceType} create failed.`)}let h=await t.stateBackend.read(t.stateScope,e=>e.getResource(f)?.remote_id),g=m.execution?.results??[],_=g.find(e=>e.status===`failed`),v={resource:{type:e.resourceType,key:o,name:e.displayName,provider:t.provider,remote_id:h},config_file:t.configPath,yaml_written:!0,reused_pending:a.reusedPending,actions:m.planned.plan.actions,diagnostics:m.planned.plan.diagnostics,results:g,error:_?.error};if(i===`json`?D(v,i):(E(`Wrote ${t.configPath} with ${e.resourceType} key '${o}'.`),_||E(`Created ${e.resourceType} '${e.displayName}'.`)),_)throw new n(_.error??`Scoped ${e.resourceType} create failed.`,l.GENERAL,`The YAML declaration was kept. Fix the provider error, then re-run the same create command.`)}async function R_(e,t,r){let i=M(e);if(await Zr(i,`utf8`)!==t)throw new n(`${e} changed while resource create was being prepared.`,l.GENERAL,`Review the latest YAML and re-run the command; no file was overwritten.`);let a=await $r(i),o=M(Ir(i),`.${A(i)}.${fr()}.tmp`);await ti(o,r,{flag:`wx`,mode:a.mode});try{await Qr(o,i)}catch(e){throw await ei(o).catch(()=>void 0),e}}function z_(e){if(!e?.length)return;let t={};for(let r of e){let e=r.indexOf(`=`);if(e<=0)throw new n(`Invalid metadata '${r}'.`,l.USAGE,`Use --metadata key=value.`);let i=r.slice(0,e).trim();if(!i)throw new n(`Metadata key must not be empty.`,l.USAGE);t[i]=r.slice(e+1)}return t}async function B_(e,t){let r=[];for(let i of e??[]){let e=i.startsWith(`@`)?await Zr(M(i.slice(1)),`utf8`):i,a;try{a=JSON.parse(e)}catch(e){throw new n(`Invalid ${t} JSON: ${e instanceof Error?e.message:String(e)}`,l.USAGE)}Array.isArray(a)?r.push(...a):r.push(a)}return r}function V_(e,t){for(let e of t)E(`[${e.severity}] ${e.code}: ${e.message}`);for(let t of e.filter(e=>e.action!==`no-op`))E(` ${t.action===`create`?`+`:t.action===`update`?`~`:`-`} ${Yh(t.address)}`)}const H_={name:{type:`string`,valueHint:`<name>`,required:!0,description:{"en-US":`Remote Agent display name; the YAML key is generated automatically`,"zh-CN":`远端 Agent 显示名称;YAML key 将自动生成`}},model:{type:`string`,valueHint:`<model>`,required:!0,description:{"en-US":`Model ID`,"zh-CN":`模型 ID`}},instructions:{type:`string`,valueHint:`<text|path>`,required:!0,description:{"en-US":`Inline instructions or a ./, ../, or absolute file path`,"zh-CN":`内联指令,或以 ./、../、/ 开头的文件路径`}},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`Agent description`,"zh-CN":`Agent 描述`}},skill:{type:`array`,valueHint:`<id>`,description:{"en-US":`Existing remote Skill ID (repeatable)`,"zh-CN":`已存在的远端 Skill ID(可重复)`}},skillDir:{type:`array`,valueHint:`<path>`,description:{"en-US":`Local Skill directory or ZIP to declare, upload, and attach through the same scoped create (repeatable)`,"zh-CN":`通过同一次定向创建声明、上传并绑定的本地 Skill 目录或 ZIP(可重复)`}},type:{type:`string`,valueHint:`<custom|official>`,choices:[`custom`,`official`],description:{"en-US":`Type applied to every --skill value (default: custom)`,"zh-CN":`应用于所有 --skill 的类型(默认:custom)`}},tool:{type:`array`,valueHint:`<name>`,description:{"en-US":`Builtin tool name (repeatable)`,"zh-CN":`内置工具名称(可重复)`}},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},yes:{type:`switch`,description:{"en-US":`Write YAML and run the scoped remote create`,"zh-CN":`写入 YAML 并执行定向远端创建`}}};function U_(e){return P_({displayName:e.displayName,provider:e.provider,resourceTypes:[`agent`,`template`],declarations:e.agents,candidate:e.candidate,effectiveName:(e,t)=>typeof t.name==`string`?t.name:e,fallbackKey:`agent`,state:e.state})}function W_(e){if(e===void 0||e===`custom`)return`custom`;if(e===`official`)return`official`;throw new n(`--type must be either custom or official.`,l.USAGE)}function G_(e,t=`custom`){let r=new Set,i=[];for(let a of e??[]){let e=a.trim();if(!e)throw new n(`--skill values must not be empty.`,l.USAGE);r.has(e)||(r.add(e),i.push({type:t,skill_id:e}))}return i}function K_(e){let t=e=>Array.isArray(e)?e.map(t):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,n])=>[e,t(n)]));return JSON.stringify(t(e))}function q_(e){let t=new Set(e.state.listResources().filter(t=>t.address.provider===e.provider&&t.address.type===`skill`).map(e=>e.address.name)),r=Object.entries(e.declarations).filter(([t,n])=>(typeof n.name==`string`?n.name:t)===e.displayName),i=r.find(([n,r])=>t.has(n)&&K_(r)===K_(e.candidate));if(i)return{key:i[0],needsCreate:!1,reusedPending:!1,reusedTracked:!0};if(r.find(([e])=>t.has(e)))throw new n(`Skill '${e.displayName}' is already tracked with a different declaration.`,l.USAGE,"Modify its existing YAML declaration and run full `bl managed-agent apply`, or bind its remote ID with --skill.");return{...P_({displayName:e.displayName,provider:e.provider,resourceTypes:[`skill`],declarations:e.declarations,candidate:e.candidate,effectiveName:(e,t)=>typeof t.name==`string`?t.name:e,fallbackKey:`skill`,state:e.state}),needsCreate:!0,reusedTracked:!1}}async function J_(e,t){let r={...e.config.skills??{}},i=new Map,a=new Map;for(let o of t??[]){let t=o.trim();if(!t)throw new n(`--skill-dir values must not be empty.`,l.USAGE);let s=await G(()=>Ni(t,{basePath:process.cwd()})),c=await $r(s.sourcePath);if(!(c.isDirectory()||c.isFile()&&Lr(s.sourcePath).toLowerCase()===`.zip`))throw new n(`--skill-dir requires a Skill directory or .zip file: ${t}`,l.USAGE);if(i.has(s.sourcePath))continue;let u=Rr(Ir(e.configPath),s.sourcePath).split(zr).join(`/`)||`.`,d={name:s.name,source:u,origin:`custom`,provider:e.provider},f=await I_({project:e,group:`skills`,rawDeclaration:d}),p=await e.stateBackend.read(e.stateScope,t=>q_({displayName:s.name,provider:e.provider,declarations:r,candidate:f,state:t})),m=a.get(p.key);if(m){i.set(s.sourcePath,m);continue}let h={...p,name:s.name,source:u,rawDeclaration:d,resolvedDeclaration:f};r[p.key]=f,i.set(s.sourcePath,h),a.set(p.key,h)}return[...a.values()]}var Y_=C({description:{"en-US":`Declare and create one Managed Agent through an isolated YAML apply`,"zh-CN":`通过隔离的 YAML Apply 声明并创建一个托管 Agent`},auth:`apiKey`,usageArgs:`--name <name> --model <model> --instructions <text|path> [--description <text>] [--skill <id>...] [--type custom|official] [--skill-dir <path>...] [--tool <name>...] [--file <path>] [--yes]`,flags:H_,exampleArgs:[`--name assistant --model qwen3.8-max --instructions "You are helpful."`,`--name assistant --model qwen3.8-max --instructions ./prompts/assistant.md --skill skill_abc --yes`,`--name slides --model qwen3.8-max --instructions ./prompts/slides.md --skill skill_pptx --type official --yes`,`--name reviewer --model qwen3.8-max --instructions ./prompts/reviewer.md --skill-dir ./skills/code-review --yes`],notes:[...U,{"en-US":`Without --yes, previews the generated YAML key and scoped plan. --dry-run stays offline. Unrelated resources are not refreshed or drift-checked.`,"zh-CN":`不带 --yes 时预览自动生成的 YAML key 和定向计划;--dry-run 完全离线。无关资源不会刷新或检测 Drift。`},{"en-US":`--skill writes an external Skill reference directly into the Agent declaration. --type defaults to custom; use --type official for platform Skills. These Skills are not managed through the top-level skills map.`,"zh-CN":`--skill 会把外部 Skill 引用直接写入 Agent 声明。--type 默认为 custom;平台 Skill 使用 --type official。这些 Skill 不通过顶层 skills 资源管理。`},{"en-US":`--skill-dir accepts a local Skill directory or ZIP, writes it as a top-level custom Skill declaration, and writes its generated YAML key into the Agent skills list. Skill and Agent are created together in dependency order. --type applies only to --skill IDs.`,"zh-CN":`--skill-dir 接收本地 Skill 目录或 ZIP,将其写为顶层 custom Skill 声明,并把生成的 YAML key 写入 Agent 的 skills 列表;Skill 与 Agent 按依赖顺序一并创建。--type 只作用于 --skill ID。`}],validate:e=>{if(!e.name.trim())return`--name must not be empty.`;if(!e.model.trim())return`--model must not be empty.`;if(!e.instructions.trim())return`--instructions must not be empty.`;if(e.type&&!e.skill?.length)return`--type requires at least one --skill.`;if(e.skill?.some(e=>!e.trim()))return`--skill values must not be empty.`;if(e.skillDir?.some(e=>!e.trim()))return`--skill-dir values must not be empty.`},async run(e){let{flags:t,settings:r}=e,i=w(r.output),a=await F_(e,t.file??`agents.yaml`),o=a.provider,s=G_(t.skill,W_(t.type)),c=await J_(a,t.skillDir),u=[...s,...c.map(e=>e.key)],d=pi(void 0,{name:t.name.trim(),description:t.description,model:t.model,instructions:t.instructions,provider:o,builtinTools:t.tool}).agent;d.skills=u;let f=structuredClone(a.config);f.skills={...f.skills};for(let e of c)f.skills[e.key]=e.resolvedDeclaration;f._resolved=!0;let p=await I_({project:{...a,config:f},group:`agents`,rawDeclaration:d}),m=await a.stateBackend.read(a.stateScope,e=>U_({displayName:t.name.trim(),provider:o,agents:a.config.agents??{},candidate:p,state:e})),h=m.key;f.agents={...f.agents,[h]:p},f._resolved=!0;let g=Ur(a.source);if(g.errors.length>0)throw new n(`YAML parse error: ${g.errors.map(e=>e.message).join(`; `)}`,l.USAGE);for(let e of c)g.setIn([`skills`,e.key],e.rawDeclaration);g.setIn([`agents`,h],d);let _=g.toString(),v={type:`agent`,name:h,provider:o},y=[...c.filter(e=>e.needsCreate).map(e=>({type:`skill`,name:e.key,provider:o})),v],b={projectName:a.projectName,config:f,configPath:a.configPath,providers:{[o]:f.providers[o]},stateBackend:a.stateBackend,stateScope:a.stateScope};if(r.dryRun||!t.yes){let e=await G(()=>K(()=>Yi(b,{provider:o,scope:{roots:y},refresh:!r.dryRun,quiet:i===`json`,mode:`create-only`}))),n=!e.plan.diagnostics.some(e=>e.severity===`error`),s={agent:{key:h,name:t.name.trim(),provider:o,skills:u},local_skills:c.map(e=>({key:e.key,name:e.name,source:e.source,reused_pending:e.reusedPending,reused_tracked:e.reusedTracked})),config_file:a.configPath,yaml_written:!1,reused_pending:m.reusedPending,requires_confirmation:!r.dryRun,ready_to_create:n,actions:e.plan.actions,diagnostics:e.plan.diagnostics};if(i===`json`)D(s,i);else{for(let e of c)E(`Generated Skill YAML key: ${e.key}`);E(`Generated Agent YAML key: ${h}`);for(let t of e.plan.diagnostics)E(`[${t.severity}] ${t.code}: ${t.message}`);for(let t of e.plan.actions.filter(e=>e.action!==`no-op`))E(` ${t.action===`create`?`+`:t.action===`update`?`~`:`-`} ${Yh(t.address)}`);E(r.dryRun?`Dry run: YAML, State, and remote resources were not changed.`:`Preview only: re-run with --yes to write YAML and create this Agent.`)}return}await R_(a.configPath,a.source,_);let x;try{x=await G(()=>K(()=>sa(b,{provider:o,scope:{roots:y},refresh:!0,quiet:i===`json`,mode:`create-only`,policy:`block`})))}catch(e){throw qh(e,`The YAML declarations were kept. Fix the related dependency or provider error, then re-run the same create command.`,`Scoped Agent and Skill create failed.`)}let S=await a.stateBackend.read(a.stateScope,e=>({agentId:e.getResource(v)?.remote_id,skillIds:Object.fromEntries(c.map(t=>[t.key,e.getResource({type:`skill`,name:t.key,provider:o})?.remote_id]))})),ee=x.execution?.results??[],te=ee.find(e=>e.status===`failed`),ne=te?`failed`:`completed`,re={agent:{key:h,name:t.name.trim(),provider:o,remote_id:S.agentId,skills:u},local_skills:c.map(e=>({key:e.key,name:e.name,source:e.source,remote_id:S.skillIds[e.key],reused_pending:e.reusedPending,reused_tracked:e.reusedTracked})),config_file:a.configPath,yaml_written:!0,reused_pending:m.reusedPending,status:ne,actions:x.planned.plan.actions,diagnostics:x.planned.plan.diagnostics,results:ee,error:te?.error};if(i===`json`?D(re,i):(E(`Wrote ${a.configPath} with Agent key '${h}'${c.length?` and ${c.length} local Skill declaration(s)`:``}.`),E(ne===`completed`?`Created Agent '${t.name.trim()}'.`:`Scoped create ${ne}: ${te?.error??`unknown error`}`)),te)throw new n(te.error??`Scoped Agent create failed.`,l.GENERAL,`The YAML declarations were kept. Fix the related dependency or provider error, then re-run the same create command.`)}}),X_=C({description:{"en-US":`Declare and create one Managed Agent Environment through a scoped YAML apply`,"zh-CN":`通过定向 YAML Apply 声明并创建一个托管 Agent Environment`},auth:`apiKey`,usageArgs:`--name <name> [--description <text>] [--metadata <key=value>...] [--apt <package>...] [--pip <package>...] [--npm <package>...] [--cargo <package>...] [--gem <package>...] [--go <package>...] [--file <path>] [--yes]`,flags:{name:{type:`string`,valueHint:`<name>`,required:!0,description:{"en-US":`Remote Environment display name; the YAML key is generated automatically`,"zh-CN":`远端 Environment 显示名称;YAML key 将自动生成`}},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`Environment description`,"zh-CN":`Environment 描述`}},metadata:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Metadata entry (repeatable)`,"zh-CN":`Metadata 条目(可重复)`}},apt:Z_(`APT`),pip:Z_(`pip`),npm:Z_(`npm`),cargo:Z_(`Cargo`),gem:Z_(`Ruby gem`),go:Z_(`Go`),file:Q_(),yes:$_()},exampleArgs:[`--name Development`,`--name Development --pip pandas --npm typescript --metadata owner=platform --yes`],notes:[...U,...j_,{"en-US":`Creates a cloud Environment with unrestricted networking. Without --yes, only previews the generated YAML key and scoped plan.`,"zh-CN":`创建使用 unrestricted 网络的 cloud Environment。不带 --yes 时仅预览自动生成的 YAML key 和定向计划。`}],validate:e=>e.name.trim()?void 0:`--name must not be empty.`,async run(e){let t=await F_(e,e.flags.file??`agents.yaml`),n=Object.fromEntries([`apt`,`pip`,`npm`,`cargo`,`gem`,`go`].map(t=>[t,e.flags[t]]).filter(e=>Array.isArray(e[1])&&e[1].length>0)),r={name:e.flags.name.trim(),description:e.flags.description,provider:t.provider,config:{type:`cloud`,networking:{type:`unrestricted`},...Object.keys(n).length>0?{packages:n}:{}},metadata:z_(e.flags.metadata)},i=await I_({project:t,group:`environments`,rawDeclaration:r});await L_({host:e,project:t,group:`environments`,resourceType:`environment`,displayName:e.flags.name.trim(),rawDeclaration:r,resolvedDeclaration:i,existingDeclarations:t.config.environments??{},effectiveName:(e,t)=>typeof t.name==`string`?t.name:e,fallbackKey:`environment`,yes:e.flags.yes})}});function Z_(e){return{type:`array`,valueHint:`<package>`,description:{"en-US":`${e} package (repeatable)`,"zh-CN":`${e} 软件包(可重复)`}}}function Q_(){return{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}}function $_(){return{type:`switch`,description:{"en-US":`Write YAML and run the scoped remote create`,"zh-CN":`写入 YAML 并执行定向远端创建`}}}var ev=C({description:{"en-US":`Declare and create one custom Managed Agent Skill from a local source`,"zh-CN":`从本地来源声明并创建一个自定义托管 Agent Skill`},auth:`apiKey`,usageArgs:`--source <directory|zip|SKILL.md> [--file <path>] [--yes]`,flags:{source:{type:`string`,valueHint:`<directory|zip|SKILL.md>`,required:!0,description:{"en-US":`Local Skill directory, ZIP archive, or single SKILL.md`,"zh-CN":`本地 Skill 目录、ZIP 压缩包或单个 SKILL.md`}},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},yes:{type:`switch`,description:{"en-US":`Write YAML and upload the Skill through the scoped create`,"zh-CN":`写入 YAML 并通过定向创建上传 Skill`}}},exampleArgs:[`--source ./skills/code-review`,`--source ./skill.zip --yes`],notes:[...U,...j_,{"en-US":`The YAML key is derived from SKILL.md frontmatter name. Remote URLs remain available through handwritten YAML plus full apply.`,"zh-CN":`YAML key 从 SKILL.md frontmatter 的 name 生成。远程 URL 仍可手工写入 YAML 后执行全量 Apply。`}],validate:e=>e.source.trim()?void 0:`--source must not be empty.`,async run(e){let t=await F_(e,e.flags.file??`agents.yaml`),r=await Ni(e.flags.source,{basePath:process.cwd()}),i=Rr(Ir(t.configPath),r.sourcePath).split(zr).join(`/`)||`.`,a=t.config.skills??{};if(await t.stateBackend.read(t.stateScope,e=>e.listResources().some(e=>{if(e.address.provider!==t.provider||e.address.type!==`skill`)return!1;let n=a[e.address.name];return(typeof n?.name==`string`?n.name:e.address.name)===r.name})))throw new n(`Skill '${r.name}' is already tracked.`,l.USAGE,"Modify its existing YAML declaration and run full `bl managed-agent apply` to create a new version.");let o={name:r.name,source:i,origin:`custom`,provider:t.provider},s=await I_({project:t,group:`skills`,rawDeclaration:o});await L_({host:e,project:t,group:`skills`,resourceType:`skill`,displayName:r.name,rawDeclaration:o,resolvedDeclaration:s,existingDeclarations:a,effectiveName:(e,t)=>typeof t.name==`string`?t.name:e,fallbackKey:`skill`,yes:e.flags.yes})}}),tv=C({description:{"en-US":`Declare and create one empty Managed Agent Vault through a scoped YAML apply`,"zh-CN":`通过定向 YAML Apply 声明并创建一个空的托管 Agent Vault`},auth:`apiKey`,usageArgs:`--name <name> [--metadata <key=value>...] [--file <path>] [--yes]`,flags:{name:{type:`string`,valueHint:`<name>`,required:!0,description:{"en-US":`Remote Vault display name; the YAML key is generated automatically`,"zh-CN":`远端 Vault 显示名称;YAML key 将自动生成`}},metadata:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Metadata entry (repeatable)`,"zh-CN":`Metadata 条目(可重复)`}},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},yes:{type:`switch`,description:{"en-US":`Write YAML and run the scoped remote create`,"zh-CN":`写入 YAML 并执行定向远端创建`}}},exampleArgs:[`--name Production`,`--name Production --metadata owner=platform --yes`],notes:[...U,...j_,{"en-US":"Creates an empty Vault. Add secrets later with `vault credential create`.","zh-CN":"创建空 Vault;随后使用 `vault credential create` 添加 Secret。"}],validate:e=>e.name.trim()?void 0:`--name must not be empty.`,async run(e){let t=await F_(e,e.flags.file??`agents.yaml`),n={display_name:e.flags.name.trim(),provider:t.provider,credentials:[],metadata:z_(e.flags.metadata)},r=await I_({project:t,group:`vaults`,rawDeclaration:n});await L_({host:e,project:t,group:`vaults`,resourceType:`vault`,displayName:e.flags.name.trim(),rawDeclaration:n,resolvedDeclaration:r,existingDeclarations:t.config.vaults??{},effectiveName:(e,t)=>typeof t.display_name==`string`?t.display_name:e,fallbackKey:`vault`,yes:e.flags.yes})}}),nv=C({description:{"en-US":`Append and create one environment-variable Credential in a tracked Vault`,"zh-CN":`在已跟踪 Vault 中追加并创建一个环境变量 Credential`},auth:`apiKey`,usageArgs:`--vault <yaml-key> --name <name> --secret-name <name> --secret-env <env-name> [--metadata <key=value>...] [--file <path>] [--yes]`,flags:{vault:{type:`string`,valueHint:`<yaml-key>`,required:!0,description:{"en-US":`Existing tracked Vault key from agents.yaml`,"zh-CN":`agents.yaml 中已跟踪的 Vault key`}},name:{type:`string`,valueHint:`<name>`,required:!0,description:{"en-US":`Credential display name`,"zh-CN":`Credential 显示名称`}},secretName:{type:`string`,valueHint:`<name>`,required:!0,description:{"en-US":`Environment variable name exposed to the Agent`,"zh-CN":`提供给 Agent 的环境变量名`}},secretEnv:{type:`string`,valueHint:`<env-name>`,required:!0,description:{"en-US":`Local environment variable containing the secret value`,"zh-CN":`保存真实 Secret 的本地环境变量名`}},metadata:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Metadata entry (repeatable)`,"zh-CN":`Metadata 条目(可重复)`}},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},yes:{type:`switch`,description:{"en-US":`Write YAML and create the remote Credential`,"zh-CN":`写入 YAML 并创建远端 Credential`}}},exampleArgs:[`--vault production --name api-token --secret-name API_TOKEN --secret-env PROD_API_TOKEN`,`--vault production --name api-token --secret-name API_TOKEN --secret-env PROD_API_TOKEN --yes`],notes:[...U,...j_,{"en-US":`--secret-env is an environment variable name, not the secret itself. The CLI auto-loads the nearest .env from the current directory upward; shell exports and CI secret injection also work.`,"zh-CN":`--secret-env 接收环境变量名,不接收 Secret 本身。CLI 会从当前目录向上自动加载最近的 .env,也支持 Shell export 和 CI Secret 注入。`},{"en-US":"YAML stores only ${ENV_NAME}. Never commit .env; subsequent full apply runs must provide the same environment variable.","zh-CN":"YAML 只保存 ${ENV_NAME}。不要提交 .env;后续执行全量 Apply 时仍需提供同名环境变量。"}],validate:e=>{if(!e.vault.trim())return`--vault must not be empty.`;if(!e.name.trim())return`--name must not be empty.`;if(!e.secretName.trim())return`--secret-name must not be empty.`;if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.secretEnv))return`--secret-env must be a valid environment variable name.`},async run(e){let t=w(e.settings.output);fi();let r=process.env[e.flags.secretEnv],i=await F_(e,e.flags.file??`agents.yaml`).finally(()=>{delete process.env[e.flags.secretEnv]});if(!i.config.vaults?.[e.flags.vault])throw new n(`Vault '${e.flags.vault}' is not declared in agents.yaml.`,l.USAGE);if(e.flags.yes&&!e.settings.dryRun&&!r)throw new n(`Environment variable '${e.flags.secretEnv}' is not set or is empty.`,l.USAGE,`Set it in your shell, CI secret store, or a local .env file, then re-run with --secret-env ${e.flags.secretEnv}.`);let a=z_(e.flags.metadata),o={name:e.flags.name.trim(),type:`environment_variable`,secret_name:e.flags.secretName.trim(),secret_value:`\${${e.flags.secretEnv}}`,networking:{type:`unrestricted`},...a?{metadata:a}:{}},s={...o,secret_value:r??`__dry_run_secret__`},c=Ur(i.source);if(c.errors.length>0)throw new n(`YAML parse error: ${c.errors.map(e=>e.message).join(`; `)}`,l.USAGE);let u=c.toJS().vaults?.[e.flags.vault]?.credentials??[],d=u.filter(e=>!!(e&&typeof e==`object`&&!Array.isArray(e)&&e.name===o.name)),f=!1;if(d.length>0){let t=u.at(-1),r=d[0];if(d.length!==1||r!==t||!rv(r,o))throw new n(`Vault '${e.flags.vault}' already declares a different credential named '${o.name}'.`,l.USAGE,"Modify the existing YAML declaration and run full `bl managed-agent apply`; create never overwrites it.");f=!0}let p=structuredClone(i.config),m=p.vaults,h=m[e.flags.vault];f||(m[e.flags.vault]={...h,credentials:[...h.credentials??[],s]});let g=(await G(()=>Qi(p,{projectName:i.projectName,basePath:Ir(i.configPath)}))).config;f||c.addIn([`vaults`,e.flags.vault,`credentials`],o);let _=f?i.source:c.toString(),v={projectName:i.projectName,config:g,configPath:i.configPath,providers:{[i.provider]:g.providers[i.provider]},stateBackend:i.stateBackend,stateScope:i.stateScope};if(e.settings.dryRun||!e.flags.yes){let n=await G(()=>K(()=>Xi(v,e.flags.vault,e.flags.name.trim(),{provider:i.provider,refresh:!e.settings.dryRun,quiet:t===`json`,checkRemote:!e.settings.dryRun}))),r={vault:{key:e.flags.vault,remote_id:n.vaultRemoteId},credential:{name:e.flags.name.trim(),secret_name:e.flags.secretName.trim(),secret_env:e.flags.secretEnv},config_file:i.configPath,yaml_written:!1,reused_pending:f,requires_confirmation:!e.settings.dryRun,ready_to_create:!0,remote_checked:n.remoteChecked,reuse_remote:n.reuseRemote};t===`json`?D(r,t):(E(`Vault: ${e.flags.vault}`),E(`Credential: ${e.flags.name.trim()} (secret from ${e.flags.secretEnv})`),E(e.settings.dryRun?`Dry run: YAML, State, and remote resources were not changed.`:`Preview only: re-run with --yes to append YAML and create this Credential.`));return}await R_(i.configPath,i.source,_);let y;try{y=await G(()=>K(()=>gi(v,e.flags.vault,e.flags.name.trim(),{provider:i.provider,refresh:!0,quiet:t===`json`})))}catch(e){throw qh(e,`The YAML declaration was kept. Restore the same secret environment variable and re-run this command; an already-created matching Credential will be adopted.`,`Vault Credential create failed.`)}let b={vault:{key:e.flags.vault,remote_id:y.vaultRemoteId},credential:{id:y.credentialId,name:e.flags.name.trim(),secret_name:e.flags.secretName.trim(),secret_env:e.flags.secretEnv},config_file:i.configPath,yaml_written:!0,reused_pending:f,adopted:y.adopted,status:`completed`};t===`json`?D(b,t):E(`Wrote ${i.configPath} and created Credential '${e.flags.name.trim()}'.`)}});function rv(e,t){return iv(e)===iv(t)}function iv(e){let t=e=>Array.isArray(e)?e.map(t):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,n])=>[e,t(n)]));return JSON.stringify(t(e))}var av=C({description:{"en-US":`Declare and create one Managed Agent Deployment through a scoped YAML apply`,"zh-CN":`通过定向 YAML Apply 声明并创建一个托管 Agent Deployment`},auth:`apiKey`,usageArgs:`--name <name> --agent <yaml-key> (--message <text>... | --event <json|@path>...) [--agent-version <number>] [--environment <yaml-key>] [--vault <yaml-key>...] [--resource <json|@path>...] [--schedule <cron> --timezone <timezone>] [--description <text>] [--metadata <key=value>...] [--file <path>] [--yes]`,flags:{name:{type:`string`,valueHint:`<name>`,required:!0,description:{"en-US":`Remote Deployment display name; the YAML key is generated automatically`,"zh-CN":`远端 Deployment 显示名称;YAML key 将自动生成`}},agent:{type:`string`,valueHint:`<yaml-key>`,required:!0,description:{"en-US":`Existing Agent key from agents.yaml`,"zh-CN":`agents.yaml 中已有的 Agent key`}},agentVersion:{type:`number`,valueHint:`<number>`,description:{"en-US":`Agent version`,"zh-CN":`Agent 版本`}},environment:{type:`string`,valueHint:`<yaml-key>`,description:{"en-US":`Existing Environment key from agents.yaml`,"zh-CN":`agents.yaml 中已有的 Environment key`}},vault:{type:`array`,valueHint:`<yaml-key>`,description:{"en-US":`Existing Vault key from agents.yaml (repeatable)`,"zh-CN":`agents.yaml 中已有的 Vault key(可重复)`}},message:{type:`array`,valueHint:`<text>`,description:{"en-US":`Initial user message (repeatable)`,"zh-CN":`初始用户消息(可重复)`}},event:{type:`array`,valueHint:`<json|@path>`,description:{"en-US":`Initial user.message or system.message JSON (repeatable)`,"zh-CN":`初始 user.message 或 system.message JSON(可重复)`}},resource:{type:`array`,valueHint:`<json|@path>`,description:{"en-US":`File Resource JSON with source or file_id (repeatable)`,"zh-CN":`包含 source 或 file_id 的 File Resource JSON(可重复)`}},schedule:{type:`string`,valueHint:`<cron>`,description:{"en-US":`Five-field cron expression`,"zh-CN":`五段式 Cron 表达式`}},timezone:{type:`string`,valueHint:`<timezone>`,description:{"en-US":`IANA schedule timezone`,"zh-CN":`Schedule 的 IANA 时区`}},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`Deployment description`,"zh-CN":`Deployment 描述`}},metadata:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Metadata entry (repeatable)`,"zh-CN":`Metadata 条目(可重复)`}},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},yes:{type:`switch`,description:{"en-US":`Write YAML and run the scoped remote create`,"zh-CN":`写入 YAML 并执行定向远端创建`}}},exampleArgs:[{"en-US":`--name Daily --agent assistant --message "Generate the report"`,"zh-CN":`--name Daily --agent assistant --message "生成报告"`},{"en-US":`--name Daily --agent assistant --event '{"type":"system.message","content":"Be concise"}' --yes`,"zh-CN":`--name Daily --agent assistant --event '{"type":"system.message","content":"保持简洁"}' --yes`}],notes:[...U,...j_,{"en-US":`Initial Events must contain 1-50 user.message/system.message entries. --resource accepts only File Resources in this release.`,"zh-CN":`Initial Events 必须包含 1–50 条 user.message/system.message;本期 --resource 仅接受 File Resource。`},{"en-US":`Use either repeatable --message values or repeatable --event values; the two input forms cannot be mixed.`,"zh-CN":`重复使用 --message 或重复使用 --event;两种输入形式不能混用。`}],validate:e=>{if(!e.name.trim())return`--name must not be empty.`;if(!e.agent.trim())return`--agent must not be empty.`;if(e.message?.length&&e.event?.length)return`--message and --event cannot be used together.`;if(!e.message?.length&&!e.event?.length)return`Pass at least one --message or --event.`;if(!!e.schedule!=!!e.timezone)return`--schedule and --timezone must be provided together.`;if(e.agentVersion!==void 0&&(!Number.isInteger(e.agentVersion)||e.agentVersion<1))return`--agent-version must be a positive integer.`},async run(e){let t=await F_(e,e.flags.file??`agents.yaml`),r=[...(e.flags.message??[]).map(e=>({type:`user.message`,content:e})),...ov(await B_(e.flags.event,`event`))];if(r.length<1||r.length>50)throw new n(`Initial Events must contain 1-50 entries.`,l.USAGE);let i=sv(await B_(e.flags.resource,`resource`));if(e.flags.schedule&&e.flags.schedule.trim().split(/\s+/).length!==5)throw new n(`--schedule must be a five-field cron expression.`,l.USAGE);e.flags.timezone&&cv(e.flags.timezone);let a={name:e.flags.name.trim(),agent:e.flags.agent,agent_version:e.flags.agentVersion,environment:e.flags.environment,vaults:e.flags.vault,resources:i,initial_events:r,schedule:e.flags.schedule&&e.flags.timezone?{expression:e.flags.schedule,timezone:e.flags.timezone}:void 0,description:e.flags.description,provider:t.provider,metadata:z_(e.flags.metadata)},o=await I_({project:t,group:`deployments`,rawDeclaration:a});await L_({host:e,project:t,group:`deployments`,resourceType:`deployment`,displayName:e.flags.name.trim(),rawDeclaration:a,resolvedDeclaration:o,existingDeclarations:t.config.deployments??{},effectiveName:(e,t)=>typeof t.name==`string`?t.name:e,fallbackKey:`deployment`,yes:e.flags.yes})}});function ov(e){return e.map(e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`Each --event must be a JSON object.`,l.USAGE);let t=e;if(t.type!==`user.message`&&t.type!==`system.message`)throw new n(`--event type must be user.message or system.message.`,l.USAGE);if(typeof t.content!=`string`||!t.content.trim())throw new n(`--event content must be a non-empty string.`,l.USAGE);return{type:t.type,content:t.content}})}function sv(e){return e.map(e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`Each --resource must be a JSON object.`,l.USAGE);let t=e;if(t.type!==`file`)throw new n(`--resource currently accepts only type=file.`,l.USAGE);let r=typeof t.source==`string`?t.source:void 0,i=typeof t.file_id==`string`?t.file_id:void 0;if(!!r==!!i)throw new n(`A File Resource must provide exactly one of source or file_id.`,l.USAGE);if(t.mount_path!==void 0&&typeof t.mount_path!=`string`)throw new n(`File Resource mount_path must be a string.`,l.USAGE);return{type:`file`,source:r,file_id:i,mount_path:t.mount_path}})}function cv(e){try{new Intl.DateTimeFormat(`en-US`,{timeZone:e}).format()}catch{throw new n(`Invalid IANA timezone: ${e}`,l.USAGE)}}const lv={...q,...J,...Qg},uv={...q,limit:J.limit,...Zg,...Qg},dv={...q,agentId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Agent ID`,"zh-CN":`Agent ID`}},agentVersion:{type:`number`,valueHint:`<n>`,description:{"en-US":`Specific agent version`,"zh-CN":`指定 Agent 版本`}}},fv={...q,...J,agentId:dv.agentId};function pv(e){return e.map(e=>[e.id,Z(e.name),Z(e.version),Z(e.type),Z(e.updated_at)])}var mv=C({description:{"en-US":`Get a Managed Agent`,"zh-CN":`获取托管 Agent 详情`},auth:`apiKey`,usageArgs:`--agent-id <id> [--agent-version <n>] [--file <path>]`,flags:dv,exampleArgs:[`--agent-id agent_abc`,`--agent-id agent_abc --agent-version 3 --output json`],notes:U,validate:e=>e.agentVersion!==void 0&&(!Number.isInteger(e.agentVersion)||e.agentVersion<1)?`--agent-version must be a positive integer.`:void 0,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>Ti(await W(e,e.flags.file??`agents.yaml`),e.flags.agentId,{provider:`bailian`,version:e.flags.agentVersion})));if(t===`json`){D(n,t);return}E(`ID: ${n.id}`),E(`Name: ${Z(n.name)}`),E(`Description: ${Z(n.description,120)}`),E(`Version: ${Z(n.version)}`),E(`Type: ${Z(n.type)}`),E(`Created: ${Z(n.created_at)}`),E(`Updated: ${Z(n.updated_at)}`)}}),hv=C({description:{"en-US":`List Managed Agents`,"zh-CN":`列出托管 Agent`},auth:`apiKey`,usageArgs:`[--limit <n>] [--page <cursor>] [--all] [--include-archived] [--file <path>]`,flags:lv,exampleArgs:[``,`--limit 50`,`--all --include-archived --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return Xg(async n=>{let r=await Ii(t,{provider:`bailian`,limit:e.flags.limit,page:n,include_archived:e.flags.includeArchived});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`agents`,items:n.items,headers:[`ID`,`NAME`,`VERSION`,`TYPE`,`UPDATED`],rows:pv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No agents found.`})}}),gv=C({description:{"en-US":`Search Managed Agents`,"zh-CN":`搜索托管 Agent`},auth:`apiKey`,usageArgs:`--query <text> [--limit <n>] [--page-limit <n>] [--include-archived]`,flags:uv,exampleArgs:[`--query assistant`,`--query code --page-limit 20 --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return t_(async n=>{let r=await Ii(t,{provider:`bailian`,limit:e.flags.limit??100,page:n,include_archived:e.flags.includeArchived});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},t=>e_(e.flags.query,t.id,t.name,t.description),e.flags.pageLimit)}));X({format:t,key:`agents`,items:n.items,headers:[`ID`,`NAME`,`VERSION`,`TYPE`,`UPDATED`],rows:pv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching agents found.`})}}),_v=C({description:{"en-US":`List Managed Agent versions`,"zh-CN":`列出托管 Agent 版本`},auth:`apiKey`,usageArgs:`--agent-id <id> [--limit <n>] [--page <cursor>] [--all]`,flags:fv,exampleArgs:[`--agent-id agent_abc`,`--agent-id agent_abc --all --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return Xg(async n=>{let r=await Fi(t,e.flags.agentId,{provider:`bailian`,limit:e.flags.limit,page:n});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`versions`,items:n.items,headers:[`ID`,`NAME`,`VERSION`,`TYPE`,`UPDATED`],rows:pv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No agent versions found.`})}});const vv={...q,...J,...Qg},yv={...q,limit:J.limit,...Zg,...Qg},bv={...q,environmentId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Environment ID`,"zh-CN":`Environment ID`}}};function xv(e){return e.map(e=>[e.id,Z(e.name),Z(e.scope),Z(e.version),Z(e.updated_at)])}var Sv=C({description:{"en-US":`Get a Managed Agent environment`,"zh-CN":`获取托管 Agent 环境详情`},auth:`apiKey`,usageArgs:`--environment-id <id>`,flags:bv,exampleArgs:[`--environment-id env_abc`],notes:U,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>Oi(await W(e,e.flags.file??`agents.yaml`),e.flags.environmentId,{provider:`bailian`})));if(t===`json`){D(n,t);return}E(`ID: ${n.id}`),E(`Name: ${Z(n.name)}`),E(`Description: ${Z(n.description,120)}`),E(`Scope: ${Z(n.scope)}`),E(`Version: ${Z(n.version)}`),E(`Updated: ${Z(n.updated_at)}`)}}),Cv=C({description:{"en-US":`List Managed Agent environments`,"zh-CN":`列出托管 Agent 环境`},auth:`apiKey`,usageArgs:`[--limit <n>] [--page <cursor>] [--all] [--include-archived]`,flags:vv,exampleArgs:[``,`--all --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return Xg(async n=>{let r=await zi(t,{provider:`bailian`,limit:e.flags.limit,page:n,include_archived:e.flags.includeArchived});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`environments`,items:n.items,headers:[`ID`,`NAME`,`SCOPE`,`VERSION`,`UPDATED`],rows:xv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No environments found.`})}}),wv=C({description:{"en-US":`Search Managed Agent environments`,"zh-CN":`搜索托管 Agent 环境`},auth:`apiKey`,usageArgs:`--query <text> [--limit <n>] [--page-limit <n>] [--include-archived]`,flags:yv,exampleArgs:[`--query sandbox`,`--query production --page-limit 20 --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return t_(async n=>{let r=await zi(t,{provider:`bailian`,limit:e.flags.limit??100,page:n,include_archived:e.flags.includeArchived});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},t=>e_(e.flags.query,t.id,t.name,t.description),e.flags.pageLimit)}));X({format:t,key:`environments`,items:n.items,headers:[`ID`,`NAME`,`SCOPE`,`VERSION`,`UPDATED`],rows:xv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching environments found.`})}}),Tv=C({description:{"en-US":`Download a Managed Agent skill version`,"zh-CN":`下载托管 Agent Skill 版本`},auth:`apiKey`,usageArgs:`--skill-id <id> --skill-version <version> --output-file <path> [--force]`,flags:T_,exampleArgs:[`--skill-id skill_abc --skill-version 3 --output-file ./skill.zip`],notes:U,async run(e){let t=w(e.settings.output);if(e.settings.dryRun){D({would_download_skill:e.flags.skillId,version:e.flags.skillVersion,output_file:e.flags.outputFile},t);return}let n=await G(()=>K(async()=>xi(await W(e,e.flags.file??`agents.yaml`),e.flags.skillId,e.flags.skillVersion,{provider:`bailian`}))),r=await l_(e.flags.outputFile,n,e.flags.force);t===`json`?D({downloaded:e.flags.skillId,version:e.flags.skillVersion,output_file:r},t):E(`Skill downloaded to ${r}`)}}),Ev=C({description:{"en-US":`Get a Managed Agent skill`,"zh-CN":`获取托管 Agent Skill 详情`},auth:`apiKey`,usageArgs:`--skill-id <id>`,flags:C_,exampleArgs:[`--skill-id skill_abc`],notes:U,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>ki(await W(e,e.flags.file??`agents.yaml`),e.flags.skillId,{provider:`bailian`})));if(t===`json`){D(n,t);return}E(`ID: ${n.id}`),E(`Name: ${n.name}`),E(`Description: ${Z(n.description,120)}`),E(`Source: ${n.source}`),E(`Status: ${n.status}`),E(`Version: ${Z(n.latest_version)}`)}}),Dv=C({description:{"en-US":`Search Managed Agent skills`,"zh-CN":`搜索托管 Agent Skill`},auth:`apiKey`,usageArgs:`--query <text> [--source custom|official|all] [--limit <n>] [--page-limit <n>]`,flags:S_,exampleArgs:[`--query browser --source official`,`--query report --source all --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=e.flags.source??`custom`,r=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`),r=n=>t_(async r=>{let i=await Hi(t,{provider:`bailian`,source:n,limit:e.flags.limit??100,page:r});return{items:i.data,hasMore:i.has_more,nextPage:i.next_page}},t=>e_(e.flags.query,t.id,t.name,t.description),e.flags.pageLimit);if(n!==`all`)return r(n);let[i,a]=await Promise.all([r(`custom`),r(`official`)]);return{items:[...i.items,...a.items],hasMore:i.hasMore||a.hasMore,nextPage:void 0,scannedPages:i.scannedPages+a.scannedPages,truncated:i.truncated||a.truncated}}));X({format:t,key:`skills`,items:r.items,headers:[`ID`,`NAME`,`SOURCE`,`STATUS`,`VERSION`,`UPDATED`],rows:E_(r.items),hasMore:r.hasMore,nextPage:r.nextPage,truncated:r.truncated,scannedPages:r.scannedPages,emptyMessage:`No matching skills found.`})}}),Ov=C({description:{"en-US":`List Managed Agent skill versions`,"zh-CN":`列出托管 Agent Skill 版本`},auth:`apiKey`,usageArgs:`--skill-id <id> [--limit <n>] [--page <cursor>] [--all]`,flags:w_,exampleArgs:[`--skill-id skill_abc`,`--skill-id skill_abc --all --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return Xg(async n=>{let r=await Vi(t,e.flags.skillId,{provider:`bailian`,limit:e.flags.limit,page:n});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`versions`,items:n.items,headers:[`VERSION`,`NAME`,`TYPE`,`STATUS`,`UPDATED`],rows:D_(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No skill versions found.`})}});const kv={...q,...J,...Qg},Av={...q,limit:J.limit,...Zg,...Qg},jv={...q,vaultId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Vault ID`,"zh-CN":`Vault ID`}}};function Mv(e){return e.map(e=>[e.id,Z(e.display_name),Z(e.type),Z(e.created_at),Z(e.updated_at)])}var Nv=C({description:{"en-US":`Get a Managed Agent vault`,"zh-CN":`获取托管 Agent Vault 详情`},auth:`apiKey`,usageArgs:`--vault-id <id>`,flags:jv,exampleArgs:[`--vault-id vault_abc`],notes:U,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>Ai(await W(e,e.flags.file??`agents.yaml`),e.flags.vaultId,{provider:`bailian`})));if(t===`json`){D(n,t);return}E(`ID: ${n.id}`),E(`Name: ${Z(n.display_name)}`),E(`Type: ${Z(n.type)}`),E(`Created: ${Z(n.created_at)}`),E(`Updated: ${Z(n.updated_at)}`)}}),Pv=C({description:{"en-US":`List Managed Agent vaults`,"zh-CN":`列出托管 Agent Vault`},auth:`apiKey`,usageArgs:`[--limit <n>] [--page <cursor>] [--all] [--include-archived]`,flags:kv,exampleArgs:[``,`--all --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return Xg(async n=>{let r=await Ui(t,{provider:`bailian`,limit:e.flags.limit,page:n,include_archived:e.flags.includeArchived});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`vaults`,items:n.items,headers:[`ID`,`NAME`,`TYPE`,`CREATED`,`UPDATED`],rows:Mv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No vaults found.`})}}),Fv=C({description:{"en-US":`Search Managed Agent vaults`,"zh-CN":`搜索托管 Agent Vault`},auth:`apiKey`,usageArgs:`--query <text> [--limit <n>] [--page-limit <n>] [--include-archived]`,flags:Av,exampleArgs:[`--query github`,`--query production --page-limit 20 --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return t_(async n=>{let r=await Ui(t,{provider:`bailian`,limit:e.flags.limit??100,page:n,include_archived:e.flags.includeArchived});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},t=>e_(e.flags.query,t.id,t.display_name,t.metadata),e.flags.pageLimit)}));X({format:t,key:`vaults`,items:n.items,headers:[`ID`,`NAME`,`TYPE`,`CREATED`,`UPDATED`],rows:Mv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching vaults found.`})}});const Iv={deploymentId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Deployment ID`,"zh-CN":`Deployment ID`}}},Lv={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by agent ID`,"zh-CN":`按 Agent ID 筛选`}},status:{type:`string`,valueHint:`<status>`,choices:[`active`,`paused`],description:{"en-US":`Filter by deployment status`,"zh-CN":`按 Deployment 状态筛选`}},...Qg,createdAtGte:{type:`string`,valueHint:`<timestamp>`,description:{"en-US":`Created at or after this timestamp`,"zh-CN":`创建时间不早于该时间戳`}},createdAtLte:{type:`string`,valueHint:`<timestamp>`,description:{"en-US":`Created at or before this timestamp`,"zh-CN":`创建时间不晚于该时间戳`}}},Rv={...q,...J,...Lv},zv={...q,...Iv},Bv={...q,...J,query:Zg.query,...Lv},Vv={...q,...Iv,...J},Hv={...q,runId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Deployment run ID`,"zh-CN":`Deployment Run ID`}}},Uv={...q,deployment:{type:`string`,valueHint:`<name>`,description:{"en-US":`Logical deployment name in agents.yaml/state`,"zh-CN":`agents.yaml/State 中的逻辑 Deployment 名称`}},deploymentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Direct deployment ID`,"zh-CN":`直接指定 Deployment ID`}}};function Wv(e){if(!!e.deployment==!!e.deploymentId)return`Provide exactly one of --deployment or --deployment-id.`}function Gv(e){return e.map(e=>[Z(e.id),e.status,Z(e.schedule?.expression),Z(e.paused_reason?.type)])}function Kv(e){return e.map(e=>[e.id,Z(e.deployment_id),Z(e.session_id),Z(e.status),Z(e.created_at)])}async function qv(e,t){if(t.deploymentId)return t.deploymentId;let n=e.state.getResource({provider:`bailian`,type:`deployment`,name:t.deployment});if(!n?.remote_id)throw new ui(`Deployment '${t.deployment}' is not tracked in state. Use --deployment-id or run managed-agent apply/import first.`);return n.remote_id}var Jv=C({description:{"en-US":`Get a Managed Agent deployment`,"zh-CN":`获取托管 Agent Deployment 详情`},auth:`apiKey`,usageArgs:`--deployment-id <id>`,flags:zv,exampleArgs:[`--deployment-id dep_abc`],notes:U,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>Ei(await W(e,e.flags.file??`agents.yaml`),e.flags.deploymentId,{provider:`bailian`})));t===`json`?D(n,t):(E(`ID: ${Z(n.id)}`),E(`Status: ${n.status}`),E(`Schedule:${Z(n.schedule?.expression)}`),E(`Paused: ${Z(n.paused_reason)}`))}}),Yv=C({description:{"en-US":`List Managed Agent deployments`,"zh-CN":`列出托管 Agent Deployment`},auth:`apiKey`,usageArgs:`[--agent-id <id>] [--status active|paused] [--limit <n>] [--page <cursor>] [--all]`,flags:Rv,exampleArgs:[``,`--status active --all --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return Xg(async n=>{let r=await Ri(t,{provider:`bailian`,agent_id:e.flags.agentId,status:e.flags.status,include_archived:e.flags.includeArchived,created_at_gte:e.flags.createdAtGte,created_at_lte:e.flags.createdAtLte,limit:e.flags.limit,page:n});return{items:r.deployments,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`deployments`,items:n.items,headers:[`ID`,`STATUS`,`SCHEDULE`,`PAUSED REASON`],rows:Gv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No deployments found.`})}});function Xv(e){return C({description:e?{"en-US":`Pause a Managed Agent deployment`,"zh-CN":`暂停托管 Agent Deployment`}:{"en-US":`Unpause a Managed Agent deployment`,"zh-CN":`恢复托管 Agent Deployment`},auth:`apiKey`,risk:{level:`high`,message:e?{"en-US":`This pauses the specified Managed Agent deployment and stops its scheduled executions until resumed.`,"zh-CN":`该操作会暂停指定的托管 Agent Deployment,并停止其定时执行直至恢复。`}:{"en-US":`This resumes the specified Managed Agent deployment and may restart scheduled executions and related usage.`,"zh-CN":`该操作会恢复指定的托管 Agent Deployment,可能重新开始定时执行并产生相关用量。`}},usageArgs:`(--deployment <name> | --deployment-id <id>)`,flags:Uv,exampleArgs:[`--deployment daily-report --dry-run`,`--deployment-id dep_abc --yes`],notes:U,validate:Wv,async run(t){let n=w(t.settings.output);if(t.settings.dryRun){D({[e?`would_pause_deployment`:`would_unpause_deployment`]:t.flags.deploymentId??t.flags.deployment,target_kind:t.flags.deploymentId?`id`:`state_name`},n);return}let r=await G(()=>K(async()=>{let n=await W(t,t.flags.file??`agents.yaml`),r=await qv(n,t.flags);return{deploymentId:r,deployment:await ra(n,r,e,{provider:`bailian`})}}));n===`json`?D({deployment_id:r.deploymentId,deployment:r.deployment},n):E(`Deployment ${r.deploymentId} ${e?`paused`:`unpaused`}.`)}})}var Zv=Xv(!0),Qv=C({description:{"en-US":`Run a Managed Agent deployment now`,"zh-CN":`立即运行托管 Agent Deployment`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This immediately starts a run for the specified Managed Agent deployment and may incur usage or trigger configured actions.`,"zh-CN":`该操作会立即运行指定的托管 Agent Deployment,可能产生用量或触发已配置的动作。`}},usageArgs:`(--deployment <name> | --deployment-id <id>)`,flags:Uv,exampleArgs:[`--deployment daily-report --dry-run`,`--deployment-id dep_abc --yes`],notes:U,validate:Wv,async run(e){let t=w(e.settings.output);if(e.settings.dryRun){D({would_run_deployment:e.flags.deploymentId??e.flags.deployment,target_kind:e.flags.deploymentId?`id`:`state_name`},t);return}let n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`),n=await qv(t,e.flags);return{deploymentId:n,run:await $i(t,n,{provider:`bailian`})}}));t===`json`?D({deployment_id:n.deploymentId,...n.run},t):E(`Deployment ${n.deploymentId} started. Run: ${n.run.run_id??`-`}`)}}),$v=C({description:{"en-US":`Get a Managed Agent deployment run`,"zh-CN":`获取托管 Agent Deployment Run 详情`},auth:`apiKey`,usageArgs:`--run-id <id>`,flags:Hv,exampleArgs:[`--run-id run_abc`],notes:U,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>Di(await W(e,e.flags.file??`agents.yaml`),e.flags.runId,{provider:`bailian`})));t===`json`?D(n,t):(E(`ID: ${n.id}`),E(`Deployment: ${Z(n.deployment_id)}`),E(`Session: ${Z(n.session_id)}`),E(`Status: ${Z(n.status)}`),E(`Created: ${Z(n.created_at)}`),E(`Error: ${Z(n.error)}`))}}),ey=C({description:{"en-US":`List runs for a Managed Agent deployment`,"zh-CN":`列出托管 Agent Deployment Run`},auth:`apiKey`,usageArgs:`--deployment-id <id> [--limit <n>] [--page <cursor>] [--all]`,flags:Vv,exampleArgs:[`--deployment-id dep_abc`,`--deployment-id dep_abc --all --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return Xg(async n=>{let r=await Li(t,e.flags.deploymentId,{provider:`bailian`,limit:e.flags.limit,page:n});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`runs`,items:n.items,headers:[`ID`,`DEPLOYMENT`,`SESSION`,`STATUS`,`CREATED`],rows:Kv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No deployment runs found.`})}}),ty=C({description:{"en-US":`Search Managed Agent deployments`,"zh-CN":`搜索托管 Agent Deployment`},auth:`apiKey`,usageArgs:`--query <text> [--limit <n>] [--page <cursor>] [--all]`,flags:Bv,exampleArgs:[`--query report`,`--query nightly --all --output json`],notes:[...U,{"en-US":`Deployment search maps --query to the provider's server-side keyword parameter.`,"zh-CN":`Deployment 搜索会把 --query 映射为 Provider 服务端 keyword 参数。`}],validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return Xg(async n=>{let r=await Ri(t,{provider:`bailian`,keyword:e.flags.query,agent_id:e.flags.agentId,status:e.flags.status,include_archived:e.flags.includeArchived,created_at_gte:e.flags.createdAtGte,created_at_lte:e.flags.createdAtLte,limit:e.flags.limit,page:n});return{items:r.deployments,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`deployments`,items:n.items,headers:[`ID`,`STATUS`,`SCHEDULE`,`PAUSED REASON`],rows:Gv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No matching deployments found.`})}}),ny=Xv(!1);const ry={sessionId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Session ID`,"zh-CN":`Session ID`}}},iy={...q,limit:J.limit,...Zg,agent:{type:`string`,valueHint:`<name>`,description:{"en-US":`Filter by configured agent name`,"zh-CN":`按配置中的 Agent 名称筛选`}},statuses:{type:`string`,valueHint:`<statuses>`,description:{"en-US":`Comma-separated session statuses`,"zh-CN":`Session 状态,多个以逗号分隔`}},createdAtGte:{type:`string`,valueHint:`<timestamp>`,description:{"en-US":`Created at or after this timestamp`,"zh-CN":`创建时间不早于该时间戳`}},createdAtLte:{type:`string`,valueHint:`<timestamp>`,description:{"en-US":`Created at or before this timestamp`,"zh-CN":`创建时间不晚于该时间戳`}}},ay={...q,...ry,title:{type:`string`,valueHint:`<title>`,description:{"en-US":`New session title`,"zh-CN":`新的 Session 标题`}},metadata:{type:`string`,valueHint:`<json|@path>`,description:{"en-US":`String-valued metadata JSON or @file`,"zh-CN":`值为字符串的 Metadata JSON 或 @file`}}},oy={...q,...ry};function sy(e){return e.map(e=>[e.id,Z(e.title),Z(e.agent_id),e.status,Z(e.updated_at)])}async function cy(e){if(!e)return;let t=await c_(e);if(!t||typeof t!=`object`||Array.isArray(t))throw new n(`--metadata must be a JSON object.`,l.USAGE);for(let[e,r]of Object.entries(t))if(typeof r!=`string`)throw new n(`Metadata value for '${e}' must be a string.`,l.USAGE);return t}const ly=C({description:{"en-US":`Search Managed Agent sessions`,"zh-CN":`搜索托管 Agent Session`},auth:`apiKey`,usageArgs:`--query <text> [--agent <name>] [--statuses <statuses>] [--limit <n>] [--page-limit <n>]`,flags:iy,exampleArgs:[`--query debug`,`--query failed --statuses failed --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return t_(async n=>{let r=await Gi(t,{agent:e.flags.agent,provider:`bailian`,filter:{page:n,limit:e.flags.limit??100,statuses:$g(e.flags.statuses),created_at_gte:e.flags.createdAtGte,created_at_lte:e.flags.createdAtLte}});return{items:r.summaries,hasMore:r.hasMore,nextPage:r.nextPage}},t=>e_(e.flags.query,t.session.id,t.session.title,t.session.status,t.session.agent_id,t.agentName),e.flags.pageLimit)})),r=n.items.map(e=>e.session);X({format:t,key:`sessions`,items:r,headers:[`ID`,`TITLE`,`AGENT`,`STATUS`,`UPDATED`],rows:sy(r),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching sessions found.`})}}),uy=C({description:{"en-US":`Update a Managed Agent session`,"zh-CN":`更新托管 Agent Session`},auth:`apiKey`,usageArgs:`--session-id <id> [--title <title>] [--metadata <json|@path>]`,flags:ay,exampleArgs:[`--session-id sess_abc --title 'investigation'`,`--session-id sess_abc --metadata @metadata.json`],notes:U,validate:e=>!e.title&&!e.metadata?`Provide --title or --metadata.`:void 0,async run(e){let t=w(e.settings.output),n={title:e.flags.title,metadata:await cy(e.flags.metadata)};if(e.settings.dryRun){D({would_update_session:e.flags.sessionId,input:n},t);return}let r=await G(()=>K(async()=>ca(await W(e,e.flags.file??`agents.yaml`),e.flags.sessionId,n,{provider:`bailian`})));t===`json`?D(r,t):E(`Session ${r.id} updated.`)}}),dy=C({description:{"en-US":`Archive a Managed Agent session`,"zh-CN":`归档托管 Agent Session`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This archives the specified remote Managed Agent Session.`,"zh-CN":`该操作会归档指定的远端托管 Agent Session。`}},usageArgs:`--session-id <id>`,flags:oy,exampleArgs:[`--session-id sess_abc --dry-run`,`--session-id sess_abc --yes`],notes:U,async run(e){let t=w(e.settings.output);if(e.settings.dryRun){D({would_archive_session:e.flags.sessionId},t);return}let n=await G(()=>K(async()=>di(await W(e,e.flags.file??`agents.yaml`),e.flags.sessionId,{provider:`bailian`})));t===`json`?D({archived:e.flags.sessionId,session:n},t):E(`Session ${e.flags.sessionId} archived.`)}}),fy={sessionId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Session ID`,"zh-CN":`Session ID`}}},py={...q,...fy},my={...py,outputFile:{type:`string`,valueHint:`<path>`,required:!0,description:{"en-US":`Destination ZIP path`,"zh-CN":`目标 ZIP 路径`}},force:{type:`switch`,description:{"en-US":`Overwrite an existing output file`,"zh-CN":`覆盖已存在的输出文件`}}};function hy(e){return e instanceof Error?e.message:String(e)}async function gy(e,t,n){let r=await ji(e,t,n),i=n??(e.providers.size===1?Array.from(e.providers.keys())[0]:`bailian`),a=[],o=[],s=[];try{o=(await Xg(async r=>{let i=await Wi(e,t,{provider:n,limit:100,page_token:r,order:`asc`});return{items:i.events,hasMore:i.has_more,nextPage:i.next_page}},!0)).items}catch(e){a.push({component:`events`,message:hy(e)})}try{s=(await Xg(async r=>{let i=await Bi(e,{provider:n,scope_id:t,limit:100,page:r});return{items:i.data,hasMore:i.has_more,nextPage:i.next_page}},!0)).items}catch(e){a.push({component:`files`,message:hy(e)})}return{session:r,events:ba(o),files:s,capabilities:wi(i),errors:a}}const _y=String.raw`(?:api[_-]?key|access[_-]?key|private[_-]?key|secret|token|authorization|credential|password|signature|signed[_-]?url)`,vy=RegExp(`${_y}|tool[_-]?input`,`i`),yy=RegExp(`([?&][^=&#\\s]*(?:${_y})[^=&#\\s]*=)[^&#\\s"'<>),}\\]]*`,`gi`),by=RegExp(`("[^"]*(?:${_y})[^"]*"\\s*:\\s*")[^"]*(")`,`gi`),xy=RegExp(`('[^']*(?:${_y})[^']*'\\s*:\\s*')[^']*(')`,`gi`),Sy=RegExp(`(\\b[^\\s=:,;]*(?:${_y})[^\\s=:,;]*\\s*=\\s*)(?!\\[REDACTED\\])(?:"[^"]*"|'[^']*'|[^\\s,;&]+)`,`gi`),Cy=/\b(authorization\s*:\s*)(?:bearer\s+)?[^\s,;]+/gi,wy=/\b(bearer\s+)[A-Za-z0-9._~+/=-]+/gi,Ty=/\bsk-[A-Za-z0-9_-]{8,}\b/g;function Ey(e){return e.replace(yy,`$1[REDACTED]`).replace(by,`$1[REDACTED]$2`).replace(xy,`$1[REDACTED]$2`).replace(Sy,`$1[REDACTED]`).replace(Cy,`$1[REDACTED]`).replace(wy,`$1[REDACTED]`).replace(Ty,`[REDACTED]`)}function Dy(e){return Array.isArray(e)?e.map(Dy):typeof e==`string`?Ey(e):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,vy.test(e)?`[REDACTED]`:Dy(t)]))}function Oy(e){return new TextEncoder().encode(`${JSON.stringify(Dy(e),null,2)}\n`)}function ky(e){let t=4294967295;for(let n of e){t^=n;for(let e=0;e<8;e+=1)t=t>>>1^(t&1?3988292384:0)}return(t^4294967295)>>>0}function Ay(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function jy(e){let t=e.reduce((e,[,t])=>e+t,0),n=new ArrayBuffer(t),r=new DataView(n),i=0;for(let[t,n]of e)n===2?r.setUint16(i,t,!0):r.setUint32(i,t,!0),i+=n;return new Uint8Array(n)}function My(e){let t=new TextEncoder,n=[],r=[],i=0;for(let a of e){let e=t.encode(a.name),o=ky(a.content),s=Ay([jy([[67324752,4],[20,2],[0,2],[0,2],[0,2],[0,2],[o,4],[a.content.length,4],[a.content.length,4],[e.length,2],[0,2]]),e,a.content]);n.push(s);let c=jy([[33639248,4],[20,2],[20,2],[0,2],[0,2],[0,2],[0,2],[o,4],[a.content.length,4],[a.content.length,4],[e.length,2],[0,2],[0,2],[0,2],[0,2],[0,4],[i,4]]);r.push(Ay([c,e])),i+=s.length}let a=Ay(r),o=jy([[101010256,4],[0,2],[0,2],[e.length,2],[e.length,2],[a.length,4],[i,4],[0,2]]);return Ay([...n,a,o])}const Ny=C({description:{"en-US":`Aggregate session diagnostics`,"zh-CN":`聚合 Session 诊断信息`},auth:`apiKey`,usageArgs:`--session-id <id>`,flags:py,exampleArgs:[`--session-id sess_abc`,`--session-id sess_abc --output json`],notes:U,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>gy(await W(e,e.flags.file??`agents.yaml`),e.flags.sessionId,`bailian`))),r=Dy(n);if(t===`json`){D(r,t);return}E(`Session: ${n.session.id} (${n.session.status})`),E(`Events: ${n.events.length}`),E(`Scoped files: ${n.files.length}`),E(`Partial errors: ${n.errors.length}`);for(let e of n.errors)E(` ${e.component}: ${e.message}`)}}),Py=C({description:{"en-US":`Export session diagnostics as a ZIP`,"zh-CN":`将 Session 诊断信息导出为 ZIP`},auth:`apiKey`,usageArgs:`--session-id <id> --output-file <path> [--force]`,flags:my,exampleArgs:[`--session-id sess_abc --output-file ./session-debug.zip`],notes:[...U,{"en-US":`The ZIP contains metadata only; file bodies and credential-like values are excluded/redacted.`,"zh-CN":`ZIP 仅包含元数据;不会包含文件正文,凭证类字段会被移除或脱敏。`}],async run(e){let t=w(e.settings.output);if(e.settings.dryRun){D({would_export_session:e.flags.sessionId,output_file:e.flags.outputFile},t);return}let n=await G(()=>K(async()=>gy(await W(e,e.flags.file??`agents.yaml`),e.flags.sessionId,`bailian`))),r={schema_version:1,generated_at:new Date().toISOString(),session_id:n.session.id,partial:n.errors.length>0,counts:{events:n.events.length,files:n.files.length,errors:n.errors.length},contents:[`session.json`,`events.json`,`files.json`,`capabilities.json`,`errors.json`],note:`File bodies are not included. Credential-like fields are redacted.`},i=My([{name:`manifest.json`,content:Oy(r)},{name:`session.json`,content:Oy(n.session)},{name:`events.json`,content:Oy(n.events)},{name:`files.json`,content:Oy(n.files)},{name:`capabilities.json`,content:Oy(n.capabilities)},{name:`errors.json`,content:Oy(n.errors)}]),a=await l_(e.flags.outputFile,i,e.flags.force);t===`json`?D({exported:n.session.id,output_file:a,partial:r.partial},t):E(`Session diagnostics exported to ${a}${r.partial?` (partial)`:``}`)}}),Fy={fileId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Remote file ID`,"zh-CN":`远端 File ID`}}},Iy={scopeId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by scope ID`,"zh-CN":`按 Scope ID 筛选`}}},Ly={...q,path:{type:`string`,valueHint:`<path>`,required:!0,description:{"en-US":`Local file path`,"zh-CN":`本地文件路径`}},filename:{type:`string`,valueHint:`<name>`,description:{"en-US":`Remote filename override`,"zh-CN":`覆盖远端文件名`}},mimeType:{type:`string`,valueHint:`<type>`,description:{"en-US":`MIME type override`,"zh-CN":`覆盖 MIME 类型`}}},Ry={...q,...J,...Iy},zy={...q,limit:J.limit,...Zg,...Iy},By={...q,...Fy},Vy={...By,outputFile:{type:`string`,valueHint:`<path>`,required:!0,description:{"en-US":`Destination path`,"zh-CN":`目标路径`}},force:{type:`switch`,description:{"en-US":`Overwrite an existing output file`,"zh-CN":`覆盖已存在的输出文件`}}},Hy={...By};function Uy(e){return e.map(e=>[e.id,Z(e.filename),Z(e.status),String(e.size_bytes),Z(e.scope?.id),Z(e.created_at)])}const Wy=C({description:{"en-US":`Upload a Managed Agent file`,"zh-CN":`上传托管 Agent 文件`},auth:`apiKey`,usageArgs:`--path <path> [--filename <name>] [--mime-type <type>]`,flags:Ly,exampleArgs:[`--path ./report.pdf`],notes:U,async run(e){let t=w(e.settings.output);if(e.settings.dryRun){D({would_upload_file:e.flags.path,filename:e.flags.filename??A(e.flags.path),mime_type:e.flags.mimeType??u_(e.flags.path)},t);return}let n=await s_(e.flags.path),r=await G(()=>K(async()=>la(await W(e,e.flags.file??`agents.yaml`),n,e.flags.filename??A(e.flags.path),{provider:`bailian`,mimeType:e.flags.mimeType??u_(e.flags.path)})));t===`json`?D(r,t):E(`File uploaded: ${r.id} (${r.filename})`)}}),Gy=C({description:{"en-US":`List Managed Agent files`,"zh-CN":`列出托管 Agent 文件`},auth:`apiKey`,usageArgs:`[--scope-id <id>] [--limit <n>] [--page <cursor>] [--all]`,flags:Ry,exampleArgs:[``,`--scope-id sess_abc --all --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return Xg(async n=>{let r=await Bi(t,{provider:`bailian`,scope_id:e.flags.scopeId,limit:e.flags.limit,page:n});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`files`,items:n.items,headers:[`ID`,`FILENAME`,`STATUS`,`BYTES`,`SCOPE`,`CREATED`],rows:Uy(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No files found.`})}}),Ky=C({description:{"en-US":`Get Managed Agent file metadata`,"zh-CN":`获取托管 Agent 文件元数据`},auth:`apiKey`,usageArgs:`--file-id <id>`,flags:By,exampleArgs:[`--file-id file_abc`],notes:U,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>Ci(await W(e,e.flags.file??`agents.yaml`),e.flags.fileId,{provider:`bailian`})));t===`json`?D(n,t):(E(`ID: ${n.id}`),E(`Filename: ${n.filename}`),E(`MIME: ${n.mime_type}`),E(`Bytes: ${n.size_bytes}`),E(`Status: ${Z(n.status)}`),E(`Scope: ${Z(n.scope?.id)}`))}}),qy=C({description:{"en-US":`Search Managed Agent files`,"zh-CN":`搜索托管 Agent 文件`},auth:`apiKey`,usageArgs:`--query <text> [--scope-id <id>] [--limit <n>] [--page-limit <n>]`,flags:zy,exampleArgs:[`--query report`,`--query pdf --scope-id sess_abc --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return t_(async n=>{let r=await Bi(t,{provider:`bailian`,scope_id:e.flags.scopeId,limit:e.flags.limit??100,page:n});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},t=>e_(e.flags.query,t.id,t.filename,t.mime_type),e.flags.pageLimit)}));X({format:t,key:`files`,items:n.items,headers:[`ID`,`FILENAME`,`STATUS`,`BYTES`,`SCOPE`,`CREATED`],rows:Uy(n.items),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching files found.`})}}),Jy=C({description:{"en-US":`Download Managed Agent file content`,"zh-CN":`下载托管 Agent 文件内容`},auth:`apiKey`,usageArgs:`--file-id <id> --output-file <path> [--force]`,flags:Vy,exampleArgs:[`--file-id file_abc --output-file ./artifact.pdf`],notes:U,async run(e){let t=w(e.settings.output);if(e.settings.dryRun){D({would_download_file:e.flags.fileId,output_file:e.flags.outputFile},t);return}let n=await G(()=>K(async()=>bi(await W(e,e.flags.file??`agents.yaml`),e.flags.fileId,{provider:`bailian`}))),r=await l_(e.flags.outputFile,n,e.flags.force);t===`json`?D({downloaded:e.flags.fileId,output_file:r},t):E(`File downloaded to ${r}`)}}),Yy=C({description:{"en-US":`Delete a Managed Agent file`,"zh-CN":`删除托管 Agent 文件`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the specified remote Managed Agent file.`,"zh-CN":`该操作会永久删除指定的远端托管 Agent 文件。`}},usageArgs:`--file-id <id>`,flags:Hy,exampleArgs:[`--file-id file_abc --dry-run`,`--file-id file_abc --yes`],notes:U,async run(e){let t=w(e.settings.output);if(e.settings.dryRun){D({would_delete_file:e.flags.fileId},t);return}await G(()=>K(async()=>{await _i(await W(e,e.flags.file??`agents.yaml`),e.flags.fileId,{provider:`bailian`})})),t===`json`?D({deleted:e.flags.fileId},t):E(`File ${e.flags.fileId} deleted.`)}}),Xy={loginInfo:`zeldaEasy.cornerstone-portal.cs-console.loginInfo`,initSpace:`zeldaEasy.bailian-dash-workspace.space.initSpace`,queryBuyResult:`zeldaEasy.bailian-commerce.bill.queryBuyPostpaidResult`,commodityOrderInfo:`zeldaEasy.bailian-commerce.bill.postpaidCommodityOrderInfo`,buyCommodity:`zeldaEasy.bailian-commerce.bill.buyPostpaidCommodity`},Zy={accessKeyId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Alibaba Cloud Access Key ID`,"zh-CN":`阿里云 Access Key ID`}},accessKeySecret:{type:`string`,valueHint:`<secret>`,description:{"en-US":`Alibaba Cloud Access Key Secret`,"zh-CN":`阿里云 Access Key Secret`}},securityToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Alibaba Cloud STS Security Token (optional)`,"zh-CN":`阿里云 STS Security Token(可选)`}}},Qy=1e3;function $y(e){return new Promise(t=>setTimeout(t,e))}function eb(e){return e?.data?.DataV2?.data?.data}function tb(e){let t=e?.data?.data;if(!Array.isArray(t)||t.length===0)return;let n=(t.find(e=>e?.defaultAgent===!0)??t[0])?.tenantId,r=typeof n==`string`?Number(n):n;return typeof r==`number`&&Number.isFinite(r)?r:void 0}var nb=C({description:{"en-US":`Initialize Bailian workspace and activate postpaid services`,"zh-CN":`初始化百炼 Workspace 并开通后付费服务`},auth:`none`,usageArgs:`--access-key-id <id> --access-key-secret <secret> [--security-token <token>]`,flags:Zy,exampleArgs:[`--access-key-id LTAIxxxxx --access-key-secret xxxxx`],async run(e){let{settings:t,flags:r}=e,i=w(t.output);if(t.dryRun){D({apis:[{step:0,api:`GenerateCLIAccessToken`,description:`Generate CLI access token from AK/SK`},{step:1,api:Xy.loginInfo,description:`Check login & workspace status`},{step:2,api:Xy.initSpace,description:`Initialize workspace (if needed)`},{step:3,api:`CreateUser`,description:`Create console user via BailianControl OpenAPI (CreateUser)`},{step:4,api:`ListWorkspaces`,description:`List workspaces to resolve agentId`},{step:5,api:`ResetPolicies4Agent`,description:`Authorize user permissions`},{step:6,api:Xy.queryBuyResult,description:`Query postpaid order status`},{step:7,api:Xy.commodityOrderInfo,description:`Query commodity activation status`},{step:8,api:Xy.buyCommodity,description:`Activate postpaid commodities (if needed)`}]},i);return}let{accessKeyId:a,accessKeySecret:o}=r;if(!a||!o)throw new n(`workspace init requires --access-key-id and --access-key-secret.`,l.USAGE);let s=r.securityToken||void 0,c=(await We({identity:e.identity,settings:t,baseUrl:e.client.baseUrl,accessKeyId:a,accessKeySecret:o,securityToken:s})).cliAccessToken;if(!c)throw new n(`Failed to generate CLI access token from AK/SK.`,l.GENERAL);let u=Oe(t),d={region:u.consoleRegion,site:u.consoleSite,...u.consoleSwitchAgent==null?{}:{switchAgent:u.consoleSwitchAgent},token:c},f=t.verbose,p=async(e,r={})=>{f&&process.stderr.write(`> ${e}\n`);try{let n=await ue(d,t.timeout,{api:e,data:r},t);return f&&process.stderr.write(`< ${JSON.stringify(n)}\n`),n}catch(e){if(f){let t=e instanceof n?e.rawResponse??e.message:String(e);process.stderr.write(`< ERROR: ${t}\n`)}throw e}};E(`Checking workspace status...`);let m=eb(await p(Xy.loginInfo));m?.spaceInited===!0?E(`Workspace already initialized.`):(E(`Initializing workspace...`),await p(Xy.initSpace),E(`Workspace initialized.`));let h=m?.aliyun?.uid;if(typeof h!=`string`||h.length===0)throw new n(`Console login info did not include aliyun.uid.`,l.GENERAL);let g={identity:e.identity,settings:t,baseUrl:e.client.baseUrl,regionId:u.consoleRegion,accessKeyId:a,accessKeySecret:o,securityToken:s};try{await he({...g,reqDTO:{outerKey:h,nickName:h,userName:h}})}catch(e){if(!(e instanceof n)||!/already exists/i.test(e.message))throw e;E(`Console user already exists, continuing.`)}E(`Resolving workspace agent...`);let _=tb(await ft(g));if(_==null)throw new n(`Could not resolve agentId from ListWorkspaces response.`,l.GENERAL,`Re-run with --verbose to inspect the ListWorkspaces response body.`);E(`Authorizing user permissions...`),await Qt({...g,outerKey:h,agentId:_,policyIndexList:[1]}),await rb(p,i)}});async function rb(e,t){E(`Checking service activation status...`);let r;for(let t=0;t<20;t++){let n=eb(await e(Xy.queryBuyResult));if(r=typeof n==`string`?n:n?.result,r!==`buying`)break;t===0&&E(`Service activation in progress, polling...`),await $y(Qy)}if(r===`fail`)throw new n(`Service activation failed.`,l.GENERAL);if(r===`success`){await ob(e,t);return}await ab(e,t)}function ib(e){let t=eb(e);return Array.isArray(t)?t:[]}async function ab(e,t){let n=ib(await e(Xy.commodityOrderInfo)),r=n.filter(e=>e.status===11);if(r.length>0){E(`Warning: Some services are overdue:`);for(let e of r)E(` - ${e.commodityCode}`)}let i=n.filter(e=>e.status===1);if(i.length>0){E(`Activating ${i.length} postpaid services...`),await e(Xy.buyCommodity),await ob(e,t);return}D({status:`ready`,activeServices:n.filter(e=>e.status===10).map(e=>e.commodityCode)},t)}async function ob(e,t){E(`Waiting for services to activate...`);for(let n=0;n<20;n++){let n=ib(await e(Xy.commodityOrderInfo));if(n.filter(e=>e.status!==10&&e.status!==11).length===0){let e=n.filter(e=>e.status===11);if(e.length>0){E(`Warning: Some services are overdue:`);for(let t of e)E(` - ${t.commodityCode}`)}D({status:`ready`,activeServices:n.filter(e=>e.status===10).map(e=>e.commodityCode)},t);return}await $y(Qy)}throw new n(`Timed out waiting for services to activate.`,l.TIMEOUT)}var sb=C({description:{"en-US":`Install or upgrade an allowlisted Command Pack`,"zh-CN":`安装或升级白名单内的 Command Pack`},auth:`none`,usageArgs:`--package <name[@version]>`,flags:{package:{type:`string`,valueHint:`<name[@version]>`,description:{"en-US":`Allowlisted Command Pack package and optional version or tag`,"zh-CN":`白名单内的 Command Pack 包名,以及可选的版本或 Tag`},required:!0}},exampleArgs:[`--package @ali/bailian-plugin-agent`,`--package @ali/bailian-plugin-agent@beta`],async run(e){D({installed:await e.commandPacks.install(e.flags.package)},w(e.settings.output))}}),cb=C({description:{"en-US":`Link an allowlisted local Command Pack for development`,"zh-CN":`链接白名单内的本地 Command Pack 用于开发`},auth:`none`,usageArgs:`--path <directory>`,flags:{path:{type:`string`,valueHint:`<directory>`,description:{"en-US":`Local Command Pack package directory`,"zh-CN":`本地 Command Pack 包目录`},required:!0}},exampleArgs:[`--path ../bailian-plugin-agent`],async run(e){D({linked:await e.commandPacks.link(e.flags.path)},w(e.settings.output))}}),lb=C({description:{"en-US":`List installed Command Packs and their load status`,"zh-CN":`列出已安装的 Command Pack 及其加载状态`},auth:`none`,exampleArgs:[``,`--output json`],async run(e){let t=await e.commandPacks.list(),n=w(e.settings.output);if(n===`json`){D({command_packs:t},n);return}if(t.length===0){E(`No Command Packs installed.`);return}let r=t.map(e=>[e.name,e.version??`-`,e.source,e.status,e.commands.join(`, `)||e.error||`-`]);for(let e of Xn([`NAME`,`VERSION`,`SOURCE`,`STATUS`,`COMMANDS / ERROR`],r))E(e)}}),ub=C({description:{"en-US":`Remove an installed Command Pack`,"zh-CN":`移除已安装的 Command Pack`},auth:`none`,usageArgs:`--name <package>`,flags:{name:{type:`string`,valueHint:`<package>`,description:{"en-US":`Allowlisted Command Pack package name`,"zh-CN":`白名单内的 Command Pack 包名`},required:!0}},exampleArgs:[`--name @ali/bailian-plugin-agent`],async run(e){await e.commandPacks.remove(e.flags.name),D({removed:e.flags.name},w(e.settings.output))}}),db=C({description:{"en-US":`Install skills from the Bailian skill registry into local agents`,"zh-CN":`将百炼 Skill Registry 中的 Skill 安装到本地 Agent`},auth:`none`,usageArgs:`--all | --name <name,...>`,flags:{all:{type:`switch`,description:{"en-US":`Install all skills from the registry`,"zh-CN":`安装 Registry 中的全部 Skill`}},name:{type:`string`,valueHint:`<name,...>`,description:{"en-US":`Comma-separated skill names to install`,"zh-CN":`要安装的 Skill 名称,以逗号分隔`}}},validate(e){if(e.all&&e.name)return`Use either --all or --name, not both`;if(!e.all&&!e.name)return`Specify --all to install everything or --name <name,...> for specific skills`},exampleArgs:[`--all`,`--name spark-video,bailian-model-recommend`],async run(e){let t=e.settings.outputExplicit?e.settings.output:`json`,r=await ze(),i=Object.keys(r.skills),a=e.flags.all?`all`:zt(e.flags.name,!1),o=a===`all`?i:a,s=qt(),c=Ee(),u=await sn(o.map(e=>async()=>{let t=r.skills[e];if(!t)return{name:e,status:`failed`,reason:`skill not found in registry`};try{let n=await it(e,t,c,s.skills[e]?.links??[]);return s.skills[e]=n.lockEntry,{name:e,status:`installed`,publishedAt:t.publishedAt,agents:n.linkedAgents}}catch(t){return{name:e,status:`failed`,reason:t instanceof Error?t.message:String(t)}}}),3);if(Mn(s),t===`json`)D({registry:et(),agents:c.map(e=>e.id),skills:u},t);else if(u.length===0)E(`Skill registry is empty; no skills to install.`);else{let e=u.map(e=>[e.name,e.status,e.publishedAt?e.publishedAt.slice(0,10):`-`,e.status===`installed`?e.agents?.join(`, `)||`-`:e.reason??`-`]);for(let t of Xn([`NAME`,`STATUS`,`PUBLISHED`,`AGENTS / REASON`],e))E(t)}let d=u.filter(e=>e.status===`failed`);if(d.length>0)throw new n(`${d.length}/${u.length} skill(s) failed to install`,l.GENERAL,`Check the reason for failed skills in the output; network failures can be retried with bl skill add`)}}),fb=C({description:{"en-US":`Update installed skills to the latest registry versions`,"zh-CN":`将已安装的 Skill 更新到 Registry 最新版本`},auth:`none`,usageArgs:`[--all] [--name <name,...>]`,flags:{all:{type:`switch`,description:{"en-US":`Update all installed skills (default when neither --all nor --name is given)`,"zh-CN":`更新全部已安装 Skill(未指定 --all 或 --name 时的默认行为)`}},name:{type:`string`,valueHint:`<name,...>`,description:{"en-US":`Comma-separated skill names to update (must be already installed)`,"zh-CN":`要更新的 Skill 名称,以逗号分隔(必须已安装)`}}},validate(e){if(e.all&&e.name)return`Use either --all or --name, not both`},exampleArgs:[``,`--all`,`--name spark-video`],async run(e){let t=e.settings.outputExplicit?e.settings.output:`json`,r=e.flags.all||!e.flags.name?`all`:zt(e.flags.name,!1),i=await ze(),a=qt(),o=new Set(yt()),s=Ee(),c=[],u=[];if(r===`all`)for(let[e,t]of Object.entries(a.skills)){let n=i.skills[e];if(!n){c.push({name:e,status:`skipped`,reason:`delisted from remote; local copy retained`});continue}if(n.contentHash===t.contentHash&&o.has(e)){let n=Ne(e,s,t.links??[]);a.skills[e]={...t,links:n.links},c.push({name:e,status:`up-to-date`,publishedAt:t.publishedAt});continue}u.push(e)}else for(let e of r){if(!a.skills[e]){c.push({name:e,status:`failed`,reason:`not installed; run bl skill add --name `+e+` first`});continue}u.push(e)}let d=await sn(u.map(e=>async()=>{let t=i.skills[e];if(!t)return{name:e,status:`failed`,reason:`skill not found in registry`};try{let n=await it(e,t,s,a.skills[e]?.links??[]);return a.skills[e]=n.lockEntry,{name:e,status:`updated`,publishedAt:t.publishedAt}}catch(t){return{name:e,status:`failed`,reason:t instanceof Error?t.message:String(t)}}}),3);if(c.push(...d),Mn(a),t===`json`)D({registry:et(),skills:c},t);else if(c.length===0)E(`No skills installed locally; run bl skill add first.`);else{let e=c.map(e=>[e.name,e.status,e.publishedAt?e.publishedAt.slice(0,10):`-`]);for(let t of Xn([`NAME`,`STATUS`,`PUBLISHED`],e))E(t);let t=c.filter(e=>(e.status===`skipped`||e.status===`failed`)&&e.reason);if(t.length>0){E(``);for(let e of t)E(` ${e.name}: ${e.reason}`)}}let f=c.filter(e=>e.status===`failed`);if(f.length>0)throw new n(`${f.length} skill(s) failed to update`,l.GENERAL,`Check the reason for failed skills in the output; network failures can be retried with bl skill update`)}}),pb=C({description:{"en-US":`Remove locally installed skills (registry is untouched)`,"zh-CN":`移除本地已安装的 Skill(不修改 Registry)`},auth:`none`,usageArgs:`--name <all|name,...>`,flags:{name:{type:`string`,valueHint:`<all|name,...>`,description:{"en-US":`Skills to remove: all or comma-separated skill names`,"zh-CN":`要移除的 Skill:all 或以逗号分隔的 Skill 名称`},required:!0}},exampleArgs:[`--name spark-video`,`--name all`],async run(e){let t=e.settings.outputExplicit?e.settings.output:`json`,r=zt(e.flags.name,!1),i=qt(),a=r===`all`?Object.keys(i.skills):r;if(a.length===0){D({skills:[]},t),t===`text`&&E(`No skills installed locally; nothing to remove.`);return}let o=new Set(yt()),s=[];for(let e of a){let t=i.skills[e];if(!t){s.push({name:e,status:`failed`,reason:o.has(e)?`directory not managed by bl skill (untracked); remove manually if needed`:`not installed`});continue}try{let n=Cn(e,t.links??[]);Zt(e),delete i.skills[e],s.push({name:e,status:`removed`,removedLinks:n.length})}catch(t){s.push({name:e,status:`failed`,reason:t instanceof Error?t.message:String(t)})}}if(Mn(i),t===`json`)D({skills:s},t);else{let e=s.map(e=>[e.name,e.status,e.status===`removed`?`reclaimed ${e.removedLinks} agent link(s)`:e.reason??`-`]);for(let t of Xn([`NAME`,`STATUS`,`DETAIL`],e))E(t)}let c=s.filter(e=>e.status===`failed`);if(c.length>0)throw new n(`${c.length}/${s.length} skill(s) failed to remove`,l.GENERAL,`Check the reason for failed skills in the output; use bl skill list to verify local install status`)}});function mb(e){return e?e.length>60?`${e.slice(0,59)}…`:e:`-`}var hb=C({description:{"en-US":`List registry skills and diff against local installs`,"zh-CN":`列出 Registry Skill,并与本地安装结果比较`},auth:`none`,exampleArgs:[``,`--output json`],notes:[{"en-US":`STATUS: installed | outdated | not-installed | missing (lock has it, dir deleted) | untracked (dir exists, not managed)`,"zh-CN":`STATUS:installed | outdated | not-installed | missing(Lock 中存在但目录已删除)| untracked(目录存在但未被管理)`}],async run(e){let t=e.settings.outputExplicit?e.settings.output:`json`,n=await ze(),r=me(n,qt(),yt());if(t===`json`){D({registry:et(),...n.updatedAt?{updatedAt:n.updatedAt}:{},skills:r},t);return}if(r.length===0){E(`Skill registry is empty and no skills are installed locally.`);return}let i=r.map(e=>[e.name,e.status,e.publishedAt?e.publishedAt.slice(0,19).replace(`T`,` `):`-`,mb(e.description)]);for(let e of Xn([`NAME`,`STATUS`,`UPDATEDAT`,`DESCRIPTION`],i))E(e)}});const gb=`json`,_b={success:`success`,partial:`partial`,failed:`failed`};var vb=C({description:{"en-US":`Install all bailian-* skills (one-shot bootstrap for new environments)`,"zh-CN":`安装全部 bailian-* Skill(用于新环境的一次性初始化)`},auth:`none`,usageArgs:``,exampleArgs:[``],notes:[{"en-US":"Fetches the registry index and installs every skill whose name starts with `bailian-`.","zh-CN":"获取 Registry 索引并安装名称以 `bailian-` 开头的所有 Skill。"},{"en-US":"Equivalent to: `bl skill add --all` (filtered to `bailian-*` skills).","zh-CN":"等价于:`bl skill add --all`(筛选为 `bailian-*` Skill)。"}],async run(e){let t=e.settings.outputExplicit?e.settings.output:gb,r=await ze(),i=Object.keys(r.skills).filter(e=>e.startsWith(`bailian-`)),a=qt(),o=Ee(),s=await sn(i.map(e=>async()=>{let t=r.skills[e];try{let n=await it(e,t,o,a.skills[e]?.links??[]);return a.skills[e]=n.lockEntry,{name:e,status:_b.success}}catch(t){return{name:e,status:_b.failed,reason:t instanceof Error?t.message:String(t)}}}),3);Mn(a);let c=s.filter(e=>e.status===_b.success),u=s.filter(e=>e.status===_b.failed),d=u.length===0?_b.success:c.length===0?_b.failed:_b.partial;if(t===gb){let e=o.map(e=>e.id),n={status:d,skills:c.map(e=>e.name)};u.length>0&&(n.failed=u.map(t=>({name:t.name,reason:t.reason,agents:e}))),D(n,t)}else if(s.length===0)E(`No bailian-* skills found in the registry.`);else if(E(d===_b.success?`Installed ${c.length} bailian-* skills.`:`Installed ${c.length}/${s.length} bailian-* skills.`),u.length>0){E(`Failed:`);for(let e of u)E(` ${e.name}: ${e.reason}`)}if(u.length>0)throw new n(`${u.length}/${s.length} skill(s) failed to install`,l.GENERAL,`Check the reason for failed skills in the output; network failures can be retried with bl skill init`)}});const yb=[{id:`code-interpreter`,imageName:`代码解释器`,imageUrl:`fc-e2b-registry.cn-beijing.cr.aliyuncs.com/runtime/code-interpreter-v1:v0.0.44`,icon:`https://img.alicdn.com/imgextra/i2/O1CN01iX8RH9ckFvC093x2_!!6000000000905-2-tps-72-72.png`,description:{"en-US":`Python / Node.js runtimes with common data-processing libraries`,"zh-CN":`Python / Node.js 运行时+常用数据处理库`}},{id:`browser`,imageName:`浏览器`,imageUrl:`fc-e2b-registry.cn-beijing.cr.aliyuncs.com/runtime/browser:v0.0.44`,icon:`https://img.alicdn.com/imgextra/i4/O1CN01ShCbPEunrRI093x2_!!6000000000155-2-tps-72-72.png`,description:{"en-US":`Chromium and a visual desktop for clicking, filling forms, and screenshots`,"zh-CN":`Chromium +可视化桌面,支持点击/ 填表/截图`}},{id:`all-in-one`,imageName:`全能型`,imageUrl:`fc-e2b-registry.cn-beijing.cr.aliyuncs.com/runtime/all-in-one:v0.0.44`,icon:`https://img.alicdn.com/imgextra/i1/O1CN01smhklUahsyE093x2_!!6000000006657-2-tps-72-72.png`,description:{"en-US":`Code execution and browser capabilities together`,"zh-CN":`代码执行+浏览器双能力`}}],bb=yb.flatMap(e=>[e.id,e.imageName]),xb=yb.map(e=>({"en-US":`${e.id} (${e.imageName}): ${e.description[`en-US`]}. ${e.imageUrl}`,"zh-CN":`${e.id}(${e.imageName}):${e.description[`zh-CN`]}。${e.imageUrl}`}));function Sb(e){let t=yb.find(t=>t.id===e||t.imageName===e);if(!t)throw new x(`Unknown built-in image / 未知内置镜像: ${e}. ${bb.join(`, `)}`);return t}const Cb=C({description:{"en-US":`List the built-in Sandbox base images (offline)`,"zh-CN":`列出 CLI 内置的 Sandbox 基础镜像(离线)`},auth:`none`,exampleArgs:[``,`--output json`,`--quiet`],notes:[{"en-US":`Use a preset ID or Chinese name with template create/update --image. These are pinned cn-beijing images; other environments may differ. Use --from-image for a custom image.`,"zh-CN":`在 template create/update 中通过 --image 传入预设 ID 或中文名。这些是固定版本的 cn-beijing 镜像,其他环境可能不同;自定义镜像使用 --from-image。`},...xb],async run(e){if(e.settings.quiet){for(let e of yb)E(e.id);return}if(w(e.settings.output)===`json`){D(yb,`json`);return}for(let e of yb)E(`${e.id} (${e.imageName})`),E(` ${e.imageUrl}`),E(` ${e.description[`en-US`]} / ${e.description[`zh-CN`]}`)}}),wb={workspaceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Workspace ID for the default Sandbox endpoint; optional with a configured base URL`,"zh-CN":`默认 Sandbox Endpoint 的 Workspace ID;已配置 Base URL 时可省略`}}},Tb={body:{type:`string`,valueHint:`<json|@path>`,description:{"en-US":`JSON request body, inline or loaded from an @file path; explicit flags override it`,"zh-CN":`JSON 请求体,可内联或从 @文件路径读取;显式 Flag 优先`}}},Eb={instanceTimeout:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Sandbox lifetime after this operation (300-604800 seconds)`,"zh-CN":`本次操作后的 Sandbox 存活时间(300–604800 秒)`}}},Db={showCredentials:{type:`switch`,description:{"en-US":`Print envd and traffic access tokens instead of redacting them`,"zh-CN":`输出 envd 与流量访问 Token 原值,不进行脱敏`}}},Ob={pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Template build polling interval (default: 5 seconds)`,"zh-CN":`模版构建轮询间隔(默认:5 秒)`}}},kb=[{"en-US":`Auth: uses a Bailian API Key as an Authorization Bearer token; no E2B key is sent.`,"zh-CN":`鉴权:使用百炼 API Key 作为 Authorization Bearer Token;不会发送 E2B Key。`},{"en-US":`Base URL: --base-url > DASHSCOPE_BASE_URL > login/profile base_url. The CLI uses its origin and appends /api/v1/agentstudio/sandbox; otherwise it uses the workspace-scoped cn-beijing endpoint.`,"zh-CN":`Base URL 优先级:--base-url > DASHSCOPE_BASE_URL > 登录/Profile 的 base_url。CLI 取其 origin 并追加 /api/v1/agentstudio/sandbox;未配置时使用工作空间的 cn-beijing Endpoint。`},{"en-US":`Without a configured base URL, workspace is required: --workspace-id > BAILIAN_WORKSPACE_ID > config workspace_id.`,"zh-CN":`未配置 Base URL 时必须提供 Workspace:--workspace-id > BAILIAN_WORKSPACE_ID > 配置项 workspace_id。`},{"en-US":`Sandbox is currently available in cn-beijing only and requires prior SLR authorization.`,"zh-CN":`Sandbox 当前仅支持 cn-beijing,首次使用前需完成 SLR 授权。`},{"en-US":`Global --timeout limits HTTP requests and total template-build polling; --instance-timeout maps to the Sandbox API lifetime field.`,"zh-CN":`全局 --timeout 限制 HTTP 请求和模版构建总轮询时间;--instance-timeout 映射到 Sandbox API 的实例存活时间字段。`}];function Ab(e,t){return e.client.url(cn(t),()=>ln(jb(e)))}function jb(e){let t=e.flags.workspaceId||e.settings.workspaceId;if(!t)throw new n(`Workspace ID is required when no base URL is configured. / 未配置 Base URL 时必须提供 Workspace ID。`,l.USAGE,`Pass --workspace-id, set BAILIAN_WORKSPACE_ID, configure workspace_id, or set --base-url. / 请传入 --workspace-id、设置 BAILIAN_WORKSPACE_ID 或 workspace_id 配置,或通过 --base-url 指定地址。`);return t}function Mb(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new n(`${t} must contain a JSON object.`,l.USAGE);return e}async function Nb(e){if(!e)return{};let t=e.startsWith(`@`)?e.slice(1):void 0;if(t!==void 0&&t.length===0)throw new n(`--body @path must include a file path.`,l.USAGE);let r=t===void 0?e:await Zr(t,`utf8`);try{return Mb(JSON.parse(r),t?`Body file ${t}`:`--body`)}catch(e){throw e instanceof n?e:e instanceof SyntaxError?new n(t?`Body file ${t} contains invalid JSON.`:`--body contains invalid JSON.`,l.USAGE):e}}function Q(e,t,n){n!==void 0&&(e[t]=n)}function Pb(e,t){let r={};for(let i of e??[]){let e=i.indexOf(`=`);if(e<=0)throw new n(`${t} values must use KEY=VALUE format.`,l.USAGE);let a=i.slice(0,e).trim();if(!a)throw new n(`${t} values must include a non-empty key.`,l.USAGE);r[a]=i.slice(e+1)}return r}function Fb(e,t,n){if(Object.keys(n).length===0)return;let r=e[t];e[t]={...typeof r==`object`&&r&&!Array.isArray(r)?r:{},...n}}function Ib(e,t,r,i){if(e!==void 0&&(typeof e!=`number`||!Number.isInteger(e)||e<r||e>i))throw new n(`${t} must be an integer between ${r} and ${i}.`,l.USAGE)}function Lb(e,t){if(typeof e!=`number`||!Number.isInteger(e)||e<=0)throw new n(`${t} must be a positive integer.`,l.USAGE)}const Rb=new Set([`envdAccessToken`,`trafficAccessToken`]),zb=/(?:token|secret|password|credential|api[_-]?key)/i;function Bb(e,t){if(Array.isArray(e))return e.map(e=>Bb(e,t));if(typeof e!=`object`||!e)return e;let n={};for(let[r,i]of Object.entries(e)){if(Rb.has(r)||zb.test(r)||t&&(r===`envVars`||r===`envConfig`)){i==null?n[r]=i:n[r]=(r===`envVars`||r===`envConfig`)&&typeof i==`object`&&!Array.isArray(i)?Object.fromEntries(Object.keys(i).map(e=>[e,`[REDACTED]`])):`[REDACTED]`;continue}n[r]=Bb(i,t)}return n}function Vb(e){return Bb(e,!1)}function Hb(e){return Bb(e,!0)}function $(e){return e==null||e===``?`-`:Array.isArray(e)?e.join(`,`):typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:JSON.stringify(e)??`-`}const Ub=`sandbox_template`,Wb=C({description:{"en-US":`Upload a workspace file for Sandbox template mounts`,"zh-CN":`上传工作空间文件,供 Sandbox 模版挂载使用`},auth:`apiKey`,usageArgs:`--path <path> [--filename <name>] [--mime-type <type>]`,flags:{...wb,path:{type:`string`,valueHint:`<path>`,required:!0,description:{"en-US":`Local file path`,"zh-CN":`本地文件路径`}},filename:{type:`string`,valueHint:`<name>`,description:{"en-US":`Remote filename override`,"zh-CN":`覆盖远端文件名`}},mimeType:{type:`string`,valueHint:`<type>`,description:{"en-US":`Multipart file MIME type (default: application/octet-stream)`,"zh-CN":`Multipart 文件部分的 MIME 类型(默认:application/octet-stream)`}}},exampleArgs:[`--path ./config.json --output json`,`--path ./config.json --quiet`,`--path ./notes.txt --filename notes.txt --mime-type text/plain --dry-run --output json`],notes:[{"en-US":`POST /api/v1/agentstudio/files with multipart fields file and source=sandbox_template. Uses a Bailian Bearer API Key, not Console authentication or an E2B key; no agents.yaml is needed.`,"zh-CN":`向 /api/v1/agentstudio/files 发送 multipart 字段 file 和 source=sandbox_template。使用百炼 Bearer API Key,不使用 Console 鉴权或 E2B Key;无需 agents.yaml。`},{"en-US":`Base URL follows Sandbox: --base-url > DASHSCOPE_BASE_URL > login/profile base_url. Without one, --workspace-id > BAILIAN_WORKSPACE_ID > config workspace_id selects the cn-beijing origin. The upload path has no /sandbox prefix.`,"zh-CN":`Base URL 沿用 Sandbox:--base-url > DASHSCOPE_BASE_URL > 登录/Profile 的 base_url。未配置时,按 --workspace-id > BAILIAN_WORKSPACE_ID > 配置项 workspace_id 选择 cn-beijing 地址。上传路径不带 /sandbox 前缀。`},{"en-US":`Returns the upload response immediately; --quiet prints only its id. Upload does not wait for security review: status=checking is not ready to mount. Use an available file's id as mntConfig[].originFileId in template create/update --body, together with mountPath and optional originFileName, in the same workspace. This does not transfer files into a running instance.`,"zh-CN":`上传响应返回后立即输出,--quiet 仅输出 id。不会等待安全审核:status=checking 不代表已可挂载。在同一工作空间的 template create/update --body 中,将可用文件的 id 填入 mntConfig[].originFileId,同时传入 mountPath 和可选的 originFileName。此命令不向运行中的实例传文件。`},{"en-US":`--dry-run previews the endpoint, source, and local path without reading or uploading the file. The service detects the MIME type and enforces upload limits.`,"zh-CN":`--dry-run 仅预览 Endpoint、source 和本地路径,不读取或上传文件。MIME 类型检测和上传限制由服务端执行。`}],async run(e){let t=e.client.url(S(),()=>ln(jb(e))),r=e.flags.filename??A(e.flags.path),i=e.flags.mimeType??`application/octet-stream`,a=w(e.settings.output);if(e.settings.dryRun){D({method:`POST`,endpoint:t,request:{source:Ub,file:{path:e.flags.path,filename:r,mimeType:i}}},a);return}let o=new Uint8Array(await Zr(e.flags.path)),s=new FormData;s.append(`source`,Ub),s.append(`file`,new Blob([o],{type:i}),r);let c=await e.client.requestJson({method:`POST`,path:t,body:s});if(!c||typeof c.id!=`string`||!c.id.trim())throw new n(`Upload response did not contain a File ID. / 上传响应未包含 File ID。`,l.GENERAL);e.settings.quiet?E(c.id):D(Vb(c),a)}}),Gb={sandboxId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Sandbox instance ID`,"zh-CN":`Sandbox 实例 ID`}}},Kb={...wb,...Tb,templateId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Ready template ID; may alternatively be supplied as templateID in --body`,"zh-CN":`已就绪的模版 ID;也可通过 --body 中的 templateID 提供`}},...Eb,allowInternetAccess:{type:`boolean`,valueHint:`<bool>`,description:{"en-US":`Allow public internet access`,"zh-CN":`允许访问公网`}},metadata:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Instance metadata entry; repeat for multiple values`,"zh-CN":`实例 Metadata 键值;可重复传入`}},env:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Instance environment variable; repeat for multiple values`,"zh-CN":`实例环境变量;可重复传入`}},autoPause:{type:`boolean`,valueHint:`<bool>`,description:{"en-US":`Pause the instance when its timeout expires`,"zh-CN":`实例超时后自动暂停`}},autoResume:{type:`boolean`,valueHint:`<bool>`,description:{"en-US":`Automatically resume a paused instance when connecting`,"zh-CN":`连接已暂停实例时自动恢复`}},allowOut:{type:`array`,valueHint:`<address>`,description:{"en-US":`Outbound allow-list entry; repeat for multiple values`,"zh-CN":`出站白名单条目;可重复传入`}},denyOut:{type:`array`,valueHint:`<address>`,description:{"en-US":`Outbound deny-list entry; repeat for multiple values`,"zh-CN":`出站黑名单条目;可重复传入`}},maskRequestHost:{type:`string`,valueHint:`<host>`,description:{"en-US":`Override the outbound request Host header`,"zh-CN":`覆盖出站请求的 Host Header`}},...Db},qb={...wb,templateId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by template ID`,"zh-CN":`按模版 ID 筛选`}},sandboxId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by sandbox ID`,"zh-CN":`按 Sandbox ID 筛选`}},state:{type:`string`,valueHint:`<state>`,description:{"en-US":`Filter by state, for example running or paused`,"zh-CN":`按状态筛选,例如 running 或 paused`}},limit:{type:`number`,valueHint:`<n>`,description:{"en-US":`Maximum results (1-50)`,"zh-CN":`最大返回数量(1–50)`}}},Jb={...wb,...Gb,...Db},Yb={...wb,...Gb},Xb={...wb,...Gb,...Tb,...Eb,...Db};async function Zb(e){let t=await Nb(e.body);Q(t,`templateID`,e.templateId),Q(t,`timeout`,e.instanceTimeout),Q(t,`allow_internet_access`,e.allowInternetAccess),Q(t,`autoPause`,e.autoPause),Q(t,`autoResume`,e.autoResume),Fb(t,`metadata`,Pb(e.metadata,`--metadata`)),Fb(t,`envVars`,Pb(e.env,`--env`));let r={};if(Q(r,`allowOut`,e.allowOut),Q(r,`denyOut`,e.denyOut),Q(r,`maskRequestHost`,e.maskRequestHost),Fb(t,`network`,r),typeof t.templateID!=`string`||t.templateID.trim().length===0)throw new n(`Sandbox create requires --template-id or templateID in --body.`,l.USAGE);return Ib(t.timeout,`Sandbox timeout`,300,604800),t}async function Qb(e){let t=await Nb(e.body);return Q(t,`timeout`,e.instanceTimeout),Ib(t.timeout,`Sandbox timeout`,300,604800),t}function $b(e,t){let n=t.showCredentials?e:Vb(e);if(t.quiet){E($(e.sandboxID));return}D(n,t.format)}const ex=C({description:{"en-US":`Create a Sandbox instance`,"zh-CN":`创建 Sandbox 实例`},auth:`apiKey`,usageArgs:`(--template-id <id> | --body <json|@path>) [flags]`,flags:Kb,exampleArgs:[`--template-id tpl-xxx --instance-timeout 3600`,`--template-id tpl-xxx --base-url https://workspace.cn-beijing.maas.aliyuncs.com`,`--body @sandbox.json --dry-run --output json`,`--template-id tpl-xxx --show-credentials --output json`],notes:kb,async run(e){let t=w(e.settings.output),n=Ab(e,g.sandboxes),r=await Zb(e.flags);if(e.settings.dryRun){D({method:`POST`,endpoint:n,request:Hb(r)},t);return}$b(await e.client.requestJson({path:n,method:`POST`,body:r}),{format:t,quiet:e.settings.quiet,showCredentials:e.flags.showCredentials})}}),tx=C({description:{"en-US":`List Sandbox instances`,"zh-CN":`列出 Sandbox 实例`},auth:`apiKey`,usageArgs:`[--template-id <id>] [--sandbox-id <id>] [--state <state>] [--limit <n>]`,flags:qb,exampleArgs:[``,`--state running --limit 20`,`--template-id tpl-xxx --output json`],notes:kb,validate(e){if(e.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>50))return`--limit must be an integer between 1 and 50.`},async run(e){let t=new URL(Ab(e,g.sandboxList));e.flags.templateId&&t.searchParams.set(`templateID`,e.flags.templateId),e.flags.sandboxId&&t.searchParams.set(`sandboxID`,e.flags.sandboxId),e.flags.state&&t.searchParams.set(`state`,e.flags.state),e.flags.limit!==void 0&&t.searchParams.set(`limit`,String(e.flags.limit));let n=await e.client.requestJson({path:t.toString(),method:`GET`});if(e.settings.quiet){for(let e of n)E($(e.sandboxID));return}let r=w(e.settings.output);if(r===`json`){D(n,r);return}if(n.length===0){E(`No Sandbox instances found.`);return}let i=n.map(e=>[$(e.sandboxID),$(e.templateID),$(e.state),$(e.cpuCount),$(e.memoryMB),$(e.startedAt),$(e.endAt)]);for(let e of Xn([`ID`,`TEMPLATE`,`STATE`,`CPU`,`MEMORY_MB`,`STARTED_AT`,`END_AT`],i))E(e)}}),nx=C({description:{"en-US":`Get Sandbox instance details`,"zh-CN":`获取 Sandbox 实例详情`},auth:`apiKey`,usageArgs:`--sandbox-id <id> [--show-credentials]`,flags:Jb,exampleArgs:[`--sandbox-id sbx-xxx`,`--sandbox-id sbx-xxx --show-credentials --output json`],notes:kb,async run(e){let t=Ab(e,dn(e.flags.sandboxId));$b(await e.client.requestJson({path:t,method:`GET`}),{format:w(e.settings.output),quiet:e.settings.quiet,showCredentials:e.flags.showCredentials})}});function rx(e){let t=e===`connect`?`Connect to`:`Resume`,n=e===`connect`?`连接`:`恢复`;return C({description:{"en-US":`${t} a Sandbox instance and return connection information`,"zh-CN":`${n} Sandbox 实例并返回连接信息`},auth:`apiKey`,usageArgs:`--sandbox-id <id> [--instance-timeout <seconds>] [--show-credentials]`,flags:Xb,exampleArgs:[`--sandbox-id sbx-xxx --instance-timeout 3600`,`--sandbox-id sbx-xxx --show-credentials --output json`],notes:kb,async run(t){let n=w(t.settings.output),r=Ab(t,un(t.flags.sandboxId,e)),i=await Qb(t.flags);if(t.settings.dryRun){D({method:`POST`,endpoint:r,request:Hb(i)},n);return}$b(await t.client.requestJson({path:r,method:`POST`,body:Object.keys(i).length>0?i:void 0}),{format:n,quiet:t.settings.quiet,showCredentials:t.flags.showCredentials})}})}const ix=rx(`connect`),ax=rx(`resume`),ox=C({description:{"en-US":`Pause a Sandbox instance`,"zh-CN":`暂停 Sandbox 实例`},auth:`apiKey`,usageArgs:`--sandbox-id <id>`,flags:Yb,exampleArgs:[`--sandbox-id sbx-xxx`,`--sandbox-id sbx-xxx --dry-run --output json`],notes:kb,async run(e){let t=w(e.settings.output),n=Ab(e,un(e.flags.sandboxId,`pause`));if(e.settings.dryRun){D({method:`POST`,endpoint:n,request:null},t);return}await e.client.request({path:n,method:`POST`}),e.settings.quiet?E(e.flags.sandboxId):D({sandboxID:e.flags.sandboxId,paused:!0},t)}}),sx=C({description:{"en-US":`Release a Sandbox instance`,"zh-CN":`释放 Sandbox 实例`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently releases the Sandbox instance and cannot be undone.`,"zh-CN":`该操作会永久释放 Sandbox 实例,且无法撤销。`}},usageArgs:`--sandbox-id <id>`,flags:Yb,exampleArgs:[`--sandbox-id sbx-xxx --dry-run`,`--sandbox-id sbx-xxx --yes`],notes:kb,async run(e){let t=w(e.settings.output),n=Ab(e,dn(e.flags.sandboxId));if(e.settings.dryRun){D({method:`DELETE`,endpoint:n,request:null},t);return}await e.client.request({path:n,method:`DELETE`}),e.settings.quiet?E(e.flags.sandboxId):D({sandboxID:e.flags.sandboxId,deleted:!0},t)}}),cx={async:{type:`switch`,description:{"en-US":`Return the submitted templateID/buildID immediately without polling`,"zh-CN":`提交后立即返回 templateID/buildID,不轮询构建状态`}}},lx={templateId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Sandbox template ID`,"zh-CN":`Sandbox 模版 ID`}}},ux={image:{type:`string`,valueHint:`<preset>`,choices:bb,description:{"en-US":`Built-in image ID or Chinese name; fills fromImage and imageName`,"zh-CN":`内置镜像 ID 或中文名;自动填写 fromImage 和 imageName`}},name:{type:`string`,valueHint:`<name>`,description:{"en-US":`Template name`,"zh-CN":`模版名称`}},cpuCount:{type:`number`,valueHint:`<cores>`,description:{"en-US":`vCPU count`,"zh-CN":`vCPU 核数`}},memoryMb:{type:`number`,valueHint:`<mb>`,description:{"en-US":`Memory in MB`,"zh-CN":`内存大小(MB)`}},fromImage:{type:`string`,valueHint:`<image>`,description:{"en-US":`Base image identifier`,"zh-CN":`基础镜像标识`}},imageName:{type:`string`,valueHint:`<name>`,description:{"en-US":`Base image display name`,"zh-CN":`基础镜像展示名称`}},env:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Template environment variable; repeat for multiple values`,"zh-CN":`模版环境变量;可重复传入`}},allowOut:{type:`array`,valueHint:`<address>`,description:{"en-US":`Outbound allow-list entry; repeat for multiple values`,"zh-CN":`出站白名单条目;可重复传入`}},denyOut:{type:`array`,valueHint:`<address>`,description:{"en-US":`Outbound deny-list entry; repeat for multiple values`,"zh-CN":`出站黑名单条目;可重复传入`}},autoPauseTime:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Automatically pause after 300-604800 seconds`,"zh-CN":`在 300–604800 秒后自动暂停`}},maxRunningTime:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Maximum running lifetime in seconds (300-604800)`,"zh-CN":`最大运行时间(秒,300–604800)`}},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`Template description`,"zh-CN":`模版描述`}}},dx={...wb,...Tb,...ux,tag:{type:`array`,valueHint:`<tag>`,description:{"en-US":`E2B tag; repeat for multiple values`,"zh-CN":`E2B Tag;可重复传入`}},alias:{type:`string`,valueHint:`<alias>`,description:{"en-US":`E2B template alias`,"zh-CN":`E2B 模版别名`}},...cx,...Ob},fx={...wb,...lx,...Tb,...ux,...cx,...Ob},px={...wb,limit:{type:`number`,valueHint:`<n>`,description:{"en-US":`Maximum results (1-100)`,"zh-CN":`最大返回数量(1–100)`}},cursor:{type:`string`,valueHint:`<cursor>`,description:{"en-US":`Server-side pagination cursor`,"zh-CN":`服务端分页 Cursor`}}},mx={...wb,...lx},hx={...wb,...lx,buildId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Template build ID`,"zh-CN":`模版构建 ID`}}};function gx(e,t){if(t.image!==void 0){let n=Sb(t.image);e.fromImage=n.imageUrl,e.imageName=n.imageName}Q(e,`name`,t.name),Q(e,`cpuCount`,t.cpuCount),Q(e,`memoryMB`,t.memoryMb),Q(e,`fromImage`,t.fromImage),Q(e,`imageName`,t.imageName),Q(e,`autoPauseTime`,t.autoPauseTime),Q(e,`maxRunningTimeout`,t.maxRunningTime),Q(e,`description`,t.description),Fb(e,`envConfig`,Pb(t.env,`--env`));let n={};Q(n,`allowOut`,t.allowOut),Q(n,`denyOut`,t.denyOut),Fb(e,`networkConfig`,n)}function _x(e,t){if(t&&(typeof e.name!=`string`||e.name.trim().length===0))throw new n(`Template create requires --name or name in --body.`,l.USAGE);let r=e.cpuCount!==void 0,i=e.memoryMB!==void 0;if(t&&(!r||!i))throw new n(`Template create requires both --cpu-count and --memory-mb, or their --body fields.`,l.USAGE);if(r!==i)throw new n(`cpuCount and memoryMB must be provided together.`,l.USAGE);if(r&&Lb(e.cpuCount,`cpuCount`),i&&Lb(e.memoryMB,`memoryMB`),Ib(e.autoPauseTime,`autoPauseTime`,300,604800),Ib(e.maxRunningTimeout,`maxRunningTimeout`,300,604800),!t&&Object.keys(e).length===0)throw new n(`Template update requires at least one field.`,l.USAGE)}async function vx(e){let t=await Nb(e.body);return gx(t,e),Q(t,`tags`,e.tag),Q(t,`alias`,e.alias),_x(t,!0),t}async function yx(e){let t=await Nb(e.body);return gx(t,e),_x(t,!1),t}async function bx(e,t,r,i){let a=Date.now()+t.timeout*1e3,o=Hn(`Waiting for template build...`);t.quiet||o.start();try{for(;;){let s=a-Date.now();if(s<=0)break;let c=await e.requestJson({path:r,method:`GET`,timeout:s/1e3});if(t.quiet||o.update(`Build status: ${c.status??`unknown`}`),c.status===`ready`)return o.stop(`Template build ready.`),c;if(c.status===`error`)throw o.stop(`Template build failed.`),new n(c.reason?.message??(c.reason?.code===void 0?`Template build failed.`:`${c.reason.code}`),l.GENERAL);let u=Math.min(i*1e3,a-Date.now());u>0&&await new Promise(e=>setTimeout(e,u))}}finally{o.stop()}throw new n(`Template build polling timed out.`,l.TIMEOUT,`Increase --timeout or query the build status command with the returned IDs.`)}function xx(e){if(e.pollInterval!==void 0&&(!Number.isInteger(e.pollInterval)||e.pollInterval<=0))return`--poll-interval must be a positive integer.`}async function Sx(e){let t=w(e.settings.output);if(!e.response.templateID||!e.response.buildID)throw new n(`Template mutation response is missing templateID or buildID.`,l.GENERAL);if(e.async){e.settings.quiet?E(`${e.response.templateID}\t${e.response.buildID}`):D(e.response,t);return}let r=new URL(cn(fn(e.response.templateID,e.response.buildID)),e.endpoint).toString(),i;try{i=await bx(e.client,e.settings,r,e.pollInterval??5)}catch(r){let i=`Submitted build / 已提交的构建: templateID=${e.response.templateID}, buildID=${e.response.buildID}.\nCheck this build with sandbox template build-status before submitting another build. / 请先通过 sandbox template build-status 查询本次构建,再决定是否重新提交。`;if(r instanceof n)throw new n(r.message,r.exitCode,[r.hint,i].filter(Boolean).join(`
|
|
2838
|
-
`),{api:r.api,rawResponse:r.rawResponse,cause:r.cause});let a={templateID:e.response.templateID,buildID:e.response.buildID,hint:i};throw process.stderr.write(t===`json`?`${JSON.stringify(a,null,2)}\n\n`:`${i}\n`),r}e.settings.quiet?E($(e.response.templateID)):D({template:e.response,build:i},t)}const Cx=C({description:{"en-US":`Create a Sandbox template`,"zh-CN":`创建 Sandbox 模版`},auth:`apiKey`,usageArgs:`(--name <name> --cpu-count <cores> --memory-mb <mb> | --body <json|@path>) [flags]`,flags:dx,exampleArgs:[`--name browser --image browser --cpu-count 1 --memory-mb 2048`,`--name python --cpu-count 1 --memory-mb 2048`,`--body @template.json --async --output json`,`--name browser --cpu-count 4 --memory-mb 8192 --dry-run --output json`],notes:[...kb,...xb,{"en-US":`--image overrides body fromImage/imageName; explicit --from-image/--image-name override the corresponding preset fields. Without --image, image behavior is unchanged.`,"zh-CN":`--image 覆盖 body 中的 fromImage/imageName;显式 --from-image/--image-name 再覆盖对应预设字段。不传 --image 时保持原有镜像行为。`},{"en-US":`For local file mounts, use sandbox file upload first; put the available file's id into --body mntConfig[].originFileId with mountPath and optional originFileName. Upload and template must use the same workspace. Other complete nested structures can also be supplied through --body.`,"zh-CN":`挂载本地文件前先调用 sandbox file upload;将可用文件的 id 填入 --body 的 mntConfig[].originFileId,并传入 mountPath 和可选的 originFileName。上传和模版须位于同一工作空间。其他完整嵌套结构也可通过 --body 提供。`},{"en-US":`By default the command waits for build status ready; --async returns the submitted build immediately.`,"zh-CN":`默认等待构建状态变为 ready;--async 会立即返回已提交的构建信息。`}],validate:xx,async run(e){let t=w(e.settings.output),n=Ab(e,g.templateCreate),r=await vx(e.flags);if(e.settings.dryRun){D({method:`POST`,endpoint:n,request:Hb(r)},t);return}await Sx({response:await e.client.requestJson({path:n,method:`POST`,body:r}),endpoint:n,client:e.client,settings:e.settings,async:e.flags.async,pollInterval:e.flags.pollInterval})}}),wx=C({description:{"en-US":`List Sandbox templates`,"zh-CN":`列出 Sandbox 模版`},auth:`apiKey`,usageArgs:`[--limit <n>] [--cursor <cursor>]`,flags:px,exampleArgs:[``,`--limit 100 --output json`],notes:[...kb,{"en-US":`The API response does not expose a next cursor, so automatic --all pagination is unavailable.`,"zh-CN":`API 响应未提供下一页 Cursor,因此不支持自动 --all 翻页。`}],validate(e){if(e.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>100))return`--limit must be an integer between 1 and 100.`},async run(e){let t=new URL(Ab(e,g.templateList));e.flags.limit!==void 0&&t.searchParams.set(`limit`,String(e.flags.limit)),e.flags.cursor&&t.searchParams.set(`cursor`,e.flags.cursor);let n=await e.client.requestJson({path:t.toString(),method:`GET`});if(e.settings.quiet){for(let e of n)E($(e.templateID));return}let r=w(e.settings.output);if(r===`json`){D(n,r);return}if(n.length===0){E(`No Sandbox templates found.`);return}let i=n.map(e=>[$(e.templateID),$(e.templateName),$(e.cpuCount),$(e.memoryMB),$(e.spawnCount),$(e.buildCount),$(e.updatedAt)]);for(let e of Xn([`ID`,`NAME`,`CPU`,`MEMORY_MB`,`INSTANCES`,`BUILDS`,`UPDATED_AT`],i))E(e)}}),Tx=C({description:{"en-US":`Get Sandbox template details`,"zh-CN":`获取 Sandbox 模版详情`},auth:`apiKey`,usageArgs:`--template-id <id>`,flags:mx,exampleArgs:[`--template-id tpl-xxx`,`--template-id tpl-xxx --output json`],notes:kb,async run(e){let t=Ab(e,pn(e.flags.templateId)),n=await e.client.requestJson({path:t,method:`GET`});e.settings.quiet?E($(n.templateID)):D(n,w(e.settings.output))}}),Ex=C({description:{"en-US":`Update a Sandbox template`,"zh-CN":`更新 Sandbox 模版`},auth:`apiKey`,usageArgs:`--template-id <id> (--body <json|@path> | [fields])`,flags:fx,exampleArgs:[`--template-id tpl-xxx --image all-in-one`,`--template-id tpl-xxx --cpu-count 4 --memory-mb 8192`,`--template-id tpl-xxx --body @template-update.json --async --output json`,`--template-id tpl-xxx --description updated --dry-run --output json`],notes:[...kb,...xb,{"en-US":`--image overrides body fromImage/imageName; explicit --from-image/--image-name override the corresponding preset fields. Without --image, image behavior is unchanged.`,"zh-CN":`--image 覆盖 body 中的 fromImage/imageName;显式 --from-image/--image-name 再覆盖对应预设字段。不传 --image 时保持原有镜像行为。`},{"en-US":`Supplying envConfig or --env replaces the template's complete environment map.`,"zh-CN":`传入 envConfig 或 --env 会整体替换模版的环境变量 Map。`},{"en-US":`Use sandbox file upload for local mount files. In --body mntConfig[], set originFileId to the available file's id and supply mountPath; upload and template must use the same workspace.`,"zh-CN":`本地挂载文件先通过 sandbox file upload 上传。在 --body 的 mntConfig[] 中,将 originFileId 设为可用文件的 id 并传入 mountPath;上传和模版须位于同一工作空间。`},{"en-US":`By default the command waits for build status ready; --async returns the submitted build immediately.`,"zh-CN":`默认等待构建状态变为 ready;--async 会立即返回已提交的构建信息。`}],validate:xx,async run(e){let t=w(e.settings.output),n=Ab(e,pn(e.flags.templateId)),r=await yx(e.flags);if(e.settings.dryRun){D({method:`PUT`,endpoint:n,request:Hb(r)},t);return}await Sx({response:await e.client.requestJson({path:n,method:`PUT`,body:r}),endpoint:n,client:e.client,settings:e.settings,async:e.flags.async,pollInterval:e.flags.pollInterval})}}),Dx=C({description:{"en-US":`Get Sandbox template build status`,"zh-CN":`获取 Sandbox 模版构建状态`},auth:`apiKey`,usageArgs:`--template-id <id> --build-id <id>`,flags:hx,exampleArgs:[`--template-id tpl-xxx --build-id build-xxx`,`--template-id tpl-xxx --build-id build-xxx --output json`],notes:kb,async run(e){let t=Ab(e,fn(e.flags.templateId,e.flags.buildId)),n=await e.client.requestJson({path:t,method:`GET`});e.settings.quiet?E($(n.status)):D(n,w(e.settings.output))}}),Ox=C({description:{"en-US":`Delete a Sandbox template`,"zh-CN":`删除 Sandbox 模版`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the Sandbox template and cannot be undone.`,"zh-CN":`该操作会永久删除 Sandbox 模版,且无法撤销。`}},usageArgs:`--template-id <id>`,flags:mx,exampleArgs:[`--template-id tpl-xxx --dry-run`,`--template-id tpl-xxx --yes`],notes:[...kb,{"en-US":`The server rejects deletion while running or paused instances still use the template.`,"zh-CN":`仍有运行中或已暂停实例使用该模版时,服务端会拒绝删除。`}],async run(e){let t=w(e.settings.output),n=Ab(e,pn(e.flags.templateId));if(e.settings.dryRun){D({method:`DELETE`,endpoint:n,request:null},t);return}await e.client.request({path:n,method:`DELETE`}),e.settings.quiet?E(e.flags.templateId):D({templateID:e.flags.templateId,deleted:!0},t)}});export{Qf as advisorRecommend,dl as appCall,pl as appList,qa as authGenerateAccessToken,Wa as authLogin,Ka as authLogout,Ga as authStatus,il as configAgent,Uo as configList,Ho as configSet,Vo as configShow,bc as configUi,Wo as configUse,Id as consoleCall,Zp as datasetDelete,Xp as datasetGet,Yp as datasetList,Jp as datasetUpload,Qp as datasetValidate,Wm as deployAudioCreate,Zm as deployDelete,qm as deployGet,Gm as deployImageCreate,Km as deployList,Jm as deployModels,Qm as deployPause,$m as deployResume,Ym as deployScale,Um as deployTextCreate,Xm as deployUpdate,Fd as fileUpload,pm as finetuneAudioCreate,bm as finetuneCancel,Pm as finetuneCapability,Em as finetuneCheckpoints,xm as finetuneDelete,Dm as finetuneExport,ym as finetuneGet,mm as finetuneImageCreate,gm as finetuneList,Tm as finetuneLogs,Lm as finetunePrice,fm as finetuneTextCreate,hm as finetuneVideoCreate,Mm as finetuneWatch,go as imageEdit,fo as imageGenerate,Uu as knowledgeCategoryAdd,Wu as knowledgeCategoryDelete,Hu as knowledgeCategoryList,zl as knowledgeChat,ju as knowledgeChunkAdd,Ru as knowledgeChunkDelete,Mu as knowledgeChunkList,Fu as knowledgeChunkUpdate,Ju as knowledgeCollectionCreate,Yu as knowledgeCollectionGet,cu as knowledgeDocDelete,Xu as knowledgeDocImportOss,Gl as knowledgeDocList,Jl as knowledgeDocStatus,lu as knowledgeDocTag,nu as knowledgeDocUpload,qu as knowledgeFileDelete,Ku as knowledgeFileGet,Gu as knowledgeFileList,au as knowledgeKbCreate,su as knowledgeKbDelete,Wl as knowledgeKbInfo,Bl as knowledgeKbList,Vu as knowledgeKbStats,ou as knowledgeKbUpdate,xl as knowledgeRetrieve,Nl as knowledgeSearch,Ou as knowledgeServiceCopy,_u as knowledgeServiceCreate,Du as knowledgeServiceDelete,Eu as knowledgeServiceDeploy,gu as knowledgeServiceGet,pu as knowledgeServiceList,Tu as knowledgeServiceUpdate,Y_ as managedAgentAgentCreate,mv as managedAgentAgentGet,hv as managedAgentAgentList,gv as managedAgentAgentSearch,_v as managedAgentAgentVersions,Qh as managedAgentApply,av as managedAgentDeploymentCreate,Jv as managedAgentDeploymentGet,Yv as managedAgentDeploymentList,Zv as managedAgentDeploymentPause,Qv as managedAgentDeploymentRun,$v as managedAgentDeploymentRunsGet,ey as managedAgentDeploymentRunsList,ty as managedAgentDeploymentSearch,ny as managedAgentDeploymentUnpause,$h as managedAgentDestroy,X_ as managedAgentEnvironmentCreate,Sv as managedAgentEnvironmentGet,Cv as managedAgentEnvironmentList,wv as managedAgentEnvironmentSearch,Yy as managedAgentFileDelete,Jy as managedAgentFileDownload,Ky as managedAgentFileGet,Gy as managedAgentFileList,qy as managedAgentFileSearch,Wy as managedAgentFileUpload,Th as managedAgentInit,Zh as managedAgentPlan,yg as managedAgentPlayground,Cg as managedAgentProjectBuild,xg as managedAgentProjectInit,wg as managedAgentProjectPublish,Sg as managedAgentProjectValidate,Dg as managedAgentProjectVersionDisable,Eg as managedAgentProjectVersionEnable,Ag as managedAgentProjectVersionList,Mg as managedAgentProjectVersionPreview,Ng as managedAgentProjectVersionRestore,kg as managedAgentProjectVersionStatus,Tg as managedAgentProjectWorkbench,dy as managedAgentSessionArchive,Yg as managedAgentSessionCreate,Ny as managedAgentSessionDebug,i_ as managedAgentSessionDelete,__ as managedAgentSessionEventList,__ as managedAgentSessionEvents,v_ as managedAgentSessionEventSend,y_ as managedAgentSessionEventStream,Py as managedAgentSessionExport,r_ as managedAgentSessionGet,n_ as managedAgentSessionList,a_ as managedAgentSessionRun,ly as managedAgentSessionSearch,o_ as managedAgentSessionSend,uy as managedAgentSessionUpdate,ev as managedAgentSkillCreate,Tv as managedAgentSkillDownload,Ev as managedAgentSkillGet,A_ as managedAgentSkillList,Dv as managedAgentSkillSearch,Ov as managedAgentSkillVersions,Bg as managedAgentStateImport,Fg as managedAgentStateList,Lg as managedAgentStateRm,Ig as managedAgentStateShow,Jh as managedAgentValidate,tv as managedAgentVaultCreate,nv as managedAgentVaultCredentialCreate,Nv as managedAgentVaultGet,Pv as managedAgentVaultList,Fv as managedAgentVaultSearch,od as mcpCall,cd as mcpList,ld as mcpTools,ml as memoryAdd,vl as memoryDelete,gl as memoryList,yl as memoryProfileCreate,bl as memoryProfileGet,hl as memorySearch,_l as memoryUpdate,up as modelList,Kp as permissionGrant,Vp as permissionList,qp as permissionRevoke,Mf as pipelineRun,Lf as pipelineValidate,sb as pluginInstall,cb as pluginLink,lb as pluginList,ub as pluginRemove,Rp as quotaCheck,Tp as quotaDelete,jp as quotaHistory,Cp as quotaList,wp as quotaUpdate,ix as sandboxConnect,ex as sandboxCreate,sx as sandboxDelete,Wb as sandboxFileUpload,nx as sandboxGet,tx as sandboxList,Cb as sandboxOfficialImages,ox as sandboxPause,ax as sandboxResume,Dx as sandboxTemplateBuildStatus,Cx as sandboxTemplateCreate,Ox as sandboxTemplateDelete,Tx as sandboxTemplateGet,wx as sandboxTemplateList,Ex as sandboxTemplateUpdate,dd as searchWeb,db as skillAdd,vb as skillInit,hb as skillList,pb as skillRemove,fb as skillUpdate,Sd as speechRecognize,gd as speechSynthesize,Ad as speechVocabularyCreate,Pd as speechVocabularyDelete,Md as speechVocabularyGet,jd as speechVocabularyList,Nd as speechVocabularyUpdate,ro as textChat,uo as textOmni,xh as tokenPlanAddMember,vh as tokenPlanAssignSeats,mh as tokenPlanCreateKey,uh as tokenPlanListSeats,ul as update,Af as usageCodingPlan,lf as usageFree,uf as usageFreetier,mf as usageStats,hf as usageSummary,Cf as usageTokenPlan,wo as videoDownload,xo as videoEdit,bo as videoGenerate,So as videoRef,Co as videoTaskGet,Oo as visionDescribe,nb as workspaceInit,hp as workspaceList};
|
|
2838
|
+
`):e.type===`error`&&process.stderr.write(`\n[error] ${e.content??`unknown error`}\n`)}function $g(e,t,n={}){if(t)process.stdout.write(`${JSON.stringify({...n,events:ba(e.result.events),has_more:e.result.has_more,next_page:e.result.next_page},null,2)}\n`);else{for(let t of e.result.events)Qg(t);Jg(e.terminalStatus,t)}Xg(e.terminalStatus,Yg(e.result.events))}function e_(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean):void 0}var t_=C({description:{"en-US":`Create a new session for an agent`,"zh-CN":`为 Agent 创建新 Session`},auth:`apiKey`,usageArgs:`[--agent <name>] [--environment <name>] [--title <title>] [--file <path>]`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},agent:{type:`string`,valueHint:`<name>`,description:{"en-US":`Agent name (auto-detected when only one agent is configured)`,"zh-CN":`Agent 名称(仅配置一个 Agent 时自动识别)`}},environment:{type:`string`,valueHint:`<name>`,description:{"en-US":`Override agent's declared environment`,"zh-CN":`覆盖 Agent 声明的环境`}},vault:{type:`string`,valueHint:`<name>`,description:{"en-US":`Override agent's declared vault`,"zh-CN":`覆盖 Agent 声明的 Vault`}},memoryStores:{type:`string`,valueHint:`<names>`,description:{"en-US":`Override agent's memory stores (comma-separated)`,"zh-CN":`覆盖 Agent 的 Memory Store(以逗号分隔)`}},title:{type:`string`,valueHint:`<title>`,description:{"en-US":`Session title`,"zh-CN":`Session 标题`}}},exampleArgs:[``,`--agent assistant`,{"en-US":`--agent assistant --title 'debug run'`,"zh-CN":`--agent assistant --title '调试运行'`}],notes:U,async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=n.file??`agents.yaml`;if(t.dryRun){D({would_create_session:{agent:n.agent??`auto`,provider:`bailian`,environment:n.environment,vault:n.vault,memory_stores:e_(n.memoryStores),title:n.title},config_file:i},r);return}let{agentName:a,session:o}=await G(()=>K(async()=>hi(await W(e,i),{agent:n.agent,provider:`bailian`,environment:n.environment,vault:n.vault,memoryStores:e_(n.memoryStores),title:n.title})));if(r===`json`){D({agent:a,session:o},r);return}E(`Session created: ${o.id}`),E(` Agent: ${a}`),E(` Environment: ${o.environment_id}`),E(` Status: ${o.status}`),o.vault_ids.length&&E(` Vaults: ${o.vault_ids.join(`, `)}`),o.memory_store_ids.length&&E(` Memory: ${o.memory_store_ids.join(`, `)}`)}});async function n_(e,t,n){let r=await e(n),i=[...r.items],a=r.hasMore,o=r.nextPage;for(;t&&o;){let t=await e(o);i.push(...t.items),a=t.hasMore,o=t.nextPage}return{items:i,hasMore:a,nextPage:o}}const q={file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}},J={limit:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page size (1-100)`,"zh-CN":`单页数量(1-100)`}},page:{type:`string`,valueHint:`<cursor>`,description:{"en-US":`Opaque page cursor returned by a previous request`,"zh-CN":`上一次请求返回的不透明分页 Cursor`}},all:{type:`switch`,description:{"en-US":`Fetch all pages by following opaque cursors`,"zh-CN":`跟随不透明 Cursor 获取全部分页`}}},r_={query:{type:`string`,valueHint:`<text>`,required:!0,description:{"en-US":`Case-insensitive text to find in IDs, names, and descriptions`,"zh-CN":`在 ID、名称和描述中进行不区分大小写的文本搜索`}},pageLimit:{type:`number`,valueHint:`<n>`,description:{"en-US":`Maximum pages to scan for client-side search (default: 10)`,"zh-CN":`客户端搜索最多扫描的页数(默认:10)`}}},i_={includeArchived:{type:`switch`,description:{"en-US":`Include archived resources`,"zh-CN":`包含已归档资源`}}};function Y(e){if(e.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>100))return`--limit must be an integer between 1 and 100.`;if(e.pageLimit!==void 0&&(!Number.isInteger(e.pageLimit)||e.pageLimit<1||e.pageLimit>100))return`--page-limit must be an integer between 1 and 100.`}function a_(e){if(!e)return;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t.length>0?t:void 0}function o_(e,...t){let n=e.trim().toLocaleLowerCase();return n?t.some(e=>e==null?!1:(typeof e==`string`?e:JSON.stringify(e)).toLocaleLowerCase().includes(n)):!0}async function s_(e,t,n=10){let r=[],i,a=!1,o,s=0;do{let n=await e(i);s+=1,r.push(...n.items.filter(t)),a=n.hasMore,o=n.nextPage,i=n.nextPage}while(a&&i&&s<n);return{items:r,hasMore:a,nextPage:o,scannedPages:s,truncated:!!(a&&o)}}function X(e){let{format:t,key:n,items:r,headers:i,rows:a,hasMore:o=!1,nextPage:s,truncated:c,scannedPages:l,emptyMessage:u=`No resources found.`}=e;if(t===`json`){D({[n]:r,has_more:o,next_page:s,...c===void 0?{}:{truncated:c},...l===void 0?{}:{scanned_pages:l}},t);return}if(r.length===0){E(u);return}for(let e of Xn(i,a))E(e);E(`\nTotal: ${r.length}`),c?E(`Search stopped at --page-limit; more pages remain.`):o&&E(`More results are available.${s?` Next page: ${s}`:``}`)}function Z(e,t=40){if(e==null||e===``)return`-`;let n=typeof e==`string`?e:JSON.stringify(e);return n.length>t?`${n.slice(0,t-3)}...`:n}var c_=C({description:{"en-US":`List sessions from the provider`,"zh-CN":`列出 Provider 中的 Session`},auth:`apiKey`,usageArgs:`[--agent <name>] [--statuses <statuses>] [--limit <n>] [--page <cursor>] [--all]`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},agent:{type:`string`,valueHint:`<name>`,description:{"en-US":`Filter by agent name`,"zh-CN":`按 Agent 名称筛选`}},all:{type:`switch`,description:{"en-US":`Fetch all pages by following the cursor`,"zh-CN":`跟随 Cursor 获取全部分页`}},limit:J.limit,page:J.page,statuses:{type:`string`,valueHint:`<statuses>`,description:{"en-US":`Comma-separated session statuses`,"zh-CN":`Session 状态,多个以逗号分隔`}},createdAtGte:{type:`string`,valueHint:`<timestamp>`,description:{"en-US":`Created at or after this RFC 3339 timestamp`,"zh-CN":`创建时间不早于该 RFC 3339 时间戳`}},createdAtLte:{type:`string`,valueHint:`<timestamp>`,description:{"en-US":`Created at or before this RFC 3339 timestamp`,"zh-CN":`创建时间不晚于该 RFC 3339 时间戳`}}},exampleArgs:[``,`--agent assistant`,`--all`],notes:U,validate:Y,async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=n.file??`agents.yaml`,{items:a,hasMore:o,nextPage:s}=await G(()=>K(async()=>{let t=await W(e,i);return n_(async e=>{let r=await Gi(t,{agent:n.agent,provider:`bailian`,filter:{page:e,limit:n.limit,statuses:a_(n.statuses),created_at_gte:n.createdAtGte,created_at_lte:n.createdAtLte}});return{items:r.summaries,hasMore:r.hasMore,nextPage:r.nextPage}},n.all,n.page)})),c=a.map(e=>e.session);if(r===`json`){D({sessions:c,has_more:o,next_page:s},r);return}if(c.length===0){E(`No sessions found.`);return}let l=new Map(a.filter(e=>e.agentName).map(e=>[e.session.id,e.agentName])),u=[`ID`,`TITLE`,`AGENT`,`STATUS`,`CREATED`],d=c.map(e=>[e.id,(e.title??``).slice(0,20),l.get(e.id)??e.agent_id.slice(0,12),e.status,e.created_at]);for(let e of Xn(u,d))E(e);E(`\nTotal: ${c.length}`),o&&E(`More sessions available. Use --all to fetch all.`)}}),l_=C({description:{"en-US":`Get details of a session`,"zh-CN":`获取 Session 详情`},auth:`apiKey`,usageArgs:`--session-id <id> [--file <path>]`,flags:{sessionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Session ID (required)`,"zh-CN":`Session ID(必填)`},required:!0},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}},exampleArgs:[`--session-id sess_abc123`],notes:U,async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=n.file??`agents.yaml`,a=await G(()=>K(async()=>ji(await W(e,i),n.sessionId,`bailian`)));if(r===`json`){D(a,r);return}E(` ID: ${a.id}`),E(` Agent: ${a.agent_id}`),E(` Environment: ${a.environment_id}`),E(` Status: ${a.status}`),a.title&&E(` Title: ${a.title}`),E(` Created: ${a.created_at}`),E(` Updated: ${a.updated_at}`)}}),u_=C({description:{"en-US":`Delete a session`,"zh-CN":`删除 Session`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This deletes the specified remote managed Agent Session.`,"zh-CN":`该操作会删除指定的远端托管 Agent Session。`}},usageArgs:`--session-id <id> [--file <path>]`,flags:{sessionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Session ID (required)`,"zh-CN":`Session ID(必填)`},required:!0},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}},exampleArgs:[`--session-id sess_abc123 --yes`],notes:U,async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=n.file??`agents.yaml`;if(t.dryRun){D({would_delete_session:n.sessionId,provider:`bailian`,config_file:i},r);return}await G(()=>K(async()=>{await vi(await W(e,i),n.sessionId,`bailian`)})),r===`json`?D({deleted:n.sessionId},r):E(`Session ${n.sessionId} deleted.`)}}),d_=C({description:{"en-US":`Create a session, send a message, and stream the response`,"zh-CN":`创建 Session、发送消息并流式输出响应`},auth:`apiKey`,usageArgs:`--prompt <text> [--agent <name>] [--no-stream] [--file <path>]`,flags:{prompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Prompt to send (required)`,"zh-CN":`要发送的 Prompt(必填)`},required:!0},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},agent:{type:`string`,valueHint:`<name>`,description:{"en-US":`Agent name (auto-detected when only one agent is configured)`,"zh-CN":`Agent 名称(仅配置一个 Agent 时自动识别)`}},environment:{type:`string`,valueHint:`<name>`,description:{"en-US":`Override agent's declared environment`,"zh-CN":`覆盖 Agent 声明的环境`}},vault:{type:`string`,valueHint:`<name>`,description:{"en-US":`Override agent's declared vault`,"zh-CN":`覆盖 Agent 声明的 Vault`}},memoryStores:{type:`string`,valueHint:`<names>`,description:{"en-US":`Override agent's memory stores (comma-separated)`,"zh-CN":`覆盖 Agent 的 Memory Store(以逗号分隔)`}},title:{type:`string`,valueHint:`<title>`,description:{"en-US":`Session title`,"zh-CN":`Session 标题`}},noStream:{type:`switch`,description:{"en-US":`Use polling instead of SSE streaming`,"zh-CN":`使用轮询代替 SSE 流式传输`}}},exampleArgs:[{"en-US":`--prompt "hello"`,"zh-CN":`--prompt "你好"`},{"en-US":`--agent assistant --prompt "summarize this repo"`,"zh-CN":`--agent assistant --prompt "总结这个代码仓库"`}],notes:[...U,{"en-US":"--output json emits one envelope: { session_id, provider, agent, events } — read session_id to chain `session send/get/events/delete`.","zh-CN":"--output json 输出一个 Envelope:{ session_id, provider, agent, events }。读取 session_id 后可串联调用 `session send/get/events/delete`。"}],async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=n.file??`agents.yaml`,a=r===`json`,o={agent:n.agent,provider:`bailian`,environment:n.environment,vault:n.vault,memoryStores:e_(n.memoryStores),title:n.title};if(t.dryRun){D({would_run:{prompt:n.prompt,agent:n.agent??`auto`,provider:`bailian`,environment:n.environment,vault:n.vault,memory_stores:o.memoryStores,title:n.title,mode:n.noStream?`polling`:`streaming`},config_file:i},r);return}await G(()=>K(async()=>{let t=await W(e,i);if(n.noStream){let e=await aa(t,n.prompt,o);a||process.stderr.write(`Session created: ${e.session.id}\n`),$g(e,a,{session_id:e.session.id,provider:e.provider,agent:e.agentName})}else{let e=await ia(t,n.prompt,o);a||process.stderr.write(`Session created: ${e.session.id}\n`),await Zg(e.events,a,{session_id:e.session.id,provider:e.provider,agent:e.agentName})}}))}}),f_=C({description:{"en-US":`Send a message to an existing session and stream the response`,"zh-CN":`向已有 Session 发送消息并流式输出响应`},auth:`apiKey`,usageArgs:`--session-id <id> --message <text> [--no-stream] [--file <path>]`,flags:{sessionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Session ID (required)`,"zh-CN":`Session ID(必填)`},required:!0},message:{type:`string`,valueHint:`<text>`,description:{"en-US":`Message to send (required)`,"zh-CN":`要发送的消息(必填)`},required:!0},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},noStream:{type:`switch`,description:{"en-US":`Use polling instead of SSE streaming`,"zh-CN":`使用轮询代替 SSE 流式传输`}}},exampleArgs:[{"en-US":`--session-id sess_abc123 --message "continue"`,"zh-CN":`--session-id sess_abc123 --message "继续"`}],notes:U,async run(e){let{settings:t,flags:n}=e,r=w(t.output),i=n.file??`agents.yaml`,a=r===`json`;if(t.dryRun){D({would_send:{session_id:n.sessionId,message:n.message,provider:`bailian`,mode:n.noStream?`polling`:`streaming`},config_file:i},r);return}await G(()=>K(async()=>{let t=await W(e,i);n.noStream?$g(await ta(t,n.sessionId,n.message,{provider:`bailian`}),a,{session_id:n.sessionId}):await Zg(await na(t,n.sessionId,n.message,{provider:`bailian`}),a,{session_id:n.sessionId})}))}});async function p_(e){return new Uint8Array(await Zr(M(e)))}async function m_(e){let t=e.startsWith(`@`)?await Zr(M(e.slice(1)),`utf8`):e;try{return JSON.parse(t)}catch(e){throw new n(`Invalid JSON input: ${e instanceof Error?e.message:String(e)}`,l.USAGE)}}async function h_(e,t,r=!1){let i=M(e);await Xr(Ir(i),{recursive:!0});let a=`${i}.${fr()}.tmp`;await ti(a,t,{flag:`wx`});try{if(r)await Qr(a,i);else{try{await Yr(a,i)}catch(e){throw e.code===`EEXIST`?new n(`Output file already exists: ${i}`,l.USAGE,`Choose another --output-file path or re-run with --force.`):e}await ei(a)}return i}catch(e){throw await ei(a).catch(()=>void 0),e}}function g_(e){let t=A(e).toLocaleLowerCase();return t.endsWith(`.json`)?`application/json`:t.endsWith(`.md`)?`text/markdown`:t.endsWith(`.txt`)?`text/plain`:t.endsWith(`.pdf`)?`application/pdf`:t.endsWith(`.png`)?`image/png`:t.endsWith(`.jpg`)||t.endsWith(`.jpeg`)?`image/jpeg`:t.endsWith(`.zip`)?`application/zip`:`application/octet-stream`}const __={sessionId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Session ID`,"zh-CN":`Session ID`}}},v_={...q,...__,...J,order:{type:`string`,valueHint:`<order>`,choices:[`asc`,`desc`],description:{"en-US":`Event order: asc or desc`,"zh-CN":`事件顺序:asc 或 desc`}},types:{type:`string`,valueHint:`<types>`,description:{"en-US":`Comma-separated raw event types`,"zh-CN":`原始事件类型,多个以逗号分隔`}},createdAtGte:{type:`string`,valueHint:`<timestamp>`,description:{"en-US":`Created at or after this timestamp`,"zh-CN":`创建时间不早于该时间戳`}},createdAtLte:{type:`string`,valueHint:`<timestamp>`,description:{"en-US":`Created at or before this timestamp`,"zh-CN":`创建时间不晚于该时间戳`}}},y_={...q,...__,event:{type:`string`,valueHint:`<json|@path>`,required:!0,description:{"en-US":`Raw event object/array as JSON or @event.json`,"zh-CN":`原始事件对象/数组 JSON,或 @event.json`}}},b_={...q,...__,afterId:{type:`string`,valueHint:`<event-id>`,description:{"en-US":`Resume after this event ID`,"zh-CN":`从该 Event ID 之后继续`}}};function x_(e){return e.map(e=>[Z(e.id),e.raw_type,Z(e.session_thread_id),Z(e.content??e.status??e.tool_name,70)])}function S_(e){let t=Array.isArray(e)?e:[e];if(t.length===0||t.some(e=>!e||typeof e!=`object`||Array.isArray(e)))throw new n(`Event input must be a JSON object or a non-empty array of objects.`,l.USAGE);for(let[e,r]of t.entries()){let t=ci.safeParse(r);if(t.success)continue;let i=t.error.issues[0];throw new n(`Invalid event at index ${e}${i?.path.length?` at ${i.path.join(`.`)}`:``}: ${i?.message??`does not match the Session event schema`}.`,l.USAGE)}return t}const C_=C({description:{"en-US":`List events for a Managed Agent session`,"zh-CN":`列出托管 Agent Session 事件`},auth:`apiKey`,usageArgs:`--session-id <id> [--types <types>] [--order asc|desc] [--limit <n>] [--page <cursor>] [--all]`,flags:v_,exampleArgs:[`--session-id sess_abc`,`--session-id sess_abc --all --output json`],notes:[...U,{"en-US":`--types is applied client-side to each page returned by the provider.`,"zh-CN":`--types 会在客户端对 Provider 返回的每一页结果进行过滤。`}],validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return n_(async n=>{let r=await Wi(t,e.flags.sessionId,{provider:`bailian`,limit:e.flags.limit,page_token:n,order:e.flags.order,types:a_(e.flags.types),created_at_gte:e.flags.createdAtGte,created_at_lte:e.flags.createdAtLte});return{items:r.events,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`events`,items:ba(n.items),headers:[`ID`,`TYPE`,`THREAD`,`CONTENT`],rows:x_(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No events found.`})}}),w_=C({description:{"en-US":`Send raw events to a Managed Agent session`,"zh-CN":`向托管 Agent Session 发送原始事件`},auth:`apiKey`,usageArgs:`--session-id <id> --event <json|@path>`,flags:y_,exampleArgs:[`--session-id sess_abc --event '{"type":"message","role":"user","content":[{"type":"text","text":"hello"}]}'`,`--session-id sess_abc --event @event.json`],notes:U,async run(e){let t=w(e.settings.output),n=S_(await m_(e.flags.event));if(e.settings.dryRun){D({would_send_events:n,session_id:e.flags.sessionId},t);return}let r=await G(()=>K(async()=>ea(await W(e,e.flags.file??`agents.yaml`),e.flags.sessionId,n,{provider:`bailian`})));t===`json`?D({session_id:e.flags.sessionId,...r},t):E(`Sent ${n.length} event(s): ${r.event_ids.join(`, `)}`)}}),T_=C({description:{"en-US":`Stream events from a Managed Agent session`,"zh-CN":`流式读取托管 Agent Session 事件`},auth:`apiKey`,usageArgs:`--session-id <id> [--after-id <event-id>]`,flags:b_,exampleArgs:[`--session-id sess_abc`,`--session-id sess_abc --after-id evt_123 --output json`],notes:[...U,{"en-US":`When the provider has no native event cursor, --after-id resumes through paginated history polling and event ID de-duplication.`,"zh-CN":`当 Provider 不支持原生事件 Cursor 时,--after-id 会通过分页历史轮询和 Event ID 去重实现续传。`}],async run(e){let t=w(e.settings.output);await G(()=>K(async()=>{let n=await W(e,e.flags.file??`agents.yaml`),r=[];for await(let i of oa(n,e.flags.sessionId,{provider:`bailian`,after_id:e.flags.afterId}))if(r.push(i),t!==`json`&&E(JSON.stringify(ba([i])[0])),i.type===`status`&&Pi(i.status))break;t===`json`&&D({session_id:e.flags.sessionId,events:ba(r)},t)}))}}),E_={source:{type:`string`,valueHint:`<source>`,choices:[`custom`,`official`,`all`],description:{"en-US":`Skill catalog: custom (default), official, or all`,"zh-CN":`Skill Catalog:custom(默认)、official 或 all`}}},D_={...q,...J,...E_},O_={...q,limit:J.limit,...r_,...E_},k_={...q,skillId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Skill ID`,"zh-CN":`Skill ID`}}},A_={...k_,...J},j_={...k_,skillVersion:{type:`string`,valueHint:`<version>`,required:!0,description:{"en-US":`Skill version`,"zh-CN":`Skill 版本`}},outputFile:{type:`string`,valueHint:`<path>`,required:!0,description:{"en-US":`Destination ZIP path`,"zh-CN":`目标 ZIP 路径`}},force:{type:`switch`,description:{"en-US":`Overwrite an existing output file`,"zh-CN":`覆盖已存在的输出文件`}}};function M_(e){return e.map(e=>[e.id,Z(e.name),e.source,e.status,Z(e.latest_version),Z(e.updated_at??e.created_at)])}function N_(e){return e.map(e=>[Z(e.version),Z(e.name),Z(e.type),Z(e.status),Z(e.updated_at??e.created_at)])}function P_(e,t){return{source:e,skills:t.items,has_more:t.hasMore,next_page:t.nextPage}}async function F_(e,t,n){return n_(async r=>{let i=await Hi(e,{provider:`bailian`,source:t,limit:n.limit,page:r});return{items:i.data,hasMore:i.has_more,nextPage:i.next_page}},n.all,n.page)}var I_=C({description:{"en-US":`List Managed Agent skills`,"zh-CN":`列出托管 Agent Skill`},auth:`apiKey`,usageArgs:`[--source custom|official|all] [--limit <n>] [--page <cursor>] [--all]`,flags:D_,exampleArgs:[``,`--source official`,`--source all --all --output json`],notes:[...U,{"en-US":`--source all combines one page from each catalog, or every page with --all; it does not accept --page.`,"zh-CN":`--source all 默认合并两个 Catalog 的各一页,传入 --all 时获取全部分页;该模式不接受 --page。`}],validate:e=>Y(e)??(e.source===`all`&&e.page?`--source all cannot be combined with --page.`:void 0),async run(e){let t=w(e.settings.output),n=e.flags.source??`custom`,r=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);if(n!==`all`)return F_(t,n,{limit:e.flags.limit,page:e.flags.page,all:e.flags.all});let[r,i]=await Promise.all([F_(t,`custom`,{limit:e.flags.limit,all:e.flags.all}),F_(t,`official`,{limit:e.flags.limit,all:e.flags.all})]);return{items:[...r.items,...i.items],hasMore:r.hasMore||i.hasMore,nextPage:void 0}}));if(t===`json`){D(P_(n,r),t);return}X({format:t,key:`skills`,items:r.items,headers:[`ID`,`NAME`,`SOURCE`,`STATUS`,`VERSION`,`UPDATED`],rows:M_(r.items),hasMore:r.hasMore,nextPage:r.nextPage,emptyMessage:`No skills found.`})}});const L_=[{"en-US":`Without --yes, this command only previews. --dry-run is fully offline. The scoped flow checks only the target resource and its transitive dependencies; unrelated resources are not refreshed or drift-checked.`,"zh-CN":`不带 --yes 时仅预览;--dry-run 完全离线。定向流程只检查目标资源及其传递依赖,不刷新或检测无关资源的 Drift。`}];function R_(e){let t=e=>Array.isArray(e)?e.map(t):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,n])=>[e,t(n)]));return JSON.stringify(t(e))}function z_(e,t=`resource`){return e.normalize(`NFKC`).trim().toLowerCase().replace(/[^\p{L}\p{N}]+/gu,`-`).replace(/^-+|-+$/g,``)||t}function B_(e){let t=new Set(e.state.listResources().filter(t=>t.address.provider===e.provider&&e.resourceTypes.includes(t.address.type)).map(e=>e.address.name)),n=R_(e.candidate);for(let[r,i]of Object.entries(e.declarations))if(!(e.effectiveName(r,i)!==e.displayName||t.has(r))&&R_(i)===n)return{key:r,reusedPending:!0};let r=z_(e.displayName,e.fallbackKey);if(!(r in e.declarations))return{key:r,reusedPending:!1};let i=2;for(;`${r}-${i}`in e.declarations;)i+=1;return{key:`${r}-${i}`,reusedPending:!1}}async function V_(e,t){let r=await Zr(M(t),`utf8`).catch(e=>{throw e.code===`ENOENT`?new n(`Config file not found: ${t}`,l.USAGE,"Run `bl managed-agent init` first."):e}),i=await G(()=>qh(e,t,{credentials:`none`})),a=await Zr(i.configPath,`utf8`);if(a!==r)throw new n(`${t} changed while it was being loaded.`,l.GENERAL,`Re-run the command against the latest file.`);let o=`bailian`;e.settings.dryRun||Vh(i.config.providers,[o]),Gh(e);let s=new si({configPath:i.configPath});return{...i,source:a,provider:o,stateBackend:s,stateScope:Hh(i.configPath,i.projectName)}}async function H_(e){let t=`__bailian_cli_create_candidate__`,n=structuredClone(e.project.config),r=n[e.group]??{};return n[e.group]={...r,[t]:e.rawDeclaration},(await G(()=>Qi(n,{projectName:e.project.projectName,basePath:Ir(e.project.configPath)}))).config[e.group]?.[t]??e.rawDeclaration}async function U_(e){let{project:t,host:r}=e,i=w(r.settings.output),a=await t.stateBackend.read(t.stateScope,n=>B_({displayName:e.displayName,provider:t.provider,resourceTypes:[e.resourceType],declarations:e.existingDeclarations,candidate:e.resolvedDeclaration,effectiveName:e.effectiveName,fallbackKey:e.fallbackKey,state:n})),o=a.key,s=structuredClone(t.config),c=s[e.group]??{};s[e.group]={...c,[o]:e.resolvedDeclaration},s._resolved=!0;let u=Ur(t.source);if(u.errors.length>0)throw new n(`YAML parse error: ${u.errors.map(e=>e.message).join(`; `)}`,l.USAGE);u.setIn([e.group,o],e.rawDeclaration);let d=u.toString(),f={type:e.resourceType,name:o,provider:t.provider},p={projectName:t.projectName,config:s,configPath:t.configPath,providers:{[t.provider]:t.config.providers[t.provider]},stateBackend:t.stateBackend,stateScope:t.stateScope};if(r.settings.dryRun||!e.yes){let n=await G(()=>K(()=>Yi(p,{provider:t.provider,scope:{roots:[f]},mode:`create-only`,refresh:!r.settings.dryRun,quiet:i===`json`}))),s=!n.plan.diagnostics.some(e=>e.severity===`error`),c={resource:{type:e.resourceType,key:o,name:e.displayName,provider:t.provider},config_file:t.configPath,yaml_written:!1,reused_pending:a.reusedPending,requires_confirmation:!r.settings.dryRun,ready_to_create:s,actions:n.plan.actions,diagnostics:n.plan.diagnostics};i===`json`?D(c,i):(E(`Generated YAML key: ${o}`),q_(n.plan.actions,n.plan.diagnostics),E(r.settings.dryRun?`Dry run: YAML, State, and remote resources were not changed.`:`Preview only: re-run with --yes to write YAML and create this resource.`));return}await W_(t.configPath,t.source,d);let m;try{m=await G(()=>K(()=>sa(p,{provider:t.provider,scope:{roots:[f]},mode:`create-only`,refresh:!0,quiet:i===`json`,policy:`block`})))}catch(t){throw $h(t,`The YAML declaration was kept. Fix the related dependency or provider error, then re-run the same create command.`,`Scoped ${e.resourceType} create failed.`)}let h=await t.stateBackend.read(t.stateScope,e=>e.getResource(f)?.remote_id),g=m.execution?.results??[],_=g.find(e=>e.status===`failed`),v={resource:{type:e.resourceType,key:o,name:e.displayName,provider:t.provider,remote_id:h},config_file:t.configPath,yaml_written:!0,reused_pending:a.reusedPending,actions:m.planned.plan.actions,diagnostics:m.planned.plan.diagnostics,results:g,error:_?.error};if(i===`json`?D(v,i):(E(`Wrote ${t.configPath} with ${e.resourceType} key '${o}'.`),_||E(`Created ${e.resourceType} '${e.displayName}'.`)),_)throw new n(_.error??`Scoped ${e.resourceType} create failed.`,l.GENERAL,`The YAML declaration was kept. Fix the provider error, then re-run the same create command.`)}async function W_(e,t,r){let i=M(e);if(await Zr(i,`utf8`)!==t)throw new n(`${e} changed while resource create was being prepared.`,l.GENERAL,`Review the latest YAML and re-run the command; no file was overwritten.`);let a=await $r(i),o=M(Ir(i),`.${A(i)}.${fr()}.tmp`);await ti(o,r,{flag:`wx`,mode:a.mode});try{await Qr(o,i)}catch(e){throw await ei(o).catch(()=>void 0),e}}function G_(e){if(!e?.length)return;let t={};for(let r of e){let e=r.indexOf(`=`);if(e<=0)throw new n(`Invalid metadata '${r}'.`,l.USAGE,`Use --metadata key=value.`);let i=r.slice(0,e).trim();if(!i)throw new n(`Metadata key must not be empty.`,l.USAGE);t[i]=r.slice(e+1)}return t}async function K_(e,t){let r=[];for(let i of e??[]){let e=i.startsWith(`@`)?await Zr(M(i.slice(1)),`utf8`):i,a;try{a=JSON.parse(e)}catch(e){throw new n(`Invalid ${t} JSON: ${e instanceof Error?e.message:String(e)}`,l.USAGE)}Array.isArray(a)?r.push(...a):r.push(a)}return r}function q_(e,t){for(let e of t)E(`[${e.severity}] ${e.code}: ${e.message}`);for(let t of e.filter(e=>e.action!==`no-op`))E(` ${t.action===`create`?`+`:t.action===`update`?`~`:`-`} ${tg(t.address)}`)}const J_={name:{type:`string`,valueHint:`<name>`,required:!0,description:{"en-US":`Remote Agent display name; the YAML key is generated automatically`,"zh-CN":`远端 Agent 显示名称;YAML key 将自动生成`}},model:{type:`string`,valueHint:`<model>`,required:!0,description:{"en-US":`Model ID`,"zh-CN":`模型 ID`}},instructions:{type:`string`,valueHint:`<text|path>`,required:!0,description:{"en-US":`Inline instructions or a ./, ../, or absolute file path`,"zh-CN":`内联指令,或以 ./、../、/ 开头的文件路径`}},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`Agent description`,"zh-CN":`Agent 描述`}},skill:{type:`array`,valueHint:`<id>`,description:{"en-US":`Existing remote Skill ID (repeatable)`,"zh-CN":`已存在的远端 Skill ID(可重复)`}},skillDir:{type:`array`,valueHint:`<path>`,description:{"en-US":`Local Skill directory or ZIP to declare, upload, and attach through the same scoped create (repeatable)`,"zh-CN":`通过同一次定向创建声明、上传并绑定的本地 Skill 目录或 ZIP(可重复)`}},type:{type:`string`,valueHint:`<custom|official>`,choices:[`custom`,`official`],description:{"en-US":`Type applied to every --skill value (default: custom)`,"zh-CN":`应用于所有 --skill 的类型(默认:custom)`}},tool:{type:`array`,valueHint:`<name>`,description:{"en-US":`Builtin tool name (repeatable)`,"zh-CN":`内置工具名称(可重复)`}},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},yes:{type:`switch`,description:{"en-US":`Write YAML and run the scoped remote create`,"zh-CN":`写入 YAML 并执行定向远端创建`}}};function Y_(e){return B_({displayName:e.displayName,provider:e.provider,resourceTypes:[`agent`,`template`],declarations:e.agents,candidate:e.candidate,effectiveName:(e,t)=>typeof t.name==`string`?t.name:e,fallbackKey:`agent`,state:e.state})}function X_(e){if(e===void 0||e===`custom`)return`custom`;if(e===`official`)return`official`;throw new n(`--type must be either custom or official.`,l.USAGE)}function Z_(e,t=`custom`){let r=new Set,i=[];for(let a of e??[]){let e=a.trim();if(!e)throw new n(`--skill values must not be empty.`,l.USAGE);r.has(e)||(r.add(e),i.push({type:t,skill_id:e}))}return i}function Q_(e){let t=e=>Array.isArray(e)?e.map(t):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,n])=>[e,t(n)]));return JSON.stringify(t(e))}function $_(e){let t=new Set(e.state.listResources().filter(t=>t.address.provider===e.provider&&t.address.type===`skill`).map(e=>e.address.name)),r=Object.entries(e.declarations).filter(([t,n])=>(typeof n.name==`string`?n.name:t)===e.displayName),i=r.find(([n,r])=>t.has(n)&&Q_(r)===Q_(e.candidate));if(i)return{key:i[0],needsCreate:!1,reusedPending:!1,reusedTracked:!0};if(r.find(([e])=>t.has(e)))throw new n(`Skill '${e.displayName}' is already tracked with a different declaration.`,l.USAGE,"Modify its existing YAML declaration and run full `bl managed-agent apply`, or bind its remote ID with --skill.");return{...B_({displayName:e.displayName,provider:e.provider,resourceTypes:[`skill`],declarations:e.declarations,candidate:e.candidate,effectiveName:(e,t)=>typeof t.name==`string`?t.name:e,fallbackKey:`skill`,state:e.state}),needsCreate:!0,reusedTracked:!1}}async function ev(e,t){let r={...e.config.skills??{}},i=new Map,a=new Map;for(let o of t??[]){let t=o.trim();if(!t)throw new n(`--skill-dir values must not be empty.`,l.USAGE);let s=await G(()=>Ni(t,{basePath:process.cwd()})),c=await $r(s.sourcePath);if(!(c.isDirectory()||c.isFile()&&Lr(s.sourcePath).toLowerCase()===`.zip`))throw new n(`--skill-dir requires a Skill directory or .zip file: ${t}`,l.USAGE);if(i.has(s.sourcePath))continue;let u=Rr(Ir(e.configPath),s.sourcePath).split(zr).join(`/`)||`.`,d={name:s.name,source:u,origin:`custom`,provider:e.provider},f=await H_({project:e,group:`skills`,rawDeclaration:d}),p=await e.stateBackend.read(e.stateScope,t=>$_({displayName:s.name,provider:e.provider,declarations:r,candidate:f,state:t})),m=a.get(p.key);if(m){i.set(s.sourcePath,m);continue}let h={...p,name:s.name,source:u,rawDeclaration:d,resolvedDeclaration:f};r[p.key]=f,i.set(s.sourcePath,h),a.set(p.key,h)}return[...a.values()]}var tv=C({description:{"en-US":`Declare and create one Managed Agent through an isolated YAML apply`,"zh-CN":`通过隔离的 YAML Apply 声明并创建一个托管 Agent`},auth:`apiKey`,usageArgs:`--name <name> --model <model> --instructions <text|path> [--description <text>] [--skill <id>...] [--type custom|official] [--skill-dir <path>...] [--tool <name>...] [--file <path>] [--yes]`,flags:J_,exampleArgs:[`--name assistant --model qwen3.8-max --instructions "You are helpful."`,`--name assistant --model qwen3.8-max --instructions ./prompts/assistant.md --skill skill_abc --yes`,`--name slides --model qwen3.8-max --instructions ./prompts/slides.md --skill skill_pptx --type official --yes`,`--name reviewer --model qwen3.8-max --instructions ./prompts/reviewer.md --skill-dir ./skills/code-review --yes`],notes:[...U,{"en-US":`Without --yes, previews the generated YAML key and scoped plan. --dry-run stays offline. Unrelated resources are not refreshed or drift-checked.`,"zh-CN":`不带 --yes 时预览自动生成的 YAML key 和定向计划;--dry-run 完全离线。无关资源不会刷新或检测 Drift。`},{"en-US":`--skill writes an external Skill reference directly into the Agent declaration. --type defaults to custom; use --type official for platform Skills. These Skills are not managed through the top-level skills map.`,"zh-CN":`--skill 会把外部 Skill 引用直接写入 Agent 声明。--type 默认为 custom;平台 Skill 使用 --type official。这些 Skill 不通过顶层 skills 资源管理。`},{"en-US":`--skill-dir accepts a local Skill directory or ZIP, writes it as a top-level custom Skill declaration, and writes its generated YAML key into the Agent skills list. Skill and Agent are created together in dependency order. --type applies only to --skill IDs.`,"zh-CN":`--skill-dir 接收本地 Skill 目录或 ZIP,将其写为顶层 custom Skill 声明,并把生成的 YAML key 写入 Agent 的 skills 列表;Skill 与 Agent 按依赖顺序一并创建。--type 只作用于 --skill ID。`}],validate:e=>{if(!e.name.trim())return`--name must not be empty.`;if(!e.model.trim())return`--model must not be empty.`;if(!e.instructions.trim())return`--instructions must not be empty.`;if(e.type&&!e.skill?.length)return`--type requires at least one --skill.`;if(e.skill?.some(e=>!e.trim()))return`--skill values must not be empty.`;if(e.skillDir?.some(e=>!e.trim()))return`--skill-dir values must not be empty.`},async run(e){let{flags:t,settings:r}=e,i=w(r.output),a=await V_(e,t.file??`agents.yaml`),o=a.provider,s=Z_(t.skill,X_(t.type)),c=await ev(a,t.skillDir),u=[...s,...c.map(e=>e.key)],d=pi(void 0,{name:t.name.trim(),description:t.description,model:t.model,instructions:t.instructions,provider:o,builtinTools:t.tool}).agent;d.skills=u;let f=structuredClone(a.config);f.skills={...f.skills};for(let e of c)f.skills[e.key]=e.resolvedDeclaration;f._resolved=!0;let p=await H_({project:{...a,config:f},group:`agents`,rawDeclaration:d}),m=await a.stateBackend.read(a.stateScope,e=>Y_({displayName:t.name.trim(),provider:o,agents:a.config.agents??{},candidate:p,state:e})),h=m.key;f.agents={...f.agents,[h]:p},f._resolved=!0;let g=Ur(a.source);if(g.errors.length>0)throw new n(`YAML parse error: ${g.errors.map(e=>e.message).join(`; `)}`,l.USAGE);for(let e of c)g.setIn([`skills`,e.key],e.rawDeclaration);g.setIn([`agents`,h],d);let _=g.toString(),v={type:`agent`,name:h,provider:o},y=[...c.filter(e=>e.needsCreate).map(e=>({type:`skill`,name:e.key,provider:o})),v],b={projectName:a.projectName,config:f,configPath:a.configPath,providers:{[o]:f.providers[o]},stateBackend:a.stateBackend,stateScope:a.stateScope};if(r.dryRun||!t.yes){let e=await G(()=>K(()=>Yi(b,{provider:o,scope:{roots:y},refresh:!r.dryRun,quiet:i===`json`,mode:`create-only`}))),n=!e.plan.diagnostics.some(e=>e.severity===`error`),s={agent:{key:h,name:t.name.trim(),provider:o,skills:u},local_skills:c.map(e=>({key:e.key,name:e.name,source:e.source,reused_pending:e.reusedPending,reused_tracked:e.reusedTracked})),config_file:a.configPath,yaml_written:!1,reused_pending:m.reusedPending,requires_confirmation:!r.dryRun,ready_to_create:n,actions:e.plan.actions,diagnostics:e.plan.diagnostics};if(i===`json`)D(s,i);else{for(let e of c)E(`Generated Skill YAML key: ${e.key}`);E(`Generated Agent YAML key: ${h}`);for(let t of e.plan.diagnostics)E(`[${t.severity}] ${t.code}: ${t.message}`);for(let t of e.plan.actions.filter(e=>e.action!==`no-op`))E(` ${t.action===`create`?`+`:t.action===`update`?`~`:`-`} ${tg(t.address)}`);E(r.dryRun?`Dry run: YAML, State, and remote resources were not changed.`:`Preview only: re-run with --yes to write YAML and create this Agent.`)}return}await W_(a.configPath,a.source,_);let x;try{x=await G(()=>K(()=>sa(b,{provider:o,scope:{roots:y},refresh:!0,quiet:i===`json`,mode:`create-only`,policy:`block`})))}catch(e){throw $h(e,`The YAML declarations were kept. Fix the related dependency or provider error, then re-run the same create command.`,`Scoped Agent and Skill create failed.`)}let S=await a.stateBackend.read(a.stateScope,e=>({agentId:e.getResource(v)?.remote_id,skillIds:Object.fromEntries(c.map(t=>[t.key,e.getResource({type:`skill`,name:t.key,provider:o})?.remote_id]))})),ee=x.execution?.results??[],te=ee.find(e=>e.status===`failed`),ne=te?`failed`:`completed`,re={agent:{key:h,name:t.name.trim(),provider:o,remote_id:S.agentId,skills:u},local_skills:c.map(e=>({key:e.key,name:e.name,source:e.source,remote_id:S.skillIds[e.key],reused_pending:e.reusedPending,reused_tracked:e.reusedTracked})),config_file:a.configPath,yaml_written:!0,reused_pending:m.reusedPending,status:ne,actions:x.planned.plan.actions,diagnostics:x.planned.plan.diagnostics,results:ee,error:te?.error};if(i===`json`?D(re,i):(E(`Wrote ${a.configPath} with Agent key '${h}'${c.length?` and ${c.length} local Skill declaration(s)`:``}.`),E(ne===`completed`?`Created Agent '${t.name.trim()}'.`:`Scoped create ${ne}: ${te?.error??`unknown error`}`)),te)throw new n(te.error??`Scoped Agent create failed.`,l.GENERAL,`The YAML declarations were kept. Fix the related dependency or provider error, then re-run the same create command.`)}}),nv=C({description:{"en-US":`Declare and create one Managed Agent Environment through a scoped YAML apply`,"zh-CN":`通过定向 YAML Apply 声明并创建一个托管 Agent Environment`},auth:`apiKey`,usageArgs:`--name <name> [--description <text>] [--metadata <key=value>...] [--apt <package>...] [--pip <package>...] [--npm <package>...] [--cargo <package>...] [--gem <package>...] [--go <package>...] [--file <path>] [--yes]`,flags:{name:{type:`string`,valueHint:`<name>`,required:!0,description:{"en-US":`Remote Environment display name; the YAML key is generated automatically`,"zh-CN":`远端 Environment 显示名称;YAML key 将自动生成`}},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`Environment description`,"zh-CN":`Environment 描述`}},metadata:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Metadata entry (repeatable)`,"zh-CN":`Metadata 条目(可重复)`}},apt:rv(`APT`),pip:rv(`pip`),npm:rv(`npm`),cargo:rv(`Cargo`),gem:rv(`Ruby gem`),go:rv(`Go`),file:iv(),yes:av()},exampleArgs:[`--name Development`,`--name Development --pip pandas --npm typescript --metadata owner=platform --yes`],notes:[...U,...L_,{"en-US":`Creates a cloud Environment with unrestricted networking. Without --yes, only previews the generated YAML key and scoped plan.`,"zh-CN":`创建使用 unrestricted 网络的 cloud Environment。不带 --yes 时仅预览自动生成的 YAML key 和定向计划。`}],validate:e=>e.name.trim()?void 0:`--name must not be empty.`,async run(e){let t=await V_(e,e.flags.file??`agents.yaml`),n=Object.fromEntries([`apt`,`pip`,`npm`,`cargo`,`gem`,`go`].map(t=>[t,e.flags[t]]).filter(e=>Array.isArray(e[1])&&e[1].length>0)),r={name:e.flags.name.trim(),description:e.flags.description,provider:t.provider,config:{type:`cloud`,networking:{type:`unrestricted`},...Object.keys(n).length>0?{packages:n}:{}},metadata:G_(e.flags.metadata)},i=await H_({project:t,group:`environments`,rawDeclaration:r});await U_({host:e,project:t,group:`environments`,resourceType:`environment`,displayName:e.flags.name.trim(),rawDeclaration:r,resolvedDeclaration:i,existingDeclarations:t.config.environments??{},effectiveName:(e,t)=>typeof t.name==`string`?t.name:e,fallbackKey:`environment`,yes:e.flags.yes})}});function rv(e){return{type:`array`,valueHint:`<package>`,description:{"en-US":`${e} package (repeatable)`,"zh-CN":`${e} 软件包(可重复)`}}}function iv(){return{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}}function av(){return{type:`switch`,description:{"en-US":`Write YAML and run the scoped remote create`,"zh-CN":`写入 YAML 并执行定向远端创建`}}}var ov=C({description:{"en-US":`Declare and create one custom Managed Agent Skill from a local source`,"zh-CN":`从本地来源声明并创建一个自定义托管 Agent Skill`},auth:`apiKey`,usageArgs:`--source <directory|zip|SKILL.md> [--file <path>] [--yes]`,flags:{source:{type:`string`,valueHint:`<directory|zip|SKILL.md>`,required:!0,description:{"en-US":`Local Skill directory, ZIP archive, or single SKILL.md`,"zh-CN":`本地 Skill 目录、ZIP 压缩包或单个 SKILL.md`}},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},yes:{type:`switch`,description:{"en-US":`Write YAML and upload the Skill through the scoped create`,"zh-CN":`写入 YAML 并通过定向创建上传 Skill`}}},exampleArgs:[`--source ./skills/code-review`,`--source ./skill.zip --yes`],notes:[...U,...L_,{"en-US":`The YAML key is derived from SKILL.md frontmatter name. Remote URLs remain available through handwritten YAML plus full apply.`,"zh-CN":`YAML key 从 SKILL.md frontmatter 的 name 生成。远程 URL 仍可手工写入 YAML 后执行全量 Apply。`}],validate:e=>e.source.trim()?void 0:`--source must not be empty.`,async run(e){let t=await V_(e,e.flags.file??`agents.yaml`),r=await Ni(e.flags.source,{basePath:process.cwd()}),i=Rr(Ir(t.configPath),r.sourcePath).split(zr).join(`/`)||`.`,a=t.config.skills??{};if(await t.stateBackend.read(t.stateScope,e=>e.listResources().some(e=>{if(e.address.provider!==t.provider||e.address.type!==`skill`)return!1;let n=a[e.address.name];return(typeof n?.name==`string`?n.name:e.address.name)===r.name})))throw new n(`Skill '${r.name}' is already tracked.`,l.USAGE,"Modify its existing YAML declaration and run full `bl managed-agent apply` to create a new version.");let o={name:r.name,source:i,origin:`custom`,provider:t.provider},s=await H_({project:t,group:`skills`,rawDeclaration:o});await U_({host:e,project:t,group:`skills`,resourceType:`skill`,displayName:r.name,rawDeclaration:o,resolvedDeclaration:s,existingDeclarations:a,effectiveName:(e,t)=>typeof t.name==`string`?t.name:e,fallbackKey:`skill`,yes:e.flags.yes})}}),sv=C({description:{"en-US":`Declare and create one empty Managed Agent Vault through a scoped YAML apply`,"zh-CN":`通过定向 YAML Apply 声明并创建一个空的托管 Agent Vault`},auth:`apiKey`,usageArgs:`--name <name> [--metadata <key=value>...] [--file <path>] [--yes]`,flags:{name:{type:`string`,valueHint:`<name>`,required:!0,description:{"en-US":`Remote Vault display name; the YAML key is generated automatically`,"zh-CN":`远端 Vault 显示名称;YAML key 将自动生成`}},metadata:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Metadata entry (repeatable)`,"zh-CN":`Metadata 条目(可重复)`}},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},yes:{type:`switch`,description:{"en-US":`Write YAML and run the scoped remote create`,"zh-CN":`写入 YAML 并执行定向远端创建`}}},exampleArgs:[`--name Production`,`--name Production --metadata owner=platform --yes`],notes:[...U,...L_,{"en-US":"Creates an empty Vault. Add secrets later with `vault credential create`.","zh-CN":"创建空 Vault;随后使用 `vault credential create` 添加 Secret。"}],validate:e=>e.name.trim()?void 0:`--name must not be empty.`,async run(e){let t=await V_(e,e.flags.file??`agents.yaml`),n={display_name:e.flags.name.trim(),provider:t.provider,credentials:[],metadata:G_(e.flags.metadata)},r=await H_({project:t,group:`vaults`,rawDeclaration:n});await U_({host:e,project:t,group:`vaults`,resourceType:`vault`,displayName:e.flags.name.trim(),rawDeclaration:n,resolvedDeclaration:r,existingDeclarations:t.config.vaults??{},effectiveName:(e,t)=>typeof t.display_name==`string`?t.display_name:e,fallbackKey:`vault`,yes:e.flags.yes})}}),cv=C({description:{"en-US":`Append and create one environment-variable Credential in a tracked Vault`,"zh-CN":`在已跟踪 Vault 中追加并创建一个环境变量 Credential`},auth:`apiKey`,usageArgs:`--vault <yaml-key> --name <name> --secret-name <name> --secret-env <env-name> [--metadata <key=value>...] [--file <path>] [--yes]`,flags:{vault:{type:`string`,valueHint:`<yaml-key>`,required:!0,description:{"en-US":`Existing tracked Vault key from agents.yaml`,"zh-CN":`agents.yaml 中已跟踪的 Vault key`}},name:{type:`string`,valueHint:`<name>`,required:!0,description:{"en-US":`Credential display name`,"zh-CN":`Credential 显示名称`}},secretName:{type:`string`,valueHint:`<name>`,required:!0,description:{"en-US":`Environment variable name exposed to the Agent`,"zh-CN":`提供给 Agent 的环境变量名`}},secretEnv:{type:`string`,valueHint:`<env-name>`,required:!0,description:{"en-US":`Local environment variable containing the secret value`,"zh-CN":`保存真实 Secret 的本地环境变量名`}},metadata:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Metadata entry (repeatable)`,"zh-CN":`Metadata 条目(可重复)`}},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},yes:{type:`switch`,description:{"en-US":`Write YAML and create the remote Credential`,"zh-CN":`写入 YAML 并创建远端 Credential`}}},exampleArgs:[`--vault production --name api-token --secret-name API_TOKEN --secret-env PROD_API_TOKEN`,`--vault production --name api-token --secret-name API_TOKEN --secret-env PROD_API_TOKEN --yes`],notes:[...U,...L_,{"en-US":`--secret-env is an environment variable name, not the secret itself. The CLI auto-loads the nearest .env from the current directory upward; shell exports and CI secret injection also work.`,"zh-CN":`--secret-env 接收环境变量名,不接收 Secret 本身。CLI 会从当前目录向上自动加载最近的 .env,也支持 Shell export 和 CI Secret 注入。`},{"en-US":"YAML stores only ${ENV_NAME}. Never commit .env; subsequent full apply runs must provide the same environment variable.","zh-CN":"YAML 只保存 ${ENV_NAME}。不要提交 .env;后续执行全量 Apply 时仍需提供同名环境变量。"}],validate:e=>{if(!e.vault.trim())return`--vault must not be empty.`;if(!e.name.trim())return`--name must not be empty.`;if(!e.secretName.trim())return`--secret-name must not be empty.`;if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.secretEnv))return`--secret-env must be a valid environment variable name.`},async run(e){let t=w(e.settings.output);fi();let r=process.env[e.flags.secretEnv],i=await V_(e,e.flags.file??`agents.yaml`).finally(()=>{delete process.env[e.flags.secretEnv]});if(!i.config.vaults?.[e.flags.vault])throw new n(`Vault '${e.flags.vault}' is not declared in agents.yaml.`,l.USAGE);if(e.flags.yes&&!e.settings.dryRun&&!r)throw new n(`Environment variable '${e.flags.secretEnv}' is not set or is empty.`,l.USAGE,`Set it in your shell, CI secret store, or a local .env file, then re-run with --secret-env ${e.flags.secretEnv}.`);let a=G_(e.flags.metadata),o={name:e.flags.name.trim(),type:`environment_variable`,secret_name:e.flags.secretName.trim(),secret_value:`\${${e.flags.secretEnv}}`,networking:{type:`unrestricted`},...a?{metadata:a}:{}},s={...o,secret_value:r??`__dry_run_secret__`},c=Ur(i.source);if(c.errors.length>0)throw new n(`YAML parse error: ${c.errors.map(e=>e.message).join(`; `)}`,l.USAGE);let u=c.toJS().vaults?.[e.flags.vault]?.credentials??[],d=u.filter(e=>!!(e&&typeof e==`object`&&!Array.isArray(e)&&e.name===o.name)),f=!1;if(d.length>0){let t=u.at(-1),r=d[0];if(d.length!==1||r!==t||!lv(r,o))throw new n(`Vault '${e.flags.vault}' already declares a different credential named '${o.name}'.`,l.USAGE,"Modify the existing YAML declaration and run full `bl managed-agent apply`; create never overwrites it.");f=!0}let p=structuredClone(i.config),m=p.vaults,h=m[e.flags.vault];f||(m[e.flags.vault]={...h,credentials:[...h.credentials??[],s]});let g=(await G(()=>Qi(p,{projectName:i.projectName,basePath:Ir(i.configPath)}))).config;f||c.addIn([`vaults`,e.flags.vault,`credentials`],o);let _=f?i.source:c.toString(),v={projectName:i.projectName,config:g,configPath:i.configPath,providers:{[i.provider]:g.providers[i.provider]},stateBackend:i.stateBackend,stateScope:i.stateScope};if(e.settings.dryRun||!e.flags.yes){let n=await G(()=>K(()=>Xi(v,e.flags.vault,e.flags.name.trim(),{provider:i.provider,refresh:!e.settings.dryRun,quiet:t===`json`,checkRemote:!e.settings.dryRun}))),r={vault:{key:e.flags.vault,remote_id:n.vaultRemoteId},credential:{name:e.flags.name.trim(),secret_name:e.flags.secretName.trim(),secret_env:e.flags.secretEnv},config_file:i.configPath,yaml_written:!1,reused_pending:f,requires_confirmation:!e.settings.dryRun,ready_to_create:!0,remote_checked:n.remoteChecked,reuse_remote:n.reuseRemote};t===`json`?D(r,t):(E(`Vault: ${e.flags.vault}`),E(`Credential: ${e.flags.name.trim()} (secret from ${e.flags.secretEnv})`),E(e.settings.dryRun?`Dry run: YAML, State, and remote resources were not changed.`:`Preview only: re-run with --yes to append YAML and create this Credential.`));return}await W_(i.configPath,i.source,_);let y;try{y=await G(()=>K(()=>gi(v,e.flags.vault,e.flags.name.trim(),{provider:i.provider,refresh:!0,quiet:t===`json`})))}catch(e){throw $h(e,`The YAML declaration was kept. Restore the same secret environment variable and re-run this command; an already-created matching Credential will be adopted.`,`Vault Credential create failed.`)}let b={vault:{key:e.flags.vault,remote_id:y.vaultRemoteId},credential:{id:y.credentialId,name:e.flags.name.trim(),secret_name:e.flags.secretName.trim(),secret_env:e.flags.secretEnv},config_file:i.configPath,yaml_written:!0,reused_pending:f,adopted:y.adopted,status:`completed`};t===`json`?D(b,t):E(`Wrote ${i.configPath} and created Credential '${e.flags.name.trim()}'.`)}});function lv(e,t){return uv(e)===uv(t)}function uv(e){let t=e=>Array.isArray(e)?e.map(t):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,n])=>[e,t(n)]));return JSON.stringify(t(e))}var dv=C({description:{"en-US":`Declare and create one Managed Agent Deployment through a scoped YAML apply`,"zh-CN":`通过定向 YAML Apply 声明并创建一个托管 Agent Deployment`},auth:`apiKey`,usageArgs:`--name <name> --agent <yaml-key> (--message <text>... | --event <json|@path>...) [--agent-version <number>] [--environment <yaml-key>] [--vault <yaml-key>...] [--resource <json|@path>...] [--schedule <cron> --timezone <timezone>] [--description <text>] [--metadata <key=value>...] [--file <path>] [--yes]`,flags:{name:{type:`string`,valueHint:`<name>`,required:!0,description:{"en-US":`Remote Deployment display name; the YAML key is generated automatically`,"zh-CN":`远端 Deployment 显示名称;YAML key 将自动生成`}},agent:{type:`string`,valueHint:`<yaml-key>`,required:!0,description:{"en-US":`Existing Agent key from agents.yaml`,"zh-CN":`agents.yaml 中已有的 Agent key`}},agentVersion:{type:`number`,valueHint:`<number>`,description:{"en-US":`Agent version`,"zh-CN":`Agent 版本`}},environment:{type:`string`,valueHint:`<yaml-key>`,description:{"en-US":`Existing Environment key from agents.yaml`,"zh-CN":`agents.yaml 中已有的 Environment key`}},vault:{type:`array`,valueHint:`<yaml-key>`,description:{"en-US":`Existing Vault key from agents.yaml (repeatable)`,"zh-CN":`agents.yaml 中已有的 Vault key(可重复)`}},message:{type:`array`,valueHint:`<text>`,description:{"en-US":`Initial user message (repeatable)`,"zh-CN":`初始用户消息(可重复)`}},event:{type:`array`,valueHint:`<json|@path>`,description:{"en-US":`Initial user.message or system.message JSON (repeatable)`,"zh-CN":`初始 user.message 或 system.message JSON(可重复)`}},resource:{type:`array`,valueHint:`<json|@path>`,description:{"en-US":`File Resource JSON with source or file_id (repeatable)`,"zh-CN":`包含 source 或 file_id 的 File Resource JSON(可重复)`}},schedule:{type:`string`,valueHint:`<cron>`,description:{"en-US":`Five-field cron expression`,"zh-CN":`五段式 Cron 表达式`}},timezone:{type:`string`,valueHint:`<timezone>`,description:{"en-US":`IANA schedule timezone`,"zh-CN":`Schedule 的 IANA 时区`}},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`Deployment description`,"zh-CN":`Deployment 描述`}},metadata:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Metadata entry (repeatable)`,"zh-CN":`Metadata 条目(可重复)`}},file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}},yes:{type:`switch`,description:{"en-US":`Write YAML and run the scoped remote create`,"zh-CN":`写入 YAML 并执行定向远端创建`}}},exampleArgs:[{"en-US":`--name Daily --agent assistant --message "Generate the report"`,"zh-CN":`--name Daily --agent assistant --message "生成报告"`},{"en-US":`--name Daily --agent assistant --event '{"type":"system.message","content":"Be concise"}' --yes`,"zh-CN":`--name Daily --agent assistant --event '{"type":"system.message","content":"保持简洁"}' --yes`}],notes:[...U,...L_,{"en-US":`Initial Events must contain 1-50 user.message/system.message entries. --resource accepts only File Resources in this release.`,"zh-CN":`Initial Events 必须包含 1–50 条 user.message/system.message;本期 --resource 仅接受 File Resource。`},{"en-US":`Use either repeatable --message values or repeatable --event values; the two input forms cannot be mixed.`,"zh-CN":`重复使用 --message 或重复使用 --event;两种输入形式不能混用。`}],validate:e=>{if(!e.name.trim())return`--name must not be empty.`;if(!e.agent.trim())return`--agent must not be empty.`;if(e.message?.length&&e.event?.length)return`--message and --event cannot be used together.`;if(!e.message?.length&&!e.event?.length)return`Pass at least one --message or --event.`;if(!!e.schedule!=!!e.timezone)return`--schedule and --timezone must be provided together.`;if(e.agentVersion!==void 0&&(!Number.isInteger(e.agentVersion)||e.agentVersion<1))return`--agent-version must be a positive integer.`},async run(e){let t=await V_(e,e.flags.file??`agents.yaml`),r=[...(e.flags.message??[]).map(e=>({type:`user.message`,content:e})),...fv(await K_(e.flags.event,`event`))];if(r.length<1||r.length>50)throw new n(`Initial Events must contain 1-50 entries.`,l.USAGE);let i=pv(await K_(e.flags.resource,`resource`));if(e.flags.schedule&&e.flags.schedule.trim().split(/\s+/).length!==5)throw new n(`--schedule must be a five-field cron expression.`,l.USAGE);e.flags.timezone&&mv(e.flags.timezone);let a={name:e.flags.name.trim(),agent:e.flags.agent,agent_version:e.flags.agentVersion,environment:e.flags.environment,vaults:e.flags.vault,resources:i,initial_events:r,schedule:e.flags.schedule&&e.flags.timezone?{expression:e.flags.schedule,timezone:e.flags.timezone}:void 0,description:e.flags.description,provider:t.provider,metadata:G_(e.flags.metadata)},o=await H_({project:t,group:`deployments`,rawDeclaration:a});await U_({host:e,project:t,group:`deployments`,resourceType:`deployment`,displayName:e.flags.name.trim(),rawDeclaration:a,resolvedDeclaration:o,existingDeclarations:t.config.deployments??{},effectiveName:(e,t)=>typeof t.name==`string`?t.name:e,fallbackKey:`deployment`,yes:e.flags.yes})}});function fv(e){return e.map(e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`Each --event must be a JSON object.`,l.USAGE);let t=e;if(t.type!==`user.message`&&t.type!==`system.message`)throw new n(`--event type must be user.message or system.message.`,l.USAGE);if(typeof t.content!=`string`||!t.content.trim())throw new n(`--event content must be a non-empty string.`,l.USAGE);return{type:t.type,content:t.content}})}function pv(e){return e.map(e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`Each --resource must be a JSON object.`,l.USAGE);let t=e;if(t.type!==`file`)throw new n(`--resource currently accepts only type=file.`,l.USAGE);let r=typeof t.source==`string`?t.source:void 0,i=typeof t.file_id==`string`?t.file_id:void 0;if(!!r==!!i)throw new n(`A File Resource must provide exactly one of source or file_id.`,l.USAGE);if(t.mount_path!==void 0&&typeof t.mount_path!=`string`)throw new n(`File Resource mount_path must be a string.`,l.USAGE);return{type:`file`,source:r,file_id:i,mount_path:t.mount_path}})}function mv(e){try{new Intl.DateTimeFormat(`en-US`,{timeZone:e}).format()}catch{throw new n(`Invalid IANA timezone: ${e}`,l.USAGE)}}const hv={...q,...J,...i_},gv={...q,limit:J.limit,...r_,...i_},_v={...q,agentId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Agent ID`,"zh-CN":`Agent ID`}},agentVersion:{type:`number`,valueHint:`<n>`,description:{"en-US":`Specific agent version`,"zh-CN":`指定 Agent 版本`}}},vv={...q,...J,agentId:_v.agentId};function yv(e){return e.map(e=>[e.id,Z(e.name),Z(e.version),Z(e.type),Z(e.updated_at)])}var bv=C({description:{"en-US":`Get a Managed Agent`,"zh-CN":`获取托管 Agent 详情`},auth:`apiKey`,usageArgs:`--agent-id <id> [--agent-version <n>] [--file <path>]`,flags:_v,exampleArgs:[`--agent-id agent_abc`,`--agent-id agent_abc --agent-version 3 --output json`],notes:U,validate:e=>e.agentVersion!==void 0&&(!Number.isInteger(e.agentVersion)||e.agentVersion<1)?`--agent-version must be a positive integer.`:void 0,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>Ti(await W(e,e.flags.file??`agents.yaml`),e.flags.agentId,{provider:`bailian`,version:e.flags.agentVersion})));if(t===`json`){D(n,t);return}E(`ID: ${n.id}`),E(`Name: ${Z(n.name)}`),E(`Description: ${Z(n.description,120)}`),E(`Version: ${Z(n.version)}`),E(`Type: ${Z(n.type)}`),E(`Created: ${Z(n.created_at)}`),E(`Updated: ${Z(n.updated_at)}`)}}),xv=C({description:{"en-US":`List Managed Agents`,"zh-CN":`列出托管 Agent`},auth:`apiKey`,usageArgs:`[--limit <n>] [--page <cursor>] [--all] [--include-archived] [--file <path>]`,flags:hv,exampleArgs:[``,`--limit 50`,`--all --include-archived --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return n_(async n=>{let r=await Ii(t,{provider:`bailian`,limit:e.flags.limit,page:n,include_archived:e.flags.includeArchived});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`agents`,items:n.items,headers:[`ID`,`NAME`,`VERSION`,`TYPE`,`UPDATED`],rows:yv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No agents found.`})}}),Sv=C({description:{"en-US":`Search Managed Agents`,"zh-CN":`搜索托管 Agent`},auth:`apiKey`,usageArgs:`--query <text> [--limit <n>] [--page-limit <n>] [--include-archived]`,flags:gv,exampleArgs:[`--query assistant`,`--query code --page-limit 20 --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return s_(async n=>{let r=await Ii(t,{provider:`bailian`,limit:e.flags.limit??100,page:n,include_archived:e.flags.includeArchived});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},t=>o_(e.flags.query,t.id,t.name,t.description),e.flags.pageLimit)}));X({format:t,key:`agents`,items:n.items,headers:[`ID`,`NAME`,`VERSION`,`TYPE`,`UPDATED`],rows:yv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching agents found.`})}}),Cv=C({description:{"en-US":`List Managed Agent versions`,"zh-CN":`列出托管 Agent 版本`},auth:`apiKey`,usageArgs:`--agent-id <id> [--limit <n>] [--page <cursor>] [--all]`,flags:vv,exampleArgs:[`--agent-id agent_abc`,`--agent-id agent_abc --all --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return n_(async n=>{let r=await Fi(t,e.flags.agentId,{provider:`bailian`,limit:e.flags.limit,page:n});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`versions`,items:n.items,headers:[`ID`,`NAME`,`VERSION`,`TYPE`,`UPDATED`],rows:yv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No agent versions found.`})}});const wv={...q,...J,...i_},Tv={...q,limit:J.limit,...r_,...i_},Ev={...q,environmentId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Environment ID`,"zh-CN":`Environment ID`}}};function Dv(e){return e.map(e=>[e.id,Z(e.name),Z(e.scope),Z(e.version),Z(e.updated_at)])}var Ov=C({description:{"en-US":`Get a Managed Agent environment`,"zh-CN":`获取托管 Agent 环境详情`},auth:`apiKey`,usageArgs:`--environment-id <id>`,flags:Ev,exampleArgs:[`--environment-id env_abc`],notes:U,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>Oi(await W(e,e.flags.file??`agents.yaml`),e.flags.environmentId,{provider:`bailian`})));if(t===`json`){D(n,t);return}E(`ID: ${n.id}`),E(`Name: ${Z(n.name)}`),E(`Description: ${Z(n.description,120)}`),E(`Scope: ${Z(n.scope)}`),E(`Version: ${Z(n.version)}`),E(`Updated: ${Z(n.updated_at)}`)}}),kv=C({description:{"en-US":`List Managed Agent environments`,"zh-CN":`列出托管 Agent 环境`},auth:`apiKey`,usageArgs:`[--limit <n>] [--page <cursor>] [--all] [--include-archived]`,flags:wv,exampleArgs:[``,`--all --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return n_(async n=>{let r=await zi(t,{provider:`bailian`,limit:e.flags.limit,page:n,include_archived:e.flags.includeArchived});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`environments`,items:n.items,headers:[`ID`,`NAME`,`SCOPE`,`VERSION`,`UPDATED`],rows:Dv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No environments found.`})}}),Av=C({description:{"en-US":`Search Managed Agent environments`,"zh-CN":`搜索托管 Agent 环境`},auth:`apiKey`,usageArgs:`--query <text> [--limit <n>] [--page-limit <n>] [--include-archived]`,flags:Tv,exampleArgs:[`--query sandbox`,`--query production --page-limit 20 --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return s_(async n=>{let r=await zi(t,{provider:`bailian`,limit:e.flags.limit??100,page:n,include_archived:e.flags.includeArchived});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},t=>o_(e.flags.query,t.id,t.name,t.description),e.flags.pageLimit)}));X({format:t,key:`environments`,items:n.items,headers:[`ID`,`NAME`,`SCOPE`,`VERSION`,`UPDATED`],rows:Dv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching environments found.`})}}),jv=C({description:{"en-US":`Download a Managed Agent skill version`,"zh-CN":`下载托管 Agent Skill 版本`},auth:`apiKey`,usageArgs:`--skill-id <id> --skill-version <version> --output-file <path> [--force]`,flags:j_,exampleArgs:[`--skill-id skill_abc --skill-version 3 --output-file ./skill.zip`],notes:U,async run(e){let t=w(e.settings.output);if(e.settings.dryRun){D({would_download_skill:e.flags.skillId,version:e.flags.skillVersion,output_file:e.flags.outputFile},t);return}let n=await G(()=>K(async()=>xi(await W(e,e.flags.file??`agents.yaml`),e.flags.skillId,e.flags.skillVersion,{provider:`bailian`}))),r=await h_(e.flags.outputFile,n,e.flags.force);t===`json`?D({downloaded:e.flags.skillId,version:e.flags.skillVersion,output_file:r},t):E(`Skill downloaded to ${r}`)}}),Mv=C({description:{"en-US":`Get a Managed Agent skill`,"zh-CN":`获取托管 Agent Skill 详情`},auth:`apiKey`,usageArgs:`--skill-id <id>`,flags:k_,exampleArgs:[`--skill-id skill_abc`],notes:U,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>ki(await W(e,e.flags.file??`agents.yaml`),e.flags.skillId,{provider:`bailian`})));if(t===`json`){D(n,t);return}E(`ID: ${n.id}`),E(`Name: ${n.name}`),E(`Description: ${Z(n.description,120)}`),E(`Source: ${n.source}`),E(`Status: ${n.status}`),E(`Version: ${Z(n.latest_version)}`)}}),Nv=C({description:{"en-US":`Search Managed Agent skills`,"zh-CN":`搜索托管 Agent Skill`},auth:`apiKey`,usageArgs:`--query <text> [--source custom|official|all] [--limit <n>] [--page-limit <n>]`,flags:O_,exampleArgs:[`--query browser --source official`,`--query report --source all --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=e.flags.source??`custom`,r=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`),r=n=>s_(async r=>{let i=await Hi(t,{provider:`bailian`,source:n,limit:e.flags.limit??100,page:r});return{items:i.data,hasMore:i.has_more,nextPage:i.next_page}},t=>o_(e.flags.query,t.id,t.name,t.description),e.flags.pageLimit);if(n!==`all`)return r(n);let[i,a]=await Promise.all([r(`custom`),r(`official`)]);return{items:[...i.items,...a.items],hasMore:i.hasMore||a.hasMore,nextPage:void 0,scannedPages:i.scannedPages+a.scannedPages,truncated:i.truncated||a.truncated}}));X({format:t,key:`skills`,items:r.items,headers:[`ID`,`NAME`,`SOURCE`,`STATUS`,`VERSION`,`UPDATED`],rows:M_(r.items),hasMore:r.hasMore,nextPage:r.nextPage,truncated:r.truncated,scannedPages:r.scannedPages,emptyMessage:`No matching skills found.`})}}),Pv=C({description:{"en-US":`List Managed Agent skill versions`,"zh-CN":`列出托管 Agent Skill 版本`},auth:`apiKey`,usageArgs:`--skill-id <id> [--limit <n>] [--page <cursor>] [--all]`,flags:A_,exampleArgs:[`--skill-id skill_abc`,`--skill-id skill_abc --all --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return n_(async n=>{let r=await Vi(t,e.flags.skillId,{provider:`bailian`,limit:e.flags.limit,page:n});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`versions`,items:n.items,headers:[`VERSION`,`NAME`,`TYPE`,`STATUS`,`UPDATED`],rows:N_(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No skill versions found.`})}});const Fv={...q,...J,...i_},Iv={...q,limit:J.limit,...r_,...i_},Lv={...q,vaultId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Vault ID`,"zh-CN":`Vault ID`}}};function Rv(e){return e.map(e=>[e.id,Z(e.display_name),Z(e.type),Z(e.created_at),Z(e.updated_at)])}var zv=C({description:{"en-US":`Get a Managed Agent vault`,"zh-CN":`获取托管 Agent Vault 详情`},auth:`apiKey`,usageArgs:`--vault-id <id>`,flags:Lv,exampleArgs:[`--vault-id vault_abc`],notes:U,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>Ai(await W(e,e.flags.file??`agents.yaml`),e.flags.vaultId,{provider:`bailian`})));if(t===`json`){D(n,t);return}E(`ID: ${n.id}`),E(`Name: ${Z(n.display_name)}`),E(`Type: ${Z(n.type)}`),E(`Created: ${Z(n.created_at)}`),E(`Updated: ${Z(n.updated_at)}`)}}),Bv=C({description:{"en-US":`List Managed Agent vaults`,"zh-CN":`列出托管 Agent Vault`},auth:`apiKey`,usageArgs:`[--limit <n>] [--page <cursor>] [--all] [--include-archived]`,flags:Fv,exampleArgs:[``,`--all --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return n_(async n=>{let r=await Ui(t,{provider:`bailian`,limit:e.flags.limit,page:n,include_archived:e.flags.includeArchived});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`vaults`,items:n.items,headers:[`ID`,`NAME`,`TYPE`,`CREATED`,`UPDATED`],rows:Rv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No vaults found.`})}}),Vv=C({description:{"en-US":`Search Managed Agent vaults`,"zh-CN":`搜索托管 Agent Vault`},auth:`apiKey`,usageArgs:`--query <text> [--limit <n>] [--page-limit <n>] [--include-archived]`,flags:Iv,exampleArgs:[`--query github`,`--query production --page-limit 20 --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return s_(async n=>{let r=await Ui(t,{provider:`bailian`,limit:e.flags.limit??100,page:n,include_archived:e.flags.includeArchived});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},t=>o_(e.flags.query,t.id,t.display_name,t.metadata),e.flags.pageLimit)}));X({format:t,key:`vaults`,items:n.items,headers:[`ID`,`NAME`,`TYPE`,`CREATED`,`UPDATED`],rows:Rv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching vaults found.`})}});const Hv={deploymentId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Deployment ID`,"zh-CN":`Deployment ID`}}},Uv={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by agent ID`,"zh-CN":`按 Agent ID 筛选`}},status:{type:`string`,valueHint:`<status>`,choices:[`active`,`paused`],description:{"en-US":`Filter by deployment status`,"zh-CN":`按 Deployment 状态筛选`}},...i_,createdAtGte:{type:`string`,valueHint:`<timestamp>`,description:{"en-US":`Created at or after this timestamp`,"zh-CN":`创建时间不早于该时间戳`}},createdAtLte:{type:`string`,valueHint:`<timestamp>`,description:{"en-US":`Created at or before this timestamp`,"zh-CN":`创建时间不晚于该时间戳`}}},Wv={...q,...J,...Uv},Gv={...q,...Hv},Kv={...q,...J,query:r_.query,...Uv},qv={...q,...Hv,...J},Jv={...q,runId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Deployment run ID`,"zh-CN":`Deployment Run ID`}}},Yv={...q,deployment:{type:`string`,valueHint:`<name>`,description:{"en-US":`Logical deployment name in agents.yaml/state`,"zh-CN":`agents.yaml/State 中的逻辑 Deployment 名称`}},deploymentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Direct deployment ID`,"zh-CN":`直接指定 Deployment ID`}}};function Xv(e){if(!!e.deployment==!!e.deploymentId)return`Provide exactly one of --deployment or --deployment-id.`}function Zv(e){return e.map(e=>[Z(e.id),e.status,Z(e.schedule?.expression),Z(e.paused_reason?.type)])}function Qv(e){return e.map(e=>[e.id,Z(e.deployment_id),Z(e.session_id),Z(e.status),Z(e.created_at)])}async function $v(e,t){if(t.deploymentId)return t.deploymentId;let n=e.state.getResource({provider:`bailian`,type:`deployment`,name:t.deployment});if(!n?.remote_id)throw new ui(`Deployment '${t.deployment}' is not tracked in state. Use --deployment-id or run managed-agent apply/import first.`);return n.remote_id}var ey=C({description:{"en-US":`Get a Managed Agent deployment`,"zh-CN":`获取托管 Agent Deployment 详情`},auth:`apiKey`,usageArgs:`--deployment-id <id>`,flags:Gv,exampleArgs:[`--deployment-id dep_abc`],notes:U,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>Ei(await W(e,e.flags.file??`agents.yaml`),e.flags.deploymentId,{provider:`bailian`})));t===`json`?D(n,t):(E(`ID: ${Z(n.id)}`),E(`Status: ${n.status}`),E(`Schedule:${Z(n.schedule?.expression)}`),E(`Paused: ${Z(n.paused_reason)}`))}}),ty=C({description:{"en-US":`List Managed Agent deployments`,"zh-CN":`列出托管 Agent Deployment`},auth:`apiKey`,usageArgs:`[--agent-id <id>] [--status active|paused] [--limit <n>] [--page <cursor>] [--all]`,flags:Wv,exampleArgs:[``,`--status active --all --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return n_(async n=>{let r=await Ri(t,{provider:`bailian`,agent_id:e.flags.agentId,status:e.flags.status,include_archived:e.flags.includeArchived,created_at_gte:e.flags.createdAtGte,created_at_lte:e.flags.createdAtLte,limit:e.flags.limit,page:n});return{items:r.deployments,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`deployments`,items:n.items,headers:[`ID`,`STATUS`,`SCHEDULE`,`PAUSED REASON`],rows:Zv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No deployments found.`})}});function ny(e){return C({description:e?{"en-US":`Pause a Managed Agent deployment`,"zh-CN":`暂停托管 Agent Deployment`}:{"en-US":`Unpause a Managed Agent deployment`,"zh-CN":`恢复托管 Agent Deployment`},auth:`apiKey`,risk:{level:`high`,message:e?{"en-US":`This pauses the specified Managed Agent deployment and stops its scheduled executions until resumed.`,"zh-CN":`该操作会暂停指定的托管 Agent Deployment,并停止其定时执行直至恢复。`}:{"en-US":`This resumes the specified Managed Agent deployment and may restart scheduled executions and related usage.`,"zh-CN":`该操作会恢复指定的托管 Agent Deployment,可能重新开始定时执行并产生相关用量。`}},usageArgs:`(--deployment <name> | --deployment-id <id>)`,flags:Yv,exampleArgs:[`--deployment daily-report --dry-run`,`--deployment-id dep_abc --yes`],notes:U,validate:Xv,async run(t){let n=w(t.settings.output);if(t.settings.dryRun){D({[e?`would_pause_deployment`:`would_unpause_deployment`]:t.flags.deploymentId??t.flags.deployment,target_kind:t.flags.deploymentId?`id`:`state_name`},n);return}let r=await G(()=>K(async()=>{let n=await W(t,t.flags.file??`agents.yaml`),r=await $v(n,t.flags);return{deploymentId:r,deployment:await ra(n,r,e,{provider:`bailian`})}}));n===`json`?D({deployment_id:r.deploymentId,deployment:r.deployment},n):E(`Deployment ${r.deploymentId} ${e?`paused`:`unpaused`}.`)}})}var ry=ny(!0),iy=C({description:{"en-US":`Run a Managed Agent deployment now`,"zh-CN":`立即运行托管 Agent Deployment`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This immediately starts a run for the specified Managed Agent deployment and may incur usage or trigger configured actions.`,"zh-CN":`该操作会立即运行指定的托管 Agent Deployment,可能产生用量或触发已配置的动作。`}},usageArgs:`(--deployment <name> | --deployment-id <id>)`,flags:Yv,exampleArgs:[`--deployment daily-report --dry-run`,`--deployment-id dep_abc --yes`],notes:U,validate:Xv,async run(e){let t=w(e.settings.output);if(e.settings.dryRun){D({would_run_deployment:e.flags.deploymentId??e.flags.deployment,target_kind:e.flags.deploymentId?`id`:`state_name`},t);return}let n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`),n=await $v(t,e.flags);return{deploymentId:n,run:await $i(t,n,{provider:`bailian`})}}));t===`json`?D({deployment_id:n.deploymentId,...n.run},t):E(`Deployment ${n.deploymentId} started. Run: ${n.run.run_id??`-`}`)}}),ay=C({description:{"en-US":`Get a Managed Agent deployment run`,"zh-CN":`获取托管 Agent Deployment Run 详情`},auth:`apiKey`,usageArgs:`--run-id <id>`,flags:Jv,exampleArgs:[`--run-id run_abc`],notes:U,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>Di(await W(e,e.flags.file??`agents.yaml`),e.flags.runId,{provider:`bailian`})));t===`json`?D(n,t):(E(`ID: ${n.id}`),E(`Deployment: ${Z(n.deployment_id)}`),E(`Session: ${Z(n.session_id)}`),E(`Status: ${Z(n.status)}`),E(`Created: ${Z(n.created_at)}`),E(`Error: ${Z(n.error)}`))}}),oy=C({description:{"en-US":`List runs for a Managed Agent deployment`,"zh-CN":`列出托管 Agent Deployment Run`},auth:`apiKey`,usageArgs:`--deployment-id <id> [--limit <n>] [--page <cursor>] [--all]`,flags:qv,exampleArgs:[`--deployment-id dep_abc`,`--deployment-id dep_abc --all --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return n_(async n=>{let r=await Li(t,e.flags.deploymentId,{provider:`bailian`,limit:e.flags.limit,page:n});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`runs`,items:n.items,headers:[`ID`,`DEPLOYMENT`,`SESSION`,`STATUS`,`CREATED`],rows:Qv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No deployment runs found.`})}}),sy=C({description:{"en-US":`Search Managed Agent deployments`,"zh-CN":`搜索托管 Agent Deployment`},auth:`apiKey`,usageArgs:`--query <text> [--limit <n>] [--page <cursor>] [--all]`,flags:Kv,exampleArgs:[`--query report`,`--query nightly --all --output json`],notes:[...U,{"en-US":`Deployment search maps --query to the provider's server-side keyword parameter.`,"zh-CN":`Deployment 搜索会把 --query 映射为 Provider 服务端 keyword 参数。`}],validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return n_(async n=>{let r=await Ri(t,{provider:`bailian`,keyword:e.flags.query,agent_id:e.flags.agentId,status:e.flags.status,include_archived:e.flags.includeArchived,created_at_gte:e.flags.createdAtGte,created_at_lte:e.flags.createdAtLte,limit:e.flags.limit,page:n});return{items:r.deployments,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`deployments`,items:n.items,headers:[`ID`,`STATUS`,`SCHEDULE`,`PAUSED REASON`],rows:Zv(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No matching deployments found.`})}}),cy=ny(!1);const ly={sessionId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Session ID`,"zh-CN":`Session ID`}}},uy={...q,limit:J.limit,...r_,agent:{type:`string`,valueHint:`<name>`,description:{"en-US":`Filter by configured agent name`,"zh-CN":`按配置中的 Agent 名称筛选`}},statuses:{type:`string`,valueHint:`<statuses>`,description:{"en-US":`Comma-separated session statuses`,"zh-CN":`Session 状态,多个以逗号分隔`}},createdAtGte:{type:`string`,valueHint:`<timestamp>`,description:{"en-US":`Created at or after this timestamp`,"zh-CN":`创建时间不早于该时间戳`}},createdAtLte:{type:`string`,valueHint:`<timestamp>`,description:{"en-US":`Created at or before this timestamp`,"zh-CN":`创建时间不晚于该时间戳`}}},dy={...q,...ly,title:{type:`string`,valueHint:`<title>`,description:{"en-US":`New session title`,"zh-CN":`新的 Session 标题`}},metadata:{type:`string`,valueHint:`<json|@path>`,description:{"en-US":`String-valued metadata JSON or @file`,"zh-CN":`值为字符串的 Metadata JSON 或 @file`}}},fy={...q,...ly};function py(e){return e.map(e=>[e.id,Z(e.title),Z(e.agent_id),e.status,Z(e.updated_at)])}async function my(e){if(!e)return;let t=await m_(e);if(!t||typeof t!=`object`||Array.isArray(t))throw new n(`--metadata must be a JSON object.`,l.USAGE);for(let[e,r]of Object.entries(t))if(typeof r!=`string`)throw new n(`Metadata value for '${e}' must be a string.`,l.USAGE);return t}const hy=C({description:{"en-US":`Search Managed Agent sessions`,"zh-CN":`搜索托管 Agent Session`},auth:`apiKey`,usageArgs:`--query <text> [--agent <name>] [--statuses <statuses>] [--limit <n>] [--page-limit <n>]`,flags:uy,exampleArgs:[`--query debug`,`--query failed --statuses failed --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return s_(async n=>{let r=await Gi(t,{agent:e.flags.agent,provider:`bailian`,filter:{page:n,limit:e.flags.limit??100,statuses:a_(e.flags.statuses),created_at_gte:e.flags.createdAtGte,created_at_lte:e.flags.createdAtLte}});return{items:r.summaries,hasMore:r.hasMore,nextPage:r.nextPage}},t=>o_(e.flags.query,t.session.id,t.session.title,t.session.status,t.session.agent_id,t.agentName),e.flags.pageLimit)})),r=n.items.map(e=>e.session);X({format:t,key:`sessions`,items:r,headers:[`ID`,`TITLE`,`AGENT`,`STATUS`,`UPDATED`],rows:py(r),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching sessions found.`})}}),gy=C({description:{"en-US":`Update a Managed Agent session`,"zh-CN":`更新托管 Agent Session`},auth:`apiKey`,usageArgs:`--session-id <id> [--title <title>] [--metadata <json|@path>]`,flags:dy,exampleArgs:[`--session-id sess_abc --title 'investigation'`,`--session-id sess_abc --metadata @metadata.json`],notes:U,validate:e=>!e.title&&!e.metadata?`Provide --title or --metadata.`:void 0,async run(e){let t=w(e.settings.output),n={title:e.flags.title,metadata:await my(e.flags.metadata)};if(e.settings.dryRun){D({would_update_session:e.flags.sessionId,input:n},t);return}let r=await G(()=>K(async()=>ca(await W(e,e.flags.file??`agents.yaml`),e.flags.sessionId,n,{provider:`bailian`})));t===`json`?D(r,t):E(`Session ${r.id} updated.`)}}),_y=C({description:{"en-US":`Archive a Managed Agent session`,"zh-CN":`归档托管 Agent Session`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This archives the specified remote Managed Agent Session.`,"zh-CN":`该操作会归档指定的远端托管 Agent Session。`}},usageArgs:`--session-id <id>`,flags:fy,exampleArgs:[`--session-id sess_abc --dry-run`,`--session-id sess_abc --yes`],notes:U,async run(e){let t=w(e.settings.output);if(e.settings.dryRun){D({would_archive_session:e.flags.sessionId},t);return}let n=await G(()=>K(async()=>di(await W(e,e.flags.file??`agents.yaml`),e.flags.sessionId,{provider:`bailian`})));t===`json`?D({archived:e.flags.sessionId,session:n},t):E(`Session ${e.flags.sessionId} archived.`)}}),vy={sessionId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Session ID`,"zh-CN":`Session ID`}}},yy={...q,...vy},by={...yy,outputFile:{type:`string`,valueHint:`<path>`,required:!0,description:{"en-US":`Destination ZIP path`,"zh-CN":`目标 ZIP 路径`}},force:{type:`switch`,description:{"en-US":`Overwrite an existing output file`,"zh-CN":`覆盖已存在的输出文件`}}};function xy(e){return e instanceof Error?e.message:String(e)}async function Sy(e,t,n){let r=await ji(e,t,n),i=n??(e.providers.size===1?Array.from(e.providers.keys())[0]:`bailian`),a=[],o=[],s=[];try{o=(await n_(async r=>{let i=await Wi(e,t,{provider:n,limit:100,page_token:r,order:`asc`});return{items:i.events,hasMore:i.has_more,nextPage:i.next_page}},!0)).items}catch(e){a.push({component:`events`,message:xy(e)})}try{s=(await n_(async r=>{let i=await Bi(e,{provider:n,scope_id:t,limit:100,page:r});return{items:i.data,hasMore:i.has_more,nextPage:i.next_page}},!0)).items}catch(e){a.push({component:`files`,message:xy(e)})}return{session:r,events:ba(o),files:s,capabilities:wi(i),errors:a}}const Cy=String.raw`(?:api[_-]?key|access[_-]?key|private[_-]?key|secret|token|authorization|credential|password|signature|signed[_-]?url)`,wy=RegExp(`${Cy}|tool[_-]?input`,`i`),Ty=RegExp(`([?&][^=&#\\s]*(?:${Cy})[^=&#\\s]*=)[^&#\\s"'<>),}\\]]*`,`gi`),Ey=RegExp(`("[^"]*(?:${Cy})[^"]*"\\s*:\\s*")[^"]*(")`,`gi`),Dy=RegExp(`('[^']*(?:${Cy})[^']*'\\s*:\\s*')[^']*(')`,`gi`),Oy=RegExp(`(\\b[^\\s=:,;]*(?:${Cy})[^\\s=:,;]*\\s*=\\s*)(?!\\[REDACTED\\])(?:"[^"]*"|'[^']*'|[^\\s,;&]+)`,`gi`),ky=/\b(authorization\s*:\s*)(?:bearer\s+)?[^\s,;]+/gi,Ay=/\b(bearer\s+)[A-Za-z0-9._~+/=-]+/gi,jy=/\bsk-[A-Za-z0-9_-]{8,}\b/g;function My(e){return e.replace(Ty,`$1[REDACTED]`).replace(Ey,`$1[REDACTED]$2`).replace(Dy,`$1[REDACTED]$2`).replace(Oy,`$1[REDACTED]`).replace(ky,`$1[REDACTED]`).replace(Ay,`$1[REDACTED]`).replace(jy,`[REDACTED]`)}function Ny(e){return Array.isArray(e)?e.map(Ny):typeof e==`string`?My(e):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,wy.test(e)?`[REDACTED]`:Ny(t)]))}function Py(e){return new TextEncoder().encode(`${JSON.stringify(Ny(e),null,2)}\n`)}function Fy(e){let t=4294967295;for(let n of e){t^=n;for(let e=0;e<8;e+=1)t=t>>>1^(t&1?3988292384:0)}return(t^4294967295)>>>0}function Iy(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function Ly(e){let t=e.reduce((e,[,t])=>e+t,0),n=new ArrayBuffer(t),r=new DataView(n),i=0;for(let[t,n]of e)n===2?r.setUint16(i,t,!0):r.setUint32(i,t,!0),i+=n;return new Uint8Array(n)}function Ry(e){let t=new TextEncoder,n=[],r=[],i=0;for(let a of e){let e=t.encode(a.name),o=Fy(a.content),s=Iy([Ly([[67324752,4],[20,2],[0,2],[0,2],[0,2],[0,2],[o,4],[a.content.length,4],[a.content.length,4],[e.length,2],[0,2]]),e,a.content]);n.push(s);let c=Ly([[33639248,4],[20,2],[20,2],[0,2],[0,2],[0,2],[0,2],[o,4],[a.content.length,4],[a.content.length,4],[e.length,2],[0,2],[0,2],[0,2],[0,2],[0,4],[i,4]]);r.push(Iy([c,e])),i+=s.length}let a=Iy(r),o=Ly([[101010256,4],[0,2],[0,2],[e.length,2],[e.length,2],[a.length,4],[i,4],[0,2]]);return Iy([...n,a,o])}const zy=C({description:{"en-US":`Aggregate session diagnostics`,"zh-CN":`聚合 Session 诊断信息`},auth:`apiKey`,usageArgs:`--session-id <id>`,flags:yy,exampleArgs:[`--session-id sess_abc`,`--session-id sess_abc --output json`],notes:U,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>Sy(await W(e,e.flags.file??`agents.yaml`),e.flags.sessionId,`bailian`))),r=Ny(n);if(t===`json`){D(r,t);return}E(`Session: ${n.session.id} (${n.session.status})`),E(`Events: ${n.events.length}`),E(`Scoped files: ${n.files.length}`),E(`Partial errors: ${n.errors.length}`);for(let e of n.errors)E(` ${e.component}: ${e.message}`)}}),By=C({description:{"en-US":`Export session diagnostics as a ZIP`,"zh-CN":`将 Session 诊断信息导出为 ZIP`},auth:`apiKey`,usageArgs:`--session-id <id> --output-file <path> [--force]`,flags:by,exampleArgs:[`--session-id sess_abc --output-file ./session-debug.zip`],notes:[...U,{"en-US":`The ZIP contains metadata only; file bodies and credential-like values are excluded/redacted.`,"zh-CN":`ZIP 仅包含元数据;不会包含文件正文,凭证类字段会被移除或脱敏。`}],async run(e){let t=w(e.settings.output);if(e.settings.dryRun){D({would_export_session:e.flags.sessionId,output_file:e.flags.outputFile},t);return}let n=await G(()=>K(async()=>Sy(await W(e,e.flags.file??`agents.yaml`),e.flags.sessionId,`bailian`))),r={schema_version:1,generated_at:new Date().toISOString(),session_id:n.session.id,partial:n.errors.length>0,counts:{events:n.events.length,files:n.files.length,errors:n.errors.length},contents:[`session.json`,`events.json`,`files.json`,`capabilities.json`,`errors.json`],note:`File bodies are not included. Credential-like fields are redacted.`},i=Ry([{name:`manifest.json`,content:Py(r)},{name:`session.json`,content:Py(n.session)},{name:`events.json`,content:Py(n.events)},{name:`files.json`,content:Py(n.files)},{name:`capabilities.json`,content:Py(n.capabilities)},{name:`errors.json`,content:Py(n.errors)}]),a=await h_(e.flags.outputFile,i,e.flags.force);t===`json`?D({exported:n.session.id,output_file:a,partial:r.partial},t):E(`Session diagnostics exported to ${a}${r.partial?` (partial)`:``}`)}}),Vy={fileId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Remote file ID`,"zh-CN":`远端 File ID`}}},Hy={scopeId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by scope ID`,"zh-CN":`按 Scope ID 筛选`}}},Uy={...q,path:{type:`string`,valueHint:`<path>`,required:!0,description:{"en-US":`Local file path`,"zh-CN":`本地文件路径`}},filename:{type:`string`,valueHint:`<name>`,description:{"en-US":`Remote filename override`,"zh-CN":`覆盖远端文件名`}},mimeType:{type:`string`,valueHint:`<type>`,description:{"en-US":`MIME type override`,"zh-CN":`覆盖 MIME 类型`}}},Wy={...q,...J,...Hy},Gy={...q,limit:J.limit,...r_,...Hy},Ky={...q,...Vy},qy={...Ky,outputFile:{type:`string`,valueHint:`<path>`,required:!0,description:{"en-US":`Destination path`,"zh-CN":`目标路径`}},force:{type:`switch`,description:{"en-US":`Overwrite an existing output file`,"zh-CN":`覆盖已存在的输出文件`}}},Jy={...Ky};function Yy(e){return e.map(e=>[e.id,Z(e.filename),Z(e.status),String(e.size_bytes),Z(e.scope?.id),Z(e.created_at)])}const Xy=C({description:{"en-US":`Upload a Managed Agent file`,"zh-CN":`上传托管 Agent 文件`},auth:`apiKey`,usageArgs:`--path <path> [--filename <name>] [--mime-type <type>]`,flags:Uy,exampleArgs:[`--path ./report.pdf`],notes:U,async run(e){let t=w(e.settings.output);if(e.settings.dryRun){D({would_upload_file:e.flags.path,filename:e.flags.filename??A(e.flags.path),mime_type:e.flags.mimeType??g_(e.flags.path)},t);return}let n=await p_(e.flags.path),r=await G(()=>K(async()=>la(await W(e,e.flags.file??`agents.yaml`),n,e.flags.filename??A(e.flags.path),{provider:`bailian`,mimeType:e.flags.mimeType??g_(e.flags.path)})));t===`json`?D(r,t):E(`File uploaded: ${r.id} (${r.filename})`)}}),Zy=C({description:{"en-US":`List Managed Agent files`,"zh-CN":`列出托管 Agent 文件`},auth:`apiKey`,usageArgs:`[--scope-id <id>] [--limit <n>] [--page <cursor>] [--all]`,flags:Wy,exampleArgs:[``,`--scope-id sess_abc --all --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return n_(async n=>{let r=await Bi(t,{provider:`bailian`,scope_id:e.flags.scopeId,limit:e.flags.limit,page:n});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},e.flags.all,e.flags.page)}));X({format:t,key:`files`,items:n.items,headers:[`ID`,`FILENAME`,`STATUS`,`BYTES`,`SCOPE`,`CREATED`],rows:Yy(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No files found.`})}}),Qy=C({description:{"en-US":`Get Managed Agent file metadata`,"zh-CN":`获取托管 Agent 文件元数据`},auth:`apiKey`,usageArgs:`--file-id <id>`,flags:Ky,exampleArgs:[`--file-id file_abc`],notes:U,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>Ci(await W(e,e.flags.file??`agents.yaml`),e.flags.fileId,{provider:`bailian`})));t===`json`?D(n,t):(E(`ID: ${n.id}`),E(`Filename: ${n.filename}`),E(`MIME: ${n.mime_type}`),E(`Bytes: ${n.size_bytes}`),E(`Status: ${Z(n.status)}`),E(`Scope: ${Z(n.scope?.id)}`))}}),$y=C({description:{"en-US":`Search Managed Agent files`,"zh-CN":`搜索托管 Agent 文件`},auth:`apiKey`,usageArgs:`--query <text> [--scope-id <id>] [--limit <n>] [--page-limit <n>]`,flags:Gy,exampleArgs:[`--query report`,`--query pdf --scope-id sess_abc --output json`],notes:U,validate:Y,async run(e){let t=w(e.settings.output),n=await G(()=>K(async()=>{let t=await W(e,e.flags.file??`agents.yaml`);return s_(async n=>{let r=await Bi(t,{provider:`bailian`,scope_id:e.flags.scopeId,limit:e.flags.limit??100,page:n});return{items:r.data,hasMore:r.has_more,nextPage:r.next_page}},t=>o_(e.flags.query,t.id,t.filename,t.mime_type),e.flags.pageLimit)}));X({format:t,key:`files`,items:n.items,headers:[`ID`,`FILENAME`,`STATUS`,`BYTES`,`SCOPE`,`CREATED`],rows:Yy(n.items),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching files found.`})}}),eb=C({description:{"en-US":`Download Managed Agent file content`,"zh-CN":`下载托管 Agent 文件内容`},auth:`apiKey`,usageArgs:`--file-id <id> --output-file <path> [--force]`,flags:qy,exampleArgs:[`--file-id file_abc --output-file ./artifact.pdf`],notes:U,async run(e){let t=w(e.settings.output);if(e.settings.dryRun){D({would_download_file:e.flags.fileId,output_file:e.flags.outputFile},t);return}let n=await G(()=>K(async()=>bi(await W(e,e.flags.file??`agents.yaml`),e.flags.fileId,{provider:`bailian`}))),r=await h_(e.flags.outputFile,n,e.flags.force);t===`json`?D({downloaded:e.flags.fileId,output_file:r},t):E(`File downloaded to ${r}`)}}),tb=C({description:{"en-US":`Delete a Managed Agent file`,"zh-CN":`删除托管 Agent 文件`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the specified remote Managed Agent file.`,"zh-CN":`该操作会永久删除指定的远端托管 Agent 文件。`}},usageArgs:`--file-id <id>`,flags:Jy,exampleArgs:[`--file-id file_abc --dry-run`,`--file-id file_abc --yes`],notes:U,async run(e){let t=w(e.settings.output);if(e.settings.dryRun){D({would_delete_file:e.flags.fileId},t);return}await G(()=>K(async()=>{await _i(await W(e,e.flags.file??`agents.yaml`),e.flags.fileId,{provider:`bailian`})})),t===`json`?D({deleted:e.flags.fileId},t):E(`File ${e.flags.fileId} deleted.`)}}),nb={loginInfo:`zeldaEasy.cornerstone-portal.cs-console.loginInfo`,initSpace:`zeldaEasy.bailian-dash-workspace.space.initSpace`,queryBuyResult:`zeldaEasy.bailian-commerce.bill.queryBuyPostpaidResult`,commodityOrderInfo:`zeldaEasy.bailian-commerce.bill.postpaidCommodityOrderInfo`,buyCommodity:`zeldaEasy.bailian-commerce.bill.buyPostpaidCommodity`},rb={accessKeyId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Alibaba Cloud Access Key ID`,"zh-CN":`阿里云 Access Key ID`}},accessKeySecret:{type:`string`,valueHint:`<secret>`,description:{"en-US":`Alibaba Cloud Access Key Secret`,"zh-CN":`阿里云 Access Key Secret`}},securityToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Alibaba Cloud STS Security Token (optional)`,"zh-CN":`阿里云 STS Security Token(可选)`}}},ib=1e3;function ab(e){return new Promise(t=>setTimeout(t,e))}function ob(e){return e?.data?.DataV2?.data?.data}function sb(e){let t=e?.data?.data;if(!Array.isArray(t)||t.length===0)return;let n=(t.find(e=>e?.defaultAgent===!0)??t[0])?.tenantId,r=typeof n==`string`?Number(n):n;return typeof r==`number`&&Number.isFinite(r)?r:void 0}var cb=C({description:{"en-US":`Initialize Bailian workspace and activate postpaid services`,"zh-CN":`初始化百炼 Workspace 并开通后付费服务`},auth:`none`,usageArgs:`--access-key-id <id> --access-key-secret <secret> [--security-token <token>]`,flags:rb,exampleArgs:[`--access-key-id LTAIxxxxx --access-key-secret xxxxx`],async run(e){let{settings:t,flags:r}=e,i=w(t.output);if(t.dryRun){D({apis:[{step:0,api:`GenerateCLIAccessToken`,description:`Generate CLI access token from AK/SK`},{step:1,api:nb.loginInfo,description:`Check login & workspace status`},{step:2,api:nb.initSpace,description:`Initialize workspace (if needed)`},{step:3,api:`CreateUser`,description:`Create console user via BailianControl OpenAPI (CreateUser)`},{step:4,api:`ListWorkspaces`,description:`List workspaces to resolve agentId`},{step:5,api:`ResetPolicies4Agent`,description:`Authorize user permissions`},{step:6,api:nb.queryBuyResult,description:`Query postpaid order status`},{step:7,api:nb.commodityOrderInfo,description:`Query commodity activation status`},{step:8,api:nb.buyCommodity,description:`Activate postpaid commodities (if needed)`}]},i);return}let{accessKeyId:a,accessKeySecret:o}=r;if(!a||!o)throw new n(`workspace init requires --access-key-id and --access-key-secret.`,l.USAGE);let s=r.securityToken||void 0,c=(await We({identity:e.identity,settings:t,baseUrl:e.client.baseUrl,accessKeyId:a,accessKeySecret:o,securityToken:s})).cliAccessToken;if(!c)throw new n(`Failed to generate CLI access token from AK/SK.`,l.GENERAL);let u=Oe(t),d={region:u.consoleRegion,site:u.consoleSite,...u.consoleSwitchAgent==null?{}:{switchAgent:u.consoleSwitchAgent},token:c},f=t.verbose,p=async(e,r={})=>{f&&process.stderr.write(`> ${e}\n`);try{let n=await ue(d,t.timeout,{api:e,data:r},t);return f&&process.stderr.write(`< ${JSON.stringify(n)}\n`),n}catch(e){if(f){let t=e instanceof n?e.rawResponse??e.message:String(e);process.stderr.write(`< ERROR: ${t}\n`)}throw e}};E(`Checking workspace status...`);let m=ob(await p(nb.loginInfo));m?.spaceInited===!0?E(`Workspace already initialized.`):(E(`Initializing workspace...`),await p(nb.initSpace),E(`Workspace initialized.`));let h=m?.aliyun?.uid;if(typeof h!=`string`||h.length===0)throw new n(`Console login info did not include aliyun.uid.`,l.GENERAL);let g={identity:e.identity,settings:t,baseUrl:e.client.baseUrl,regionId:u.consoleRegion,accessKeyId:a,accessKeySecret:o,securityToken:s};try{await he({...g,reqDTO:{outerKey:h,nickName:h,userName:h}})}catch(e){if(!(e instanceof n)||!/already exists/i.test(e.message))throw e;E(`Console user already exists, continuing.`)}E(`Resolving workspace agent...`);let _=sb(await ft(g));if(_==null)throw new n(`Could not resolve agentId from ListWorkspaces response.`,l.GENERAL,`Re-run with --verbose to inspect the ListWorkspaces response body.`);E(`Authorizing user permissions...`),await Qt({...g,outerKey:h,agentId:_,policyIndexList:[1]}),await lb(p,i)}});async function lb(e,t){E(`Checking service activation status...`);let r;for(let t=0;t<20;t++){let n=ob(await e(nb.queryBuyResult));if(r=typeof n==`string`?n:n?.result,r!==`buying`)break;t===0&&E(`Service activation in progress, polling...`),await ab(ib)}if(r===`fail`)throw new n(`Service activation failed.`,l.GENERAL);if(r===`success`){await fb(e,t);return}await db(e,t)}function ub(e){let t=ob(e);return Array.isArray(t)?t:[]}async function db(e,t){let n=ub(await e(nb.commodityOrderInfo)),r=n.filter(e=>e.status===11);if(r.length>0){E(`Warning: Some services are overdue:`);for(let e of r)E(` - ${e.commodityCode}`)}let i=n.filter(e=>e.status===1);if(i.length>0){E(`Activating ${i.length} postpaid services...`),await e(nb.buyCommodity),await fb(e,t);return}D({status:`ready`,activeServices:n.filter(e=>e.status===10).map(e=>e.commodityCode)},t)}async function fb(e,t){E(`Waiting for services to activate...`);for(let n=0;n<20;n++){let n=ub(await e(nb.commodityOrderInfo));if(n.filter(e=>e.status!==10&&e.status!==11).length===0){let e=n.filter(e=>e.status===11);if(e.length>0){E(`Warning: Some services are overdue:`);for(let t of e)E(` - ${t.commodityCode}`)}D({status:`ready`,activeServices:n.filter(e=>e.status===10).map(e=>e.commodityCode)},t);return}await ab(ib)}throw new n(`Timed out waiting for services to activate.`,l.TIMEOUT)}var pb=C({description:{"en-US":`Install or upgrade an allowlisted Command Pack`,"zh-CN":`安装或升级白名单内的 Command Pack`},auth:`none`,usageArgs:`--package <name[@version]>`,flags:{package:{type:`string`,valueHint:`<name[@version]>`,description:{"en-US":`Allowlisted Command Pack package and optional version or tag`,"zh-CN":`白名单内的 Command Pack 包名,以及可选的版本或 Tag`},required:!0}},exampleArgs:[`--package @ali/bailian-plugin-agent`,`--package @ali/bailian-plugin-agent@beta`],async run(e){D({installed:await e.commandPacks.install(e.flags.package)},w(e.settings.output))}}),mb=C({description:{"en-US":`Link an allowlisted local Command Pack for development`,"zh-CN":`链接白名单内的本地 Command Pack 用于开发`},auth:`none`,usageArgs:`--path <directory>`,flags:{path:{type:`string`,valueHint:`<directory>`,description:{"en-US":`Local Command Pack package directory`,"zh-CN":`本地 Command Pack 包目录`},required:!0}},exampleArgs:[`--path ../bailian-plugin-agent`],async run(e){D({linked:await e.commandPacks.link(e.flags.path)},w(e.settings.output))}}),hb=C({description:{"en-US":`List installed Command Packs and their load status`,"zh-CN":`列出已安装的 Command Pack 及其加载状态`},auth:`none`,exampleArgs:[``,`--output json`],async run(e){let t=await e.commandPacks.list(),n=w(e.settings.output);if(n===`json`){D({command_packs:t},n);return}if(t.length===0){E(`No Command Packs installed.`);return}let r=t.map(e=>[e.name,e.version??`-`,e.source,e.status,e.commands.join(`, `)||e.error||`-`]);for(let e of Xn([`NAME`,`VERSION`,`SOURCE`,`STATUS`,`COMMANDS / ERROR`],r))E(e)}}),gb=C({description:{"en-US":`Remove an installed Command Pack`,"zh-CN":`移除已安装的 Command Pack`},auth:`none`,usageArgs:`--name <package>`,flags:{name:{type:`string`,valueHint:`<package>`,description:{"en-US":`Allowlisted Command Pack package name`,"zh-CN":`白名单内的 Command Pack 包名`},required:!0}},exampleArgs:[`--name @ali/bailian-plugin-agent`],async run(e){await e.commandPacks.remove(e.flags.name),D({removed:e.flags.name},w(e.settings.output))}}),_b=C({description:{"en-US":`Install skills from the Bailian skill registry into local agents`,"zh-CN":`将百炼 Skill Registry 中的 Skill 安装到本地 Agent`},auth:`none`,usageArgs:`--all | --name <name,...>`,flags:{all:{type:`switch`,description:{"en-US":`Install all skills from the registry`,"zh-CN":`安装 Registry 中的全部 Skill`}},name:{type:`string`,valueHint:`<name,...>`,description:{"en-US":`Comma-separated skill names to install`,"zh-CN":`要安装的 Skill 名称,以逗号分隔`}}},validate(e){if(e.all&&e.name)return`Use either --all or --name, not both`;if(!e.all&&!e.name)return`Specify --all to install everything or --name <name,...> for specific skills`},exampleArgs:[`--all`,`--name spark-video,bailian-model-recommend`],async run(e){let t=e.settings.outputExplicit?e.settings.output:`json`,r=await ze(),i=Object.keys(r.skills),a=e.flags.all?`all`:zt(e.flags.name,!1),o=a===`all`?i:a,s=qt(),c=Ee(),u=await sn(o.map(e=>async()=>{let t=r.skills[e];if(!t)return{name:e,status:`failed`,reason:`skill not found in registry`};try{let n=await it(e,t,c,s.skills[e]?.links??[]);return s.skills[e]=n.lockEntry,{name:e,status:`installed`,publishedAt:t.publishedAt,agents:n.linkedAgents}}catch(t){return{name:e,status:`failed`,reason:t instanceof Error?t.message:String(t)}}}),3);if(Mn(s),t===`json`)D({registry:et(),agents:c.map(e=>e.id),skills:u},t);else if(u.length===0)E(`Skill registry is empty; no skills to install.`);else{let e=u.map(e=>[e.name,e.status,e.publishedAt?e.publishedAt.slice(0,10):`-`,e.status===`installed`?e.agents?.join(`, `)||`-`:e.reason??`-`]);for(let t of Xn([`NAME`,`STATUS`,`PUBLISHED`,`AGENTS / REASON`],e))E(t)}let d=u.filter(e=>e.status===`failed`);if(d.length>0)throw new n(`${d.length}/${u.length} skill(s) failed to install`,l.GENERAL,`Check the reason for failed skills in the output; network failures can be retried with bl skill add`)}}),vb=C({description:{"en-US":`Update installed skills to the latest registry versions`,"zh-CN":`将已安装的 Skill 更新到 Registry 最新版本`},auth:`none`,usageArgs:`[--all] [--name <name,...>]`,flags:{all:{type:`switch`,description:{"en-US":`Update all installed skills (default when neither --all nor --name is given)`,"zh-CN":`更新全部已安装 Skill(未指定 --all 或 --name 时的默认行为)`}},name:{type:`string`,valueHint:`<name,...>`,description:{"en-US":`Comma-separated skill names to update (must be already installed)`,"zh-CN":`要更新的 Skill 名称,以逗号分隔(必须已安装)`}}},validate(e){if(e.all&&e.name)return`Use either --all or --name, not both`},exampleArgs:[``,`--all`,`--name spark-video`],async run(e){let t=e.settings.outputExplicit?e.settings.output:`json`,r=e.flags.all||!e.flags.name?`all`:zt(e.flags.name,!1),i=await ze(),a=qt(),o=new Set(yt()),s=Ee(),c=[],u=[];if(r===`all`)for(let[e,t]of Object.entries(a.skills)){let n=i.skills[e];if(!n){c.push({name:e,status:`skipped`,reason:`delisted from remote; local copy retained`});continue}if(n.contentHash===t.contentHash&&o.has(e)){let n=Ne(e,s,t.links??[]);a.skills[e]={...t,links:n.links},c.push({name:e,status:`up-to-date`,publishedAt:t.publishedAt});continue}u.push(e)}else for(let e of r){if(!a.skills[e]){c.push({name:e,status:`failed`,reason:`not installed; run bl skill add --name `+e+` first`});continue}u.push(e)}let d=await sn(u.map(e=>async()=>{let t=i.skills[e];if(!t)return{name:e,status:`failed`,reason:`skill not found in registry`};try{let n=await it(e,t,s,a.skills[e]?.links??[]);return a.skills[e]=n.lockEntry,{name:e,status:`updated`,publishedAt:t.publishedAt}}catch(t){return{name:e,status:`failed`,reason:t instanceof Error?t.message:String(t)}}}),3);if(c.push(...d),Mn(a),t===`json`)D({registry:et(),skills:c},t);else if(c.length===0)E(`No skills installed locally; run bl skill add first.`);else{let e=c.map(e=>[e.name,e.status,e.publishedAt?e.publishedAt.slice(0,10):`-`]);for(let t of Xn([`NAME`,`STATUS`,`PUBLISHED`],e))E(t);let t=c.filter(e=>(e.status===`skipped`||e.status===`failed`)&&e.reason);if(t.length>0){E(``);for(let e of t)E(` ${e.name}: ${e.reason}`)}}let f=c.filter(e=>e.status===`failed`);if(f.length>0)throw new n(`${f.length} skill(s) failed to update`,l.GENERAL,`Check the reason for failed skills in the output; network failures can be retried with bl skill update`)}}),yb=C({description:{"en-US":`Remove locally installed skills (registry is untouched)`,"zh-CN":`移除本地已安装的 Skill(不修改 Registry)`},auth:`none`,usageArgs:`--name <all|name,...>`,flags:{name:{type:`string`,valueHint:`<all|name,...>`,description:{"en-US":`Skills to remove: all or comma-separated skill names`,"zh-CN":`要移除的 Skill:all 或以逗号分隔的 Skill 名称`},required:!0}},exampleArgs:[`--name spark-video`,`--name all`],async run(e){let t=e.settings.outputExplicit?e.settings.output:`json`,r=zt(e.flags.name,!1),i=qt(),a=r===`all`?Object.keys(i.skills):r;if(a.length===0){D({skills:[]},t),t===`text`&&E(`No skills installed locally; nothing to remove.`);return}let o=new Set(yt()),s=[];for(let e of a){let t=i.skills[e];if(!t){s.push({name:e,status:`failed`,reason:o.has(e)?`directory not managed by bl skill (untracked); remove manually if needed`:`not installed`});continue}try{let n=Cn(e,t.links??[]);Zt(e),delete i.skills[e],s.push({name:e,status:`removed`,removedLinks:n.length})}catch(t){s.push({name:e,status:`failed`,reason:t instanceof Error?t.message:String(t)})}}if(Mn(i),t===`json`)D({skills:s},t);else{let e=s.map(e=>[e.name,e.status,e.status===`removed`?`reclaimed ${e.removedLinks} agent link(s)`:e.reason??`-`]);for(let t of Xn([`NAME`,`STATUS`,`DETAIL`],e))E(t)}let c=s.filter(e=>e.status===`failed`);if(c.length>0)throw new n(`${c.length}/${s.length} skill(s) failed to remove`,l.GENERAL,`Check the reason for failed skills in the output; use bl skill list to verify local install status`)}});function bb(e){return e?e.length>60?`${e.slice(0,59)}…`:e:`-`}var xb=C({description:{"en-US":`List registry skills and diff against local installs`,"zh-CN":`列出 Registry Skill,并与本地安装结果比较`},auth:`none`,exampleArgs:[``,`--output json`],notes:[{"en-US":`STATUS: installed | outdated | not-installed | missing (lock has it, dir deleted) | untracked (dir exists, not managed)`,"zh-CN":`STATUS:installed | outdated | not-installed | missing(Lock 中存在但目录已删除)| untracked(目录存在但未被管理)`}],async run(e){let t=e.settings.outputExplicit?e.settings.output:`json`,n=await ze(),r=me(n,qt(),yt());if(t===`json`){D({registry:et(),...n.updatedAt?{updatedAt:n.updatedAt}:{},skills:r},t);return}if(r.length===0){E(`Skill registry is empty and no skills are installed locally.`);return}let i=r.map(e=>[e.name,e.status,e.publishedAt?e.publishedAt.slice(0,19).replace(`T`,` `):`-`,bb(e.description)]);for(let e of Xn([`NAME`,`STATUS`,`UPDATEDAT`,`DESCRIPTION`],i))E(e)}});const Sb=`json`,Cb={success:`success`,partial:`partial`,failed:`failed`};var wb=C({description:{"en-US":`Install all bailian-* skills (one-shot bootstrap for new environments)`,"zh-CN":`安装全部 bailian-* Skill(用于新环境的一次性初始化)`},auth:`none`,usageArgs:``,exampleArgs:[``],notes:[{"en-US":"Fetches the registry index and installs every skill whose name starts with `bailian-`.","zh-CN":"获取 Registry 索引并安装名称以 `bailian-` 开头的所有 Skill。"},{"en-US":"Equivalent to: `bl skill add --all` (filtered to `bailian-*` skills).","zh-CN":"等价于:`bl skill add --all`(筛选为 `bailian-*` Skill)。"}],async run(e){let t=e.settings.outputExplicit?e.settings.output:Sb,r=await ze(),i=Object.keys(r.skills).filter(e=>e.startsWith(`bailian-`)),a=qt(),o=Ee(),s=await sn(i.map(e=>async()=>{let t=r.skills[e];try{let n=await it(e,t,o,a.skills[e]?.links??[]);return a.skills[e]=n.lockEntry,{name:e,status:Cb.success}}catch(t){return{name:e,status:Cb.failed,reason:t instanceof Error?t.message:String(t)}}}),3);Mn(a);let c=s.filter(e=>e.status===Cb.success),u=s.filter(e=>e.status===Cb.failed),d=u.length===0?Cb.success:c.length===0?Cb.failed:Cb.partial;if(t===Sb){let e=o.map(e=>e.id),n={status:d,skills:c.map(e=>e.name)};u.length>0&&(n.failed=u.map(t=>({name:t.name,reason:t.reason,agents:e}))),D(n,t)}else if(s.length===0)E(`No bailian-* skills found in the registry.`);else if(E(d===Cb.success?`Installed ${c.length} bailian-* skills.`:`Installed ${c.length}/${s.length} bailian-* skills.`),u.length>0){E(`Failed:`);for(let e of u)E(` ${e.name}: ${e.reason}`)}if(u.length>0)throw new n(`${u.length}/${s.length} skill(s) failed to install`,l.GENERAL,`Check the reason for failed skills in the output; network failures can be retried with bl skill init`)}});const Tb=[{id:`code-interpreter`,imageName:`代码解释器`,imageUrl:`fc-e2b-registry.cn-beijing.cr.aliyuncs.com/runtime/code-interpreter-v1:v0.0.44`,icon:`https://img.alicdn.com/imgextra/i2/O1CN01iX8RH9ckFvC093x2_!!6000000000905-2-tps-72-72.png`,description:{"en-US":`Python / Node.js runtimes with common data-processing libraries`,"zh-CN":`Python / Node.js 运行时+常用数据处理库`}},{id:`browser`,imageName:`浏览器`,imageUrl:`fc-e2b-registry.cn-beijing.cr.aliyuncs.com/runtime/browser:v0.0.44`,icon:`https://img.alicdn.com/imgextra/i4/O1CN01ShCbPEunrRI093x2_!!6000000000155-2-tps-72-72.png`,description:{"en-US":`Chromium and a visual desktop for clicking, filling forms, and screenshots`,"zh-CN":`Chromium +可视化桌面,支持点击/ 填表/截图`}},{id:`all-in-one`,imageName:`全能型`,imageUrl:`fc-e2b-registry.cn-beijing.cr.aliyuncs.com/runtime/all-in-one:v0.0.44`,icon:`https://img.alicdn.com/imgextra/i1/O1CN01smhklUahsyE093x2_!!6000000006657-2-tps-72-72.png`,description:{"en-US":`Code execution and browser capabilities together`,"zh-CN":`代码执行+浏览器双能力`}}],Eb=Tb.flatMap(e=>[e.id,e.imageName]),Db=Tb.map(e=>({"en-US":`${e.id} (${e.imageName}): ${e.description[`en-US`]}. ${e.imageUrl}`,"zh-CN":`${e.id}(${e.imageName}):${e.description[`zh-CN`]}。${e.imageUrl}`}));function Ob(e){let t=Tb.find(t=>t.id===e||t.imageName===e);if(!t)throw new x(`Unknown built-in image / 未知内置镜像: ${e}. ${Eb.join(`, `)}`);return t}const kb=C({description:{"en-US":`List the built-in Sandbox base images (offline)`,"zh-CN":`列出 CLI 内置的 Sandbox 基础镜像(离线)`},auth:`none`,exampleArgs:[``,`--output json`,`--quiet`],notes:[{"en-US":`Use a preset ID or Chinese name with template create/update --image. These are pinned cn-beijing images; other environments may differ. Use --from-image for a custom image.`,"zh-CN":`在 template create/update 中通过 --image 传入预设 ID 或中文名。这些是固定版本的 cn-beijing 镜像,其他环境可能不同;自定义镜像使用 --from-image。`},...Db],async run(e){if(e.settings.quiet){for(let e of Tb)E(e.id);return}if(w(e.settings.output)===`json`){D(Tb,`json`);return}for(let e of Tb)E(`${e.id} (${e.imageName})`),E(` ${e.imageUrl}`),E(` ${e.description[`en-US`]} / ${e.description[`zh-CN`]}`)}}),Ab={workspaceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Workspace ID for the default Sandbox endpoint; optional with a configured base URL`,"zh-CN":`默认 Sandbox Endpoint 的 Workspace ID;已配置 Base URL 时可省略`}}},jb={body:{type:`string`,valueHint:`<json|@path>`,description:{"en-US":`JSON request body, inline or loaded from an @file path; explicit flags override it`,"zh-CN":`JSON 请求体,可内联或从 @文件路径读取;显式 Flag 优先`}}},Mb={instanceTimeout:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Sandbox lifetime after this operation (300-604800 seconds)`,"zh-CN":`本次操作后的 Sandbox 存活时间(300–604800 秒)`}}},Nb={showCredentials:{type:`switch`,description:{"en-US":`Print envd and traffic access tokens instead of redacting them`,"zh-CN":`输出 envd 与流量访问 Token 原值,不进行脱敏`}}},Pb={pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Template build polling interval (default: 5 seconds)`,"zh-CN":`模版构建轮询间隔(默认:5 秒)`}}},Fb=[{"en-US":`Auth: uses a Bailian API Key as an Authorization Bearer token; no E2B key is sent.`,"zh-CN":`鉴权:使用百炼 API Key 作为 Authorization Bearer Token;不会发送 E2B Key。`},{"en-US":`Base URL: --base-url > DASHSCOPE_BASE_URL > login/profile base_url. The CLI uses its origin and appends /api/v1/agentstudio/sandbox; otherwise it uses the workspace-scoped cn-beijing endpoint.`,"zh-CN":`Base URL 优先级:--base-url > DASHSCOPE_BASE_URL > 登录/Profile 的 base_url。CLI 取其 origin 并追加 /api/v1/agentstudio/sandbox;未配置时使用工作空间的 cn-beijing Endpoint。`},{"en-US":`Without a configured base URL, workspace is required: --workspace-id > BAILIAN_WORKSPACE_ID > config workspace_id.`,"zh-CN":`未配置 Base URL 时必须提供 Workspace:--workspace-id > BAILIAN_WORKSPACE_ID > 配置项 workspace_id。`},{"en-US":`Sandbox is currently available in cn-beijing only and requires prior SLR authorization.`,"zh-CN":`Sandbox 当前仅支持 cn-beijing,首次使用前需完成 SLR 授权。`},{"en-US":`Global --timeout limits HTTP requests and total template-build polling; --instance-timeout maps to the Sandbox API lifetime field.`,"zh-CN":`全局 --timeout 限制 HTTP 请求和模版构建总轮询时间;--instance-timeout 映射到 Sandbox API 的实例存活时间字段。`}];function Ib(e,t){return e.client.url(cn(t),()=>ln(Lb(e)))}function Lb(e){let t=e.flags.workspaceId||e.settings.workspaceId;if(!t)throw new n(`Workspace ID is required when no base URL is configured. / 未配置 Base URL 时必须提供 Workspace ID。`,l.USAGE,`Pass --workspace-id, set BAILIAN_WORKSPACE_ID, configure workspace_id, or set --base-url. / 请传入 --workspace-id、设置 BAILIAN_WORKSPACE_ID 或 workspace_id 配置,或通过 --base-url 指定地址。`);return t}function Rb(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new n(`${t} must contain a JSON object.`,l.USAGE);return e}async function zb(e){if(!e)return{};let t=e.startsWith(`@`)?e.slice(1):void 0;if(t!==void 0&&t.length===0)throw new n(`--body @path must include a file path.`,l.USAGE);let r=t===void 0?e:await Zr(t,`utf8`);try{return Rb(JSON.parse(r),t?`Body file ${t}`:`--body`)}catch(e){throw e instanceof n?e:e instanceof SyntaxError?new n(t?`Body file ${t} contains invalid JSON.`:`--body contains invalid JSON.`,l.USAGE):e}}function Q(e,t,n){n!==void 0&&(e[t]=n)}function Bb(e,t){let r={};for(let i of e??[]){let e=i.indexOf(`=`);if(e<=0)throw new n(`${t} values must use KEY=VALUE format.`,l.USAGE);let a=i.slice(0,e).trim();if(!a)throw new n(`${t} values must include a non-empty key.`,l.USAGE);r[a]=i.slice(e+1)}return r}function Vb(e,t,n){if(Object.keys(n).length===0)return;let r=e[t];e[t]={...typeof r==`object`&&r&&!Array.isArray(r)?r:{},...n}}function Hb(e,t,r,i){if(e!==void 0&&(typeof e!=`number`||!Number.isInteger(e)||e<r||e>i))throw new n(`${t} must be an integer between ${r} and ${i}.`,l.USAGE)}function Ub(e,t){if(typeof e!=`number`||!Number.isInteger(e)||e<=0)throw new n(`${t} must be a positive integer.`,l.USAGE)}const Wb=new Set([`envdAccessToken`,`trafficAccessToken`]),Gb=/(?:token|secret|password|credential|api[_-]?key)/i;function Kb(e,t){if(Array.isArray(e))return e.map(e=>Kb(e,t));if(typeof e!=`object`||!e)return e;let n={};for(let[r,i]of Object.entries(e)){if(Wb.has(r)||Gb.test(r)||t&&(r===`envVars`||r===`envConfig`)){i==null?n[r]=i:n[r]=(r===`envVars`||r===`envConfig`)&&typeof i==`object`&&!Array.isArray(i)?Object.fromEntries(Object.keys(i).map(e=>[e,`[REDACTED]`])):`[REDACTED]`;continue}n[r]=Kb(i,t)}return n}function qb(e){return Kb(e,!1)}function Jb(e){return Kb(e,!0)}function $(e){return e==null||e===``?`-`:Array.isArray(e)?e.join(`,`):typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:JSON.stringify(e)??`-`}const Yb=`sandbox_template`,Xb=C({description:{"en-US":`Upload a workspace file for Sandbox template mounts`,"zh-CN":`上传工作空间文件,供 Sandbox 模版挂载使用`},auth:`apiKey`,usageArgs:`--path <path> [--filename <name>] [--mime-type <type>]`,flags:{...Ab,path:{type:`string`,valueHint:`<path>`,required:!0,description:{"en-US":`Local file path`,"zh-CN":`本地文件路径`}},filename:{type:`string`,valueHint:`<name>`,description:{"en-US":`Remote filename override`,"zh-CN":`覆盖远端文件名`}},mimeType:{type:`string`,valueHint:`<type>`,description:{"en-US":`Multipart file MIME type (default: application/octet-stream)`,"zh-CN":`Multipart 文件部分的 MIME 类型(默认:application/octet-stream)`}}},exampleArgs:[`--path ./config.json --output json`,`--path ./config.json --quiet`,`--path ./notes.txt --filename notes.txt --mime-type text/plain --dry-run --output json`],notes:[{"en-US":`POST /api/v1/agentstudio/files with multipart fields file and source=sandbox_template. Uses a Bailian Bearer API Key, not Console authentication or an E2B key; no agents.yaml is needed.`,"zh-CN":`向 /api/v1/agentstudio/files 发送 multipart 字段 file 和 source=sandbox_template。使用百炼 Bearer API Key,不使用 Console 鉴权或 E2B Key;无需 agents.yaml。`},{"en-US":`Base URL follows Sandbox: --base-url > DASHSCOPE_BASE_URL > login/profile base_url. Without one, --workspace-id > BAILIAN_WORKSPACE_ID > config workspace_id selects the cn-beijing origin. The upload path has no /sandbox prefix.`,"zh-CN":`Base URL 沿用 Sandbox:--base-url > DASHSCOPE_BASE_URL > 登录/Profile 的 base_url。未配置时,按 --workspace-id > BAILIAN_WORKSPACE_ID > 配置项 workspace_id 选择 cn-beijing 地址。上传路径不带 /sandbox 前缀。`},{"en-US":`Returns the upload response immediately; --quiet prints only its id. Upload does not wait for security review: status=checking is not ready to mount. Use an available file's id as mntConfig[].originFileId in template create/update --body, together with mountPath and optional originFileName, in the same workspace. This does not transfer files into a running instance.`,"zh-CN":`上传响应返回后立即输出,--quiet 仅输出 id。不会等待安全审核:status=checking 不代表已可挂载。在同一工作空间的 template create/update --body 中,将可用文件的 id 填入 mntConfig[].originFileId,同时传入 mountPath 和可选的 originFileName。此命令不向运行中的实例传文件。`},{"en-US":`--dry-run previews the endpoint, source, and local path without reading or uploading the file. The service detects the MIME type and enforces upload limits.`,"zh-CN":`--dry-run 仅预览 Endpoint、source 和本地路径,不读取或上传文件。MIME 类型检测和上传限制由服务端执行。`}],async run(e){let t=e.client.url(S(),()=>ln(Lb(e))),r=e.flags.filename??A(e.flags.path),i=e.flags.mimeType??`application/octet-stream`,a=w(e.settings.output);if(e.settings.dryRun){D({method:`POST`,endpoint:t,request:{source:Yb,file:{path:e.flags.path,filename:r,mimeType:i}}},a);return}let o=new Uint8Array(await Zr(e.flags.path)),s=new FormData;s.append(`source`,Yb),s.append(`file`,new Blob([o],{type:i}),r);let c=await e.client.requestJson({method:`POST`,path:t,body:s});if(!c||typeof c.id!=`string`||!c.id.trim())throw new n(`Upload response did not contain a File ID. / 上传响应未包含 File ID。`,l.GENERAL);e.settings.quiet?E(c.id):D(qb(c),a)}}),Zb={sandboxId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Sandbox instance ID`,"zh-CN":`Sandbox 实例 ID`}}},Qb={...Ab,...jb,templateId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Ready template ID; may alternatively be supplied as templateID in --body`,"zh-CN":`已就绪的模版 ID;也可通过 --body 中的 templateID 提供`}},...Mb,allowInternetAccess:{type:`boolean`,valueHint:`<bool>`,description:{"en-US":`Allow public internet access`,"zh-CN":`允许访问公网`}},metadata:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Instance metadata entry; repeat for multiple values`,"zh-CN":`实例 Metadata 键值;可重复传入`}},env:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Instance environment variable; repeat for multiple values`,"zh-CN":`实例环境变量;可重复传入`}},autoPause:{type:`boolean`,valueHint:`<bool>`,description:{"en-US":`Pause the instance when its timeout expires`,"zh-CN":`实例超时后自动暂停`}},autoResume:{type:`boolean`,valueHint:`<bool>`,description:{"en-US":`Automatically resume a paused instance when connecting`,"zh-CN":`连接已暂停实例时自动恢复`}},allowOut:{type:`array`,valueHint:`<address>`,description:{"en-US":`Outbound allow-list entry; repeat for multiple values`,"zh-CN":`出站白名单条目;可重复传入`}},denyOut:{type:`array`,valueHint:`<address>`,description:{"en-US":`Outbound deny-list entry; repeat for multiple values`,"zh-CN":`出站黑名单条目;可重复传入`}},maskRequestHost:{type:`string`,valueHint:`<host>`,description:{"en-US":`Override the outbound request Host header`,"zh-CN":`覆盖出站请求的 Host Header`}},...Nb},$b={...Ab,templateId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by template ID`,"zh-CN":`按模版 ID 筛选`}},sandboxId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by sandbox ID`,"zh-CN":`按 Sandbox ID 筛选`}},state:{type:`string`,valueHint:`<state>`,description:{"en-US":`Filter by state, for example running or paused`,"zh-CN":`按状态筛选,例如 running 或 paused`}},limit:{type:`number`,valueHint:`<n>`,description:{"en-US":`Maximum results (1-50)`,"zh-CN":`最大返回数量(1–50)`}}},ex={...Ab,...Zb,...Nb},tx={...Ab,...Zb},nx={...Ab,...Zb,...jb,...Mb,...Nb};async function rx(e){let t=await zb(e.body);Q(t,`templateID`,e.templateId),Q(t,`timeout`,e.instanceTimeout),Q(t,`allow_internet_access`,e.allowInternetAccess),Q(t,`autoPause`,e.autoPause),Q(t,`autoResume`,e.autoResume),Vb(t,`metadata`,Bb(e.metadata,`--metadata`)),Vb(t,`envVars`,Bb(e.env,`--env`));let r={};if(Q(r,`allowOut`,e.allowOut),Q(r,`denyOut`,e.denyOut),Q(r,`maskRequestHost`,e.maskRequestHost),Vb(t,`network`,r),typeof t.templateID!=`string`||t.templateID.trim().length===0)throw new n(`Sandbox create requires --template-id or templateID in --body.`,l.USAGE);return Hb(t.timeout,`Sandbox timeout`,300,604800),t}async function ix(e){let t=await zb(e.body);return Q(t,`timeout`,e.instanceTimeout),Hb(t.timeout,`Sandbox timeout`,300,604800),t}function ax(e,t){let n=t.showCredentials?e:qb(e);if(t.quiet){E($(e.sandboxID));return}D(n,t.format)}const ox=C({description:{"en-US":`Create a Sandbox instance`,"zh-CN":`创建 Sandbox 实例`},auth:`apiKey`,usageArgs:`(--template-id <id> | --body <json|@path>) [flags]`,flags:Qb,exampleArgs:[`--template-id tpl-xxx --instance-timeout 3600`,`--template-id tpl-xxx --base-url https://workspace.cn-beijing.maas.aliyuncs.com`,`--body @sandbox.json --dry-run --output json`,`--template-id tpl-xxx --show-credentials --output json`],notes:Fb,async run(e){let t=w(e.settings.output),n=Ib(e,g.sandboxes),r=await rx(e.flags);if(e.settings.dryRun){D({method:`POST`,endpoint:n,request:Jb(r)},t);return}ax(await e.client.requestJson({path:n,method:`POST`,body:r}),{format:t,quiet:e.settings.quiet,showCredentials:e.flags.showCredentials})}}),sx=C({description:{"en-US":`List Sandbox instances`,"zh-CN":`列出 Sandbox 实例`},auth:`apiKey`,usageArgs:`[--template-id <id>] [--sandbox-id <id>] [--state <state>] [--limit <n>]`,flags:$b,exampleArgs:[``,`--state running --limit 20`,`--template-id tpl-xxx --output json`],notes:Fb,validate(e){if(e.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>50))return`--limit must be an integer between 1 and 50.`},async run(e){let t=new URL(Ib(e,g.sandboxList));e.flags.templateId&&t.searchParams.set(`templateID`,e.flags.templateId),e.flags.sandboxId&&t.searchParams.set(`sandboxID`,e.flags.sandboxId),e.flags.state&&t.searchParams.set(`state`,e.flags.state),e.flags.limit!==void 0&&t.searchParams.set(`limit`,String(e.flags.limit));let n=await e.client.requestJson({path:t.toString(),method:`GET`});if(e.settings.quiet){for(let e of n)E($(e.sandboxID));return}let r=w(e.settings.output);if(r===`json`){D(n,r);return}if(n.length===0){E(`No Sandbox instances found.`);return}let i=n.map(e=>[$(e.sandboxID),$(e.templateID),$(e.state),$(e.cpuCount),$(e.memoryMB),$(e.startedAt),$(e.endAt)]);for(let e of Xn([`ID`,`TEMPLATE`,`STATE`,`CPU`,`MEMORY_MB`,`STARTED_AT`,`END_AT`],i))E(e)}}),cx=C({description:{"en-US":`Get Sandbox instance details`,"zh-CN":`获取 Sandbox 实例详情`},auth:`apiKey`,usageArgs:`--sandbox-id <id> [--show-credentials]`,flags:ex,exampleArgs:[`--sandbox-id sbx-xxx`,`--sandbox-id sbx-xxx --show-credentials --output json`],notes:Fb,async run(e){let t=Ib(e,dn(e.flags.sandboxId));ax(await e.client.requestJson({path:t,method:`GET`}),{format:w(e.settings.output),quiet:e.settings.quiet,showCredentials:e.flags.showCredentials})}});function lx(e){let t=e===`connect`?`Connect to`:`Resume`,n=e===`connect`?`连接`:`恢复`;return C({description:{"en-US":`${t} a Sandbox instance and return connection information`,"zh-CN":`${n} Sandbox 实例并返回连接信息`},auth:`apiKey`,usageArgs:`--sandbox-id <id> [--instance-timeout <seconds>] [--show-credentials]`,flags:nx,exampleArgs:[`--sandbox-id sbx-xxx --instance-timeout 3600`,`--sandbox-id sbx-xxx --show-credentials --output json`],notes:Fb,async run(t){let n=w(t.settings.output),r=Ib(t,un(t.flags.sandboxId,e)),i=await ix(t.flags);if(t.settings.dryRun){D({method:`POST`,endpoint:r,request:Jb(i)},n);return}ax(await t.client.requestJson({path:r,method:`POST`,body:Object.keys(i).length>0?i:void 0}),{format:n,quiet:t.settings.quiet,showCredentials:t.flags.showCredentials})}})}const ux=lx(`connect`),dx=lx(`resume`),fx=C({description:{"en-US":`Pause a Sandbox instance`,"zh-CN":`暂停 Sandbox 实例`},auth:`apiKey`,usageArgs:`--sandbox-id <id>`,flags:tx,exampleArgs:[`--sandbox-id sbx-xxx`,`--sandbox-id sbx-xxx --dry-run --output json`],notes:Fb,async run(e){let t=w(e.settings.output),n=Ib(e,un(e.flags.sandboxId,`pause`));if(e.settings.dryRun){D({method:`POST`,endpoint:n,request:null},t);return}await e.client.request({path:n,method:`POST`}),e.settings.quiet?E(e.flags.sandboxId):D({sandboxID:e.flags.sandboxId,paused:!0},t)}}),px=C({description:{"en-US":`Release a Sandbox instance`,"zh-CN":`释放 Sandbox 实例`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently releases the Sandbox instance and cannot be undone.`,"zh-CN":`该操作会永久释放 Sandbox 实例,且无法撤销。`}},usageArgs:`--sandbox-id <id>`,flags:tx,exampleArgs:[`--sandbox-id sbx-xxx --dry-run`,`--sandbox-id sbx-xxx --yes`],notes:Fb,async run(e){let t=w(e.settings.output),n=Ib(e,dn(e.flags.sandboxId));if(e.settings.dryRun){D({method:`DELETE`,endpoint:n,request:null},t);return}await e.client.request({path:n,method:`DELETE`}),e.settings.quiet?E(e.flags.sandboxId):D({sandboxID:e.flags.sandboxId,deleted:!0},t)}}),mx={async:{type:`switch`,description:{"en-US":`Return the submitted templateID/buildID immediately without polling`,"zh-CN":`提交后立即返回 templateID/buildID,不轮询构建状态`}}},hx={templateId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Sandbox template ID`,"zh-CN":`Sandbox 模版 ID`}}},gx={image:{type:`string`,valueHint:`<preset>`,choices:Eb,description:{"en-US":`Built-in image ID or Chinese name; fills fromImage and imageName`,"zh-CN":`内置镜像 ID 或中文名;自动填写 fromImage 和 imageName`}},name:{type:`string`,valueHint:`<name>`,description:{"en-US":`Template name`,"zh-CN":`模版名称`}},cpuCount:{type:`number`,valueHint:`<cores>`,description:{"en-US":`vCPU count`,"zh-CN":`vCPU 核数`}},memoryMb:{type:`number`,valueHint:`<mb>`,description:{"en-US":`Memory in MB`,"zh-CN":`内存大小(MB)`}},fromImage:{type:`string`,valueHint:`<image>`,description:{"en-US":`Base image identifier`,"zh-CN":`基础镜像标识`}},imageName:{type:`string`,valueHint:`<name>`,description:{"en-US":`Base image display name`,"zh-CN":`基础镜像展示名称`}},env:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Template environment variable; repeat for multiple values`,"zh-CN":`模版环境变量;可重复传入`}},allowOut:{type:`array`,valueHint:`<address>`,description:{"en-US":`Outbound allow-list entry; repeat for multiple values`,"zh-CN":`出站白名单条目;可重复传入`}},denyOut:{type:`array`,valueHint:`<address>`,description:{"en-US":`Outbound deny-list entry; repeat for multiple values`,"zh-CN":`出站黑名单条目;可重复传入`}},autoPauseTime:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Automatically pause after 300-604800 seconds`,"zh-CN":`在 300–604800 秒后自动暂停`}},maxRunningTime:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Maximum running lifetime in seconds (300-604800)`,"zh-CN":`最大运行时间(秒,300–604800)`}},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`Template description`,"zh-CN":`模版描述`}}},_x={...Ab,...jb,...gx,tag:{type:`array`,valueHint:`<tag>`,description:{"en-US":`E2B tag; repeat for multiple values`,"zh-CN":`E2B Tag;可重复传入`}},alias:{type:`string`,valueHint:`<alias>`,description:{"en-US":`E2B template alias`,"zh-CN":`E2B 模版别名`}},...mx,...Pb},vx={...Ab,...hx,...jb,...gx,...mx,...Pb},yx={...Ab,limit:{type:`number`,valueHint:`<n>`,description:{"en-US":`Maximum results (1-100)`,"zh-CN":`最大返回数量(1–100)`}},cursor:{type:`string`,valueHint:`<cursor>`,description:{"en-US":`Server-side pagination cursor`,"zh-CN":`服务端分页 Cursor`}}},bx={...Ab,...hx},xx={...Ab,...hx,buildId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Template build ID`,"zh-CN":`模版构建 ID`}}};function Sx(e,t){if(t.image!==void 0){let n=Ob(t.image);e.fromImage=n.imageUrl,e.imageName=n.imageName}Q(e,`name`,t.name),Q(e,`cpuCount`,t.cpuCount),Q(e,`memoryMB`,t.memoryMb),Q(e,`fromImage`,t.fromImage),Q(e,`imageName`,t.imageName),Q(e,`autoPauseTime`,t.autoPauseTime),Q(e,`maxRunningTimeout`,t.maxRunningTime),Q(e,`description`,t.description),Vb(e,`envConfig`,Bb(t.env,`--env`));let n={};Q(n,`allowOut`,t.allowOut),Q(n,`denyOut`,t.denyOut),Vb(e,`networkConfig`,n)}function Cx(e,t){if(t&&(typeof e.name!=`string`||e.name.trim().length===0))throw new n(`Template create requires --name or name in --body.`,l.USAGE);let r=e.cpuCount!==void 0,i=e.memoryMB!==void 0;if(t&&(!r||!i))throw new n(`Template create requires both --cpu-count and --memory-mb, or their --body fields.`,l.USAGE);if(r!==i)throw new n(`cpuCount and memoryMB must be provided together.`,l.USAGE);if(r&&Ub(e.cpuCount,`cpuCount`),i&&Ub(e.memoryMB,`memoryMB`),Hb(e.autoPauseTime,`autoPauseTime`,300,604800),Hb(e.maxRunningTimeout,`maxRunningTimeout`,300,604800),!t&&Object.keys(e).length===0)throw new n(`Template update requires at least one field.`,l.USAGE)}async function wx(e){let t=await zb(e.body);return Sx(t,e),Q(t,`tags`,e.tag),Q(t,`alias`,e.alias),Cx(t,!0),t}async function Tx(e){let t=await zb(e.body);return Sx(t,e),Cx(t,!1),t}async function Ex(e,t,r,i){let a=Date.now()+t.timeout*1e3,o=Hn(`Waiting for template build...`);t.quiet||o.start();try{for(;;){let s=a-Date.now();if(s<=0)break;let c=await e.requestJson({path:r,method:`GET`,timeout:s/1e3});if(t.quiet||o.update(`Build status: ${c.status??`unknown`}`),c.status===`ready`)return o.stop(`Template build ready.`),c;if(c.status===`error`)throw o.stop(`Template build failed.`),new n(c.reason?.message??(c.reason?.code===void 0?`Template build failed.`:`${c.reason.code}`),l.GENERAL);let u=Math.min(i*1e3,a-Date.now());u>0&&await new Promise(e=>setTimeout(e,u))}}finally{o.stop()}throw new n(`Template build polling timed out.`,l.TIMEOUT,`Increase --timeout or query the build status command with the returned IDs.`)}function Dx(e){if(e.pollInterval!==void 0&&(!Number.isInteger(e.pollInterval)||e.pollInterval<=0))return`--poll-interval must be a positive integer.`}async function Ox(e){let t=w(e.settings.output);if(!e.response.templateID||!e.response.buildID)throw new n(`Template mutation response is missing templateID or buildID.`,l.GENERAL);if(e.async){e.settings.quiet?E(`${e.response.templateID}\t${e.response.buildID}`):D(e.response,t);return}let r=new URL(cn(fn(e.response.templateID,e.response.buildID)),e.endpoint).toString(),i;try{i=await Ex(e.client,e.settings,r,e.pollInterval??5)}catch(r){let i=`Submitted build / 已提交的构建: templateID=${e.response.templateID}, buildID=${e.response.buildID}.\nCheck this build with sandbox template build-status before submitting another build. / 请先通过 sandbox template build-status 查询本次构建,再决定是否重新提交。`;if(r instanceof n)throw new n(r.message,r.exitCode,[r.hint,i].filter(Boolean).join(`
|
|
2839
|
+
`),{api:r.api,rawResponse:r.rawResponse,cause:r.cause});let a={templateID:e.response.templateID,buildID:e.response.buildID,hint:i};throw process.stderr.write(t===`json`?`${JSON.stringify(a,null,2)}\n\n`:`${i}\n`),r}e.settings.quiet?E($(e.response.templateID)):D({template:e.response,build:i},t)}const kx=C({description:{"en-US":`Create a Sandbox template`,"zh-CN":`创建 Sandbox 模版`},auth:`apiKey`,usageArgs:`(--name <name> --cpu-count <cores> --memory-mb <mb> | --body <json|@path>) [flags]`,flags:_x,exampleArgs:[`--name browser --image browser --cpu-count 1 --memory-mb 2048`,`--name python --cpu-count 1 --memory-mb 2048`,`--body @template.json --async --output json`,`--name browser --cpu-count 4 --memory-mb 8192 --dry-run --output json`],notes:[...Fb,...Db,{"en-US":`--image overrides body fromImage/imageName; explicit --from-image/--image-name override the corresponding preset fields. Without --image, image behavior is unchanged.`,"zh-CN":`--image 覆盖 body 中的 fromImage/imageName;显式 --from-image/--image-name 再覆盖对应预设字段。不传 --image 时保持原有镜像行为。`},{"en-US":`For local file mounts, use sandbox file upload first; put the available file's id into --body mntConfig[].originFileId with mountPath and optional originFileName. Upload and template must use the same workspace. Other complete nested structures can also be supplied through --body.`,"zh-CN":`挂载本地文件前先调用 sandbox file upload;将可用文件的 id 填入 --body 的 mntConfig[].originFileId,并传入 mountPath 和可选的 originFileName。上传和模版须位于同一工作空间。其他完整嵌套结构也可通过 --body 提供。`},{"en-US":`By default the command waits for build status ready; --async returns the submitted build immediately.`,"zh-CN":`默认等待构建状态变为 ready;--async 会立即返回已提交的构建信息。`}],validate:Dx,async run(e){let t=w(e.settings.output),n=Ib(e,g.templateCreate),r=await wx(e.flags);if(e.settings.dryRun){D({method:`POST`,endpoint:n,request:Jb(r)},t);return}await Ox({response:await e.client.requestJson({path:n,method:`POST`,body:r}),endpoint:n,client:e.client,settings:e.settings,async:e.flags.async,pollInterval:e.flags.pollInterval})}}),Ax=C({description:{"en-US":`List Sandbox templates`,"zh-CN":`列出 Sandbox 模版`},auth:`apiKey`,usageArgs:`[--limit <n>] [--cursor <cursor>]`,flags:yx,exampleArgs:[``,`--limit 100 --output json`],notes:[...Fb,{"en-US":`The API response does not expose a next cursor, so automatic --all pagination is unavailable.`,"zh-CN":`API 响应未提供下一页 Cursor,因此不支持自动 --all 翻页。`}],validate(e){if(e.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>100))return`--limit must be an integer between 1 and 100.`},async run(e){let t=new URL(Ib(e,g.templateList));e.flags.limit!==void 0&&t.searchParams.set(`limit`,String(e.flags.limit)),e.flags.cursor&&t.searchParams.set(`cursor`,e.flags.cursor);let n=await e.client.requestJson({path:t.toString(),method:`GET`});if(e.settings.quiet){for(let e of n)E($(e.templateID));return}let r=w(e.settings.output);if(r===`json`){D(n,r);return}if(n.length===0){E(`No Sandbox templates found.`);return}let i=n.map(e=>[$(e.templateID),$(e.templateName),$(e.cpuCount),$(e.memoryMB),$(e.spawnCount),$(e.buildCount),$(e.updatedAt)]);for(let e of Xn([`ID`,`NAME`,`CPU`,`MEMORY_MB`,`INSTANCES`,`BUILDS`,`UPDATED_AT`],i))E(e)}}),jx=C({description:{"en-US":`Get Sandbox template details`,"zh-CN":`获取 Sandbox 模版详情`},auth:`apiKey`,usageArgs:`--template-id <id>`,flags:bx,exampleArgs:[`--template-id tpl-xxx`,`--template-id tpl-xxx --output json`],notes:Fb,async run(e){let t=Ib(e,pn(e.flags.templateId)),n=await e.client.requestJson({path:t,method:`GET`});e.settings.quiet?E($(n.templateID)):D(n,w(e.settings.output))}}),Mx=C({description:{"en-US":`Update a Sandbox template`,"zh-CN":`更新 Sandbox 模版`},auth:`apiKey`,usageArgs:`--template-id <id> (--body <json|@path> | [fields])`,flags:vx,exampleArgs:[`--template-id tpl-xxx --image all-in-one`,`--template-id tpl-xxx --cpu-count 4 --memory-mb 8192`,`--template-id tpl-xxx --body @template-update.json --async --output json`,`--template-id tpl-xxx --description updated --dry-run --output json`],notes:[...Fb,...Db,{"en-US":`--image overrides body fromImage/imageName; explicit --from-image/--image-name override the corresponding preset fields. Without --image, image behavior is unchanged.`,"zh-CN":`--image 覆盖 body 中的 fromImage/imageName;显式 --from-image/--image-name 再覆盖对应预设字段。不传 --image 时保持原有镜像行为。`},{"en-US":`Supplying envConfig or --env replaces the template's complete environment map.`,"zh-CN":`传入 envConfig 或 --env 会整体替换模版的环境变量 Map。`},{"en-US":`Use sandbox file upload for local mount files. In --body mntConfig[], set originFileId to the available file's id and supply mountPath; upload and template must use the same workspace.`,"zh-CN":`本地挂载文件先通过 sandbox file upload 上传。在 --body 的 mntConfig[] 中,将 originFileId 设为可用文件的 id 并传入 mountPath;上传和模版须位于同一工作空间。`},{"en-US":`By default the command waits for build status ready; --async returns the submitted build immediately.`,"zh-CN":`默认等待构建状态变为 ready;--async 会立即返回已提交的构建信息。`}],validate:Dx,async run(e){let t=w(e.settings.output),n=Ib(e,pn(e.flags.templateId)),r=await Tx(e.flags);if(e.settings.dryRun){D({method:`PUT`,endpoint:n,request:Jb(r)},t);return}await Ox({response:await e.client.requestJson({path:n,method:`PUT`,body:r}),endpoint:n,client:e.client,settings:e.settings,async:e.flags.async,pollInterval:e.flags.pollInterval})}}),Nx=C({description:{"en-US":`Get Sandbox template build status`,"zh-CN":`获取 Sandbox 模版构建状态`},auth:`apiKey`,usageArgs:`--template-id <id> --build-id <id>`,flags:xx,exampleArgs:[`--template-id tpl-xxx --build-id build-xxx`,`--template-id tpl-xxx --build-id build-xxx --output json`],notes:Fb,async run(e){let t=Ib(e,fn(e.flags.templateId,e.flags.buildId)),n=await e.client.requestJson({path:t,method:`GET`});e.settings.quiet?E($(n.status)):D(n,w(e.settings.output))}}),Px=C({description:{"en-US":`Delete a Sandbox template`,"zh-CN":`删除 Sandbox 模版`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the Sandbox template and cannot be undone.`,"zh-CN":`该操作会永久删除 Sandbox 模版,且无法撤销。`}},usageArgs:`--template-id <id>`,flags:bx,exampleArgs:[`--template-id tpl-xxx --dry-run`,`--template-id tpl-xxx --yes`],notes:[...Fb,{"en-US":`The server rejects deletion while running or paused instances still use the template.`,"zh-CN":`仍有运行中或已暂停实例使用该模版时,服务端会拒绝删除。`}],async run(e){let t=w(e.settings.output),n=Ib(e,pn(e.flags.templateId));if(e.settings.dryRun){D({method:`DELETE`,endpoint:n,request:null},t);return}await e.client.request({path:n,method:`DELETE`}),e.settings.quiet?E(e.flags.templateId):D({templateID:e.flags.templateId,deleted:!0},t)}});export{Qf as advisorRecommend,dl as appCall,pl as appList,qa as authGenerateAccessToken,Wa as authLogin,Ka as authLogout,Ga as authStatus,il as configAgent,Uo as configList,Ho as configSet,Vo as configShow,bc as configUi,Wo as configUse,Id as consoleCall,Zp as datasetDelete,Xp as datasetGet,Yp as datasetList,Jp as datasetUpload,Qp as datasetValidate,Wm as deployAudioCreate,Zm as deployDelete,qm as deployGet,Gm as deployImageCreate,Km as deployList,Jm as deployModels,Qm as deployPause,$m as deployResume,Ym as deployScale,Um as deployTextCreate,Xm as deployUpdate,Fd as fileUpload,pm as finetuneAudioCreate,bm as finetuneCancel,Pm as finetuneCapability,Em as finetuneCheckpoints,xm as finetuneDelete,Dm as finetuneExport,ym as finetuneGet,mm as finetuneImageCreate,gm as finetuneList,Tm as finetuneLogs,Lm as finetunePrice,fm as finetuneTextCreate,hm as finetuneVideoCreate,Mm as finetuneWatch,go as imageEdit,fo as imageGenerate,Uu as knowledgeCategoryAdd,Wu as knowledgeCategoryDelete,Hu as knowledgeCategoryList,zl as knowledgeChat,ju as knowledgeChunkAdd,Ru as knowledgeChunkDelete,Mu as knowledgeChunkList,Fu as knowledgeChunkUpdate,Ju as knowledgeCollectionCreate,Yu as knowledgeCollectionGet,cu as knowledgeDocDelete,Xu as knowledgeDocImportOss,Gl as knowledgeDocList,Jl as knowledgeDocStatus,lu as knowledgeDocTag,nu as knowledgeDocUpload,qu as knowledgeFileDelete,Ku as knowledgeFileGet,Gu as knowledgeFileList,au as knowledgeKbCreate,su as knowledgeKbDelete,Wl as knowledgeKbInfo,Bl as knowledgeKbList,Vu as knowledgeKbStats,ou as knowledgeKbUpdate,xl as knowledgeRetrieve,Nl as knowledgeSearch,Ou as knowledgeServiceCopy,_u as knowledgeServiceCreate,Du as knowledgeServiceDelete,Eu as knowledgeServiceDeploy,gu as knowledgeServiceGet,pu as knowledgeServiceList,Tu as knowledgeServiceUpdate,tv as managedAgentAgentCreate,bv as managedAgentAgentGet,xv as managedAgentAgentList,Sv as managedAgentAgentSearch,Cv as managedAgentAgentVersions,ig as managedAgentApply,dv as managedAgentDeploymentCreate,ey as managedAgentDeploymentGet,ty as managedAgentDeploymentList,ry as managedAgentDeploymentPause,iy as managedAgentDeploymentRun,ay as managedAgentDeploymentRunsGet,oy as managedAgentDeploymentRunsList,sy as managedAgentDeploymentSearch,cy as managedAgentDeploymentUnpause,ag as managedAgentDestroy,nv as managedAgentEnvironmentCreate,Ov as managedAgentEnvironmentGet,kv as managedAgentEnvironmentList,Av as managedAgentEnvironmentSearch,tb as managedAgentFileDelete,eb as managedAgentFileDownload,Qy as managedAgentFileGet,Zy as managedAgentFileList,$y as managedAgentFileSearch,Xy as managedAgentFileUpload,jh as managedAgentInit,rg as managedAgentPlan,Tg as managedAgentPlayground,kg as managedAgentProjectBuild,Dg as managedAgentProjectInit,Ag as managedAgentProjectPublish,Og as managedAgentProjectValidate,Ng as managedAgentProjectVersionDisable,Mg as managedAgentProjectVersionEnable,Ig as managedAgentProjectVersionList,Rg as managedAgentProjectVersionPreview,zg as managedAgentProjectVersionRestore,Fg as managedAgentProjectVersionStatus,jg as managedAgentProjectWorkbench,_y as managedAgentSessionArchive,t_ as managedAgentSessionCreate,zy as managedAgentSessionDebug,u_ as managedAgentSessionDelete,C_ as managedAgentSessionEventList,C_ as managedAgentSessionEvents,w_ as managedAgentSessionEventSend,T_ as managedAgentSessionEventStream,By as managedAgentSessionExport,l_ as managedAgentSessionGet,c_ as managedAgentSessionList,d_ as managedAgentSessionRun,hy as managedAgentSessionSearch,f_ as managedAgentSessionSend,gy as managedAgentSessionUpdate,ov as managedAgentSkillCreate,jv as managedAgentSkillDownload,Mv as managedAgentSkillGet,I_ as managedAgentSkillList,Nv as managedAgentSkillSearch,Pv as managedAgentSkillVersions,Kg as managedAgentStateImport,Vg as managedAgentStateList,Ug as managedAgentStateRm,Hg as managedAgentStateShow,eg as managedAgentValidate,sv as managedAgentVaultCreate,cv as managedAgentVaultCredentialCreate,zv as managedAgentVaultGet,Bv as managedAgentVaultList,Vv as managedAgentVaultSearch,od as mcpCall,cd as mcpList,ld as mcpTools,ml as memoryAdd,vl as memoryDelete,gl as memoryList,yl as memoryProfileCreate,bl as memoryProfileGet,hl as memorySearch,_l as memoryUpdate,up as modelList,Kp as permissionGrant,Vp as permissionList,qp as permissionRevoke,Mf as pipelineRun,Lf as pipelineValidate,pb as pluginInstall,mb as pluginLink,hb as pluginList,gb as pluginRemove,Rp as quotaCheck,Tp as quotaDelete,jp as quotaHistory,Cp as quotaList,wp as quotaUpdate,ux as sandboxConnect,ox as sandboxCreate,px as sandboxDelete,Xb as sandboxFileUpload,cx as sandboxGet,sx as sandboxList,kb as sandboxOfficialImages,fx as sandboxPause,dx as sandboxResume,Nx as sandboxTemplateBuildStatus,kx as sandboxTemplateCreate,Px as sandboxTemplateDelete,jx as sandboxTemplateGet,Ax as sandboxTemplateList,Mx as sandboxTemplateUpdate,dd as searchWeb,_b as skillAdd,wb as skillInit,xb as skillList,yb as skillRemove,vb as skillUpdate,Sd as speechRecognize,gd as speechSynthesize,Ad as speechVocabularyCreate,Pd as speechVocabularyDelete,Md as speechVocabularyGet,jd as speechVocabularyList,Nd as speechVocabularyUpdate,ro as textChat,uo as textOmni,xh as tokenPlanAddMember,vh as tokenPlanAssignSeats,mh as tokenPlanCreateKey,kh as tokenPlanHarnessQuota,uh as tokenPlanListSeats,ul as update,Af as usageCodingPlan,lf as usageFree,uf as usageFreetier,mf as usageStats,hf as usageSummary,Cf as usageTokenPlan,wo as videoDownload,xo as videoEdit,bo as videoGenerate,So as videoRef,Co as videoTaskGet,Oo as visionDescribe,cb as workspaceInit,hp as workspaceList};
|