bailian-cli-commands 2.0.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +1300 -301
- package/dist/index.mjs +117 -116
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";import{ASYNC_FLAG as t,BailianError as n,CONCURRENT_FLAG as r,DEFAULT_INSTALL_PS1_URL as i,DEFAULT_INSTALL_SCRIPT_URL as a,DEFAULT_LANGUAGE as o,DEFAULT_TRAINING_TYPE as s,DOCS_HOSTS as c,ExitCode as l,MAX_CPT_BYTES as u,MAX_DATASET_BYTES as d,MAX_MEDIA_ZIP_BYTES as f,MODEL_LIST_API as p,Modalities as m,RAG_PATHS as h,REGIONS as g,SANDBOX_PATHS as _,SEMANTIC_TOP_K as v,STRATEGIES as y,SUPPORTED_LANGUAGES as b,TRAINING_TYPES_CLI as ee,UsageError as x,agentStudioFilesPath as te,agentStudioHost as ne,analyzeIntent as re,anonymousConsoleCall as ie,appCompletionPath as ae,bailianMcpPath as oe,bailianMcpSsePath as se,buildAcsCanonicalQuery as ce,buildAsrContextMessages as le,buildAsrFlashRequest as ue,buildAsyncAsrLanguageFields as de,buildDocLink as fe,buildVocabularyRequest as pe,callConsoleGateway as me,cancelFineTune as he,chatPath as ge,collectAsrTranscriptionItems as _e,computeSkillStatuses as ve,createBailianControlUser as ye,createDeployment as be,createFineTune as xe,createInstrumentedFetch as Se,createVocabulary as Ce,defaultDeployPlan as we,defineCommand as S,deleteConfigProfile as Te,deleteDataset as Ee,deleteDeployment as De,deleteFineTune as Oe,deleteVocabulary as ke,detectInstalledAgents as Ae,detectModality as je,detectOutputFormat as C,effectiveConsoleGatewayConfig as w,estimateCptTokens as Me,estimateSftDpoTokens as Ne,exportCheckpoint as Pe,extractAsrFlashText as Fe,fanOutSkillToAgents as Ie,fetchModelCapability as Le,fetchModelDetail as Re,fetchModelGroups as ze,fetchModelGroupsAll as Be,fetchModelListAll as Ve,fetchPredictConfig as He,fetchSkillsIndex as Ue,fetchTrainingModelPrice as We,findDeploymentEntry as Ge,findModelByName as Ke,formatIssue as qe,generateCLIAccessToken as Je,generateFilename as Ye,getApiKeyLoginKind as Xe,getConfigDir as Ze,getDataset as Qe,getDeployment as $e,getFineTune as et,getFineTuneLogs as tt,getModelProfilePreset as nt,getModels as rt,getProfile as it,getSkillRegistryBaseUrl as at,getSkillsDir as ot,getUpdateInstallMethod as st,image2videoPath as ct,imageFileToDataUri as lt,installSkillWithFanout as ut,isApiKeyCapability as dt,isDashScopeGateway as ft,isLocalFile as pt,isStreamableHttpUnsupported as mt,isTrainingTypeCli as ht,knowledgeChatEndpoint as gt,knowledgeRetrievePath as _t,knowledgeSearchEndpoint as vt,listBailianControlWorkspaces as yt,listCheckpoints as bt,listDatasets as xt,listDeployableModels as St,listDeployments as Ct,listFineTunes as wt,listIndependentDeployedModels as Tt,listSkillDirsOnDisk as Et,listSupportedTrainingTypes as Dt,listVocabularies as Ot,mapApiError as kt,maskToken as At,maybeSyncWikiData as jt,mcpWebSearchPath as Mt,memoryAddPath as Nt,memoryListPath as Pt,memoryNodePath as Ft,memorySearchPath as It,modelSupportsTrainingType as Lt,modelsLimitsPath as Rt,modelsPermissionsPath as zt,normalizeConfigName as Bt,normalizeModelBaseUrl as Vt,parseBooleanValue as Ht,parseDatasetSchemaFlag as Ut,parseInstantVocabulary as Wt,parseSSE as Gt,parseSkillNames as Kt,parseVocabularyEntries as qt,pickPlanStrategy as Jt,planUnlinkSkillFromAgents as Yt,preflightBatchSizeGate as Xt,profileSchemaPath as Zt,queryVocabulary as Qt,ragEndpoint as T,rankModels as $t,readConfigFile as en,readSkillLock as tn,readTextFromPathOrStdin as nn,recallSemantic as rn,redactDataUri as an,removeSkillDir as on,requestJson as sn,resetBailianControlPolicies4Agent as cn,resolveAsrApi as ln,resolveBooleanFlag as un,resolveImageEditApi as dn,resolveImageGenerateApi as fn,resolveOutputDir as pn,resolveWatermark as mn,responsesPath as hn,runWithConcurrency as gn,sandboxApiPath as _n,sandboxBaseUrl as vn,sandboxInstanceActionPath as yn,sandboxInstancePath as bn,sandboxTemplateBuildStatusPath as xn,sandboxTemplatePath as Sn,scaleDeployment as Cn,securityAgentLogsEndpoint as wn,securityGet as Tn,securityOverviewEndpoint as En,speechRecognizePath as Dn,speechSynthesizePath as On,speechVocabularyPath as kn,startModelService as An,stopModelService as jn,stripUndefined as Mn,taskPath as Nn,trackingHeaders as Pn,trainingTypeMethodVariant as Fn,unlinkSkillFromAgents as In,unwrapResponse as Ln,updateDeployment as Rn,updateVocabulary as zn,uploadDataset as Bn,userProfilePath as Vn,validateDataset as Hn,videoGeneratePath as Un,writeConfigFile as Wn,writeSkillLock as Gn}from"bailian-cli-core";import{API_KEY_PAGE as Kn,BOOL_FLAG_PROMPT_EXTEND_API_DEFAULT as qn,BOOL_FLAG_PROMPT_EXTEND_CLI_TRUE as Jn,BOOL_FLAG_PROMPT_EXTEND_IMAGE_GENERATE as Yn,BOOL_FLAG_WATERMARK as Xn,VOICE_TTS_PAGE as Zn,ansi as E,collectPipelineHints as Qn,collectPipelineIssues as $n,createSpinner as er,displayWidth as tr,downloadFile as nr,downloadParallel as rr,emitBare as D,emitResult as O,executePipeline as ir,fetchBinaryChannelVersion as ar,fetchLatestVersion as or,formatBytes as sr,formatTable as cr,getConcurrency as lr,initPipelineSteps as ur,isValidUpdateTargetVersion as dr,mcpMarketplaceDetailPage as fr,normalizeBinaryVersion as pr,padEnd as k,performBinaryUpdate as mr,poll as hr,renderBoxTable as gr,renderGauge as _r,resolveImageSize as vr,runConcurrent as yr,streamPipelineEvents as br,supportsColor as xr}from"bailian-cli-runtime";import{createHash as Sr,randomBytes as Cr,randomUUID as wr,timingSafeEqual as Tr}from"node:crypto";import Er from"node:http";import{execFile as Dr,spawn as Or}from"node:child_process";import{copyFileSync as kr,createWriteStream as Ar,existsSync as jr,mkdirSync as Mr,readFileSync as Nr,renameSync as Pr,statSync as Fr,writeFileSync as Ir}from"fs";import{basename as Lr,dirname as Rr,extname as zr,join as Br}from"path";import{createReadStream as Vr,existsSync as A,lstatSync as Hr,mkdirSync as Ur,readFileSync as Wr,readdirSync as Gr,statSync as Kr,unlinkSync as qr,writeFileSync as Jr}from"node:fs";import{basename as Yr,dirname as Xr,extname as Zr,join as j,relative as Qr,resolve as M,sep as $r}from"node:path";import{homedir as ei}from"node:os";import{inflateRawSync as ti}from"node:zlib";import ni,{parseDocument as ri}from"yaml";import{parse as ii,stringify as ai}from"smol-toml";import{homedir as oi,platform as si}from"os";import{execSync as ci}from"child_process";import{link as li,mkdir as ui,readFile as di,rename as fi,stat as pi,unlink as mi,writeFile as hi}from"node:fs/promises";import gi from"boxen";import _i,{Chalk as vi}from"chalk";import*as yi from"@openagentpack/sdk";import{AGENTS_PROVIDER_FIELDS as bi,LocalFileStateBackend as xi,SessionEventSchema as Si,StateManager as Ci,UserError as wi,archiveRemoteSession as Ti,bootstrapRuntimeCredentialsSync as Ei,buildAgentDecl as Di,createProjectRuntime as Oi,createSessionForAgent as ki,createVaultCredentialWithStateBackend as Ai,deleteFile as ji,deleteSession as Mi,destroyPlannedProjectResources as Ni,downloadRemoteFile as Pi,downloadRemoteSkill as Fi,executePlannedProject as Ii,getFileInfo as Li,getManagedAgentProviderCapabilities as Ri,getRemoteAgent as zi,getRemoteDeployment as Bi,getRemoteDeploymentRun as Vi,getRemoteEnvironment as Hi,getRemoteSkill as Ui,getRemoteVault as Wi,getSession as Gi,importResource as Ki,inspectSkillSource as qi,isTerminalSessionStatus as Ji,listRemoteAgentVersions as Yi,listRemoteAgents as Xi,listRemoteDeploymentRuns as Zi,listRemoteDeployments as Qi,listRemoteEnvironments as $i,listRemoteFiles as ea,listRemoteSkillVersions as ta,listRemoteSkills as na,listRemoteVaults as ra,listSessionEvents as ia,listSessionSummaries as aa,parseStateAddress as oa,planDestroyProjectContext as sa,planProjectContext as ca,planProjectWithStateBackend as la,planVaultCredentialCreateWithStateBackend as ua,resolveProjectConfig as da,resolveProjectConfigFromObject as fa,runRemoteDeployment as pa,sendRemoteSessionEvents as ma,sendSessionMessagePolling as ha,sendSessionMessageStreaming as ga,setRemoteDeploymentPaused as _a,startSessionRun as va,startSessionRunPolling as ya,streamSessionEvents as ba,syncProjectResourcesWithStateBackend as xa,updateRemoteSession as Sa,uploadFile as Ca,validateProjectConfig as wa}from"@openagentpack/sdk";import{promisify as Ta}from"node:util";import{commitProjectBuild as Ea,createDirectoryWorkspaceVersionService as Da,executeProjectPublish as Oa,initializeDirectoryProject as ka,planProjectPublish as Aa,previewProjectBuild as ja,resolveDirectoryProjectRoot as Ma,validateDirectoryProject as Na}from"@openagentpack/sdk/project-workspace";import{sanitizeSessionEvents as Pa}from"@openagentpack/sdk/session-events";const Fa=/* @__PURE__ */ new Set([200,400,401,403,404,405]),Ia=[`cn-beijing`,`ap-southeast-1`,`cn-hongkong`,`ap-northeast-1`,`eu-central-1`,`us-east-1`],La={ordinary:[`https://dashscope.aliyuncs.com`,`https://dashscope-intl.aliyuncs.com`,`https://dashscope-us.aliyuncs.com`,`https://cn-hongkong.dashscope.aliyuncs.com`],"token-plan":[`https://token-plan.cn-beijing.maas.aliyuncs.com`,`https://token-plan.ap-southeast-1.maas.aliyuncs.com`]};function Ra(e,t){let n=new URL(t===`token-plan`?`/compatible-mode/v1/models`:`/api/v1/models`,`${e}/`);return t===`ordinary`&&(n.searchParams.set(`page_no`,`1`),n.searchParams.set(`page_size`,`1`)),n.toString()}function za(e){return e===`unknown`?[`ordinary`,`token-plan`]:[e]}function Ba(e){return new URL(Vt(e)).hostname.startsWith(`token-plan.`)}function Va(e,t,n,r){let i=Vt(n),a=Ra(i,r);t.has(a)||(t.add(a),e.push({baseUrl:i,kind:r,modelsUrl:a}))}function Ha(e,t){let n=Xe(e),r=za(n),i=[],a=/* @__PURE__ */ new Set;if(t.explicitBaseUrl){for(let e of r)Va(i,a,t.explicitBaseUrl,e);return i}if(t.storedBaseUrl){let e=Ba(t.storedBaseUrl);for(let o of r)(n===`unknown`||e===(o===`token-plan`))&&Va(i,a,t.storedBaseUrl,o)}if(t.workspaceId&&r.includes(`ordinary`))for(let e of Ia)Va(i,a,`https://${t.workspaceId}.${e}.maas.aliyuncs.com`,`ordinary`);for(let e of r)for(let t of La[e])Va(i,a,t,e);return i}function Ua(e){if(!(e instanceof n))return!1;let t=e.api?.httpStatus;return t!==void 0&&Fa.has(t)}async function Wa(e,t,r){let i=Ha(t,r),a=await Promise.all(i.map(async n=>{try{return await sn(e,{url:n.modelsUrl,headers:{Authorization:`Bearer ${t}`},timeout:Math.min(e.settings.timeout,5)}),{candidate:n}}catch(e){return{candidate:n,error:e}}})),o=a.find(e=>e.error===void 0);if(o)return{baseUrl:o.candidate.baseUrl,kind:o.candidate.kind};let s=a.find(e=>!Ua(e.error));if(s?.error!==void 0)throw s.error;let c=r.explicitBaseUrl?`Check that the API key belongs to this Base URL.`:`For a workspace-specific or custom endpoint, retry with --base-url <url>.`;throw new n(`API key validation failed: the key was not accepted by any supported model endpoint.`,l.AUTH,c)}async function Ga(e,t,n){let r=n.persistBaseUrl?Vt(n.persistBaseUrl):void 0;await e.authStore.login({...n.persistPatch,api_key:t,base_url:r,default_text_model:n.defaultTextModel,default_video_model:n.defaultVideoModel,default_image_to_video_model:n.defaultImageToVideoModel,default_reference_to_video_model:n.defaultReferenceToVideoModel,default_image_model:n.defaultImageModel,default_speech_model:n.defaultSpeechModel,default_speech_recognition_model:n.defaultSpeechRecognitionModel,api_key_capabilities:n.apiKeyCapabilities?[...n.apiKeyCapabilities]:void 0})}function Ka(e,t=0){return new Promise((n,r)=>{let i=e=>r(e);e.once(`error`,i),e.listen({port:t,host:`127.0.0.1`,exclusive:!0},()=>{e.off(`error`,i);let t=e.address();if(!t||typeof t==`string`){r(/* @__PURE__ */ Error(`Expected TCP socket address`));return}n(t.port)})})}function qa(e){let t=process.platform,n=t===`darwin`?`open`:t===`win32`?`cmd`:`xdg-open`,r=t===`win32`?[`/c`,`start`,``,e]:[e];return new Promise((e,t)=>{Dr(n,r,{windowsHide:!0},n=>{n?t(n):e()})})}function Ja(e){return qa(e)}const Ya=/* @__PURE__ */ RegExp(`\r
|
|
1
|
+
import{createRequire as e}from"node:module";import{ASYNC_FLAG as t,BailianError as n,CONCURRENT_FLAG as r,DEFAULT_INSTALL_PS1_URL as i,DEFAULT_INSTALL_SCRIPT_URL as a,DEFAULT_LANGUAGE as o,DEFAULT_TRAINING_TYPE as s,DOCS_HOSTS as c,ExitCode as l,MAX_CPT_BYTES as u,MAX_DATASET_BYTES as d,MAX_MEDIA_ZIP_BYTES as f,MODEL_LIST_API as p,Modalities as m,RAG_PATHS as h,REGIONS as g,SANDBOX_PATHS as _,SEMANTIC_TOP_K as v,STRATEGIES as y,SUPPORTED_LANGUAGES as b,TRAINING_TYPES_CLI as ee,UsageError as x,agentStudioFilesPath as te,agentStudioHost as ne,analyzeIntent as re,anonymousConsoleCall as ie,appCompletionPath as ae,bailianMcpPath as oe,bailianMcpSsePath as se,buildAcsCanonicalQuery as ce,buildAsrContextMessages as le,buildAsrFlashRequest as ue,buildAsyncAsrLanguageFields as de,buildDocLink as fe,buildPrepaidInfo as pe,buildReservationCapacity as me,buildVocabularyRequest as he,callConsoleGateway as ge,cancelFineTune as _e,chatPath as ve,collectAsrTranscriptionItems as ye,computeSkillStatuses as be,createBailianControlUser as xe,createCapacityInstance as Se,createDeployment as Ce,createFineTune as we,createInstrumentedFetch as Te,createVocabulary as Ee,defaultDeployPlan as De,defineCommand as S,deleteCapacityInstance as Oe,deleteConfigProfile as ke,deleteDataset as Ae,deleteDeployment as je,deleteFineTune as Me,deleteVocabulary as Ne,detectInstalledAgents as Pe,detectModality as Fe,detectOutputFormat as C,effectiveConsoleGatewayConfig as w,estimateCptTokens as Ie,estimateSftDpoTokens as Le,exportCheckpoint as Re,extractAsrFlashText as ze,fanOutSkillToAgents as Be,fetchModelCapability as Ve,fetchModelDetail as He,fetchModelGroups as Ue,fetchModelGroupsAll as We,fetchModelListAll as Ge,fetchPredictConfig as Ke,fetchSkillsIndex as qe,fetchTrainingModelPrice as Je,findDeploymentEntry as Ye,findModelByName as Xe,formatIssue as Ze,generateCLIAccessToken as Qe,generateFilename as $e,getApiKeyLoginKind as et,getCapacityInstance as tt,getCapacityOperation as nt,getConfigDir as rt,getDataset as it,getDeployment as at,getFineTune as ot,getFineTuneLogs as st,getModelProfilePreset as ct,getModels as lt,getProfile as ut,getSkillRegistryBaseUrl as dt,getSkillsDir as ft,getUpdateInstallMethod as pt,hasPrepaidFlags as mt,image2videoPath as ht,imageFileToDataUri as gt,installSkillWithFanout as _t,isApiKeyCapability as vt,isDashScopeGateway as yt,isLocalFile as bt,isStreamableHttpUnsupported as xt,isTrainingTypeCli as St,knowledgeChatEndpoint as Ct,knowledgeRetrievePath as wt,knowledgeSearchEndpoint as Tt,listBailianControlWorkspaces as Et,listCapacityInstances as Dt,listCheckpoints as Ot,listDatasets as kt,listDeployableModels as At,listDeployments as jt,listFineTunes as Mt,listIndependentDeployedModels as Nt,listSkillDirsOnDisk as Pt,listSupportedTrainingTypes as Ft,listVocabularies as It,mapApiError as Lt,maskToken as Rt,maybeSyncWikiData as zt,mcpWebSearchPath as Bt,memoryAddPath as Vt,memoryListPath as Ht,memoryNodePath as Ut,memorySearchPath as Wt,modelSupportsTrainingType as Gt,modelsLimitsPath as Kt,modelsPermissionsPath as qt,normalizeConfigName as Jt,normalizeModelBaseUrl as Yt,parseBooleanValue as Xt,parseDatasetSchemaFlag as Zt,parseInstantVocabulary as Qt,parseSSE as $t,parseSkillNames as en,parseVocabularyEntries as tn,pickPlanStrategy as nn,planUnlinkSkillFromAgents as rn,preflightBatchSizeGate as an,profileSchemaPath as on,queryVocabulary as sn,ragEndpoint as T,rankModels as cn,readConfigFile as ln,readSkillLock as un,readTextFromPathOrStdin as dn,recallSemantic as fn,redactDataUri as pn,removeSkillDir as mn,renewCapacityInstance as hn,requestJson as gn,resetBailianControlPolicies4Agent as _n,resolveAsrApi as vn,resolveBooleanFlag as yn,resolveImageEditApi as bn,resolveImageGenerateApi as xn,resolveOutputDir as Sn,resolveWatermark as Cn,responsesPath as wn,runWithConcurrency as Tn,sandboxApiPath as En,sandboxBaseUrl as Dn,sandboxInstanceActionPath as On,sandboxInstancePath as kn,sandboxTemplateBuildStatusPath as An,sandboxTemplatePath as jn,scaleCapacityInstance as Mn,scaleDeployment as Nn,securityAgentLogsEndpoint as Pn,securityGet as Fn,securityOverviewEndpoint as In,speechRecognizePath as Ln,speechSynthesizePath as Rn,speechVocabularyPath as zn,startModelService as Bn,stopModelService as Vn,stripUndefined as Hn,taskPath as Un,trackingHeaders as Wn,trainingTypeMethodVariant as Gn,unlinkSkillFromAgents as Kn,unwrapResponse as qn,updateDeployment as Jn,updateDeploymentOverflow as Yn,updateVocabulary as Xn,uploadDataset as Zn,userProfilePath as Qn,validateDataset as $n,validatePrepaidFlags as er,validateReservationCapacity as tr,videoGeneratePath as nr,workspaceMaaSBaseUrl as rr,writeConfigFile as ir,writeSkillLock as ar}from"bailian-cli-core";import{API_KEY_PAGE as or,BOOL_FLAG_PROMPT_EXTEND_API_DEFAULT as sr,BOOL_FLAG_PROMPT_EXTEND_CLI_TRUE as cr,BOOL_FLAG_PROMPT_EXTEND_IMAGE_GENERATE as lr,BOOL_FLAG_WATERMARK as ur,VOICE_TTS_PAGE as dr,ansi as E,collectPipelineHints as fr,collectPipelineIssues as pr,createSpinner as mr,displayWidth as hr,downloadFile as gr,downloadParallel as _r,emitBare as D,emitResult as O,executePipeline as vr,fetchBinaryChannelVersion as yr,fetchLatestVersion as br,formatBytes as xr,formatTable as Sr,getConcurrency as Cr,initPipelineSteps as wr,isValidUpdateTargetVersion as Tr,mcpMarketplaceDetailPage as Er,normalizeBinaryVersion as Dr,padEnd as k,performBinaryUpdate as Or,poll as kr,refundConsolePage as Ar,renderBoxTable as jr,renderGauge as Mr,resolveImageSize as Nr,runConcurrent as Pr,streamPipelineEvents as Fr,supportsColor as Ir}from"bailian-cli-runtime";import{createHash as Lr,randomBytes as Rr,randomUUID as zr,timingSafeEqual as Br}from"node:crypto";import Vr from"node:http";import{execFile as Hr,spawn as Ur}from"node:child_process";import{copyFileSync as Wr,createWriteStream as Gr,existsSync as Kr,mkdirSync as qr,readFileSync as Jr,renameSync as Yr,statSync as Xr,writeFileSync as Zr}from"fs";import{basename as Qr,dirname as $r,extname as ei,join as ti}from"path";import{createReadStream as ni,existsSync as A,lstatSync as ri,mkdirSync as ii,readFileSync as ai,readdirSync as oi,statSync as si,unlinkSync as ci,writeFileSync as li}from"node:fs";import{basename as ui,dirname as di,extname as fi,join as j,relative as pi,resolve as M,sep as mi}from"node:path";import{homedir as hi}from"node:os";import{inflateRawSync as gi}from"node:zlib";import _i,{parseDocument as vi}from"yaml";import{parse as yi,stringify as bi}from"smol-toml";import{homedir as xi,platform as Si}from"os";import{execSync as Ci}from"child_process";import{link as wi,mkdir as Ti,readFile as Ei,rename as Di,stat as Oi,unlink as ki,writeFile as Ai}from"node:fs/promises";import ji from"boxen";import Mi,{Chalk as Ni}from"chalk";import*as Pi from"@openagentpack/sdk";import{AGENTS_PROVIDER_FIELDS as Fi,LocalFileStateBackend as Ii,SessionEventSchema as Li,StateManager as Ri,UserError as zi,archiveRemoteSession as Bi,bootstrapRuntimeCredentialsSync as Vi,buildAgentDecl as Hi,createProjectRuntime as Ui,createSessionForAgent as Wi,createVaultCredentialWithStateBackend as Gi,deleteFile as Ki,deleteSession as qi,destroyPlannedProjectResources as Ji,downloadRemoteFile as Yi,downloadRemoteSkill as Xi,executePlannedProject as Zi,getFileInfo as Qi,getManagedAgentProviderCapabilities as $i,getRemoteAgent as ea,getRemoteDeployment as ta,getRemoteDeploymentRun as na,getRemoteEnvironment as ra,getRemoteSkill as ia,getRemoteVault as aa,getSession as oa,importResource as sa,inspectSkillSource as ca,isTerminalSessionStatus as la,listRemoteAgentVersions as ua,listRemoteAgents as da,listRemoteDeploymentRuns as fa,listRemoteDeployments as pa,listRemoteEnvironments as ma,listRemoteFiles as ha,listRemoteSkillVersions as ga,listRemoteSkills as _a,listRemoteVaults as va,listSessionEvents as ya,listSessionSummaries as ba,parseStateAddress as xa,planDestroyProjectContext as Sa,planProjectContext as Ca,planProjectWithStateBackend as wa,planVaultCredentialCreateWithStateBackend as Ta,resolveProjectConfig as Ea,resolveProjectConfigFromObject as Da,runRemoteDeployment as Oa,sendRemoteSessionEvents as ka,sendSessionMessagePolling as Aa,sendSessionMessageStreaming as ja,setRemoteDeploymentPaused as Ma,startSessionRun as Na,startSessionRunPolling as Pa,streamSessionEvents as Fa,syncProjectResourcesWithStateBackend as Ia,updateRemoteSession as La,uploadFile as Ra,validateProjectConfig as za}from"@openagentpack/sdk";import{promisify as Ba}from"node:util";import{commitProjectBuild as Va,createDirectoryWorkspaceVersionService as Ha,executeProjectPublish as Ua,initializeDirectoryProject as Wa,planProjectPublish as Ga,previewProjectBuild as Ka,resolveDirectoryProjectRoot as qa,validateDirectoryProject as Ja}from"@openagentpack/sdk/project-workspace";import{sanitizeSessionEvents as Ya}from"@openagentpack/sdk/session-events";const Xa=/* @__PURE__ */ new Set([200,400,401,403,404,405]),Za=[`cn-beijing`,`ap-southeast-1`,`cn-hongkong`,`ap-northeast-1`,`eu-central-1`,`us-east-1`],Qa={ordinary:[`https://dashscope.aliyuncs.com`,`https://dashscope-intl.aliyuncs.com`,`https://dashscope-us.aliyuncs.com`,`https://cn-hongkong.dashscope.aliyuncs.com`],"token-plan":[`https://token-plan.cn-beijing.maas.aliyuncs.com`,`https://token-plan.ap-southeast-1.maas.aliyuncs.com`]};function $a(e,t){let n=new URL(t===`token-plan`?`/compatible-mode/v1/models`:`/api/v1/models`,`${e}/`);return t===`ordinary`&&(n.searchParams.set(`page_no`,`1`),n.searchParams.set(`page_size`,`1`)),n.toString()}function eo(e){return e===`unknown`?[`ordinary`,`token-plan`]:[e]}function to(e){return new URL(Yt(e)).hostname.startsWith(`token-plan.`)}function no(e,t,n,r){let i=Yt(n),a=$a(i,r);t.has(a)||(t.add(a),e.push({baseUrl:i,kind:r,modelsUrl:a}))}function ro(e,t){let n=et(e),r=eo(n),i=[],a=/* @__PURE__ */ new Set;if(t.explicitBaseUrl){for(let e of r)no(i,a,t.explicitBaseUrl,e);return i}if(t.storedBaseUrl){let e=to(t.storedBaseUrl);for(let o of r)(n===`unknown`||e===(o===`token-plan`))&&no(i,a,t.storedBaseUrl,o)}if(t.workspaceId&&r.includes(`ordinary`))for(let e of Za)no(i,a,`https://${t.workspaceId}.${e}.maas.aliyuncs.com`,`ordinary`);for(let e of r)for(let t of Qa[e])no(i,a,t,e);return i}function io(e){if(!(e instanceof n))return!1;let t=e.api?.httpStatus;return t!==void 0&&Xa.has(t)}async function ao(e,t,r){let i=ro(t,r),a=await Promise.all(i.map(async n=>{try{return await gn(e,{url:n.modelsUrl,headers:{Authorization:`Bearer ${t}`},timeout:Math.min(e.settings.timeout,5)}),{candidate:n}}catch(e){return{candidate:n,error:e}}})),o=a.find(e=>e.error===void 0);if(o)return{baseUrl:o.candidate.baseUrl,kind:o.candidate.kind};let s=a.find(e=>!io(e.error));if(s?.error!==void 0)throw s.error;let c=r.explicitBaseUrl?`Check that the API key belongs to this Base URL.`:`For a workspace-specific or custom endpoint, retry with --base-url <url>.`;throw new n(`API key validation failed: the key was not accepted by any supported model endpoint.`,l.AUTH,c)}async function oo(e,t,n){let r=n.persistBaseUrl?Yt(n.persistBaseUrl):void 0;await e.authStore.login({...n.persistPatch,api_key:t,base_url:r,default_text_model:n.defaultTextModel,default_video_model:n.defaultVideoModel,default_image_to_video_model:n.defaultImageToVideoModel,default_reference_to_video_model:n.defaultReferenceToVideoModel,default_image_model:n.defaultImageModel,default_speech_model:n.defaultSpeechModel,default_speech_recognition_model:n.defaultSpeechRecognitionModel,api_key_capabilities:n.apiKeyCapabilities?[...n.apiKeyCapabilities]:void 0})}function so(e,t=0){return new Promise((n,r)=>{let i=e=>r(e);e.once(`error`,i),e.listen({port:t,host:`127.0.0.1`,exclusive:!0},()=>{e.off(`error`,i);let t=e.address();if(!t||typeof t==`string`){r(/* @__PURE__ */ Error(`Expected TCP socket address`));return}n(t.port)})})}function co(e){let t=process.platform,n=t===`darwin`?`open`:t===`win32`?`cmd`:`xdg-open`,r=t===`win32`?[`/c`,`start`,``,e]:[e];return new Promise((e,t)=>{Hr(n,r,{windowsHide:!0},n=>{n?t(n):e()})})}function lo(e){return co(e)}const uo=/* @__PURE__ */ RegExp(`\r
|
|
2
2
|
\r
|
|
3
3
|
|
|
|
4
4
|
|
|
5
|
-
`),
|
|
6
|
-
`);return}let{accessToken:r,apiKey:s,baseUrl:c,consoleSite:l,consoleRegion:u,consoleSwitchAgent:d,workspaceId:f}=await
|
|
5
|
+
`),fo={domestic:`https://bailian.console.aliyun.com`,international:`https://modelstudio.console.alibabacloud.com`};function po(e){return e&&fo[e]||fo.domestic}function mo(e){return new Promise((t,n)=>{let r=0,i=[];e.on(`data`,e=>{if(r+=e.length,r>65536){n(/* @__PURE__ */ Error(`payload too large`));return}i.push(e)}),e.on(`end`,()=>t(Buffer.concat(i).toString(`utf8`))),e.on(`error`,n)})}function ho(e){let t=e.headers[`content-type`];return Array.isArray(t)?t[0]??``:typeof t==`string`?t:``}function go(e){let t=e.split(`;`);for(let e of t){let t=e.trim();if(!t.toLowerCase().startsWith(`boundary=`))continue;let n=t.slice(9).trim();return(n.startsWith(`"`)&&n.endsWith(`"`)||n.startsWith(`'`)&&n.endsWith(`'`))&&(n=n.slice(1,-1)),n.length>0?n:null}return null}function _o(e,t){let n=`--${t}`,r=e.split(n);for(let e=1;e<r.length;e++){let t=r[e];if(!/name\s*=\s*["'](?:access_token|accessToken)["']/i.test(t))continue;let n=t.match(uo);if(!n||n.index===void 0)continue;let i=t.slice(n.index+n[0].length);if(i=i.replace(/(?:\r\n)+$/g,``).replace(/\n+$/g,``).trim(),i)return i}return null}function vo(e){for(let t of[`access_token`,`accessToken`]){let n=e[t];if(typeof n==`string`&&n.trim())return n.trim()}return null}function yo(e){for(let t of[`api_key`,`apiKey`]){let n=e[t];if(typeof n==`string`&&n.trim())return n.trim()}return null}function bo(e){let t=e.trim();if(t.charCodeAt(0)===65279&&(t=t.slice(1)),!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=n,i=vo(r);if(i)return i;let a=r.data;if(a&&typeof a==`object`&&!Array.isArray(a)){let e=vo(a);if(e)return e}return null}function xo(e,t){let n=t.toLowerCase();if(!e.trim())return null;if(n.includes(`multipart/form-data`)){let n=go(t);if(n){let t=_o(e,n);if(t)return t}}if(n.includes(`application/json`)||n.includes(`text/json`)){let t=bo(e);if(t)return t}if(n.includes(`application/x-www-form-urlencoded`))try{let t=new URLSearchParams(e.trim()),n=t.get(`access_token`)??t.get(`accessToken`);if(n?.trim())return n.trim()}catch{}let r=bo(e);if(r)return r;try{let t=new URLSearchParams(e.trim()),n=t.get(`access_token`)??t.get(`accessToken`);if(n?.trim())return n.trim()}catch{}let i=go(t);if(i){let t=_o(e,i);if(t)return t}return null}function So(e){let t=e.trim();if(t.charCodeAt(0)===65279&&(t=t.slice(1)),!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=n,i=yo(r);if(i)return i;let a=r.data;if(a&&typeof a==`object`&&!Array.isArray(a)){let e=yo(a);if(e)return e}return null}function Co(e,t){let n=t.toLowerCase();if(!e.trim())return null;if(n.includes(`application/json`)||n.includes(`text/json`)){let t=So(e);if(t)return t}if(n.includes(`application/x-www-form-urlencoded`))try{let t=new URLSearchParams(e.trim()),n=t.get(`api_key`)??t.get(`apiKey`);if(n?.trim())return n.trim()}catch{}let r=So(e);if(r)return r;try{let t=new URLSearchParams(e.trim()),n=t.get(`api_key`)??t.get(`apiKey`);if(n?.trim())return n.trim()}catch{}return null}function wo(e,...t){for(let n of t){let t=e[n];if(typeof t==`string`&&t.trim())return t.trim()}return null}function To(e,t){let n={baseUrl:null,consoleSite:null,consoleRegion:null,consoleSwitchAgent:null,workspaceId:null};if(!e.trim())return n;let r=null,i=t.toLowerCase();if(i.includes(`application/json`)||i.includes(`text/json`))try{let t=JSON.parse(e.trim());t&&typeof t==`object`&&!Array.isArray(t)&&(r=t)}catch{}if(!r&&i.includes(`application/x-www-form-urlencoded`))try{let t=new URLSearchParams(e.trim());r=Object.fromEntries(t)}catch{}if(!r)try{let t=JSON.parse(e.trim());t&&typeof t==`object`&&!Array.isArray(t)&&(r=t)}catch{}return r?{baseUrl:wo(r,`base_url`,`baseUrl`),consoleSite:wo(r,`console_site`,`consoleSite`),consoleRegion:wo(r,`console_region`,`consoleRegion`),consoleSwitchAgent:wo(r,`console_switch_agent`,`consoleSwitchAgent`),workspaceId:wo(r,`workspace_id`,`workspaceId`)}:n}async function Eo(e){let t=new URL(e.url??`/`,`http://127.0.0.1`),n=t.searchParams.get(`access_token`)??t.searchParams.get(`accessToken`),r=t.searchParams.get(`api_key`)??t.searchParams.get(`apiKey`),i=t.searchParams.get(`base_url`)??t.searchParams.get(`baseUrl`),a=t.searchParams.get(`console_site`)??t.searchParams.get(`consoleSite`),o=t.searchParams.get(`console_region`)??t.searchParams.get(`consoleRegion`),s=t.searchParams.get(`console_switch_agent`)??t.searchParams.get(`consoleSwitchAgent`),c=t.searchParams.get(`workspace_id`)??t.searchParams.get(`workspaceId`),l={baseUrl:i?.trim()||null,consoleSite:a?.trim()||null,consoleRegion:o?.trim()||null,consoleSwitchAgent:s?.trim()||null,workspaceId:c?.trim()||null},u=e.method??`GET`;if(u!==`POST`&&u!==`PUT`&&u!==`PATCH`)return{accessToken:n?.trim()||null,apiKey:r?.trim()||null,...l};let d=ho(e),f;try{f=await mo(e)}catch{return{accessToken:n?.trim()||null,apiKey:r?.trim()||null,...l}}let p=n?.trim()||xo(f,d),m=r?.trim()||Co(f,d),h=To(f,d);return{accessToken:p,apiKey:m,baseUrl:l.baseUrl||h.baseUrl,consoleSite:l.consoleSite||h.consoleSite,consoleRegion:l.consoleRegion||h.consoleRegion,consoleSwitchAgent:l.consoleSwitchAgent||h.consoleSwitchAgent,workspaceId:l.workspaceId||h.workspaceId}}function Do(e){return so(e)}async function Oo(e,t,r){let i=Rr(16).toString(`hex`),a,o=Vr.createServer(async(e,n)=>{try{if(e.method===`OPTIONS`){n.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`GET, POST, PUT, PATCH, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type`}),n.end();return}if(new URL(e.url??`/`,`http://127.0.0.1`).searchParams.get(`state`)!==i){n.writeHead(400,{"Content-Type":`text/plain; charset=utf-8`}),n.end(`bad state
|
|
6
|
+
`);return}let{accessToken:r,apiKey:s,baseUrl:c,consoleSite:l,consoleRegion:u,consoleSwitchAgent:d,workspaceId:f}=await Eo(e),p=r||c||l||u||d||f;if(p||s)try{let e={access_token:r||void 0,console_site:l||void 0,console_region:u||void 0,console_switch_agent:d?Number(d):void 0,workspace_id:f||void 0};s?(await oo(t,s,{persistBaseUrl:c||void 0,persistPatch:e}),process.stderr.write(`Config saved to ${t.authStore.path}\n`)):p&&(await t.authStore.login({...e,base_url:c||void 0}),process.stderr.write(`Config saved to ${t.authStore.path}\n`))}catch(e){a=e,n.writeHead(500,{"Content-Type":`text/plain; charset=utf-8`}),n.end(`Failed to save credentials
|
|
7
7
|
`),o.close();return}n.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"Access-Control-Allow-Origin":`*`}),n.end(`OK
|
|
8
|
-
`),(p||s)&&o.close()}catch{n.statusCode=500,n.end()}}),s;try{s=await
|
|
8
|
+
`),(p||s)&&o.close()}catch{n.statusCode=500,n.end()}}),s;try{s=await Do(o)}catch(e){let t=e instanceof Error?e.message:String(e);throw new n(`Could not bind to 127.0.0.1 (no free port or permission denied): ${t}`,l.USAGE)}let c=`${e}/console-login?notice=127.0.0.1:${s}?state=${encodeURIComponent(i)}`;r?.needApiKey&&(c+=`&needapikey=true`);try{await lo(c),process.stderr.write(`Opened the login page in your default browser. This process keeps the local port open for the console; press Ctrl+C when finished (or wait for idle timeout).
|
|
9
9
|
`)}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`Could not open the default browser (${t}). Open this URL manually:\n\n`),process.stdout.write(`${c}\n`),process.stderr.write(`
|
|
10
10
|
This process keeps the local port open for the console; press Ctrl+C when finished (or wait for idle timeout).
|
|
11
|
-
`)}if(await new Promise((e,t)=>{let n=!1,r=()=>{n||(n=!0,clearTimeout(i),e())},i=setTimeout(()=>{o.close()},9e5);o.once(`close`,r),o.once(`error`,e=>{clearTimeout(i),n||(n=!0,t(e))})}),a)throw a}function
|
|
12
|
-
`)},r);return}if(r!==`text`){O({authenticated:!0,config:l,config_file:u,api_key:a,console:o,openapi:s},r);return}D(`Config: ${l}`),D(`Config file: ${u}`),D(`Authentication Status:`),D(a?` API key (model): ${a.source} ${a.masked}`:` API key (model): not configured`),D(o?` Console gateway: ${o.source} ${o.masked} (${o.region}, ${o.site})`:` Console gateway: not configured (run ${t.binName} auth login --console)`),D(s?` OpenAPI (AK/SK): ${s.source} ${s.access_key_id}`:` OpenAPI (AK/SK): not configured (run ${t.binName} auth login --open-api)`)}}),
|
|
11
|
+
`)}if(await new Promise((e,t)=>{let n=!1,r=()=>{n||(n=!0,clearTimeout(i),e())},i=setTimeout(()=>{o.close()},9e5);o.once(`close`,r),o.once(`error`,e=>{clearTimeout(i),n||(n=!0,t(e))})}),a)throw a}function ko(e){return typeof e==`string`&&e.trim().length>0}var Ao=S({description:{"en-US":`Authenticate with API key, console browser login, or OpenAPI AK/SK (credentials can coexist)`,"zh-CN":`使用 API Key、控制台浏览器登录或 OpenAPI AK/SK 进行认证(多种凭证可共存)`},auth:`none`,usageArgs:`--api-key <key> | --console | --open-api --access-key-id <id> --access-key-secret <secret>`,flags:{apiKey:{type:`string`,valueHint:`<key>`,description:{"en-US":`Model API key to validate and store`,"zh-CN":`要校验并保存的模型 API Key`}},baseUrl:{type:`string`,valueHint:`<url>`,description:{"en-US":`Model API base URL to validate and store with --api-key`,"zh-CN":`与 --api-key 一并校验并保存的模型 API Base URL`}},console:{type:`switch`,description:{"en-US":`Sign in via browser (China by default; use --console-site international for the international site). Creates an ordinary API key if needed; subscription plans require --api-key`,"zh-CN":`通过浏览器登录(默认中国站;国际站使用 --console-site international)。需要时会创建普通 API Key;订阅计划必须使用 --api-key 登录`}},consoleSite:{type:`string`,valueHint:`<site>`,description:{"en-US":`Console site: domestic, international`,"zh-CN":`控制台站点:domestic、international`}},openApi:{type:`switch`,description:{"en-US":`Store Alibaba Cloud OpenAPI AK/SK credentials`,"zh-CN":`保存阿里云 OpenAPI AK/SK 凭证`}},accessKeyId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Alibaba Cloud Access Key ID to store`,"zh-CN":`要保存的阿里云 Access Key ID`}},accessKeySecret:{type:`string`,valueHint:`<secret>`,description:{"en-US":`Alibaba Cloud Access Key Secret to store`,"zh-CN":`要保存的阿里云 Access Key Secret`}}},exampleArgs:[`--console`,`--api-key sk-xxxxx`,`--open-api --access-key-id LTAIxxxxx --access-key-secret xxxxx`],validate:e=>{let t=ko(e.apiKey),n=e.console===!0,r=e.openApi===!0;if(!t&&ko(e.baseUrl))return`Use --base-url only with --api-key`;if(!n&&ko(e.consoleSite))return`Use --console-site only with --console`;if(!r&&(ko(e.accessKeyId)||ko(e.accessKeySecret)))return`Use --open-api with --access-key-id and --access-key-secret`;if([t,n,r].filter(Boolean).length!==1)return`Choose exactly one login mode: --api-key, --console, or --open-api`;if(r&&(!ko(e.accessKeyId)||!ko(e.accessKeySecret)))return`Provide --access-key-id and --access-key-secret with --open-api`},async run(e){let{identity:t,settings:n,flags:r}=e,i=e.authStore,a={identity:t,settings:n,authStore:i},o=r.apiKey,s=r.baseUrl?Yt(r.baseUrl):void 0;if(r.console){if(n.dryRun){D(`Would bind a free port on 127.0.0.1 and open the console login URL in your browser.`);return}let e=!!(o||i.stored().apiKey);await Oo(po(r.consoleSite||n.consoleSite||`domestic`),a,{needApiKey:!e});return}if(r.openApi){if(n.dryRun){D(`Would save OpenAPI AK/SK credentials and generate CLI access token.`);return}let e=i.resolveBaseUrl();process.stderr.write(`Generating CLI access token... `);let a=(await Qe({identity:t,settings:n,baseUrl:e,accessKeyId:r.accessKeyId,accessKeySecret:r.accessKeySecret})).cliAccessToken;await i.login({access_key_id:r.accessKeyId,access_key_secret:r.accessKeySecret,access_token:a}),process.stderr.write(`OpenAPI credentials saved to ${i.path}\n`);return}if(!o)return;if(n.dryRun){D(`Would validate and save API key.`);return}let c=await ao(a,o,{explicitBaseUrl:s,storedBaseUrl:i.stored().baseUrl,workspaceId:n.workspaceId}),l=ct(c.kind===`token-plan`?`token-plan`:void 0);await oo(a,o,{persistBaseUrl:c.baseUrl,defaultTextModel:l?.defaultTextModel,defaultVideoModel:l?.defaultVideoModel,defaultImageToVideoModel:l?.defaultImageToVideoModel,defaultReferenceToVideoModel:l?.defaultReferenceToVideoModel,defaultImageModel:l?.defaultImageModel,defaultSpeechModel:l?.defaultSpeechModel,defaultSpeechRecognitionModel:l?.defaultSpeechRecognitionModel,apiKeyCapabilities:l?.apiKeyCapabilities}),process.stderr.write(`API key validated and saved to ${i.path}\n`)}}),jo=S({description:{"en-US":`Show current authentication state`,"zh-CN":`显示当前认证状态`},auth:`none`,exampleArgs:[``,`--output json`],async run(e){let{identity:t,settings:n}=e,r=C(n.output),i=e.authStore.describe(),a=i.apiKey?{source:i.apiKey.source,masked:Rt(i.apiKey.token),base_url:i.apiKey.baseUrl}:void 0,o=i.console?{source:i.console.source,masked:Rt(i.console.token),region:i.console.region,site:i.console.site}:void 0,s=i.openapi?{source:i.openapi.source,access_key_id:Rt(i.openapi.accessKeyId),access_key_secret:Rt(i.openapi.accessKeySecret)}:void 0,c=!!(a||o||s),l=n.configName??`default`,u=e.authStore.path;if(!c){O({authenticated:!1,config:l,config_file:u,message:`Not authenticated.`,hint:[`API key (model): ${t.binName} auth login --api-key <key> or DASHSCOPE_API_KEY`,`Console gateway: ${t.binName} auth login --console`,`OpenAPI (AK/SK): ${t.binName} auth login --open-api --access-key-id <id> --access-key-secret <secret>`,`Get API Key: ${or}`].join(`
|
|
12
|
+
`)},r);return}if(r!==`text`){O({authenticated:!0,config:l,config_file:u,api_key:a,console:o,openapi:s},r);return}D(`Config: ${l}`),D(`Config file: ${u}`),D(`Authentication Status:`),D(a?` API key (model): ${a.source} ${a.masked}`:` API key (model): not configured`),D(o?` Console gateway: ${o.source} ${o.masked} (${o.region}, ${o.site})`:` Console gateway: not configured (run ${t.binName} auth login --console)`),D(s?` OpenAPI (AK/SK): ${s.source} ${s.access_key_id}`:` OpenAPI (AK/SK): not configured (run ${t.binName} auth login --open-api)`)}}),Mo=S({description:{"en-US":`Clear stored credentials; full logout also clears the model Base URL`,"zh-CN":`清除已保存的凭证;完整退出还会清除模型 Base URL`},auth:`none`,usageArgs:`[--console | --open-api] [--dry-run]`,flags:{console:{type:`switch`,description:{"en-US":`Only clear the console access_token, keep api_key intact`,"zh-CN":`仅清除控制台 access_token,保留 api_key`}},openApi:{type:`switch`,description:{"en-US":`Only clear OpenAPI AK/SK/STS credentials, keep other credentials intact`,"zh-CN":`仅清除 OpenAPI AK/SK/STS 凭证,保留其他凭证`}}},exampleArgs:[``,`--console`,`--open-api`,`--dry-run`],validate:e=>e.console&&e.openApi?`Use only one scope: --console or --open-api`:void 0,async run(e){let{settings:t,flags:n}=e,r=e.authStore,i=r.stored();if(n.console){if(t.dryRun){i.console?D(`Would clear access_token from ${r.path}`):D(`No console access_token to clear.`),D(`No changes made.`);return}await r.logout(`console`)?(process.stderr.write(`Cleared access_token from ${r.path}\n`),i.apiKey&&process.stderr.write(`api_key is still configured and will be used for authentication.
|
|
13
13
|
`)):process.stderr.write(`No console access_token to clear.
|
|
14
14
|
`);return}if(n.openApi){if(t.dryRun){i.openapi?D(`Would clear access_key_id / access_key_secret / security_token from ${r.path}`):D(`No OpenAPI AK/SK credentials to clear.`),D(`No changes made.`);return}await r.logout(`openapi`)?(process.stderr.write(`Cleared access_key_id / access_key_secret / security_token from ${r.path}\n`),(i.apiKey||i.console)&&process.stderr.write(`Other credentials are still configured and will be used for authentication.
|
|
15
15
|
`)):process.stderr.write(`No OpenAPI AK/SK credentials to clear.
|
|
16
16
|
`);return}let a=i.apiKey||i.console||i.openapi||!!i.baseUrl;if(t.dryRun){D(a?`Would clear api_key / base_url / access_token / access_key_id / access_key_secret / security_token from ${r.path}`:`No credentials or model Base URL to clear.`),D(`No changes made.`);return}await r.logout(`all`)?process.stderr.write(`Cleared api_key / base_url / access_token / access_key_id / access_key_secret / security_token from ${r.path}\n`):process.stderr.write(`No credentials or model Base URL to clear.
|
|
17
|
-
`)}}),
|
|
18
|
-
`))),o&&l.write(t.reasoning_content)),t.content&&(o&&r&&(l.write(`${
|
|
19
|
-
`)}else if(a===`responses`){let n=await e.client.requestJson({path:
|
|
17
|
+
`)}}),No=S({description:{"en-US":`Generate a CLI access token using OpenAPI AK/SK`,"zh-CN":`使用 OpenAPI AK/SK 生成 CLI Access Token`},auth:`none`,usageArgs:`--access-key-id <id> --access-key-secret <secret> --security-token <token>`,flags:{accessKeyId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Alibaba Cloud Access Key ID`,"zh-CN":`阿里云 Access Key ID`},required:!0},accessKeySecret:{type:`string`,valueHint:`<secret>`,description:{"en-US":`Alibaba Cloud Access Key Secret`,"zh-CN":`阿里云 Access Key Secret`},required:!0},securityToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Alibaba Cloud STS Security Token to store (optional)`,"zh-CN":`要保存的阿里云 STS Security Token(可选)`}}},exampleArgs:[`--access-key-id LTAIxxxxx --access-key-secret xxxxx --security-token <token>`],async run(e){let{identity:t,settings:n,flags:r}=e,i=C(n.output),a=await Qe({identity:t,settings:n,baseUrl:e.client.baseUrl,accessKeyId:r.accessKeyId,accessKeySecret:r.accessKeySecret,securityToken:r.securityToken||void 0});O(a,i)}});function Po(e){return e.output.filter(e=>e.type===`message`).flatMap(e=>e.content??[]).filter(e=>e.type===`output_text`).map(e=>e.text??``).join(``)}function Fo(e){return e.type===`response.output_text.delta`?e.delta??``:``}function Io(e){return typeof e==`object`&&e?e:void 0}function Lo(e,t){let n=e?.[t];return typeof n==`string`&&n.trim()?n:void 0}function Ro(e){let t=Io(Io(e.response)?.error),n=Io(e.error);return Lo(t,`message`)??Lo(n,`message`)??Lo(e,`message`)}function zo(e){if(e.type===`response.failed`||e.type===`error`)throw new n(Ro(e)??`Response failed.`,l.GENERAL);if(e.type===`response.incomplete`){let t=Lo(Io(Io(e.response)?.incomplete_details),`reason`);throw new n(Ro(e)??(t?`Response incomplete: ${t}`:`Response incomplete.`),l.GENERAL)}return{delta:Fo(e),completed:e.type===`response.completed`}}function Bo(e){if(!e)throw new n(`Stream disconnected before completion: stream closed before response.completed.`,l.GENERAL)}const Vo={prime:{type:`switch`,description:{"en-US":`Use Prime mode with a workspace-scoped endpoint`,"zh-CN":`使用工作空间专属 Endpoint 的 Prime 模式`}},workspaceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Workspace ID for the default Prime endpoint (or set BAILIAN_WORKSPACE_ID)`,"zh-CN":`默认 Prime Endpoint 使用的 Workspace ID(也可设置 BAILIAN_WORKSPACE_ID)`}}};function Ho(e){if(e.workspaceId&&!e.prime)return`--workspace-id requires --prime.`;if(e.prime&&!e.model)return`--prime requires an explicit --model.`}function Uo(e,t){return e.client.url(t,()=>{let t=e.flags.workspaceId||e.settings.workspaceId;if(!t)throw new n(`Workspace ID is required for the default Prime endpoint.`,l.USAGE,`Pass --workspace-id, set BAILIAN_WORKSPACE_ID env, or configure: ${e.identity.binName} config set workspace_id <id>. You can also override the endpoint with --base-url.`);return rr(t)})}const Wo={api:{type:`string`,valueHint:`<chat|responses>`,choices:[`chat`,`responses`],description:{"en-US":`API to call (default: chat)`,"zh-CN":`调用的 API(默认:chat)`}},model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model ID (default: qwen3.8-max)`,"zh-CN":`模型 ID(默认:qwen3.8-max)`}},message:{type:`array`,valueHint:`<text>`,description:{"en-US":`Message text (repeatable, prefix role: to set role); or use --messages-file`,"zh-CN":`消息文本(可重复;可使用 role: 前缀指定角色),也可使用 --messages-file`}},messagesFile:{type:`string`,valueHint:`<path>`,description:{"en-US":`JSON file with messages array (use - for stdin)`,"zh-CN":`包含 messages 数组的 JSON 文件(使用 - 从 stdin 读取)`}},system:{type:`string`,valueHint:`<text>`,description:{"en-US":`System prompt`,"zh-CN":`系统提示词`}},maxTokens:{type:`number`,valueHint:`<n>`,description:{"en-US":`Maximum tokens to generate (default: 4096)`,"zh-CN":`最大生成 Token 数(默认:4096)`}},temperature:{type:`number`,valueHint:`<n>`,description:{"en-US":`Sampling temperature (0.0, 2.0]`,"zh-CN":`采样温度 (0.0, 2.0]`}},topP:{type:`number`,valueHint:`<n>`,description:{"en-US":`Nucleus sampling threshold`,"zh-CN":`核采样阈值`}},stream:{type:`switch`,description:{"en-US":`Stream response tokens (default: on in TTY)`,"zh-CN":`流式输出响应 Token(TTY 中默认开启)`}},tool:{type:`array`,valueHint:`<json-or-path>`,description:{"en-US":`Tool definition as JSON or file path (repeatable)`,"zh-CN":`JSON 格式的工具定义或文件路径(可重复)`}},enableThinking:{type:`switch`,description:{"en-US":`Enable thinking/reasoning mode (for qwen3/qwq models)`,"zh-CN":`启用思考/推理模式(适用于 qwen3/qwq 模型)`}},thinkingBudget:{type:`number`,valueHint:`<n>`,description:{"en-US":`Max tokens for thinking (default: 4096)`,"zh-CN":`思考过程最大 Token 数(默认:4096)`}},...Vo};function Go(e){let t=[],n;if(e.system&&(n=e.system),e.messagesFile){let r=dn(e.messagesFile),i=JSON.parse(r);for(let e of i)e.role===`system`?n=typeof e.content==`string`?e.content:``:t.push(e)}if(e.message){let r=/* @__PURE__ */ new Set([`system`,`user`,`assistant`]),i=e.message;for(let e of i){let i=e.indexOf(`:`),a=i===-1?``:e.slice(0,i);if(r.has(a)){let r=e.slice(i+1);a===`system`?n=r:t.push({role:a,content:r})}else t.push({role:`user`,content:e})}}return{system:n,messages:t}}var Ko=S({description:{"en-US":`Send a text model request (OpenAI compatible, DashScope)`,"zh-CN":`发送文本模型请求(OpenAI 兼容,DashScope)`},auth:`apiKey`,usageArgs:`--message <text> [flags]`,flags:Wo,exampleArgs:[{"en-US":`--message "What is Qwen?"`,"zh-CN":`--message "通义千问是什么?"`},{"en-US":`--api responses --model qwen3.8-max --tool '{"type":"web_search"}' --message "Search for recent Alibaba Cloud news"`,"zh-CN":`--api responses --model qwen3.8-max --tool '{"type":"web_search"}' --message "搜索近期的阿里云新闻"`},{"en-US":`--model qwen-max --system "You are a coding assistant." --message "Write fizzbuzz in Python"`,"zh-CN":`--model qwen-max --system "你是一名编程助手。" --message "用 Python 编写 FizzBuzz"`},{"en-US":`--message "Hello" --message "assistant:Hi!" --message "How are you?"`,"zh-CN":`--message "你好" --message "assistant:你好!" --message "你好吗?"`},`--messages-file - --stream`,{"en-US":`--message "Hello" --output json`,"zh-CN":`--message "你好" --output json`},{"en-US":`--model qwq-plus --message "Solve 1+1" --enable-thinking`,"zh-CN":`--model qwq-plus --message "计算 1+1" --enable-thinking`},{"en-US":`--prime --workspace-id <id> --model glm-5.3-prime --message "Explain this code"`,"zh-CN":`--prime --workspace-id <id> --model glm-5.3-prime --message "解释这段代码"`}],notes:[{"en-US":`Prime mode requires an explicit model and currently supports only the Chat Completions API.`,"zh-CN":`Prime 模式必须显式指定模型,且当前仅支持 Chat Completions API。`},{"en-US":`Prime endpoint: configured --base-url, DASHSCOPE_BASE_URL, or profile base_url takes precedence; otherwise workspace is resolved from --workspace-id, BAILIAN_WORKSPACE_ID, then config workspace_id.`,"zh-CN":`Prime Endpoint:已配置的 --base-url、DASHSCOPE_BASE_URL 或 Profile base_url 优先;否则按 --workspace-id、BAILIAN_WORKSPACE_ID、配置项 workspace_id 解析工作空间。`}],validate:e=>{if(!e.message&&!e.messagesFile)return`Provide --message or --messages-file.`;let t=Ho(e);if(t)return t;if(e.prime&&e.api===`responses`)return`--prime currently supports only --api chat.`;if(e.api===`responses`&&e.thinkingBudget!==void 0)return`--thinking-budget is not supported by the Responses API.`},async run(e){let{settings:t,flags:n}=e,{system:r,messages:i}=Go(n),a=n.api??`chat`,o=n.model||t.defaultTextModel||`qwen3.8-max`,s=n.stream||process.stdout.isTTY,c=C(t.output),l=[];r&&l.push({role:`system`,content:r}),l.push(...i);let u;u=a===`responses`?{model:o,input:l,max_output_tokens:n.maxTokens??4096,stream:s}:{model:o,messages:l,max_tokens:n.maxTokens??4096,stream:s},n.temperature!==void 0&&(u.temperature=n.temperature),n.topP!==void 0&&(u.top_p=n.topP),n.enableThinking&&(u.enable_thinking=!0,a===`chat`&&`messages`in u&&n.thinkingBudget!==void 0&&(u.thinking_budget=n.thinkingBudget));let d=n.prime?Uo(e,ve()):a===`responses`?wn():ve();if(n.tool){let e=n.tool.map(e=>{try{return JSON.parse(e)}catch{let t=Jr(e,`utf-8`);return JSON.parse(t)}});u.tools=e}if(t.dryRun){O(n.prime?{endpoint:d,request:u}:{request:u},c);return}if(s){let t=await e.client.request({path:d,method:`POST`,body:u,stream:!0}),n=``,r=!1,i=!1,o=c===`text`,s=process.stdout.isTTY,l=c===`json`?process.stderr:s?process.stdout:process.stderr,f=process.stdout,p=E(l);for await(let e of $t(t)){if(e.data===`[DONE]`)break;if(a===`responses`){let t;try{t=JSON.parse(e.data)}catch{continue}let r=zo(t);if(r.delta&&(n+=r.delta,o&&f.write(r.delta)),r.completed){i=!0;break}continue}try{let t=JSON.parse(e.data);for(let e of t.choices){let t=e.delta;t.reasoning_content&&(o&&!r&&(r=!0,l.write(p.dim(`Thinking:
|
|
18
|
+
`))),o&&l.write(t.reasoning_content)),t.content&&(o&&r&&(l.write(`${p.reset}\n\nResponse:\n`),r=!1),n+=t.content,o&&f.write(t.content))}}catch{}}a===`responses`&&Bo(i),r&&l.write(p.reset),c===`json`?O({content:n},c):f.write(`
|
|
19
|
+
`)}else if(a===`responses`){let n=await e.client.requestJson({path:d,method:`POST`,body:u}),r=Po(n);t.quiet||c===`text`?D(r):O(n,c)}else{let n=await e.client.requestJson({path:d,method:`POST`,body:u}),r=n.choices?.[0]?.message?.content??``;t.quiet||c===`text`?D(r):O(n,c)}}});const qo=[{voice:`Tina`,name:`甜妹`,desc:`甜美亲切`,lang:`中文/英文`},{voice:`Dylan`,name:`北京-晓东`,desc:`胡同少年`,lang:`中文/北京`},{voice:`Kiki`,name:`粤语-阿清`,desc:`甜美港妹`,lang:`中文/英文`},{voice:`Li`,name:`南京-老李`,desc:`南京大叔`,lang:`中文/英文`},{voice:`Sunny`,name:`四川-晴儿`,desc:`甜飒川妹`,lang:`中文`},{voice:`Marcus`,name:`陕西-秦川`,desc:`陕北汉子`,lang:`中文/英文`},{voice:`Eric`,name:`四川-程川`,desc:`成都大哥`,lang:`中文/英文`},{voice:`Rocky`,name:`粤语-阿强`,desc:`幽默港仔`,lang:`中文/英文`},{voice:`Jennifer`,name:`詹妮弗`,desc:`美剧大女主`,lang:`中文/英文`},{voice:`Ryan`,name:`甜茶`,desc:`美剧张力男`,lang:`中文/英文`},{voice:`Katerina`,name:`卡捷琳娜`,desc:`御姐深情女`,lang:`中文/英文`},{voice:`Peter`,name:`天津-李彼得`,desc:`天津捧哏`,lang:`中文/英文`},{voice:`Ethan`,name:`晨煦`,desc:`北方口音男`,lang:`中文/英文`}];function Jo(){let e=(e,t)=>e.padEnd(t);process.stdout.write(`
|
|
20
20
|
Omni output voices:
|
|
21
|
-
`),process.stdout.write(`${e(`VOICE ID`,12)} ${e(`NAME`,14)} ${e(`DESCRIPTION`,14)} LANGUAGE\n`),process.stdout.write(`${`-`.repeat(12)} ${`-`.repeat(14)} ${`-`.repeat(14)} ${`-`.repeat(12)}\n`);for(let t of
|
|
22
|
-
`);let te;if(b&&!s){let e=Buffer.from(b,`base64`),r=
|
|
23
|
-
`));else{let t={urls:e,saved:u,total:e.length};i&&(t.task_id=i),a&&a.length>1&&(t.task_ids=a),O(t,r)}}const
|
|
24
|
-
`)):O({urls:e,saved:s,total:e.length},r)}var Ko=S({description:{"en-US":`Generate a video from text or image (wan3.0-video / wan2.6-t2v / happyhorse-1.1-i2v)`,"zh-CN":`根据文本或图片生成视频(wan3.0-video / wan2.6-t2v / happyhorse-1.1-i2v)`},auth:`apiKey`,usageArgs:`--prompt <text> [--image <url>] [flags]`,flags:{model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model ID (default: wan3.0-video)`,"zh-CN":`模型 ID(默认:wan3.0-video)`}},prompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Video description`,"zh-CN":`视频描述`},required:!0},image:{type:`string`,valueHint:`<url>`,description:{"en-US":`Input image URL for image-to-video generation`,"zh-CN":`图生视频使用的输入图片 URL`}},lastFrame:{type:`string`,valueHint:`<url>`,description:{"en-US":`Last frame image URL (with --image, enables kf2v first+last frame mode)`,"zh-CN":`尾帧图片 URL(与 --image 配合,启用 kf2v 首尾帧模式)`}},negativePrompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Negative prompt to exclude unwanted content`,"zh-CN":`负向提示词,用于排除不需要的内容`}},resolution:{type:`string`,valueHint:`<res>`,description:{"en-US":`Resolution: 720P or 1080P (default: 1080P)`,"zh-CN":`分辨率:720P 或 1080P(默认:1080P)`}},ratio:{type:`string`,valueHint:`<ratio>`,description:{"en-US":`Aspect ratio (e.g. 16:9, 9:16, 1:1)`,"zh-CN":`宽高比(例如 16:9、9:16、1:1)`}},duration:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Video duration in seconds (default: 5)`,"zh-CN":`视频时长,单位为秒(默认:5)`}},promptExtend:{type:`boolean`,valueHint:`<bool>`,description:qn},watermark:{type:`boolean`,valueHint:`<bool>`,description:Xn},seed:{type:`number`,valueHint:`<n>`,description:{"en-US":`Random seed for reproducible generation`,"zh-CN":`用于复现生成结果的随机种子`}},download:{type:`string`,valueHint:`<path>`,description:{"en-US":`Save video to file on completion`,"zh-CN":`完成后将视频保存到文件`}},file:{type:`string`,valueHint:`<url-or-path>`,description:{"en-US":`Reference file URL or local path for file-to-video (wan3.0-video only; mutually exclusive with --image/--last-frame)`,"zh-CN":`参考文件 URL 或本地路径,用于文件生视频(仅 wan3.0-video;与 --image/--last-frame 互斥)`}},...t,...r,pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 5)`,"zh-CN":`等待任务时的轮询间隔(默认:5 秒)`}}},exampleArgs:[{"en-US":`--prompt "A person reading a book, static shot"`,"zh-CN":`--prompt "一个人正在读书,固定镜头"`},{"en-US":`--prompt "Ocean waves at sunset." --download sunset.mp4`,"zh-CN":`--prompt "日落时的海浪。" --download sunset.mp4`},{"en-US":`--image https://example.com/cat.png --prompt "Make the cat in the scene move"`,"zh-CN":`--image https://example.com/cat.png --prompt "让画面中的猫动起来"`},{"en-US":`--prompt "Mountain landscape" --resolution 720P --duration 5`,"zh-CN":`--prompt "山地景观" --resolution 720P --duration 5`},{"en-US":`--prompt "A cat playing with a ball" --watermark false`,"zh-CN":`--prompt "一只正在玩球的猫" --watermark false`}],async run(e){let{settings:t,flags:r}=e,i=r.prompt,a=r.model||(r.image?t.defaultImageToVideoModel||`wan3.0-video`:t.defaultVideoModel||`wan3.0-video`),o=C(t.output),s=r.image,c=r.lastFrame,u=r.file;if(u&&(s||c))throw new n(`--file is mutually exclusive with --image/--last-frame.`,l.USAGE);let d;s&&(d=await e.client.resolveImageInput(s,a));let f;c&&(f=await e.client.resolveImageInput(c,a));let p=!!(d&&f),m=/^wan3\./i.test(a);if(u&&!m)throw new n(`--file is only supported by wan3.0-video.`,l.USAGE);let h;u&&(h=await e.client.uploadFile(u,a));let g=mn(r.watermark,t.watermark),_=un(r.promptExtend,void 0,`prompt-extend`),v={model:a,input:{prompt:i,negative_prompt:r.negativePrompt||void 0,...h?{media:[{type:`file`,url:h}]}:p?m?{media:[{type:`first_frame`,url:d},{type:`last_frame`,url:f}]}:{first_frame_url:d,last_frame_url:f}:d?/wan[x]?2\.[1-6]/i.test(a)?{img_url:d}:{media:[{type:`first_frame`,url:d}]}:{}},parameters:{resolution:r.resolution||void 0,ratio:r.ratio||void 0,duration:r.duration||void 0,prompt_extend:_,watermark:g,seed:r.seed}};if(t.dryRun){let e=v;if(h)e={...v,input:{...v.input,media:[{type:`file`,url:an(h)}]}};else if(p){let t=an(d??``),n=an(f??``);e={...v,input:{...v.input,...m?{media:[{type:`first_frame`,url:t},{type:`last_frame`,url:n}]}:{first_frame_url:t,last_frame_url:n}}}}else if(d){let t=an(d);e={...v,input:{...v.input,.../wan[x]?2\.[1-6]/i.test(a)?{img_url:t}:{media:[{type:`first_frame`,url:t}]}}}}O({request:e},o);return}let y=lr(r),b=(await yr(y,t,()=>e.client.requestJson({path:p&&!m?ct():Un(),method:`POST`,body:v,async:!0}),`tasks`)).map(e=>e.output.task_id);if(t.quiet||process.stderr.write(`[Model: ${a}]\n`),r.async){O(b.length===1?{task_id:b[0]}:{task_ids:b},o);return}let ee=r.pollInterval??5,x=b.map(n=>{let r=e.client.url(Nn(n));return hr(e.client,t,{url:r,intervalSec:ee,timeoutSec:t.timeout,isComplete:e=>e.output.task_status===`SUCCEEDED`,isFailed:e=>e.output.task_status===`FAILED`,getStatus:e=>e.output.task_status,getErrorMessage:e=>{let t=e.output;return t.message||t.code||void 0}})}),te=await Promise.all(x),ne=[];for(let e=0;e<te.length;e++){let t=te[e],n=t.output.video_url||t.output.results&&t.output.results[0]?.url;n&&ne.push({taskId:b[e],videoUrl:n})}if(ne.length===0)throw new n(`All tasks completed but no video URLs returned.`,l.GENERAL);if(r.download){let e=r.download,{size:n}=await nr(ne[0].videoUrl,e,{quiet:t.quiet});t.quiet?D(e):O({task_id:ne[0].taskId,video_url:ne[0].videoUrl,status:`SUCCEEDED`,saved:e,size:sr(n)},o);return}let re=pn(t,{subDir:`videos`}),{join:ie}=await import(`path`),ae=[];await Promise.all(ne.map(async({taskId:e,videoUrl:n})=>{let r=ie(re,`${e}.mp4`);await nr(n,r,{quiet:t.quiet}),ae.push({task_id:e,video_url:n,saved:r})})),ae.length===1?O(ae[0],o):O({videos:ae,total:ae.length},o)}}),qo=S({description:{"en-US":`Edit a video with happyhorse-1.0-video-edit (style transfer, object replacement, etc.)`,"zh-CN":`使用 happyhorse-1.0-video-edit 编辑视频(风格转换、对象替换等)`},auth:`apiKey`,usageArgs:`--video <url> --prompt <text> [flags]`,flags:{model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model ID (default: happyhorse-1.0-video-edit)`,"zh-CN":`模型 ID(默认:happyhorse-1.0-video-edit)`}},video:{type:`string`,valueHint:`<url>`,description:{"en-US":`Input video URL or local file (mp4/mov, 2-10s)`,"zh-CN":`输入视频 URL 或本地文件(mp4/mov,2–10 秒)`},required:!0},prompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Edit instruction (e.g. "Convert the scene to a claymation style")`,"zh-CN":`编辑指令(例如“将场景转换为黏土动画风格”)`}},refImage:{type:`string`,valueHint:`<url>`,description:{"en-US":`Reference image URL (up to 4, comma-separated)`,"zh-CN":`参考图片 URL(最多 4 个,以逗号分隔)`}},negativePrompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Negative prompt to exclude unwanted content`,"zh-CN":`负向提示词,用于排除不需要的内容`}},resolution:{type:`string`,valueHint:`<res>`,description:{"en-US":`Resolution: 720P or 1080P (default: 1080P)`,"zh-CN":`分辨率:720P 或 1080P(默认:1080P)`}},ratio:{type:`string`,valueHint:`<ratio>`,description:{"en-US":`Aspect ratio (16:9, 9:16, 1:1, 4:3, 3:4)`,"zh-CN":`宽高比(16:9、9:16、1:1、4:3、3:4)`}},duration:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Output video duration in seconds (2-10)`,"zh-CN":`输出视频时长,单位为秒(2–10)`}},audioSetting:{type:`string`,valueHint:`<mode>`,description:{"en-US":`Audio: auto (default) or origin (keep original)`,"zh-CN":`音频:auto(默认)或 origin(保留原音频)`},choices:[`auto`,`origin`]},promptExtend:{type:`boolean`,valueHint:`<bool>`,description:qn},watermark:{type:`boolean`,valueHint:`<bool>`,description:Xn},seed:{type:`number`,valueHint:`<n>`,description:{"en-US":`Random seed for reproducible generation`,"zh-CN":`用于复现生成结果的随机种子`}},download:{type:`string`,valueHint:`<path>`,description:{"en-US":`Save video to file on completion`,"zh-CN":`完成后将视频保存到文件`}},...t,...r,pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 15)`,"zh-CN":`等待任务时的轮询间隔(默认:15 秒)`}}},exampleArgs:[{"en-US":`--video https://example.com/input.mp4 --prompt "Convert the entire scene to claymation style"`,"zh-CN":`--video https://example.com/input.mp4 --prompt "将整个场景转换为黏土动画风格"`},{"en-US":`--video https://example.com/input.mp4 --prompt "Replace the outfit with the style shown in the image" --ref-image https://example.com/clothes.png`,"zh-CN":`--video https://example.com/input.mp4 --prompt "将服装替换为参考图片中的款式" --ref-image https://example.com/clothes.png`},{"en-US":`--video https://example.com/input.mp4 --prompt "Convert to anime style" --resolution 720P --download output.mp4`,"zh-CN":`--video https://example.com/input.mp4 --prompt "转换为动漫风格" --resolution 720P --download output.mp4`},{"en-US":`--video https://example.com/input.mp4 --prompt "Put clothes on the kitten in the video" --watermark false`,"zh-CN":`--video https://example.com/input.mp4 --prompt "给视频中的小猫穿上衣服" --watermark false`}],async run(e){let{settings:t,flags:r}=e,i=r.video,a=r.prompt,o=r.model||`happyhorse-1.0-video-edit`,s=C(t.output),c=[{type:`video`,url:await e.client.uploadFile(i,o)}],u=r.refImage;if(u){let t=u.split(`,`).map(e=>e.trim()).filter(Boolean);for(let n of t){let t=await e.client.uploadFile(n,o);c.push({type:`reference_image`,url:t})}}let d=un(r.promptExtend,void 0,`prompt-extend`),f=mn(r.watermark,t.watermark),p={model:o,input:{prompt:a||void 0,negative_prompt:r.negativePrompt||void 0,media:c},parameters:{resolution:r.resolution||void 0,ratio:r.ratio||void 0,duration:r.duration||void 0,audio_setting:r.audioSetting||void 0,prompt_extend:d,watermark:f,seed:r.seed}};if(t.dryRun){O({request:p},s);return}let m=lr(r),h=(await yr(m,t,()=>e.client.requestJson({path:Un(),method:`POST`,body:p,async:!0}),`tasks`)).map(e=>e.output.task_id);if(t.quiet||(process.stderr.write(`[Model: ${o}]\n`),process.stderr.write(`Note: Video editing typically takes 5-8 minutes. Please be patient.
|
|
25
|
-
`)),r.async){O(h.length===1?{task_id:h[0]}:{task_ids:h},s);return}let g=r.pollInterval??15,_=Math.max(t.timeout,600),v=await Promise.all(h.map(n=>
|
|
26
|
-
`)),r.async){O(y.length===1?{task_id:y[0]}:{task_ids:y},d);return}let b=r.pollInterval??15,ee=Math.max(t.timeout,600),x=await Promise.all(y.map(n=>hr(e.client,t,{url:e.client.url(Nn(n)),intervalSec:b,timeoutSec:ee,isComplete:e=>e.output.task_status===`SUCCEEDED`,isFailed:e=>e.output.task_status===`FAILED`,getStatus:e=>e.output.task_status,getErrorMessage:e=>{let t=e.output;return t.message||t.code||void 0}}))),te=[];for(let e=0;e<x.length;e++){let t=x[e],n=t.output.video_url||t.output.results&&t.output.results[0]?.url;n&&te.push({taskId:y[e],videoUrl:n})}if(te.length===0)throw new n(`All tasks completed but no video URLs returned.`,l.GENERAL);if(r.download){let e=r.download,{size:n}=await nr(te[0].videoUrl,e,{quiet:t.quiet});t.quiet?D(e):O({task_id:te[0].taskId,video_url:te[0].videoUrl,status:`SUCCEEDED`,saved:e,size:sr(n)},d);return}let{join:ne}=await import(`path`),re=pn(t,{subDir:`videos`}),ie=[];await Promise.all(te.map(async({taskId:e,videoUrl:n})=>{let r=ne(re,`${e}.mp4`);await nr(n,r,{quiet:t.quiet}),ie.push({task_id:e,video_url:n,saved:r})})),ie.length===1?O(ie[0],d):O({videos:ie,total:ie.length},d)}}),Yo=S({description:{"en-US":`Query async task status`,"zh-CN":`查询异步任务状态`},auth:`apiKey`,usageArgs:`--task-id <id>`,flags:{taskId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Async task ID`,"zh-CN":`异步任务 ID`},required:!0}},exampleArgs:[`--task-id 3b256896-3e70-xxxx-xxxx-xxxxxxxxxxxx`,`--task-id 3b256896-3e70-xxxx --output json`],async run(e){let{settings:t,flags:n}=e,r=n.taskId,i=C(t.output);if(t.dryRun){O({task_id:r},i);return}let a=await e.client.requestJson({path:Nn(r)});if(t.quiet){D(a.output.task_status);return}O(Mn({task_id:a.output.task_id,task_status:a.output.task_status,video_url:a.output.video_url,results:a.output.results,submit_time:a.output.submit_time,scheduled_time:a.output.scheduled_time,end_time:a.output.end_time,code:a.output.code,message:a.output.message,request_id:a.request_id}),i)}}),Xo=S({description:{"en-US":`Download a completed video by task ID`,"zh-CN":`通过任务 ID 下载已完成的视频`},auth:`apiKey`,usageArgs:`--task-id <id> --out <path>`,flags:{taskId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Task ID to download from`,"zh-CN":`要下载的任务 ID`},required:!0},out:{type:`string`,valueHint:`<path>`,description:{"en-US":`Output file path`,"zh-CN":`输出文件路径`},required:!0}},exampleArgs:[`--task-id 3b256896-xxxx --out video.mp4`,`--task-id 3b256896-xxxx --out video.mp4 --quiet`],async run(e){let{settings:t,flags:r}=e,i=r.taskId,a=r.out,o=C(t.output);if(t.dryRun){O({task_id:i,action:`download`,out:a},o);return}let s=await e.client.requestJson({path:Nn(i)});if(s.output.task_status!==`SUCCEEDED`){let e=s.output.task_status,t=s.output.message||s.output.code,r=t?`Task is not complete (status: ${e}): ${t}`:`Task is not complete (status: ${e}).`;throw new n(r,l.GENERAL,e===`FAILED`?void 0:`Wait for the task to complete before downloading.`)}let c=s.output.video_url||s.output.results&&s.output.results[0]?.url;if(!c)throw new n(`No download URL available for this task.`,l.GENERAL);let{size:u}=await nr(c,a,{quiet:t.quiet});if(t.quiet){D(a);return}O({saved:a,size:sr(u)},o)}});const Zo=/* @__PURE__ */ new Set([`.mp4`,`.mov`,`.avi`,`.mkv`,`.webm`,`.flv`,`.wmv`]);function Qo(e){let t=zr(e).toLowerCase().split(`?`)[0];return!!(Zo.has(t)||/\.(mp4|mov|avi|mkv|webm|flv|wmv)(\?|$)/i.test(e))}async function $o(e){return e.startsWith(`data:`)||e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)?e:lt(e)}var es=S({description:{"en-US":`Describe an image or video using Qwen-VL`,"zh-CN":`使用 Qwen-VL 描述图片或视频`},auth:`apiKey`,usageArgs:`--image <path-or-url> [--video <url>] [--prompt <text>]`,flags:{image:{type:`string`,valueHint:`<path-or-url>`,description:{"en-US":`Local image path or URL`,"zh-CN":`本地图片路径或 URL`}},video:{type:`array`,valueHint:`<url>`,description:{"en-US":`Video file URL or local path (mp4/mov/avi/mkv/webm)`,"zh-CN":`视频文件 URL 或本地路径(mp4/mov/avi/mkv/webm)`}},prompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Question about the content (default: auto-detected)`,"zh-CN":`针对内容的问题(默认:自动识别)`}},model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Vision model (default: qwen3-vl-plus)`,"zh-CN":`视觉模型(默认:qwen3-vl-plus)`}}},exampleArgs:[`--image photo.jpg`,{"en-US":`--image https://example.com/photo.jpg --prompt "What breed is this dog?"`,"zh-CN":`--image https://example.com/photo.jpg --prompt "这只狗是什么品种?"`},{"en-US":`--video https://example.com/video.mp4 --prompt "Summarize the video content"`,"zh-CN":`--video https://example.com/video.mp4 --prompt "总结视频内容"`},`--video ./local-video.mp4`,{"en-US":`--image photo.png --prompt "Extract the text" --model qwen3-vl-plus`,"zh-CN":`--image photo.png --prompt "提取文字" --model qwen3-vl-plus`}],validate:e=>!e.image&&!e.video?.length?`Provide --image or --video.`:void 0,async run(e){let{settings:t,flags:r}=e,i=r.image,a=r.video??[],o=r.model||(e.client.usesTokenPlanEndpoint()?t.defaultTextModel:void 0)||`qwen3-vl-plus`;i&&Qo(i)&&(a.push(i),i=void 0);let s=a.length>0?`Describe the video.`:`Describe the image.`,c=r.prompt||s,u=C(t.output);if(t.dryRun){O({request:{prompt:c,image:i?an(i):void 0,video:a.length?a.map(an):void 0,model:o}},u);return}let d=[];if(a.length>0)for(let t of a){let r=t;if(pt(t)){if(!jr(t))throw new n(`Video file not found: ${t}`,l.USAGE);r=await e.client.uploadFile(t,o)}d.push({type:`video_url`,video_url:{url:r}})}if(i){let t=await $o(i),n=t;pt(i)&&t.startsWith(`data:`)&&Fr(i).size>5242880&&(n=await e.client.resolveImageInput(i,o)),d.push({type:`image_url`,image_url:{url:n}})}d.push({type:`text`,text:c});let f={model:o,messages:[{role:`user`,content:d}]},p=await e.client.requestJson({path:ge(),method:`POST`,body:f}),m=p.choices?.[0]?.message?.content;if(u!==`text`){O(p,u);return}D(m||``)}});const ts=[`language`,`base_url`,`output`,`output_dir`,`timeout`,`watermark`,`api_key`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`,`default_text_model`,`default_video_model`,`default_image_to_video_model`,`default_reference_to_video_model`,`default_image_model`,`default_speech_model`,`default_speech_recognition_model`,`default_omni_model`,`api_key_capabilities`,`workspace_id`],ns=/* @__PURE__ */ new Set([`api_key`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`]),rs=[`console_site`,`console_region`,`console_switch_agent`,`telemetry`],is=[...ts,...rs],as={language:[...b],output:[`text`,`json`],console_site:[`domestic`,`international`]},os=/* @__PURE__ */ new Set([`telemetry`,`watermark`]),ss={default_text_model:`qwen3.8-max`,default_image_model:`qwen-image-3.0`,default_video_model:`wan3.0-video`,default_image_to_video_model:`wan3.0-video`,default_reference_to_video_model:`wan3.0-video`,default_speech_model:`cosyvoice-v3-flash`,default_speech_recognition_model:`fun-asr`,default_omni_model:`qwen3.5-omni-plus`},cs={default_text_model:[{id:`qwen3.8-max`,role:`text/chat default`},{id:`qwen3-coder-plus`,role:`coding-oriented (agent config)`},{id:`qwen-flash`,role:`fast · advisor ranking`},{id:`qwen3.6-flash`,role:`fast · advisor intent`}],default_image_model:[{id:`qwen-image-3.0`,role:`image/generate default · sync`},{id:`qwen-image-2.0`,role:`image/generate · sync`},{id:`qwen-image-max`,role:`image/generate · sync`},{id:`qwen-image-edit-2.0`,role:`image/edit · sync`},{id:`wanx2.x`,role:`image/generate · async series`}],default_video_model:[{id:`wan3.0-video`,role:`video/generate · t2v / i2v / r2v default`},{id:`happyhorse-1.1-t2v`,role:`video/generate · text-to-video`},{id:`happyhorse-1.1-i2v`,role:`video/generate · image-to-video`},{id:`happyhorse-1.1-r2v`,role:`video/ref · reference-to-video`}],default_image_to_video_model:[{id:`wan3.0-video`,role:`video/generate default · image-to-video`},{id:`happyhorse-1.1-i2v`,role:`video/generate · image-to-video`}],default_reference_to_video_model:[{id:`wan3.0-video`,role:`video/ref default · reference-to-video`},{id:`happyhorse-1.1-r2v`,role:`video/ref · reference-to-video`}],default_speech_model:[{id:`cosyvoice-v3-flash`,role:`speech/synthesize (TTS) default`},{id:`qwen-audio-3.0-tts-plus`,role:`Token Plan speech/synthesize (TTS)`}],default_speech_recognition_model:[{id:`fun-asr`,role:`speech/recognize (ASR) default`},{id:`qwen-audio-3.0-asr-flash`,role:`Token Plan speech/recognize (ASR)`}],default_omni_model:[{id:`qwen3.5-omni-plus`,role:`omni/chat default`},{id:`qwen3-vl-plus`,role:`vision/describe · multimodal input`}]},ls={"base-url":`base_url`,"output-dir":`output_dir`,"api-key":`api_key`,"access-token":`access_token`,"access-key-id":`access_key_id`,"access-key-secret":`access_key_secret`,"security-token":`security_token`,"default-text-model":`default_text_model`,"default-video-model":`default_video_model`,"default-image-to-video-model":`default_image_to_video_model`,"default-reference-to-video-model":`default_reference_to_video_model`,"default-image-model":`default_image_model`,"default-speech-model":`default_speech_model`,"default-speech-recognition-model":`default_speech_recognition_model`,"default-omni-model":`default_omni_model`,"api-key-capabilities":`api_key_capabilities`,"workspace-id":`workspace_id`};function us(e){return ls[e]||e}function ds(e,t){let r=us(e);if(!ts.includes(r))throw new n(`Invalid config key "${e}". Valid keys: ${ts.join(`, `)}`,l.USAGE);if(r===`language`&&!b.includes(t))throw new n(`Invalid language "${t}". Valid values: ${b.join(`, `)}`,l.USAGE);if(r===`output`&&![`text`,`json`].includes(t))throw new n(`Invalid output format "${t}". Valid values: text, json`,l.USAGE);if(r===`timeout`){let e=Number(t);if(isNaN(e)||e<=0)throw new n(`Invalid timeout "${t}". Must be a positive number.`,l.USAGE);return e}if(r===`base_url`)return Vt(t);if(r===`watermark`)return Ht(t,`watermark`);if(r===`api_key_capabilities`){let e;if(t.trim().startsWith(`[`))try{e=JSON.parse(t)}catch{throw new n(`Invalid API Key capability list "${t}". Use comma-separated values or a JSON array.`,l.USAGE)}else e=t.split(`,`).map(e=>e.trim());if(!Array.isArray(e))throw new n(`Invalid API Key capability list. Expected an array.`,l.USAGE);let r=[];for(let t of e){if(typeof t!=`string`||!dt(t.trim()))throw new n(`Invalid API Key capability "${String(t)}".`,l.USAGE,`Use lowercase alphanumeric segments separated by '.' or '-'.`);let e=t.trim();r.includes(e)||r.push(e)}return r}return t}function fs(e,t){let r=us(e);if(ts.includes(r))return ds(e,t);if(r===`console_site`){if(![`domestic`,`international`].includes(t))throw new n(`Invalid console_site "${t}". Valid values: domestic, international`,l.USAGE);return t}if(r===`console_region`)return t;if(r===`console_switch_agent`){let e=Number(t);if(!Number.isFinite(e)||e<=0)throw new n(`Invalid console_switch_agent "${t}". Must be a positive number.`,l.USAGE);return e}if(r===`telemetry`){if(t!==`true`&&t!==`false`)throw new n(`Invalid telemetry "${t}". Valid values: true, false`,l.USAGE);return t===`true`}throw new n(`Invalid config key "${e}". Valid keys: ${is.join(`, `)}`,l.USAGE)}var ps=S({description:{"en-US":`Display current configuration`,"zh-CN":`显示当前配置`},auth:`none`,exampleArgs:[``,`--output json`],async run(e){let{settings:t,client:n}=e,r=e.configStore,i=r.read(),a=C(t.output),s={...i,language:i.language??o,base_url:n.baseUrl,output:t.output,timeout:t.timeout,watermark:t.watermark,config:t.configName??`default`,config_file:r.path};for(let e of ns)typeof s[e]==`string`&&(s[e]=At(s[e]));O(s,a)}}),ms=S({description:{"en-US":`Set a config value`,"zh-CN":`设置配置项`},auth:`none`,usageArgs:`--key <key> --value <value>`,flags:{key:{type:`string`,valueHint:`<key>`,description:{"en-US":`Config key (language, base_url, output, output_dir, timeout, watermark, api_key, api_key_capabilities, access_token, access_key_id, access_key_secret, security_token, default_*_model, workspace_id)`,"zh-CN":`配置项名称(language、base_url、output、output_dir、timeout、watermark、api_key、api_key_capabilities、access_token、access_key_id、access_key_secret、security_token、default_*_model、workspace_id)`},required:!0},value:{type:`string`,valueHint:`<value>`,description:{"en-US":`Value to set`,"zh-CN":`要设置的值`},required:!0}},exampleArgs:[`--key language --value zh-CN`,`--key output --value json`,`--key timeout --value 600`,`--key watermark --value false`,`--key base_url --value https://dashscope.aliyuncs.com`,`--config company-plan --key api-key-capabilities --value text.chat,image.generate`],async run(e){let{settings:t,flags:n}=e,r=n.key,i=n.value,a=us(r),o=ds(r,i),s=C(t.output);if(t.dryRun){O({would_set:{[a]:o},config:t.configName??`default`,config_file:e.configStore.path},s);return}if(await e.configStore.write({[a]:o}),!t.quiet){let n=ns.has(a)?At(String(o)):o;O({[a]:n,config:t.configName??`default`,config_file:e.configStore.path},s)}}}),hs=S({description:{"en-US":`List config profiles and show the active profile`,"zh-CN":`列出配置 Profile 并显示当前激活项`},auth:`none`,exampleArgs:[``,`--output json`],async run(e){let t=e.configStore.profiles(),n=[`default`,...Object.keys(t.named).sort()],r=C(e.settings.output);if(r===`json`){O({active_config:t.active,profiles:n,config_file:e.configStore.path},r);return}let i=Math.max(4,...n.map(e=>e.length));D(`${`NAME`.padEnd(i)} ACTIVE`);for(let e of n)D(`${e.padEnd(i)} ${e===t.active?`*`:``}`)}}),gs=S({description:{"en-US":`Set the active config profile`,"zh-CN":`设置当前激活的配置 Profile`},auth:`none`,usageArgs:`--name <name>`,flags:{name:{type:`string`,valueHint:`<name>`,description:{"en-US":`Existing profile name, or default`,"zh-CN":`已有 Profile 名称,或 default`},required:!0}},exampleArgs:[`--name token-plan`,`--name default`],async run(e){let t=C(e.settings.output);if(e.settings.dryRun){let n=e.configStore.validateActivation(e.flags.name);O({would_activate:n,config_file:e.configStore.path},t);return}let n=await e.configStore.activate(e.flags.name);e.settings.quiet||O({active_config:n,config_file:e.configStore.path},t)}});const _s=[[`Config - Alibaba Cloud Model Studio CLI`,`配置 - 阿里云百炼 CLI`],[`The login was not completed in time. Click "Log in" to try again.`,`登录未能及时完成。请点击“登录”重试。`],[`No connected agent can accept tasks yet. Install and connect qwen-code (or another supported agent) first, and make sure its CLI is on your PATH.`,`当前没有可接收任务的已连接 Agent。请先安装并连接 qwen-code(或其他受支持的 Agent),并确保其 CLI 位于 PATH 中。`],[`Complete a few steps to check your local environment and finish first-time setup: sign in to Bailian, connect a local coding agent, and run your first task. Each circle turns from gray to green as you go.`,`完成以下步骤以检查本地环境并完成首次配置:登录百炼、连接本地编程 Agent,并运行第一个任务。完成后,每个圆点会由灰色变为绿色。`],[`Pick a scenario to dispatch a preset task to a connected local coding agent, running in a new terminal. Tasks run in the directory where <code style="font-family:var(--mono)">bl config ui</code> was started.`,`选择一个场景,将预设任务发送给已连接的本地编程 Agent,并在新终端中运行。任务会在启动 <code style="font-family:var(--mono)">bl config ui</code> 的目录中执行。`],[`Pick a scenario to dispatch a preset task to a connected local coding agent, running in a new terminal. Tasks run in the directory where `,`选择一个场景,将预设任务发送给已连接的本地编程 Agent,并在新终端中运行。任务会在启动 `],[` was started.`,` 的目录中执行。`],[`Credentials and default models. The active profile (marked with a star) is used by every bl command. Click a profile to edit its settings.`,`管理凭证和默认模型。所有 bl 命令都会使用带星标的已激活 Profile。点击 Profile 可编辑其设置。`],[`Agent skills discovered across every local agent module (~/.agents/skills plus each agent's skills folder). Installed via <code style="font-family:var(--mono)">npx skills add</code>.`,`展示从本地各 Agent 模块中发现的 Skill(~/.agents/skills 以及各 Agent 的 skills 目录),可通过 <code style="font-family:var(--mono)">npx skills add</code> 安装。`],[`Agent skills discovered across every local agent module (~/.agents/skills plus each agent's skills folder). Installed via `,`展示从本地各 Agent 模块中发现的 Skill(~/.agents/skills 以及各 Agent 的 skills 目录),可通过 `],[`Media that bl writes into the output directory, grouped by type (images, videos, audio, files) and generation time.`,`bl 写入输出目录的媒体文件,按类型(图片、视频、音频、文件)和生成时间展示。`],[`Frameworks bl can configure. "Connected" means the bailian-cli provider is wired into that agent.`,`bl 可以配置的编程 Agent。"已连接"表示该 Agent 已接入 bailian-cli provider。`],[`Model Context Protocol servers declared in your local coding-agent configs.`,`本地编程 Agent 配置中声明的 Model Context Protocol 服务器。`],[`Create a named profile with its own credentials and default models.`,`创建一个拥有独立凭证和默认模型的命名 Profile。`],[`Inputs become fillable fields when dispatching. Reference each one in the prompt as {{key}}.`,`任务发送时,输入项会显示为可填写字段。请在提示词中使用 {{key}} 引用对应输入。`],[`The .zip must contain a SKILL.md at its root or inside a single top-level folder.`,`.zip 根目录或唯一的顶层目录中必须包含 SKILL.md。`],[`The active profile is used by every bl command.`,`所有 bl 命令都会使用已激活的 Profile。`],[`Delete profile "`,`删除 Profile“`],[`"? This permanently removes its credentials and default models.`,`”?这会永久删除其中的凭证和默认模型。`],[`Delete asset "`,`删除资产“`],[`"? This removes the file from disk.`,`”?这会从磁盘中删除该文件。`],[`MCP servers configured in Claude Code, Codex, Qwen Code or OpenCode will appear here.`,`在 Claude Code、Codex、Qwen Code 或 OpenCode 中配置的 MCP 服务器会显示在这里。`],[`Assets from <code>bl image</code>, <code>bl video</code>, <code>bl speech</code> and <code>bl omni</code> will appear here.`,`通过 <code>bl image</code>、<code>bl video</code>、<code>bl speech</code> 和 <code>bl omni</code> 生成的资产会显示在这里。`],[`Remote agents loaded from a URL will appear here.`,`通过 URL 加载的远程 Agent 会显示在这里。`],[`The CLI for this agent was not found on your PATH — install it before launching`,`未在 PATH 中找到该 Agent 的 CLI,请先安装再启动`],[`Connect this agent to bailian-cli before launching`,`请先将该 Agent 连接到 bailian-cli 再启动`],[`Install this agent before launching`,`请先安装该 Agent 再启动`],[`Open a new terminal and start this agent`,`在新终端中启动该 Agent`],[`Open the config file with the system default app`,`使用系统默认应用打开配置文件`],[`Task sent to `,`任务已发送至 `],[`. Check the newly opened terminal window.`,`。请查看新打开的终端窗口。`],[`Please enter a profile name.`,`请输入 Profile 名称。`],[`Only letters, numbers, - and _ are allowed.`,`仅允许使用字母、数字、- 和 _。`],[`"default" is reserved for the top-level profile.`,`“default”保留用于顶层 Profile。`],[`A profile named "`,`名为“`],[`" already exists.`,`”的 Profile 已存在。`],[`Saved, but activation failed: `,`已保存,但激活失败:`],[`Could not read runtime environment info.`,`无法读取运行环境信息。`],[`Runtime Node <code>`,`运行时 Node <code>`],[`</code> · platform <code>`,`</code> · 平台 <code>`],[`Signed in: `,`已登录:`],[`Connected: `,`已连接:`],[`All agents (~/.agents/skills)`,`所有 Agent(~/.agents/skills)`],[`Optional — folder name (defaults to the archive folder)`,`可选 — 文件夹名称(默认使用压缩包中的文件夹名称)`],[`Skill name (optional)`,`Skill 名称(可选)`],[`Skill package (.zip)`,`Skill 包(.zip)`],[`Please choose a .zip file.`,`请选择 .zip 文件。`],[`Install with <code>npx skills add modelstudioai/cli --all -g</code>`,`使用 <code>npx skills add modelstudioai/cli --all -g</code> 安装`],[`Skill "`,`Skill“`],[`MCP server "`,`MCP 服务器“`],[`" installed (`,`”已安装(`],[` files) to `,` 个文件),位置:`],[`" was updated.`,`”已更新。`],[`" was added to `,`”已添加至 `],[`Remove "`,`移除“`],[`" from `,`”(来源:`],[`? This rewrites the source config file.`,`)?此操作会重写来源配置文件。`],[`Could not delete this server.`,`无法删除该服务器。`],[`Delete MCP server?`,`删除 MCP 服务器?`],[`Config must be a JSON object.`,`配置必须是 JSON 对象。`],[`Invalid JSON: `,`无效的 JSON:`],[`Please enter a server name.`,`请输入服务器名称。`],[`No remote agents yet.`,`暂无远程 Agent。`],[`No agents in this category.`,`该分类下暂无 Agent。`],[`No agents match "`,`没有匹配“`],[`bailian-cli is not wired into this agent yet.`,`该 Agent 尚未连接 bailian-cli。`],[`This agent is not installed yet.`,`该 Agent 尚未安装。`],[`No scenarios in this category.`,`该分类下暂无场景。`],[`No scenarios match "`,`没有匹配“`],[`Click to edit this scenario`,`点击编辑此场景`],[`Dispatch this task to a local agent`,`将此任务发送至本地 Agent`],[`No connected agent available`,`没有可用的已连接 Agent`],[`Please fill in: `,`请填写:`],[`Input key "`,`输入键“`],[`" may only use letters, digits, underscore.`,`”只能使用字母、数字和下划线。`],[`Duplicate input key: `,`输入键重复:`],[`Title is required.`,`标题为必填项。`],[`Prompt template is required.`,`提示词模板为必填项。`],[`No assets match "`,`没有匹配“`],[`Toggle sort by generation time`,`切换生成时间排序`],[`↓ Newest first`,`↓ 最新优先`],[`↑ Oldest first`,`↑ 最早优先`],[`View details — `,`查看详情 — `],[`Available `,`可用的 `],[` models · click to use`,` 模型 · 点击使用`],[`Applies to <code>bl video generate</code> only (text/image-to-video). `,`仅适用于 <code>bl video generate</code>(文生视频/图生视频)。`],[`<code>bl video ref</code> (multi-image) and <code>bl video edit</code> keep their own `,`<code>bl video ref</code>(多图)和 <code>bl video edit</code> 仍使用各自的`],[`fixed models — pass <code>--model</code> to override those per run.`,`固定模型;可在每次运行时通过 <code>--model</code> 覆盖。`],[`No skills match "`,`没有匹配“`],[`No MCP servers match "`,`没有匹配“`],[`Install to`,`安装到`],[`Transport / Source`,`传输方式 / 来源`],[`Target agent config`,`目标 Agent 配置`],[`Server name`,`服务器名称`],[`Quick launch`,`快速启动`],[`Config files`,`配置文件`],[`Environment check`,`环境检查`],[`Edit preset scenario`,`编辑预设场景`],[`Edit scenario`,`编辑场景`],[`Save & Activate`,`保存并激活`],[`Are you sure?`,`确认执行此操作吗?`],[`Save failed`,`保存失败`],[`Create failed`,`创建失败`],[`Install failed`,`安装失败`],[`Launch failed`,`启动失败`],[`Dispatch failed`,`发送失败`],[`Delete failed`,`删除失败`],[`Created`,`已创建`],[`Dispatched`,`已发送`],[`Saved`,`已保存`],[`OK`,`确定`],[`Configuration`,`配置`],[`Settings`,`设置`],[`Status`,`状态`],[`Open`,`打开`],[`Remove`,`移除`],[`Show`,`显示`],[`Hide`,`隐藏`],[`All`,`全部`],[`Images`,`图片`],[`Videos`,`视频`],[`Files`,`文件`],[`Image`,`图片`],[`Video`,`视频`],[`Audio`,`音频`],[`File`,`文件`],[` files`,` 个文件`],[`MCPs`,`MCP 服务`],[`Coding`,`编程`],[`Generated`,`生成的`],[`API key`,`API 密钥`],[`Console gateway`,`控制台网关`],[`Account`,`账户`],[`(empty)`,`(空)`],[` (editable)`,`(可编辑)`],[` (missing)`,`(缺失)`],[`default (top-level)`,`default(顶层)`],[`This source is read-only here (its config is TOML). Edit it directly in `,`该来源在此处为只读(配置格式为 TOML)。请直接编辑:`],[`No connected local coding agent detected (e.g. qwen-code). Open the Agents page to install and connect one.`,`未检测到已连接的本地编程 Agent(例如 qwen-code)。请打开 Agent 页面进行安装和连接。`],[`Installed but not wired into bl: `,`已安装但尚未接入 bl:`],[`. Open the Agents page to finish connecting.`,`。请打开 Agent 页面完成连接。`],[`Finish the previous step first (connect a dispatchable agent), then come back to Playground to run your first scenario.`,`请先完成上一步(连接可接收任务的 Agent),再回到 Playground 运行第一个场景。`],[`Go to Playground, pick a scenario and click Run it to complete your first dispatch.`,`前往 Playground,选择一个场景并点击“运行”,完成首次任务发送。`],[`Sign in to the Bailian console to obtain credentials (opens a login page in your browser).`,`登录百炼控制台以获取凭证(将在浏览器中打开登录页面)。`],[`You have dispatched at least one task.`,`你已经成功发送过至少一个任务。`],[`Node 18 or newer is recommended.`,`建议使用 Node.js 18 或更高版本。`],[`Save & Activate`,`保存并激活`],[`Save scenario`,`保存场景`],[`Custom scenario`,`自定义场景`],[`+ Custom scenario`,`+ 自定义场景`],[`New profile`,`新建 Profile`],[`+ New profile`,`+ 新建 Profile`],[`Profile name`,`Profile 名称`],[`Target agent`,`目标 Agent`],[`Task to dispatch`,`要发送的任务`],[`Prompt template`,`提示词模板`],[`One-line description (optional)`,`一句话描述(可选)`],[`Use {{key}} placeholders for inputs`,`使用 {{key}} 作为输入占位符`],[`e.g. Translate docs to English`,`例如:将文档翻译成英文`],[`e.g. Image / Custom`,`例如:图像 / 自定义`],[`e.g. work, intl, test`,`例如:work、intl、test`],[`Search scenarios…`,`搜索场景…`],[`Search skills…`,`搜索 Skill…`],[`Search MCP servers…`,`搜索 MCP 服务器…`],[`Search agents…`,`搜索 Agent…`],[`Search assets…`,`搜索资产…`],[`Installed Skills`,`已安装的 Skill`],[`Coding Agents`,`编程 Agent`],[`Generated Assets`,`生成资产`],[`Get Started`,`开始使用`],[`Quick Start`,`快速开始`],[`Playground`,`Playground`],[`Extensions`,`扩展`],[`Workspace`,`工作区`],[`Skills`,`Skill`],[`Agents`,`Agent`],[`Assets`,`资产`],[`Config`,`配置`],[`Log in`,`登录`],[`Log out`,`退出登录`],[`Copy this URL`,`复制此链接`],[`QR code for this session URL`,`当前会话链接的二维码`],[`Collapse sidebar`,`收起侧边栏`],[`Expand sidebar`,`展开侧边栏`],[`Model Studio CLI home`,`百炼 CLI 首页`],[`Loading…`,`加载中…`],[`Delete profile`,`删除 Profile`],[`Delete asset`,`删除资产`],[`Open failed`,`打开失败`],[`Open locally`,`在本地打开`],[`View details`,`查看详情`],[`Jump backward 5 pages`,`向前跳转 5 页`],[`Jump forward 5 pages`,`向后跳转 5 页`],[`Items per page`,`每页数量`],[`No generated assets yet.`,`暂无生成资产。`],[`No assets in this category.`,`该分类下暂无资产。`],[`No skills installed.`,`尚未安装 Skill。`],[`No local MCP servers found.`,`未发现本地 MCP 服务器。`],[`No coding agents found.`,`未发现编程 Agent。`],[`No scenarios found.`,`未发现场景。`],[`Failed to load: `,`加载失败:`],[`Load failed: `,`加载失败:`],[`Save failed: `,`保存失败:`],[`Create failed: `,`创建失败:`],[`Install failed: `,`安装失败:`],[`Launch failed: `,`启动失败:`],[`Saving…`,`正在保存…`],[`Saved and activated.`,`已保存并激活。`],[`Saved.`,`已保存。`],[`Profile created and saved.`,`Profile 已创建并保存。`],[`Opening browser…`,`正在打开浏览器…`],[`Waiting for login…`,`等待登录…`],[`Signed in…`,`已登录…`],[`Login timed out`,`登录超时`],[`Authenticated`,`已认证`],[`Connect a local agent`,`连接本地 Agent`],[`Run your first task`,`运行第一个任务`],[`Sign in to Bailian`,`登录百炼`],[`Check local environment`,`检查本地环境`],[`Go to Playground`,`前往 Playground`],[`Go to Agents`,`前往 Agent`],[`Run it`,`运行`],[`Done`,`已完成`],[`Connected`,`已连接`],[`Not installed`,`未安装`],[`Installed`,`已安装`],[`Launching…`,`正在启动…`],[`Launched → `,`已启动 → `],[`Remote`,`远程`],[`Local`,`本地`],[`Add skill`,`添加 Skill`],[`+ Add skill`,`+ 添加 Skill`],[`Choose .zip file`,`选择 .zip 文件`],[`No file selected`,`未选择文件`],[`New MCP server`,`新建 MCP 服务器`],[`+ Add MCP`,`+ 添加 MCP`],[`Description`,`描述`],[`Installed in`,`安装位置`],[`Details`,`详情`],[`Type`,`类型`],[`Path`,`路径`],[`Scope`,`范围`],[`Title`,`标题`],[`Category`,`分类`],[`Inputs`,`输入项`],[`Add input`,`添加输入`],[`Create`,`创建`],[`Install`,`安装`],[`Delete`,`删除`],[`Cancel`,`取消`],[`Close`,`关闭`],[`Active`,`已激活`],[`Save`,`保存`],[`Copy`,`复制`],[`Copied`,`已复制`],[`show`,`显示`],[`hide`,`隐藏`],[`(unset)`,`(未设置)`],[` / page`,` / 页`]];function vs(){return JSON.stringify([..._s].sort(([e],[t])=>t.length-e.length)).replaceAll(`<`,`\\u003c`)}function ys(e,t){return e.replace(`<html lang="en">`,`<html lang="${t}">`).replace(`__BL_CONFIG_UI_LANGUAGE__`,t).replace(`__BL_CONFIG_UI_TRANSLATIONS__`,vs())}function bs(e){return ys(`<!doctype html>
|
|
21
|
+
`),process.stdout.write(`${e(`VOICE ID`,12)} ${e(`NAME`,14)} ${e(`DESCRIPTION`,14)} LANGUAGE\n`),process.stdout.write(`${`-`.repeat(12)} ${`-`.repeat(14)} ${`-`.repeat(14)} ${`-`.repeat(12)}\n`);for(let t of qo)process.stdout.write(`${e(t.voice,12)} ${e(t.name,14)} ${e(t.desc,14)} ${t.lang}\n`);process.stdout.write(`\nTotal: ${qo.length} voices\n`)}const Yo={wav:`wav`,mp3:`mp3`,amr:`amr`,aac:`aac`,m4a:`aac`,ogg:`ogg`,"3gp":`3gp`,"3gpp":`3gpp`},Xo=Object.keys(Yo);function Zo(e){let t=e.split(`?`)[0].split(`#`)[0],r=ei(t).slice(1).toLowerCase();if(!r)throw new n(`Cannot infer audio format from "${e}". Use a file/URL whose path ends with: ${Xo.join(`, `)}.`,l.USAGE);let i=Yo[r];if(!i)throw new n(`Unsupported audio extension ".${r}" for "${e}". Supported extensions: ${Xo.join(`, `)}.`,l.USAGE);return i}function Qo(e){let t=Buffer.alloc(44);return t.write(`RIFF`,0),t.writeUInt32LE(36+e,4),t.write(`WAVE`,8),t.write(`fmt `,12),t.writeUInt32LE(16,16),t.writeUInt16LE(1,20),t.writeUInt16LE(1,22),t.writeUInt32LE(24e3,24),t.writeUInt32LE(48e3,28),t.writeUInt16LE(2,32),t.writeUInt16LE(16,34),t.write(`data`,36),t.writeUInt32LE(e,40),t}var $o=S({description:{"en-US":`Multimodal chat with text + audio output (Qwen-Omni)`,"zh-CN":`支持文本输入与音频输出的多模态对话(Qwen-Omni)`},auth:`apiKey`,usageArgs:`--message <text> [flags]`,flags:{message:{type:`array`,valueHint:`<text>`,description:{"en-US":`Message text (repeatable, prefix role: to set role)`,"zh-CN":`消息文本(可重复;可使用 role: 前缀指定角色)`}},model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model ID (default: qwen3.5-omni-plus)`,"zh-CN":`模型 ID(默认:qwen3.5-omni-plus)`}},system:{type:`string`,valueHint:`<text>`,description:{"en-US":`System prompt`,"zh-CN":`系统提示词`}},image:{type:`array`,valueHint:`<url>`,description:{"en-US":`Image URL or local file (repeatable)`,"zh-CN":`图片 URL 或本地文件(可重复)`}},audio:{type:`array`,valueHint:`<url>`,description:{"en-US":`Audio URL or local file (.wav/.mp3/.amr/.aac/.m4a/.ogg/.3gp/.3gpp)`,"zh-CN":`音频 URL 或本地文件(.wav/.mp3/.amr/.aac/.m4a/.ogg/.3gp/.3gpp)`}},video:{type:`array`,valueHint:`<url>`,description:{"en-US":`Video file URL / local path, or comma-separated frame URLs`,"zh-CN":`视频文件 URL / 本地路径,或以逗号分隔的帧 URL`}},voice:{type:`string`,valueHint:`<voice>`,description:{"en-US":`Output voice ID (default: Tina). Use --list-voices to see all options`,"zh-CN":`输出音色 ID(默认:Tina)。使用 --list-voices 查看所有选项`}},listVoices:{type:`switch`,description:{"en-US":`List available output voices and exit`,"zh-CN":`列出可用的输出音色并退出`}},audioFormat:{type:`string`,valueHint:`<fmt>`,description:{"en-US":`Audio output format (default: wav)`,"zh-CN":`音频输出格式(默认:wav)`}},audioOut:{type:`string`,valueHint:`<path>`,description:{"en-US":`Save audio to file (default: auto-generate)`,"zh-CN":`将音频保存到文件(默认:自动生成路径)`}},textOnly:{type:`switch`,description:{"en-US":`Output text only, no audio generation`,"zh-CN":`仅输出文本,不生成音频`}},maxTokens:{type:`number`,valueHint:`<n>`,description:{"en-US":`Maximum tokens to generate`,"zh-CN":`最大生成 Token 数`}},temperature:{type:`number`,valueHint:`<n>`,description:{"en-US":`Sampling temperature (0.0, 2.0]`,"zh-CN":`采样温度 (0.0, 2.0]`}}},exampleArgs:[`--list-voices`,{"en-US":`--message "Hello, who are you?"`,"zh-CN":`--message "你好,你是谁?"`},{"en-US":`--message "Describe this image" --image ./photo.jpg`,"zh-CN":`--message "描述这张图片" --image ./photo.jpg`},{"en-US":`--message "What is this audio saying?" --audio https://example.com/audio.wav`,"zh-CN":`--message "这段音频说了什么?" --audio https://example.com/audio.wav`},{"en-US":`--message "Summarize this video" --video https://example.com/video.mp4`,"zh-CN":`--message "总结这段视频" --video https://example.com/video.mp4`},{"en-US":`--message "What is this video about?" --video ./local-video.mp4 --text-only`,"zh-CN":`--message "这段视频讲了什么?" --video ./local-video.mp4 --text-only`},{"en-US":`--message "Answer in Sichuan dialect: How's the weather today?" --voice Sunny`,"zh-CN":`--message "请用四川话回答:今天天气怎么样?" --voice Sunny`},{"en-US":`--message "Hello" --text-only --output json`,"zh-CN":`--message "你好" --text-only --output json`},{"en-US":`--message "Read this passage aloud" --audio-out greeting.wav`,"zh-CN":`--message "朗读这段文字" --audio-out greeting.wav`}],validate:e=>e.listVoices||e.message?void 0:`Missing required flag: --message`,async run(e){let{settings:t,flags:n}=e;if(n.listVoices){Jo();return}let r=n.message??[],i=n.model||t.defaultOmniModel||`qwen3.5-omni-plus`,a=n.voice||`Tina`,o=n.audioFormat||`wav`,s=n.textOnly===!0,c=C(t.output),l=[];n.system&&l.push({role:`system`,content:n.system});let u=/* @__PURE__ */ new Set([`system`,`user`,`assistant`]);for(let e of r){let t=e.indexOf(`:`),n=t===-1?``:e.slice(0,t);if(u.has(n)){let r=e.slice(t+1);n===`system`?l.push({role:`system`,content:r}):l.push({role:n,content:r})}else l.push({role:`user`,content:e})}let d=n.image||[],f=n.audio||[],p=n.video||[],m=[],h=[],g=[];if(d.length>0||f.length>0||p.length>0){for(let t of d){let n=await e.client.uploadFile(t,i);m.push(n)}for(let t of f){let n=await e.client.uploadFile(t,i);h.push({source:t,data:n})}for(let t of p)if(t.includes(`,`)){let n=t.split(`,`).map(e=>e.trim()).filter(Boolean);for(let t of n){let n=await e.client.uploadFile(t,i);g.push(`frame:${n}`)}}else{let n=await e.client.uploadFile(t,i);g.push(n)}}if(m.length>0||h.length>0||g.length>0){for(let e=l.length-1;e>=0;e--)if(l[e].role===`user`){let t=l[e].content,n=[];typeof t==`string`?n.push({type:`text`,text:t}):Array.isArray(t)&&n.push(...t);for(let e of m)n.push({type:`image_url`,image_url:{url:e}});for(let{source:e,data:t}of h)n.push({type:`input_audio`,input_audio:{data:t,format:Zo(e)}});let r=g.filter(e=>e.startsWith(`frame:`)).map(e=>e.slice(6)),i=g.filter(e=>!e.startsWith(`frame:`));r.length>0&&n.push({type:`video`,video:r});for(let e of i)n.push({type:`video_url`,video_url:{url:e}});l[e]={role:`user`,content:n};break}}let _={model:i,messages:l,stream:!0,stream_options:{include_usage:!0}};if(s||(_.modalities=[`text`,`audio`],_.audio={voice:a,format:o}),n.maxTokens!==void 0&&(_.max_tokens=n.maxTokens),n.temperature!==void 0&&(_.temperature=n.temperature),t.dryRun){O({request:_},c);return}if(!t.quiet){let e=s?`text-only`:`text+audio, voice: ${a}`;process.stderr.write(`[Model: ${i}] [${e}]\n`)}let v=await e.client.request({path:ve(),method:`POST`,body:_,stream:!0}),y=``,b=``,ee=process.stdout.isTTY,x=process.stdout;for await(let e of $t(v)){if(e.data===`[DONE]`)break;try{let t=JSON.parse(e.data);for(let e of t.choices){let t=e.delta;t.content&&(y+=t.content,ee&&x.write(t.content)),t.audio?.data&&(b+=t.audio.data)}}catch{}}ee&&y&&x.write(`
|
|
22
|
+
`);let te;if(b&&!s){let e=Buffer.from(b,`base64`),r=Qo(e.length),i=Buffer.concat([r,e]),a=n.audioOut;if(!a){let{join:e}=await import(`path`);a=e(Sn(t,{subDir:`omni`}),`omni_${Date.now()}.wav`)}Zr(a,i),te=a,t.quiet||process.stderr.write(`Audio saved: ${a}\n`)}if(!ee||c===`json`){let e={content:y};te&&(e.audio_saved=te,e.voice=a),O(e,c)}}});const es={prompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Image description`,"zh-CN":`图片描述`},required:!0},model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model ID (default: qwen-image-3.0)`,"zh-CN":`模型 ID(默认:qwen-image-3.0)`}},size:{type:`string`,valueHint:`<W*H>`,description:{"en-US":`Image size: ratio (3:4, 16:9, 1:1) or pixels (2048*2048)`,"zh-CN":`图片尺寸:比例(3:4、16:9、1:1)或像素(2048*2048)`}},n:{type:`number`,valueHint:`<count>`,description:{"en-US":`Number of images per request (default: 1, max: 6)`,"zh-CN":`每次请求生成的图片数量(默认:1,最多:6)`}},seed:{type:`number`,valueHint:`<n>`,description:{"en-US":`Random seed for reproducible generation`,"zh-CN":`用于复现生成结果的随机种子`}},negativePrompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Negative prompt to exclude unwanted content`,"zh-CN":`负向提示词,用于排除不需要的内容`}},promptExtend:{type:`boolean`,valueHint:`<bool>`,description:lr},watermark:{type:`boolean`,valueHint:`<bool>`,description:ur},...t,...r,outDir:{type:`string`,valueHint:`<dir>`,description:{"en-US":`Download images to directory`,"zh-CN":`将图片下载到指定目录`}},outPrefix:{type:`string`,valueHint:`<prefix>`,description:{"en-US":`Filename prefix (default: image)`,"zh-CN":`文件名前缀(默认:image)`}},pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 3)`,"zh-CN":`等待任务时的轮询间隔(默认:3 秒)`}}};var ts=S({description:{"en-US":`Generate images (Qwen-Image / wan2.x)`,"zh-CN":`生成图片(Qwen-Image / wan2.x)`},auth:`apiKey`,usageArgs:`--prompt <text> [flags]`,flags:es,exampleArgs:[{"en-US":`--prompt "A cat in a spacesuit on Mars"`,"zh-CN":`--prompt "一只穿着宇航服的猫站在火星上"`},{"en-US":`--prompt "Logo design" --n 3 --out-dir ./generated/`,"zh-CN":`--prompt "Logo 设计" --n 3 --out-dir ./generated/`},{"en-US":`--prompt "Mountain landscape" --size 2688*1536`,"zh-CN":`--prompt "山地景观" --size 2688*1536`},{"en-US":`--prompt "A castle" --seed 42 --prompt-extend false`,"zh-CN":`--prompt "一座城堡" --seed 42 --prompt-extend false`},{"en-US":`--prompt "Logo" --watermark false`,"zh-CN":`--prompt "Logo" --watermark false`},{"en-US":`--prompt "An alien in the space" --watermark false`,"zh-CN":`--prompt "太空中的外星人" --watermark false`},{"en-US":`--prompt "sunset" --model wan2.6-t2i --async --quiet`,"zh-CN":`--prompt "日落" --model wan2.6-t2i --async --quiet`},{"en-US":`--prompt "plush doll" --model z-image-turbo --size 1024*1024`,"zh-CN":`--prompt "毛绒玩偶" --model z-image-turbo --size 1024*1024`},{"en-US":`--prompt "sunset" --model wanx2.0-t2i-turbo --size 1024*1024`,"zh-CN":`--prompt "日落" --model wanx2.0-t2i-turbo --size 1024*1024`},{"en-US":`--prompt "Pro quality" --model qwen-image-2.0-pro`,"zh-CN":`--prompt "专业品质" --model qwen-image-2.0-pro`},{"en-US":`--prompt "Product shots" --n 2 --concurrent 3 # 6 images in parallel`,"zh-CN":`--prompt "产品摄影" --n 2 --concurrent 3 # 并行生成 6 张图片`}],async run(e){let{settings:t,flags:n}=e,r=n.prompt,i=n.model||t.defaultImageModel||`qwen-image-3.0`,a=xn(i),o=n.size||`1:1`,s=Nr(o,a.sizeProfile),c=n.n??1,l=Cr(n),u=yn(n.promptExtend,a.promptExtendDefault,`prompt-extend`),d=Cn(n.watermark,t.watermark),f={size:s,n:c,seed:n.seed,prompt_extend:u,watermark:d},p=a.inputStyle===`prompt`?{model:i,input:{prompt:r,negative_prompt:n.negativePrompt||void 0},parameters:f}:{model:i,input:{messages:[{role:`user`,content:[{text:r}]}]},parameters:{...f,negative_prompt:n.negativePrompt||void 0}},m=C(t.output);if(t.dryRun){O({request:p,mode:a.useSync?`sync`:`async`,path:a.path},m);return}t.quiet||process.stderr.write(`[Model: ${i}] [Mode: ${a.useSync?`sync`:`async`}]\n`),a.useSync?await ns(e.client,t,a.path,p,n,m,l):await rs(e.client,t,a.path,p,n,m,l)}});async function ns(e,t,r,i,a,o,s){let c=(await Pr(s,t,()=>e.requestJson({path:r,method:`POST`,body:i}))).flatMap(e=>e.output.choices||[]).flatMap(e=>e.message?.content||[]).map(e=>e.image).filter(Boolean);if(c.length===0)throw new n(`Generation completed but no images returned.`,l.GENERAL);await is(c,a,t,o)}async function rs(e,t,r,i,a,o,s){let c=(await Pr(s,t,()=>e.requestJson({path:r,method:`POST`,body:i,async:!0}),`tasks`)).map(e=>e.output.task_id);if(a.async){O({task_ids:c},o);return}let u=a.pollInterval??3,d=c.map(n=>{let r=e.url(Un(n));return kr(e,t,{url:r,intervalSec:u,timeoutSec:t.timeout,isComplete:e=>e.output.task_status===`SUCCEEDED`,isFailed:e=>e.output.task_status===`FAILED`,getStatus:e=>e.output.task_status,getErrorMessage:e=>{let t=e.output;return t.message||t.code||void 0}})}),f=await Promise.all(d),p=[];for(let e of f){if(e.output.choices){let t=e.output.choices.flatMap(e=>e.message?.content||[]).map(e=>e.image).filter(Boolean);p.push(...t)}if(e.output.results){let t=e.output.results.map(e=>e.url).filter(Boolean);t.length>0&&p.length===0&&p.push(...t)}}if(p.length===0)throw new n(`All tasks completed but no images returned.`,l.GENERAL);await is(p,a,t,o,c.length===1?c[0]:void 0,c)}async function is(e,t,n,r,i,a){let o=Sn(n,{flagDir:t.outDir,subDir:t.outDir?void 0:`images`}),s=t.prompt||``,c=t.outPrefix||$e(`image`,s),l=e.length>1?e.map((e,t)=>{let n=`${c}_${String(t+1).padStart(3,`0`)}.png`;return{url:e,destPath:ti(o,n)}}):[{url:e[0],destPath:ti(o,`${c}.png`)}],u=await _r(l,gr,{quiet:n.quiet});if(n.quiet)D(u.join(`
|
|
23
|
+
`));else{let t={urls:e,saved:u,total:e.length};i&&(t.task_id=i),a&&a.length>1&&(t.task_ids=a),O(t,r)}}const as={image:{type:`array`,valueHint:`<url>`,description:{"en-US":`Source image URL or local file path (repeatable for multi-image merge)`,"zh-CN":`源图片 URL 或本地文件路径(多图融合时可重复)`},required:!0},prompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Edit instruction text`,"zh-CN":`编辑指令文本`},required:!0},model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model ID (default: qwen-image-3.0)`,"zh-CN":`模型 ID(默认:qwen-image-3.0)`}},size:{type:`string`,valueHint:`<W*H>`,description:{"en-US":`Output image size: ratio (3:4, 16:9) or pixels (2048*2048)`,"zh-CN":`输出图片尺寸:比例(3:4、16:9)或像素(2048*2048)`}},n:{type:`number`,valueHint:`<count>`,description:{"en-US":`Number of images (default: 1, max: 6)`,"zh-CN":`图片数量(默认:1,最多:6)`}},seed:{type:`number`,valueHint:`<n>`,description:{"en-US":`Random seed for reproducible results`,"zh-CN":`用于复现结果的随机种子`}},negativePrompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Negative prompt to exclude unwanted content`,"zh-CN":`负向提示词,用于排除不需要的内容`}},function:{type:`string`,valueHint:`<name>`,description:{"en-US":`wanx*-imageedit function (default: description_edit). Examples: stylization_all, description_edit`,"zh-CN":`wanx*-imageedit 功能(默认:description_edit)。例如:stylization_all、description_edit`}},promptExtend:{type:`boolean`,valueHint:`<bool>`,description:cr},watermark:{type:`boolean`,valueHint:`<bool>`,description:ur},outDir:{type:`string`,valueHint:`<dir>`,description:{"en-US":`Download images to directory`,"zh-CN":`将图片下载到指定目录`}},outPrefix:{type:`string`,valueHint:`<prefix>`,description:{"en-US":`Filename prefix (default: edited)`,"zh-CN":`文件名前缀(默认:edited)`}},...t,...r,pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 3)`,"zh-CN":`等待任务时的轮询间隔(默认:3 秒)`}}};var os=S({description:{"en-US":`Edit an existing image with text instructions (Qwen-Image / Wan 2.7)`,"zh-CN":`使用文本指令编辑现有图片(Qwen-Image / Wan 2.7)`},auth:`apiKey`,usageArgs:`--image <url> --prompt <text> [flags]`,flags:as,exampleArgs:[{"en-US":`--image ./photo.png --prompt "Replace the background with a beach"`,"zh-CN":`--image ./photo.png --prompt "将背景替换为海滩"`},{"en-US":`--image https://example.com/logo.png --prompt "Change color to blue" --n 3`,"zh-CN":`--image https://example.com/logo.png --prompt "将颜色改为蓝色" --n 3`},{"en-US":`--image ./a.png --image ./b.png --prompt "Merge two images into one collage"`,"zh-CN":`--image ./a.png --image ./b.png --prompt "将两张图片合并成一张拼贴图"`},{"en-US":`--image https://example.com/photo.png --prompt "Remove the person" --model qwen-image-2.0-pro`,"zh-CN":`--image https://example.com/photo.png --prompt "移除人物" --model qwen-image-2.0-pro`},{"en-US":`--image ./photo.png --prompt "Change the style" --model wan2.7-image`,"zh-CN":`--image ./photo.png --prompt "更改图片风格" --model wan2.7-image`},{"en-US":`--image ./photo.png --prompt "Place the subject on a table" --model wan2.5-i2i-preview`,"zh-CN":`--image ./photo.png --prompt "将主体放在桌面上" --model wan2.5-i2i-preview`},{"en-US":`--image ./photo.png --prompt "Convert to a picture-book style" --model wanx2.1-imageedit --function stylization_all`,"zh-CN":`--image ./photo.png --prompt "转换成绘本风格" --model wanx2.1-imageedit --function stylization_all`},{"en-US":`--image ./photo.png --prompt "Replace the background with a beach" --watermark false`,"zh-CN":`--image ./photo.png --prompt "将背景替换为海滩" --watermark false`}],async run(e){let{settings:t,flags:r}=e,i=[];Array.isArray(r.image)?i=r.image:typeof r.image==`string`&&(i=[r.image]);let a=r.prompt,o=r.model||t.defaultImageModel||`qwen-image-3.0`,s=bn(o),c=await Promise.all(i.map(t=>e.client.resolveImageInput(t,o))),u=r.n??1,d=yn(r.promptExtend,s.promptExtendDefault,`prompt-extend`),f=Cn(r.watermark,t.watermark),p={size:Nr(r.size,s.sizeProfile),n:u,seed:r.seed,prompt_extend:d,watermark:f},m;if(s.inputStyle===`function-base-image`){let e=c[0];if(!e)throw new n(`wanx*-imageedit requires at least one --image as base_image_url.`,l.USAGE);m={model:o,input:{function:r.function||`description_edit`,prompt:a,base_image_url:e},parameters:p}}else if(s.inputStyle===`prompt-images`)m={model:o,input:{prompt:a,images:c,negative_prompt:r.negativePrompt||void 0},parameters:p};else{let e=c.map(e=>({image:e}));e.push({text:a}),m={model:o,input:{messages:[{role:`user`,content:e}]},parameters:{...p,negative_prompt:r.negativePrompt||void 0}}}Hn(m.parameters);let h=C(t.output);if(t.dryRun){let e=m;`messages`in m.input?e={...m,input:{messages:m.input.messages.map(e=>({...e,content:e.content.map(e=>e.image?{...e,image:pn(e.image)}:e)}))}}:`images`in m.input?e={...m,input:{...m.input,images:m.input.images?.map(e=>pn(e))}}:`base_image_url`in m.input&&(e={...m,input:{...m.input,base_image_url:pn(m.input.base_image_url),mask_image_url:m.input.mask_image_url?pn(m.input.mask_image_url):void 0}}),O({request:e,mode:s.useSync?`sync`:`async`,path:s.path},h);return}t.quiet||process.stderr.write(`[Model: ${o}] [Mode: ${s.useSync?`sync`:`async`}] [Images: ${c.length}]\n`);let g=Cr(r);s.useSync?await ss(e.client,t,s.path,m,r,h,g):await cs(e.client,t,s.path,m,r,h,g)}});async function ss(e,t,r,i,a,o,s){let c=(await Pr(s,t,()=>e.requestJson({path:r,method:`POST`,body:i}))).flatMap(e=>e.output.choices||[]).flatMap(e=>e.message?.content||[]).map(e=>e.image).filter(Boolean);if(c.length===0)throw new n(`Edit completed but no images returned.`,l.GENERAL);await ls(c,a,t,o)}async function cs(e,t,r,i,a,o,s){let c=(await Pr(s,t,()=>e.requestJson({path:r,method:`POST`,body:i,async:!0}),`tasks`)).map(e=>e.output.task_id);if(a.async){O({task_ids:c},o);return}let u=a.pollInterval??3,d=c.map(n=>kr(e,t,{url:e.url(Un(n)),intervalSec:u,timeoutSec:t.timeout,isComplete:e=>e.output.task_status===`SUCCEEDED`,isFailed:e=>e.output.task_status===`FAILED`,getStatus:e=>e.output.task_status,getErrorMessage:e=>{let t=e.output;return t.message||t.code||void 0}})),f=await Promise.all(d),p=[];for(let e of f){if(e.output.choices){let t=e.output.choices.flatMap(e=>e.message?.content||[]).map(e=>e.image).filter(Boolean);p.push(...t)}if(e.output.results){let t=e.output.results.map(e=>e.url).filter(Boolean);t.length>0&&p.length===0&&p.push(...t)}}if(p.length===0)throw new n(`All tasks completed but no images returned.`,l.GENERAL);await ls(p,a,t,o)}async function ls(e,t,n,r){let i=Sn(n,{flagDir:t.outDir,subDir:t.outDir?void 0:`images`}),a=t.outPrefix||$e(`edited`,t.prompt),o=e.length>1?e.map((e,t)=>{let n=`${a}_${String(t+1).padStart(3,`0`)}.png`;return{url:e,destPath:ti(i,n)}}):[{url:e[0],destPath:ti(i,`${a}.png`)}],s=await _r(o,gr,{quiet:n.quiet});n.quiet?D(s.join(`
|
|
24
|
+
`)):O({urls:e,saved:s,total:e.length},r)}var us=S({description:{"en-US":`Generate a video from text or image (wan3.0-video / wan2.6-t2v / happyhorse-1.1-i2v)`,"zh-CN":`根据文本或图片生成视频(wan3.0-video / wan2.6-t2v / happyhorse-1.1-i2v)`},auth:`apiKey`,usageArgs:`--prompt <text> [--image <url>] [flags]`,flags:{model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model ID (default: wan3.0-video)`,"zh-CN":`模型 ID(默认:wan3.0-video)`}},prompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Video description`,"zh-CN":`视频描述`},required:!0},image:{type:`string`,valueHint:`<url>`,description:{"en-US":`Input image URL for image-to-video generation`,"zh-CN":`图生视频使用的输入图片 URL`}},lastFrame:{type:`string`,valueHint:`<url>`,description:{"en-US":`Last frame image URL (with --image, enables kf2v first+last frame mode)`,"zh-CN":`尾帧图片 URL(与 --image 配合,启用 kf2v 首尾帧模式)`}},negativePrompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Negative prompt to exclude unwanted content`,"zh-CN":`负向提示词,用于排除不需要的内容`}},resolution:{type:`string`,valueHint:`<res>`,description:{"en-US":`Resolution: 720P or 1080P (default: 1080P)`,"zh-CN":`分辨率:720P 或 1080P(默认:1080P)`}},ratio:{type:`string`,valueHint:`<ratio>`,description:{"en-US":`Aspect ratio (e.g. 16:9, 9:16, 1:1)`,"zh-CN":`宽高比(例如 16:9、9:16、1:1)`}},duration:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Video duration in seconds (default: 5)`,"zh-CN":`视频时长,单位为秒(默认:5)`}},promptExtend:{type:`boolean`,valueHint:`<bool>`,description:sr},watermark:{type:`boolean`,valueHint:`<bool>`,description:ur},seed:{type:`number`,valueHint:`<n>`,description:{"en-US":`Random seed for reproducible generation`,"zh-CN":`用于复现生成结果的随机种子`}},download:{type:`string`,valueHint:`<path>`,description:{"en-US":`Save video to file on completion`,"zh-CN":`完成后将视频保存到文件`}},file:{type:`string`,valueHint:`<url-or-path>`,description:{"en-US":`Reference file URL or local path for file-to-video (wan3.0-video only; mutually exclusive with --image/--last-frame)`,"zh-CN":`参考文件 URL 或本地路径,用于文件生视频(仅 wan3.0-video;与 --image/--last-frame 互斥)`}},...Vo,...t,...r,pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 5)`,"zh-CN":`等待任务时的轮询间隔(默认:5 秒)`}}},exampleArgs:[{"en-US":`--prompt "A person reading a book, static shot"`,"zh-CN":`--prompt "一个人正在读书,固定镜头"`},{"en-US":`--prompt "Ocean waves at sunset." --download sunset.mp4`,"zh-CN":`--prompt "日落时的海浪。" --download sunset.mp4`},{"en-US":`--image https://example.com/cat.png --prompt "Make the cat in the scene move"`,"zh-CN":`--image https://example.com/cat.png --prompt "让画面中的猫动起来"`},{"en-US":`--prompt "Mountain landscape" --resolution 720P --duration 5`,"zh-CN":`--prompt "山地景观" --resolution 720P --duration 5`},{"en-US":`--prompt "A cat playing with a ball" --watermark false`,"zh-CN":`--prompt "一只正在玩球的猫" --watermark false`},{"en-US":`--prime --workspace-id <id> --model wan3.0-video-prime --prompt "Ocean waves at sunset"`,"zh-CN":`--prime --workspace-id <id> --model wan3.0-video-prime --prompt "日落时的海浪"`}],notes:[{"en-US":`Prime mode requires an explicit model.`,"zh-CN":`Prime 模式必须显式指定模型。`},{"en-US":`Prime endpoint: configured --base-url, DASHSCOPE_BASE_URL, or profile base_url takes precedence; otherwise workspace is resolved from --workspace-id, BAILIAN_WORKSPACE_ID, then config workspace_id.`,"zh-CN":`Prime Endpoint:已配置的 --base-url、DASHSCOPE_BASE_URL 或 Profile base_url 优先;否则按 --workspace-id、BAILIAN_WORKSPACE_ID、配置项 workspace_id 解析工作空间。`}],validate:Ho,async run(e){let{settings:t,flags:r}=e,i=r.prompt,a=r.model||(r.image?t.defaultImageToVideoModel||`wan3.0-video`:t.defaultVideoModel||`wan3.0-video`),o=C(t.output),s=r.image,c=r.lastFrame,u=r.file;if(u&&(s||c))throw new n(`--file is mutually exclusive with --image/--last-frame.`,l.USAGE);let d;s&&(d=await e.client.resolveImageInput(s,a));let f;c&&(f=await e.client.resolveImageInput(c,a));let p=!!(d&&f),m=/^wan3\./i.test(a);if(u&&!m)throw new n(`--file is only supported by wan3.0-video.`,l.USAGE);let h;u&&(h=await e.client.uploadFile(u,a));let g=Cn(r.watermark,t.watermark),_=yn(r.promptExtend,void 0,`prompt-extend`),v=p&&!m?ht():nr(),y=r.prime?Uo(e,v):v,b={model:a,input:{prompt:i,negative_prompt:r.negativePrompt||void 0,...h?{media:[{type:`file`,url:h}]}:p?m?{media:[{type:`first_frame`,url:d},{type:`last_frame`,url:f}]}:{first_frame_url:d,last_frame_url:f}:d?/wan[x]?2\.[1-6]/i.test(a)?{img_url:d}:{media:[{type:`first_frame`,url:d}]}:{}},parameters:{resolution:r.resolution||void 0,ratio:r.ratio||void 0,duration:r.duration||void 0,prompt_extend:_,watermark:g,seed:r.seed}};if(t.dryRun){let e=b;if(h)e={...b,input:{...b.input,media:[{type:`file`,url:pn(h)}]}};else if(p){let t=pn(d??``),n=pn(f??``);e={...b,input:{...b.input,...m?{media:[{type:`first_frame`,url:t},{type:`last_frame`,url:n}]}:{first_frame_url:t,last_frame_url:n}}}}else if(d){let t=pn(d);e={...b,input:{...b.input,.../wan[x]?2\.[1-6]/i.test(a)?{img_url:t}:{media:[{type:`first_frame`,url:t}]}}}}O(r.prime?{endpoint:y,request:e}:{request:e},o);return}let ee=Cr(r),x=(await Pr(ee,t,()=>e.client.requestJson({path:y,method:`POST`,body:b,async:!0}),`tasks`)).map(e=>e.output.task_id);if(t.quiet||process.stderr.write(`[Model: ${a}]\n`),r.async){O(x.length===1?{task_id:x[0]}:{task_ids:x},o);return}let te=r.pollInterval??5,ne=x.map(n=>{let i=r.prime?Uo(e,Un(n)):e.client.url(Un(n));return kr(e.client,t,{url:i,intervalSec:te,timeoutSec:t.timeout,isComplete:e=>e.output.task_status===`SUCCEEDED`,isFailed:e=>e.output.task_status===`FAILED`,getStatus:e=>e.output.task_status,getErrorMessage:e=>{let t=e.output;return t.message||t.code||void 0}})}),re=await Promise.all(ne),ie=[];for(let[e,t]of re.entries()){let n=t.output.video_url||t.output.results&&t.output.results[0]?.url;n&&ie.push({taskId:x[e],videoUrl:n})}if(ie.length===0)throw new n(`All tasks completed but no video URLs returned.`,l.GENERAL);if(r.download){let e=r.download,{size:n}=await gr(ie[0].videoUrl,e,{quiet:t.quiet});t.quiet?D(e):O({task_id:ie[0].taskId,video_url:ie[0].videoUrl,status:`SUCCEEDED`,saved:e,size:xr(n)},o);return}let ae=Sn(t,{subDir:`videos`}),{join:oe}=await import(`path`),se=[];await Promise.all(ie.map(async({taskId:e,videoUrl:n})=>{let r=oe(ae,`${e}.mp4`);await gr(n,r,{quiet:t.quiet}),se.push({task_id:e,video_url:n,saved:r})})),se.length===1?O(se[0],o):O({videos:se,total:se.length},o)}}),ds=S({description:{"en-US":`Edit a video with happyhorse-1.0-video-edit (style transfer, object replacement, etc.)`,"zh-CN":`使用 happyhorse-1.0-video-edit 编辑视频(风格转换、对象替换等)`},auth:`apiKey`,usageArgs:`--video <url> --prompt <text> [flags]`,flags:{model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model ID (default: happyhorse-1.0-video-edit)`,"zh-CN":`模型 ID(默认:happyhorse-1.0-video-edit)`}},video:{type:`string`,valueHint:`<url>`,description:{"en-US":`Input video URL or local file (mp4/mov, 2-10s)`,"zh-CN":`输入视频 URL 或本地文件(mp4/mov,2–10 秒)`},required:!0},prompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Edit instruction (e.g. "Convert the scene to a claymation style")`,"zh-CN":`编辑指令(例如“将场景转换为黏土动画风格”)`}},refImage:{type:`string`,valueHint:`<url>`,description:{"en-US":`Reference image URL (up to 4, comma-separated)`,"zh-CN":`参考图片 URL(最多 4 个,以逗号分隔)`}},negativePrompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Negative prompt to exclude unwanted content`,"zh-CN":`负向提示词,用于排除不需要的内容`}},resolution:{type:`string`,valueHint:`<res>`,description:{"en-US":`Resolution: 720P or 1080P (default: 1080P)`,"zh-CN":`分辨率:720P 或 1080P(默认:1080P)`}},ratio:{type:`string`,valueHint:`<ratio>`,description:{"en-US":`Aspect ratio (16:9, 9:16, 1:1, 4:3, 3:4)`,"zh-CN":`宽高比(16:9、9:16、1:1、4:3、3:4)`}},duration:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Output video duration in seconds (2-10)`,"zh-CN":`输出视频时长,单位为秒(2–10)`}},audioSetting:{type:`string`,valueHint:`<mode>`,description:{"en-US":`Audio: auto (default) or origin (keep original)`,"zh-CN":`音频:auto(默认)或 origin(保留原音频)`},choices:[`auto`,`origin`]},promptExtend:{type:`boolean`,valueHint:`<bool>`,description:sr},watermark:{type:`boolean`,valueHint:`<bool>`,description:ur},seed:{type:`number`,valueHint:`<n>`,description:{"en-US":`Random seed for reproducible generation`,"zh-CN":`用于复现生成结果的随机种子`}},download:{type:`string`,valueHint:`<path>`,description:{"en-US":`Save video to file on completion`,"zh-CN":`完成后将视频保存到文件`}},...t,...r,pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 15)`,"zh-CN":`等待任务时的轮询间隔(默认:15 秒)`}}},exampleArgs:[{"en-US":`--video https://example.com/input.mp4 --prompt "Convert the entire scene to claymation style"`,"zh-CN":`--video https://example.com/input.mp4 --prompt "将整个场景转换为黏土动画风格"`},{"en-US":`--video https://example.com/input.mp4 --prompt "Replace the outfit with the style shown in the image" --ref-image https://example.com/clothes.png`,"zh-CN":`--video https://example.com/input.mp4 --prompt "将服装替换为参考图片中的款式" --ref-image https://example.com/clothes.png`},{"en-US":`--video https://example.com/input.mp4 --prompt "Convert to anime style" --resolution 720P --download output.mp4`,"zh-CN":`--video https://example.com/input.mp4 --prompt "转换为动漫风格" --resolution 720P --download output.mp4`},{"en-US":`--video https://example.com/input.mp4 --prompt "Put clothes on the kitten in the video" --watermark false`,"zh-CN":`--video https://example.com/input.mp4 --prompt "给视频中的小猫穿上衣服" --watermark false`}],async run(e){let{settings:t,flags:r}=e,i=r.video,a=r.prompt,o=r.model||`happyhorse-1.0-video-edit`,s=C(t.output),c=[{type:`video`,url:await e.client.uploadFile(i,o)}],u=r.refImage;if(u){let t=u.split(`,`).map(e=>e.trim()).filter(Boolean);for(let n of t){let t=await e.client.uploadFile(n,o);c.push({type:`reference_image`,url:t})}}let d=yn(r.promptExtend,void 0,`prompt-extend`),f=Cn(r.watermark,t.watermark),p={model:o,input:{prompt:a||void 0,negative_prompt:r.negativePrompt||void 0,media:c},parameters:{resolution:r.resolution||void 0,ratio:r.ratio||void 0,duration:r.duration||void 0,audio_setting:r.audioSetting||void 0,prompt_extend:d,watermark:f,seed:r.seed}};if(t.dryRun){O({request:p},s);return}let m=Cr(r),h=(await Pr(m,t,()=>e.client.requestJson({path:nr(),method:`POST`,body:p,async:!0}),`tasks`)).map(e=>e.output.task_id);if(t.quiet||(process.stderr.write(`[Model: ${o}]\n`),process.stderr.write(`Note: Video editing typically takes 5-8 minutes. Please be patient.
|
|
25
|
+
`)),r.async){O(h.length===1?{task_id:h[0]}:{task_ids:h},s);return}let g=r.pollInterval??15,_=Math.max(t.timeout,600),v=await Promise.all(h.map(n=>kr(e.client,t,{url:e.client.url(Un(n)),intervalSec:g,timeoutSec:_,isComplete:e=>e.output.task_status===`SUCCEEDED`,isFailed:e=>e.output.task_status===`FAILED`,getStatus:e=>e.output.task_status,getErrorMessage:e=>{let t=e.output;return t.message||t.code||void 0}}))),y=[];for(let e=0;e<v.length;e++){let t=v[e],n=t.output.video_url||t.output.results&&t.output.results[0]?.url;n&&y.push({taskId:h[e],videoUrl:n})}if(y.length===0)throw new n(`All tasks completed but no video URLs returned.`,l.GENERAL);if(r.download){let e=r.download,{size:n}=await gr(y[0].videoUrl,e,{quiet:t.quiet});t.quiet?D(e):O({task_id:y[0].taskId,video_url:y[0].videoUrl,status:`SUCCEEDED`,saved:e,size:xr(n)},s);return}let b=await import(`path`),ee=Sn(t,{subDir:`videos`}),x=[];await Promise.all(y.map(async({taskId:e,videoUrl:n})=>{let r=b.join(ee,`${e}.mp4`);await gr(n,r,{quiet:t.quiet}),x.push({task_id:e,video_url:n,saved:r})})),x.length===1?O(x[0],s):O({videos:x,total:x.length},s)}}),fs=S({description:{"en-US":`Reference-to-video generation (wan3.0-video / happyhorse-1.1-r2v / wan2.6-r2v): multi-subject, multi-shot with voice`,"zh-CN":`参考生视频(wan3.0-video / happyhorse-1.1-r2v / wan2.6-r2v):支持多主体、多镜头和语音`},auth:`apiKey`,usageArgs:`--prompt <text> --image <url>... [--ref-video <url>...] [flags]`,flags:{model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model ID (default: wan3.0-video)`,"zh-CN":`模型 ID(默认:wan3.0-video)`}},prompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Video description with reference markers (image1, video1, etc.)`,"zh-CN":`包含引用标记的视频描述(image1、video1 等)`},required:!0},image:{type:`array`,valueHint:`<url>`,description:{"en-US":`Reference image URL or local file (repeatable for multiple subjects)`,"zh-CN":`参考图片 URL 或本地文件(多个主体时可重复)`}},refVideo:{type:`array`,valueHint:`<url>`,description:{"en-US":`Reference video URL or local file (repeatable)`,"zh-CN":`参考视频 URL 或本地文件(可重复)`}},imageVoice:{type:`array`,valueHint:`<url>`,description:{"en-US":`Voice URL for corresponding image (pairs by position). On wan3.0-video emitted as reference_audio (refer to Audio 1, Audio 2 in prompt)`,"zh-CN":`对应图片的语音 URL(按位置配对)。在 wan3.0-video 上作为 reference_audio 条目发送(prompt 中用「音频1」「音频2」引用)`}},videoVoice:{type:`array`,valueHint:`<url>`,description:{"en-US":`Voice URL for corresponding ref-video (pairs by position). On wan3.0-video emitted as reference_audio (refer to Audio 1, Audio 2 in prompt)`,"zh-CN":`对应参考视频的语音 URL(按位置配对)。在 wan3.0-video 上作为 reference_audio 条目发送(prompt 中用「音频1」「音频2」引用)`}},resolution:{type:`string`,valueHint:`<res>`,description:{"en-US":`Resolution: 720P or 1080P (default: 1080P)`,"zh-CN":`分辨率:720P 或 1080P(默认:1080P)`}},ratio:{type:`string`,valueHint:`<ratio>`,description:{"en-US":`Aspect ratio (16:9, 9:16, 1:1)`,"zh-CN":`宽高比(16:9、9:16、1:1)`}},duration:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Video duration in seconds (default: 5)`,"zh-CN":`视频时长,单位为秒(默认:5)`}},promptExtend:{type:`boolean`,valueHint:`<bool>`,description:sr},watermark:{type:`boolean`,valueHint:`<bool>`,description:ur},seed:{type:`number`,valueHint:`<n>`,description:{"en-US":`Random seed for reproducible generation`,"zh-CN":`用于复现生成结果的随机种子`}},download:{type:`string`,valueHint:`<path>`,description:{"en-US":`Save video to file on completion`,"zh-CN":`完成后将视频保存到文件`}},...t,...r,pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 15)`,"zh-CN":`等待任务时的轮询间隔(默认:15 秒)`}}},exampleArgs:[{"en-US":`--prompt "Image1 running on the grass" --image person.jpg`,"zh-CN":`--prompt "图片 1 中的人物在草地上奔跑" --image person.jpg`},{"en-US":`--prompt "Video 1 plays guitar, Image 1 walks over" --ref-video scene.mp4 --image person.jpg`,"zh-CN":`--prompt "视频 1 中的人物弹吉他,图片 1 中的人物走过来" --ref-video scene.mp4 --image person.jpg`},{"en-US":`--prompt "Image 1 speaks" --image person.jpg --image-voice voice.mp3 --resolution 1080P`,"zh-CN":`--prompt "图片 1 中的人物说话" --image person.jpg --image-voice voice.mp3 --resolution 1080P`},{"en-US":`--prompt "Image 1 and Image 2 have a conversation" --image a.jpg --image b.jpg --image-voice va.mp3 --image-voice vb.mp3`,"zh-CN":`--prompt "图片 1 和图片 2 中的人物进行对话" --image a.jpg --image b.jpg --image-voice va.mp3 --image-voice vb.mp3`},{"en-US":`--prompt "Image 1 drinks water" --image person.jpg --watermark false`,"zh-CN":`--prompt "图片 1 中的人物喝水" --image person.jpg --watermark false`}],validate:e=>!e.image?.length&&!e.refVideo?.length?`Provide at least one --image or --ref-video.`:void 0,async run(e){let{settings:t,flags:r}=e,i=r.prompt,a=r.image||[],o=r.refVideo||[],s=r.imageVoice||[],c=r.videoVoice||[],u=r.model||t.defaultReferenceToVideoModel||`wan3.0-video`,d=C(t.output),f=/^wan3\./i.test(u),p=[],m=[];for(let t=0;t<a.length;t++){let n={type:`reference_image`,url:await e.client.resolveImageInput(a[t],u)};if(s[t]){let r=await e.client.uploadFile(s[t],u);f?m.push({type:`reference_audio`,url:r}):n.reference_voice=r}p.push(n)}for(let t=0;t<o.length;t++){let n={type:`reference_video`,url:await e.client.uploadFile(o[t],u)};if(c[t]){let r=await e.client.uploadFile(c[t],u);f?m.push({type:`reference_audio`,url:r}):n.reference_voice=r}p.push(n)}if(f)for(let e of m)p.push(e);let h=yn(r.promptExtend,void 0,`prompt-extend`),g=Cn(r.watermark,t.watermark),_={model:u,input:{prompt:i,media:p},parameters:{resolution:r.resolution||void 0,ratio:r.ratio||void 0,duration:r.duration||void 0,prompt_extend:h,watermark:g,seed:r.seed}};if(t.dryRun){let e={..._,input:{..._.input,media:_.input.media.map(e=>({...e,url:pn(e.url),reference_voice:e.reference_voice?pn(e.reference_voice):void 0}))}};O({request:e},d);return}let v=Cr(r),y=(await Pr(v,t,()=>e.client.requestJson({path:nr(),method:`POST`,body:_,async:!0}),`tasks`)).map(e=>e.output.task_id);if(t.quiet||(process.stderr.write(`[Model: ${u}]\n`),process.stderr.write(`Note: Reference-to-video typically takes 5-10 minutes. Please be patient.
|
|
26
|
+
`)),r.async){O(y.length===1?{task_id:y[0]}:{task_ids:y},d);return}let b=r.pollInterval??15,ee=Math.max(t.timeout,600),x=await Promise.all(y.map(n=>kr(e.client,t,{url:e.client.url(Un(n)),intervalSec:b,timeoutSec:ee,isComplete:e=>e.output.task_status===`SUCCEEDED`,isFailed:e=>e.output.task_status===`FAILED`,getStatus:e=>e.output.task_status,getErrorMessage:e=>{let t=e.output;return t.message||t.code||void 0}}))),te=[];for(let e=0;e<x.length;e++){let t=x[e],n=t.output.video_url||t.output.results&&t.output.results[0]?.url;n&&te.push({taskId:y[e],videoUrl:n})}if(te.length===0)throw new n(`All tasks completed but no video URLs returned.`,l.GENERAL);if(r.download){let e=r.download,{size:n}=await gr(te[0].videoUrl,e,{quiet:t.quiet});t.quiet?D(e):O({task_id:te[0].taskId,video_url:te[0].videoUrl,status:`SUCCEEDED`,saved:e,size:xr(n)},d);return}let{join:ne}=await import(`path`),re=Sn(t,{subDir:`videos`}),ie=[];await Promise.all(te.map(async({taskId:e,videoUrl:n})=>{let r=ne(re,`${e}.mp4`);await gr(n,r,{quiet:t.quiet}),ie.push({task_id:e,video_url:n,saved:r})})),ie.length===1?O(ie[0],d):O({videos:ie,total:ie.length},d)}}),ps=S({description:{"en-US":`Query async task status`,"zh-CN":`查询异步任务状态`},auth:`apiKey`,usageArgs:`--task-id <id>`,flags:{taskId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Async task ID`,"zh-CN":`异步任务 ID`},required:!0}},exampleArgs:[`--task-id 3b256896-3e70-xxxx-xxxx-xxxxxxxxxxxx`,`--task-id 3b256896-3e70-xxxx --output json`],async run(e){let{settings:t,flags:n}=e,r=n.taskId,i=C(t.output);if(t.dryRun){O({task_id:r},i);return}let a=await e.client.requestJson({path:Un(r)});if(t.quiet){D(a.output.task_status);return}O(Hn({task_id:a.output.task_id,task_status:a.output.task_status,video_url:a.output.video_url,results:a.output.results,submit_time:a.output.submit_time,scheduled_time:a.output.scheduled_time,end_time:a.output.end_time,code:a.output.code,message:a.output.message,request_id:a.request_id}),i)}}),ms=S({description:{"en-US":`Download a completed video by task ID`,"zh-CN":`通过任务 ID 下载已完成的视频`},auth:`apiKey`,usageArgs:`--task-id <id> --out <path>`,flags:{taskId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Task ID to download from`,"zh-CN":`要下载的任务 ID`},required:!0},out:{type:`string`,valueHint:`<path>`,description:{"en-US":`Output file path`,"zh-CN":`输出文件路径`},required:!0}},exampleArgs:[`--task-id 3b256896-xxxx --out video.mp4`,`--task-id 3b256896-xxxx --out video.mp4 --quiet`],async run(e){let{settings:t,flags:r}=e,i=r.taskId,a=r.out,o=C(t.output);if(t.dryRun){O({task_id:i,action:`download`,out:a},o);return}let s=await e.client.requestJson({path:Un(i)});if(s.output.task_status!==`SUCCEEDED`){let e=s.output.task_status,t=s.output.message||s.output.code,r=t?`Task is not complete (status: ${e}): ${t}`:`Task is not complete (status: ${e}).`;throw new n(r,l.GENERAL,e===`FAILED`?void 0:`Wait for the task to complete before downloading.`)}let c=s.output.video_url||s.output.results&&s.output.results[0]?.url;if(!c)throw new n(`No download URL available for this task.`,l.GENERAL);let{size:u}=await gr(c,a,{quiet:t.quiet});if(t.quiet){D(a);return}O({saved:a,size:xr(u)},o)}});const hs=/* @__PURE__ */ new Set([`.mp4`,`.mov`,`.avi`,`.mkv`,`.webm`,`.flv`,`.wmv`]);function gs(e){let t=ei(e).toLowerCase().split(`?`)[0];return!!(hs.has(t)||/\.(mp4|mov|avi|mkv|webm|flv|wmv)(\?|$)/i.test(e))}async function _s(e){return e.startsWith(`data:`)||e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)?e:gt(e)}var vs=S({description:{"en-US":`Describe an image or video using Qwen-VL`,"zh-CN":`使用 Qwen-VL 描述图片或视频`},auth:`apiKey`,usageArgs:`--image <path-or-url> [--video <url>] [--prompt <text>]`,flags:{image:{type:`string`,valueHint:`<path-or-url>`,description:{"en-US":`Local image path or URL`,"zh-CN":`本地图片路径或 URL`}},video:{type:`array`,valueHint:`<url>`,description:{"en-US":`Video file URL or local path (mp4/mov/avi/mkv/webm)`,"zh-CN":`视频文件 URL 或本地路径(mp4/mov/avi/mkv/webm)`}},prompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Question about the content (default: auto-detected)`,"zh-CN":`针对内容的问题(默认:自动识别)`}},model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Vision model (default: qwen3-vl-plus)`,"zh-CN":`视觉模型(默认:qwen3-vl-plus)`}}},exampleArgs:[`--image photo.jpg`,{"en-US":`--image https://example.com/photo.jpg --prompt "What breed is this dog?"`,"zh-CN":`--image https://example.com/photo.jpg --prompt "这只狗是什么品种?"`},{"en-US":`--video https://example.com/video.mp4 --prompt "Summarize the video content"`,"zh-CN":`--video https://example.com/video.mp4 --prompt "总结视频内容"`},`--video ./local-video.mp4`,{"en-US":`--image photo.png --prompt "Extract the text" --model qwen3-vl-plus`,"zh-CN":`--image photo.png --prompt "提取文字" --model qwen3-vl-plus`}],validate:e=>!e.image&&!e.video?.length?`Provide --image or --video.`:void 0,async run(e){let{settings:t,flags:r}=e,i=r.image,a=r.video??[],o=r.model||(e.client.usesTokenPlanEndpoint()?t.defaultTextModel:void 0)||`qwen3-vl-plus`;i&&gs(i)&&(a.push(i),i=void 0);let s=a.length>0?`Describe the video.`:`Describe the image.`,c=r.prompt||s,u=C(t.output);if(t.dryRun){O({request:{prompt:c,image:i?pn(i):void 0,video:a.length?a.map(pn):void 0,model:o}},u);return}let d=[];if(a.length>0)for(let t of a){let r=t;if(bt(t)){if(!Kr(t))throw new n(`Video file not found: ${t}`,l.USAGE);r=await e.client.uploadFile(t,o)}d.push({type:`video_url`,video_url:{url:r}})}if(i){let t=await _s(i),n=t;bt(i)&&t.startsWith(`data:`)&&Xr(i).size>5242880&&(n=await e.client.resolveImageInput(i,o)),d.push({type:`image_url`,image_url:{url:n}})}d.push({type:`text`,text:c});let f={model:o,messages:[{role:`user`,content:d}]},p=await e.client.requestJson({path:ve(),method:`POST`,body:f}),m=p.choices?.[0]?.message?.content;if(u!==`text`){O(p,u);return}D(m||``)}});const ys=[`language`,`base_url`,`output`,`output_dir`,`timeout`,`watermark`,`api_key`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`,`default_text_model`,`default_video_model`,`default_image_to_video_model`,`default_reference_to_video_model`,`default_image_model`,`default_speech_model`,`default_speech_recognition_model`,`default_omni_model`,`api_key_capabilities`,`workspace_id`],bs=/* @__PURE__ */ new Set([`api_key`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`]),xs=[`console_site`,`console_region`,`console_switch_agent`,`telemetry`],Ss=[...ys,...xs],Cs={language:[...b],output:[`text`,`json`],console_site:[`domestic`,`international`]},ws=/* @__PURE__ */ new Set([`telemetry`,`watermark`]),Ts={default_text_model:`qwen3.8-max`,default_image_model:`qwen-image-3.0`,default_video_model:`wan3.0-video`,default_image_to_video_model:`wan3.0-video`,default_reference_to_video_model:`wan3.0-video`,default_speech_model:`cosyvoice-v3-flash`,default_speech_recognition_model:`fun-asr`,default_omni_model:`qwen3.5-omni-plus`},Es={default_text_model:[{id:`qwen3.8-max`,role:`text/chat default`},{id:`qwen3-coder-plus`,role:`coding-oriented (agent config)`},{id:`qwen-flash`,role:`fast · advisor ranking`},{id:`qwen3.6-flash`,role:`fast · advisor intent`}],default_image_model:[{id:`qwen-image-3.0`,role:`image/generate default · sync`},{id:`qwen-image-2.0`,role:`image/generate · sync`},{id:`qwen-image-max`,role:`image/generate · sync`},{id:`qwen-image-edit-2.0`,role:`image/edit · sync`},{id:`wanx2.x`,role:`image/generate · async series`}],default_video_model:[{id:`wan3.0-video`,role:`video/generate · t2v / i2v / r2v default`},{id:`happyhorse-1.1-t2v`,role:`video/generate · text-to-video`},{id:`happyhorse-1.1-i2v`,role:`video/generate · image-to-video`},{id:`happyhorse-1.1-r2v`,role:`video/ref · reference-to-video`}],default_image_to_video_model:[{id:`wan3.0-video`,role:`video/generate default · image-to-video`},{id:`happyhorse-1.1-i2v`,role:`video/generate · image-to-video`}],default_reference_to_video_model:[{id:`wan3.0-video`,role:`video/ref default · reference-to-video`},{id:`happyhorse-1.1-r2v`,role:`video/ref · reference-to-video`}],default_speech_model:[{id:`cosyvoice-v3-flash`,role:`speech/synthesize (TTS) default`},{id:`qwen-audio-3.0-tts-plus`,role:`Token Plan speech/synthesize (TTS)`}],default_speech_recognition_model:[{id:`fun-asr`,role:`speech/recognize (ASR) default`},{id:`qwen-audio-3.0-asr-flash`,role:`Token Plan speech/recognize (ASR)`}],default_omni_model:[{id:`qwen3.5-omni-plus`,role:`omni/chat default`},{id:`qwen3-vl-plus`,role:`vision/describe · multimodal input`}]},Ds={"base-url":`base_url`,"output-dir":`output_dir`,"api-key":`api_key`,"access-token":`access_token`,"access-key-id":`access_key_id`,"access-key-secret":`access_key_secret`,"security-token":`security_token`,"default-text-model":`default_text_model`,"default-video-model":`default_video_model`,"default-image-to-video-model":`default_image_to_video_model`,"default-reference-to-video-model":`default_reference_to_video_model`,"default-image-model":`default_image_model`,"default-speech-model":`default_speech_model`,"default-speech-recognition-model":`default_speech_recognition_model`,"default-omni-model":`default_omni_model`,"api-key-capabilities":`api_key_capabilities`,"workspace-id":`workspace_id`};function Os(e){return Ds[e]||e}function ks(e,t){let r=Os(e);if(!ys.includes(r))throw new n(`Invalid config key "${e}". Valid keys: ${ys.join(`, `)}`,l.USAGE);if(r===`language`&&!b.includes(t))throw new n(`Invalid language "${t}". Valid values: ${b.join(`, `)}`,l.USAGE);if(r===`output`&&![`text`,`json`].includes(t))throw new n(`Invalid output format "${t}". Valid values: text, json`,l.USAGE);if(r===`timeout`){let e=Number(t);if(isNaN(e)||e<=0)throw new n(`Invalid timeout "${t}". Must be a positive number.`,l.USAGE);return e}if(r===`base_url`)return Yt(t);if(r===`watermark`)return Xt(t,`watermark`);if(r===`api_key_capabilities`){let e;if(t.trim().startsWith(`[`))try{e=JSON.parse(t)}catch{throw new n(`Invalid API Key capability list "${t}". Use comma-separated values or a JSON array.`,l.USAGE)}else e=t.split(`,`).map(e=>e.trim());if(!Array.isArray(e))throw new n(`Invalid API Key capability list. Expected an array.`,l.USAGE);let r=[];for(let t of e){if(typeof t!=`string`||!vt(t.trim()))throw new n(`Invalid API Key capability "${String(t)}".`,l.USAGE,`Use lowercase alphanumeric segments separated by '.' or '-'.`);let e=t.trim();r.includes(e)||r.push(e)}return r}return t}function As(e,t){let r=Os(e);if(ys.includes(r))return ks(e,t);if(r===`console_site`){if(![`domestic`,`international`].includes(t))throw new n(`Invalid console_site "${t}". Valid values: domestic, international`,l.USAGE);return t}if(r===`console_region`)return t;if(r===`console_switch_agent`){let e=Number(t);if(!Number.isFinite(e)||e<=0)throw new n(`Invalid console_switch_agent "${t}". Must be a positive number.`,l.USAGE);return e}if(r===`telemetry`){if(t!==`true`&&t!==`false`)throw new n(`Invalid telemetry "${t}". Valid values: true, false`,l.USAGE);return t===`true`}throw new n(`Invalid config key "${e}". Valid keys: ${Ss.join(`, `)}`,l.USAGE)}var js=S({description:{"en-US":`Display current configuration`,"zh-CN":`显示当前配置`},auth:`none`,exampleArgs:[``,`--output json`],async run(e){let{settings:t,client:n}=e,r=e.configStore,i=r.read(),a=C(t.output),s={...i,language:i.language??o,base_url:n.baseUrl,output:t.output,timeout:t.timeout,watermark:t.watermark,config:t.configName??`default`,config_file:r.path};for(let e of bs)typeof s[e]==`string`&&(s[e]=Rt(s[e]));O(s,a)}}),Ms=S({description:{"en-US":`Set a config value`,"zh-CN":`设置配置项`},auth:`none`,usageArgs:`--key <key> --value <value>`,flags:{key:{type:`string`,valueHint:`<key>`,description:{"en-US":`Config key (language, base_url, output, output_dir, timeout, watermark, api_key, api_key_capabilities, access_token, access_key_id, access_key_secret, security_token, default_*_model, workspace_id)`,"zh-CN":`配置项名称(language、base_url、output、output_dir、timeout、watermark、api_key、api_key_capabilities、access_token、access_key_id、access_key_secret、security_token、default_*_model、workspace_id)`},required:!0},value:{type:`string`,valueHint:`<value>`,description:{"en-US":`Value to set`,"zh-CN":`要设置的值`},required:!0}},exampleArgs:[`--key language --value zh-CN`,`--key output --value json`,`--key timeout --value 600`,`--key watermark --value false`,`--key base_url --value https://dashscope.aliyuncs.com`,`--config company-plan --key api-key-capabilities --value text.chat,image.generate`],async run(e){let{settings:t,flags:n}=e,r=n.key,i=n.value,a=Os(r),o=ks(r,i),s=C(t.output);if(t.dryRun){O({would_set:{[a]:o},config:t.configName??`default`,config_file:e.configStore.path},s);return}if(await e.configStore.write({[a]:o}),!t.quiet){let n=bs.has(a)?Rt(String(o)):o;O({[a]:n,config:t.configName??`default`,config_file:e.configStore.path},s)}}}),Ns=S({description:{"en-US":`List config profiles and show the active profile`,"zh-CN":`列出配置 Profile 并显示当前激活项`},auth:`none`,exampleArgs:[``,`--output json`],async run(e){let t=e.configStore.profiles(),n=[`default`,...Object.keys(t.named).sort()],r=C(e.settings.output);if(r===`json`){O({active_config:t.active,profiles:n,config_file:e.configStore.path},r);return}let i=Math.max(4,...n.map(e=>e.length));D(`${`NAME`.padEnd(i)} ACTIVE`);for(let e of n)D(`${e.padEnd(i)} ${e===t.active?`*`:``}`)}}),Ps=S({description:{"en-US":`Set the active config profile`,"zh-CN":`设置当前激活的配置 Profile`},auth:`none`,usageArgs:`--name <name>`,flags:{name:{type:`string`,valueHint:`<name>`,description:{"en-US":`Existing profile name, or default`,"zh-CN":`已有 Profile 名称,或 default`},required:!0}},exampleArgs:[`--name token-plan`,`--name default`],async run(e){let t=C(e.settings.output);if(e.settings.dryRun){let n=e.configStore.validateActivation(e.flags.name);O({would_activate:n,config_file:e.configStore.path},t);return}let n=await e.configStore.activate(e.flags.name);e.settings.quiet||O({active_config:n,config_file:e.configStore.path},t)}});const Fs=[[`Config - Alibaba Cloud Model Studio CLI`,`配置 - 阿里云百炼 CLI`],[`The login was not completed in time. Click "Log in" to try again.`,`登录未能及时完成。请点击“登录”重试。`],[`No connected agent can accept tasks yet. Install and connect qwen-code (or another supported agent) first, and make sure its CLI is on your PATH.`,`当前没有可接收任务的已连接 Agent。请先安装并连接 qwen-code(或其他受支持的 Agent),并确保其 CLI 位于 PATH 中。`],[`Complete a few steps to check your local environment and finish first-time setup: sign in to Bailian, connect a local coding agent, and run your first task. Each circle turns from gray to green as you go.`,`完成以下步骤以检查本地环境并完成首次配置:登录百炼、连接本地编程 Agent,并运行第一个任务。完成后,每个圆点会由灰色变为绿色。`],[`Pick a scenario to dispatch a preset task to a connected local coding agent, running in a new terminal. Tasks run in the directory where <code style="font-family:var(--mono)">bl config ui</code> was started.`,`选择一个场景,将预设任务发送给已连接的本地编程 Agent,并在新终端中运行。任务会在启动 <code style="font-family:var(--mono)">bl config ui</code> 的目录中执行。`],[`Pick a scenario to dispatch a preset task to a connected local coding agent, running in a new terminal. Tasks run in the directory where `,`选择一个场景,将预设任务发送给已连接的本地编程 Agent,并在新终端中运行。任务会在启动 `],[` was started.`,` 的目录中执行。`],[`Credentials and default models. The active profile (marked with a star) is used by every bl command. Click a profile to edit its settings.`,`管理凭证和默认模型。所有 bl 命令都会使用带星标的已激活 Profile。点击 Profile 可编辑其设置。`],[`Agent skills discovered across every local agent module (~/.agents/skills plus each agent's skills folder). Installed via <code style="font-family:var(--mono)">npx skills add</code>.`,`展示从本地各 Agent 模块中发现的 Skill(~/.agents/skills 以及各 Agent 的 skills 目录),可通过 <code style="font-family:var(--mono)">npx skills add</code> 安装。`],[`Agent skills discovered across every local agent module (~/.agents/skills plus each agent's skills folder). Installed via `,`展示从本地各 Agent 模块中发现的 Skill(~/.agents/skills 以及各 Agent 的 skills 目录),可通过 `],[`Media that bl writes into the output directory, grouped by type (images, videos, audio, files) and generation time.`,`bl 写入输出目录的媒体文件,按类型(图片、视频、音频、文件)和生成时间展示。`],[`Frameworks bl can configure. "Connected" means the bailian-cli provider is wired into that agent.`,`bl 可以配置的编程 Agent。"已连接"表示该 Agent 已接入 bailian-cli provider。`],[`Model Context Protocol servers declared in your local coding-agent configs.`,`本地编程 Agent 配置中声明的 Model Context Protocol 服务器。`],[`Create a named profile with its own credentials and default models.`,`创建一个拥有独立凭证和默认模型的命名 Profile。`],[`Inputs become fillable fields when dispatching. Reference each one in the prompt as {{key}}.`,`任务发送时,输入项会显示为可填写字段。请在提示词中使用 {{key}} 引用对应输入。`],[`The .zip must contain a SKILL.md at its root or inside a single top-level folder.`,`.zip 根目录或唯一的顶层目录中必须包含 SKILL.md。`],[`The active profile is used by every bl command.`,`所有 bl 命令都会使用已激活的 Profile。`],[`Delete profile "`,`删除 Profile“`],[`"? This permanently removes its credentials and default models.`,`”?这会永久删除其中的凭证和默认模型。`],[`Delete asset "`,`删除资产“`],[`"? This removes the file from disk.`,`”?这会从磁盘中删除该文件。`],[`MCP servers configured in Claude Code, Codex, Qwen Code or OpenCode will appear here.`,`在 Claude Code、Codex、Qwen Code 或 OpenCode 中配置的 MCP 服务器会显示在这里。`],[`Assets from <code>bl image</code>, <code>bl video</code>, <code>bl speech</code> and <code>bl omni</code> will appear here.`,`通过 <code>bl image</code>、<code>bl video</code>、<code>bl speech</code> 和 <code>bl omni</code> 生成的资产会显示在这里。`],[`Remote agents loaded from a URL will appear here.`,`通过 URL 加载的远程 Agent 会显示在这里。`],[`The CLI for this agent was not found on your PATH — install it before launching`,`未在 PATH 中找到该 Agent 的 CLI,请先安装再启动`],[`Connect this agent to bailian-cli before launching`,`请先将该 Agent 连接到 bailian-cli 再启动`],[`Install this agent before launching`,`请先安装该 Agent 再启动`],[`Open a new terminal and start this agent`,`在新终端中启动该 Agent`],[`Open the config file with the system default app`,`使用系统默认应用打开配置文件`],[`Task sent to `,`任务已发送至 `],[`. Check the newly opened terminal window.`,`。请查看新打开的终端窗口。`],[`Please enter a profile name.`,`请输入 Profile 名称。`],[`Only letters, numbers, - and _ are allowed.`,`仅允许使用字母、数字、- 和 _。`],[`"default" is reserved for the top-level profile.`,`“default”保留用于顶层 Profile。`],[`A profile named "`,`名为“`],[`" already exists.`,`”的 Profile 已存在。`],[`Saved, but activation failed: `,`已保存,但激活失败:`],[`Could not read runtime environment info.`,`无法读取运行环境信息。`],[`Runtime Node <code>`,`运行时 Node <code>`],[`</code> · platform <code>`,`</code> · 平台 <code>`],[`Signed in: `,`已登录:`],[`Connected: `,`已连接:`],[`All agents (~/.agents/skills)`,`所有 Agent(~/.agents/skills)`],[`Optional — folder name (defaults to the archive folder)`,`可选 — 文件夹名称(默认使用压缩包中的文件夹名称)`],[`Skill name (optional)`,`Skill 名称(可选)`],[`Skill package (.zip)`,`Skill 包(.zip)`],[`Please choose a .zip file.`,`请选择 .zip 文件。`],[`Install with <code>npx skills add modelstudioai/cli --all -g</code>`,`使用 <code>npx skills add modelstudioai/cli --all -g</code> 安装`],[`Skill "`,`Skill“`],[`MCP server "`,`MCP 服务器“`],[`" installed (`,`”已安装(`],[` files) to `,` 个文件),位置:`],[`" was updated.`,`”已更新。`],[`" was added to `,`”已添加至 `],[`Remove "`,`移除“`],[`" from `,`”(来源:`],[`? This rewrites the source config file.`,`)?此操作会重写来源配置文件。`],[`Could not delete this server.`,`无法删除该服务器。`],[`Delete MCP server?`,`删除 MCP 服务器?`],[`Config must be a JSON object.`,`配置必须是 JSON 对象。`],[`Invalid JSON: `,`无效的 JSON:`],[`Please enter a server name.`,`请输入服务器名称。`],[`No remote agents yet.`,`暂无远程 Agent。`],[`No agents in this category.`,`该分类下暂无 Agent。`],[`No agents match "`,`没有匹配“`],[`bailian-cli is not wired into this agent yet.`,`该 Agent 尚未连接 bailian-cli。`],[`This agent is not installed yet.`,`该 Agent 尚未安装。`],[`No scenarios in this category.`,`该分类下暂无场景。`],[`No scenarios match "`,`没有匹配“`],[`Click to edit this scenario`,`点击编辑此场景`],[`Dispatch this task to a local agent`,`将此任务发送至本地 Agent`],[`No connected agent available`,`没有可用的已连接 Agent`],[`Please fill in: `,`请填写:`],[`Input key "`,`输入键“`],[`" may only use letters, digits, underscore.`,`”只能使用字母、数字和下划线。`],[`Duplicate input key: `,`输入键重复:`],[`Title is required.`,`标题为必填项。`],[`Prompt template is required.`,`提示词模板为必填项。`],[`No assets match "`,`没有匹配“`],[`Toggle sort by generation time`,`切换生成时间排序`],[`↓ Newest first`,`↓ 最新优先`],[`↑ Oldest first`,`↑ 最早优先`],[`View details — `,`查看详情 — `],[`Available `,`可用的 `],[` models · click to use`,` 模型 · 点击使用`],[`Applies to <code>bl video generate</code> only (text/image-to-video). `,`仅适用于 <code>bl video generate</code>(文生视频/图生视频)。`],[`<code>bl video ref</code> (multi-image) and <code>bl video edit</code> keep their own `,`<code>bl video ref</code>(多图)和 <code>bl video edit</code> 仍使用各自的`],[`fixed models — pass <code>--model</code> to override those per run.`,`固定模型;可在每次运行时通过 <code>--model</code> 覆盖。`],[`No skills match "`,`没有匹配“`],[`No MCP servers match "`,`没有匹配“`],[`Install to`,`安装到`],[`Transport / Source`,`传输方式 / 来源`],[`Target agent config`,`目标 Agent 配置`],[`Server name`,`服务器名称`],[`Quick launch`,`快速启动`],[`Config files`,`配置文件`],[`Environment check`,`环境检查`],[`Edit preset scenario`,`编辑预设场景`],[`Edit scenario`,`编辑场景`],[`Save & Activate`,`保存并激活`],[`Are you sure?`,`确认执行此操作吗?`],[`Save failed`,`保存失败`],[`Create failed`,`创建失败`],[`Install failed`,`安装失败`],[`Launch failed`,`启动失败`],[`Dispatch failed`,`发送失败`],[`Delete failed`,`删除失败`],[`Created`,`已创建`],[`Dispatched`,`已发送`],[`Saved`,`已保存`],[`OK`,`确定`],[`Configuration`,`配置`],[`Settings`,`设置`],[`Status`,`状态`],[`Open`,`打开`],[`Remove`,`移除`],[`Show`,`显示`],[`Hide`,`隐藏`],[`All`,`全部`],[`Images`,`图片`],[`Videos`,`视频`],[`Files`,`文件`],[`Image`,`图片`],[`Video`,`视频`],[`Audio`,`音频`],[`File`,`文件`],[` files`,` 个文件`],[`MCPs`,`MCP 服务`],[`Coding`,`编程`],[`Generated`,`生成的`],[`API key`,`API 密钥`],[`Console gateway`,`控制台网关`],[`Account`,`账户`],[`(empty)`,`(空)`],[` (editable)`,`(可编辑)`],[` (missing)`,`(缺失)`],[`default (top-level)`,`default(顶层)`],[`This source is read-only here (its config is TOML). Edit it directly in `,`该来源在此处为只读(配置格式为 TOML)。请直接编辑:`],[`No connected local coding agent detected (e.g. qwen-code). Open the Agents page to install and connect one.`,`未检测到已连接的本地编程 Agent(例如 qwen-code)。请打开 Agent 页面进行安装和连接。`],[`Installed but not wired into bl: `,`已安装但尚未接入 bl:`],[`. Open the Agents page to finish connecting.`,`。请打开 Agent 页面完成连接。`],[`Finish the previous step first (connect a dispatchable agent), then come back to Playground to run your first scenario.`,`请先完成上一步(连接可接收任务的 Agent),再回到 Playground 运行第一个场景。`],[`Go to Playground, pick a scenario and click Run it to complete your first dispatch.`,`前往 Playground,选择一个场景并点击“运行”,完成首次任务发送。`],[`Sign in to the Bailian console to obtain credentials (opens a login page in your browser).`,`登录百炼控制台以获取凭证(将在浏览器中打开登录页面)。`],[`You have dispatched at least one task.`,`你已经成功发送过至少一个任务。`],[`Node 18 or newer is recommended.`,`建议使用 Node.js 18 或更高版本。`],[`Save & Activate`,`保存并激活`],[`Save scenario`,`保存场景`],[`Custom scenario`,`自定义场景`],[`+ Custom scenario`,`+ 自定义场景`],[`New profile`,`新建 Profile`],[`+ New profile`,`+ 新建 Profile`],[`Profile name`,`Profile 名称`],[`Target agent`,`目标 Agent`],[`Task to dispatch`,`要发送的任务`],[`Prompt template`,`提示词模板`],[`One-line description (optional)`,`一句话描述(可选)`],[`Use {{key}} placeholders for inputs`,`使用 {{key}} 作为输入占位符`],[`e.g. Translate docs to English`,`例如:将文档翻译成英文`],[`e.g. Image / Custom`,`例如:图像 / 自定义`],[`e.g. work, intl, test`,`例如:work、intl、test`],[`Search scenarios…`,`搜索场景…`],[`Search skills…`,`搜索 Skill…`],[`Search MCP servers…`,`搜索 MCP 服务器…`],[`Search agents…`,`搜索 Agent…`],[`Search assets…`,`搜索资产…`],[`Installed Skills`,`已安装的 Skill`],[`Coding Agents`,`编程 Agent`],[`Generated Assets`,`生成资产`],[`Get Started`,`开始使用`],[`Quick Start`,`快速开始`],[`Playground`,`Playground`],[`Extensions`,`扩展`],[`Workspace`,`工作区`],[`Skills`,`Skill`],[`Agents`,`Agent`],[`Assets`,`资产`],[`Config`,`配置`],[`Log in`,`登录`],[`Log out`,`退出登录`],[`Copy this URL`,`复制此链接`],[`QR code for this session URL`,`当前会话链接的二维码`],[`Collapse sidebar`,`收起侧边栏`],[`Expand sidebar`,`展开侧边栏`],[`Model Studio CLI home`,`百炼 CLI 首页`],[`Loading…`,`加载中…`],[`Delete profile`,`删除 Profile`],[`Delete asset`,`删除资产`],[`Open failed`,`打开失败`],[`Open locally`,`在本地打开`],[`View details`,`查看详情`],[`Jump backward 5 pages`,`向前跳转 5 页`],[`Jump forward 5 pages`,`向后跳转 5 页`],[`Items per page`,`每页数量`],[`No generated assets yet.`,`暂无生成资产。`],[`No assets in this category.`,`该分类下暂无资产。`],[`No skills installed.`,`尚未安装 Skill。`],[`No local MCP servers found.`,`未发现本地 MCP 服务器。`],[`No coding agents found.`,`未发现编程 Agent。`],[`No scenarios found.`,`未发现场景。`],[`Failed to load: `,`加载失败:`],[`Load failed: `,`加载失败:`],[`Save failed: `,`保存失败:`],[`Create failed: `,`创建失败:`],[`Install failed: `,`安装失败:`],[`Launch failed: `,`启动失败:`],[`Saving…`,`正在保存…`],[`Saved and activated.`,`已保存并激活。`],[`Saved.`,`已保存。`],[`Profile created and saved.`,`Profile 已创建并保存。`],[`Opening browser…`,`正在打开浏览器…`],[`Waiting for login…`,`等待登录…`],[`Signed in…`,`已登录…`],[`Login timed out`,`登录超时`],[`Authenticated`,`已认证`],[`Connect a local agent`,`连接本地 Agent`],[`Run your first task`,`运行第一个任务`],[`Sign in to Bailian`,`登录百炼`],[`Check local environment`,`检查本地环境`],[`Go to Playground`,`前往 Playground`],[`Go to Agents`,`前往 Agent`],[`Run it`,`运行`],[`Done`,`已完成`],[`Connected`,`已连接`],[`Not installed`,`未安装`],[`Installed`,`已安装`],[`Launching…`,`正在启动…`],[`Launched → `,`已启动 → `],[`Remote`,`远程`],[`Local`,`本地`],[`Add skill`,`添加 Skill`],[`+ Add skill`,`+ 添加 Skill`],[`Choose .zip file`,`选择 .zip 文件`],[`No file selected`,`未选择文件`],[`New MCP server`,`新建 MCP 服务器`],[`+ Add MCP`,`+ 添加 MCP`],[`Description`,`描述`],[`Installed in`,`安装位置`],[`Details`,`详情`],[`Type`,`类型`],[`Path`,`路径`],[`Scope`,`范围`],[`Title`,`标题`],[`Category`,`分类`],[`Inputs`,`输入项`],[`Add input`,`添加输入`],[`Create`,`创建`],[`Install`,`安装`],[`Delete`,`删除`],[`Cancel`,`取消`],[`Close`,`关闭`],[`Active`,`已激活`],[`Save`,`保存`],[`Copy`,`复制`],[`Copied`,`已复制`],[`show`,`显示`],[`hide`,`隐藏`],[`(unset)`,`(未设置)`],[` / page`,` / 页`]];function Is(){return JSON.stringify([...Fs].sort(([e],[t])=>t.length-e.length)).replaceAll(`<`,`\\u003c`)}function Ls(e,t){return e.replace(`<html lang="en">`,`<html lang="${t}">`).replace(`__BL_CONFIG_UI_LANGUAGE__`,t).replace(`__BL_CONFIG_UI_TRANSLATIONS__`,Is())}function Rs(e){return Ls(`<!doctype html>
|
|
27
27
|
<html lang="en">
|
|
28
28
|
<head>
|
|
29
29
|
<meta charset="utf-8" />
|
|
@@ -2711,131 +2711,132 @@ Omni output voices:
|
|
|
2711
2711
|
<\/script>
|
|
2712
2712
|
</body>
|
|
2713
2713
|
</html>
|
|
2714
|
-
`,e)}function
|
|
2715
|
-
`;)n+=1;continue}if(i===`/`&&a===`*`){for(n+=2;n<e.length&&(e[n]!==`*`||e[n+1]!==`/`);)n+=1;n+=2;continue}t+=i,n+=1}let i=``;for(n=0,r=!1;n<t.length;){let e=t[n];if(r){if(i+=e,e===`\\`){i+=t[n+1]??``,n+=2;continue}e===`"`&&(r=!1),n+=1;continue}if(e===`"`&&(r=!0),e===`,`){let e=n+1;for(;e<t.length&&/\s/.test(t[e]);)e+=1;if(t[e]===`}`||t[e]===`]`){n+=1;continue}}i+=e,n+=1}return i}function
|
|
2716
|
-
`,{mode:384}),Pr(n,e)}function Ts(e,t){Mr(Rr(e),{recursive:!0});let n=e+`.tmp`;Ir(n,t,{mode:384}),Pr(n,e)}function Es(e){if(!jr(e))return;let t=Math.floor(Date.now()/1e3);kr(e,`${e}.bak.${t}`)}function Ds(e){return e.includes(`/apps/anthropic`)}function Os(e){let t=e.trim().replace(/\/+$/,``);if(Ds(t))return{url:t};if(t.includes(`/compatible-mode`))return{url:t.replace(/\/compatible-mode(?:\/v\d+)?/,`/apps/anthropic`),rewrittenFrom:e.trim()};try{let n=new URL(t),r=n.hostname;if((r.includes(`dashscope`)||r.includes(`maas.aliyuncs.com`)||r.includes(`token-plan`))&&(n.pathname===`/`||n.pathname===``))return{url:`${n.origin}/apps/anthropic`,rewrittenFrom:e.trim()}}catch{}throw new n(`Claude Code requires an Anthropic-compatible base URL, got "${e}".`,l.USAGE,`Use a URL ending in /apps/anthropic (not /compatible-mode/v1). Example: https://dashscope.aliyuncs.com/apps/anthropic`)}function ks(e){let t=e.trim();if(!/^[a-z0-9-]+$/.test(t))throw new n(`Invalid --region "${e}".`,l.USAGE,`Use a Model Studio region id, e.g. cn-beijing or ap-southeast-1.`);return`https://token-plan.${t}.maas.aliyuncs.com/compatible-mode/v1`}const As=[`codex`,`claude-code`,`cursor`,`qoder`,`qoderwork`,`qwenwork`,`qwen-code`,`gemini`,`opencode`,`openclaw`,`deepseek-harness`,`zcode`,`workbuddy`],js=`@deepseek-ai/dsh-mcp-client`,Ms=`__dshOtherPatches`,Ns=`mcpServers`,Ps=[`.workbuddy-ai`,`.workbuddy`,`.codebuddy`],Fs=[`.openclaw`,`.clawdbot`,`.moltbot`];function Is(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ls(e,t){if(!A(e))return{};try{let n=t(Wr(e,`utf8`));if(!Is(n))throw Error(`root value is not an object`);return n}catch(t){throw new n(`Cannot update MCP configuration because ${e} is invalid.`,l.GENERAL,`Fix the existing configuration file and retry; it was not changed.`,{cause:t})}}function Rs(e){return Ls(e,e=>JSON.parse(xs(e)))}function zs(e){return Ls(e,ii)}function Bs(e,t){let r=e[t];if(r===void 0){let n={};return e[t]=n,n}if(!Is(r))throw new n(`Cannot update MCP configuration because ${t} is not an object.`,l.GENERAL);return r}function Vs(e,t){let n=e;for(let e of t)n=Bs(n,e);return n}function Hs(e,t){let n=e.paths?.(t);return n&&n.length>0?n:[e.path(t)]}function Us(e,t,n){return e?.trim()||j(t,n)}function Ws(e,t){return e===void 0||e===`unchanged`?t:t===`updated`||e===`updated`?`updated`:e}function Gs(e){return new n(`${e===`codex`?`Codex`:e===`deepseek-harness`?`DeepSeek Harness`:e} does not support SSE MCP servers; use --transport streamable-http.`,l.USAGE)}const Ks=[`.qwenworkcn`,`.qwenwork`];function qs(e){return Ks.map(t=>j(e,t))}function Js(e){let t=qs(e);for(let e of t){let t=j(e,`mcp.json`);if(A(t))return t}for(let e of t)if(A(e))return j(e,`mcp.json`);return j(t[0],`mcp.json`)}function Ys(e){return j(e,`.config`,`opencode`,`opencode.json`)}function Xs(e){let t=process.env.OPENCLAW_CONFIG_PATH?.trim();if(t)return t;let n=Fs.map(t=>j(e,t)).find(e=>A(e));return j(n??j(e,Fs[0]),`openclaw.json`)}function Zs(e){return Us(process.env.DSH_HOME,e,`.dsh`)}function Qs(e){return j(Zs(e),`cordis.patch.yml`)}function $s(e){return j(Us(process.env.ZCODE_HOME,e,`.zcode`),`cli`,`config.json`)}function ec(e){return Ps.map(t=>j(e,t))}function tc(e){let t=j(e,`.mcp.json`);return A(t)?t:j(e,`mcp.json`)}function nc(e){let t=ec(e).filter(e=>A(e));return(t.length>0?t:[j(e,Ps[0])]).map(e=>tc(e))}function rc(e){return Is(e)&&e.name===js&&Is(e.config)}function ic(e){let t=e.config;if(Is(t)&&typeof t.serverName==`string`&&t.serverName!==``)return t.serverName}function ac(e){if(!A(e))return{[Ms]:[],[Ns]:{}};let t;try{t=ni.parse(Wr(e,`utf8`))}catch(t){throw new n(`Cannot update MCP configuration because ${e} is invalid.`,l.GENERAL,`Fix the existing configuration file and retry; it was not changed.`,{cause:t})}if(t==null)return{[Ms]:[],[Ns]:{}};if(!Array.isArray(t))throw new n(`Cannot update MCP configuration because ${e} is invalid.`,l.GENERAL,`Fix the existing configuration file and retry; it was not changed.`);let r=[],i={};for(let e of t){if(Is(e)&&Array.isArray(e.insert)){let t=[];for(let n of e.insert){if(rc(n)){let e=ic(n);if(e){i[e]=n;continue}}t.push(n)}t.length>0&&r.push({...e,insert:t});continue}if(rc(e)){let t=ic(e);if(t){i[t]=e;continue}}r.push(e)}return{[Ms]:r,[Ns]:i}}function oc(e){let t=Array.isArray(e[Ms])?e[Ms]:[],n=Is(e[Ns])?e[Ns]:{},r=[...t],i=Object.values(n);return i.length>0&&r.push({insert:i}),ni.stringify(r)}function sc(e){let t=e.serverKeys??[`mcpServers`];return{path:e.path,paths:e.paths,installed:e.installed,supports:e.supports??(()=>!0),parse:Rs,serialize:e=>`${JSON.stringify(e,null,2)}\n`,getServers:e=>Vs(e,t),buildEntry:e.buildEntry??(t=>e.typed?{type:t.transport===`sse`?`sse`:`http`,url:t.endpoint,headers:t.headers}:{url:t.endpoint,headers:t.headers})}}const cc={codex:{path:e=>j(process.env.CODEX_HOME||j(e,`.codex`),`config.toml`),installed:e=>A(process.env.CODEX_HOME||j(e,`.codex`))||A(j(process.env.CODEX_HOME||j(e,`.codex`),`config.toml`)),supports:e=>e===`streamable-http`,parse:zs,serialize:e=>`${ai(e)}\n`,getServers:e=>Bs(e,`mcp_servers`),buildEntry:e=>({url:e.endpoint,http_headers:e.headers})},"claude-code":{path:e=>j(e,`.claude.json`),installed:e=>A(j(e,`.claude`))||A(j(e,`.claude.json`)),supports:()=>!0,parse:Rs,serialize:e=>`${JSON.stringify(e,null,2)}\n`,getServers:e=>Bs(e,`mcpServers`),buildEntry:e=>({type:e.transport===`sse`?`sse`:`http`,url:e.endpoint,headers:e.headers})},cursor:sc({path:e=>j(e,`.cursor`,`mcp.json`),installed:e=>A(j(e,`.cursor`))||A(j(e,`.cursor`,`mcp.json`))}),qoder:sc({path:e=>j(e,`.qoder`,`mcp.json`),installed:e=>A(j(e,`.qoder`))||A(j(e,`.qoder`,`mcp.json`))}),qoderwork:sc({path:e=>j(e,`.qoderwork`,`mcp.json`),installed:e=>A(j(e,`.qoderwork`))||A(j(e,`.qoderwork`,`mcp.json`))}),qwenwork:sc({path:Js,installed:e=>qs(e).some(e=>A(e)||A(j(e,`mcp.json`))),buildEntry:e=>({type:e.transport===`sse`?`sse`:`streamable-http`,url:e.endpoint,headers:e.headers})}),"qwen-code":{path:e=>j(e,`.qwen`,`settings.json`),installed:e=>A(j(e,`.qwen`)),supports:()=>!0,parse:Rs,serialize:e=>`${JSON.stringify(e,null,2)}\n`,getServers:e=>Bs(e,`mcpServers`),buildEntry:e=>e.transport===`sse`?{url:e.endpoint,headers:e.headers}:{httpUrl:e.endpoint,headers:e.headers}},gemini:{path:e=>j(e,`.gemini`,`settings.json`),installed:e=>A(j(e,`.gemini`)),supports:()=>!0,parse:Rs,serialize:e=>`${JSON.stringify(e,null,2)}\n`,getServers:e=>Bs(e,`mcpServers`),buildEntry:e=>e.transport===`sse`?{url:e.endpoint,headers:e.headers}:{httpUrl:e.endpoint,headers:e.headers}},opencode:sc({path:Ys,installed:e=>A(j(e,`.config`,`opencode`))||A(Ys(e)),serverKeys:[`mcp`],buildEntry:e=>({type:`remote`,url:e.endpoint,enabled:!0,oauth:!1,headers:e.headers})}),openclaw:sc({path:Xs,installed:e=>!!process.env.OPENCLAW_CONFIG_PATH?.trim()||Fs.some(t=>A(j(e,t)))||A(Xs(e)),serverKeys:[`mcp`,`servers`],buildEntry:e=>({url:e.endpoint,transport:e.transport===`sse`?`sse`:`streamable-http`,headers:e.headers})}),"deepseek-harness":{path:Qs,installed:e=>A(Zs(e)),supports:e=>e===`streamable-http`,parse:ac,serialize:oc,getServers:e=>Bs(e,Ns),buildEntry:e=>({id:`mcp-bailian-${e.name}`,name:js,config:{serverName:e.name,transport:`streamable-http`,url:e.endpoint,headers:e.headers}})},zcode:sc({path:$s,installed:e=>A(Us(process.env.ZCODE_HOME,e,`.zcode`)),serverKeys:[`mcp`,`servers`],buildEntry:e=>({type:e.transport===`sse`?`sse`:`http`,url:e.endpoint,enabled:!0,headers:e.headers})}),workbuddy:sc({path:e=>nc(e)[0]??j(e,Ps[0],`mcp.json`),paths:nc,installed:e=>ec(e).some(e=>A(e)),typed:!0})};function lc(e){return Array.isArray(e)?`[${e.map(lc).join(`,`)}]`:Is(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${lc(e[t])}`).join(`,`)}}`:JSON.stringify(e)}function uc(e){return Sr(`sha256`).update(lc(e)).digest(`hex`)}function dc(e,t){return`${e}:${t}`}function fc(e){return j(e,`mcp-registrations.json`)}function pc(e){let t=fc(e);if(!A(t))return{version:1,registrations:{}};let r=Rs(t);if(r.version!==1||!Is(r.registrations))throw new n(`Cannot update MCP registrations because ${t} has an unsupported format.`,l.GENERAL);return r}function mc(e,t,r,i){if(e!==void 0){if(!t)throw new n(`MCP server "${i}" already exists in ${r} and is not managed by bailian-cli.`,l.GENERAL,`Choose another server name or remove the existing entry yourself.`);if(uc(e)!==t.fingerprint)throw new n(`MCP server "${i}" in ${r} conflicts with the last bailian-cli registration.`,l.GENERAL,`The entry was changed after registration; resolve it manually before retrying.`)}}function hc(e){for(let t of e.reverse())try{t.original===void 0?qr(t.path):Ts(t.path,t.original)}catch{}}function gc(e,t,r){let i=[];try{for(let t of e)Es(t.path),Ts(t.path,t.content),i.push(t);ws(fc(r),t)}catch(e){throw hc(i),new n(`Failed to update MCP Agent configuration.`,l.GENERAL,void 0,{cause:e})}}function _c(e,t){return e===`all`?As.filter(e=>cc[e].installed(t)):[e]}function vc(e){let t=pc(e.configDir),n=[],r=[];for(let i of e.agents){let a=cc[i];if(!a.supports(e.spec.transport))throw Gs(i);let o=Hs(a,e.home),s=a.path(e.home),c=dc(i,e.spec.name),l=t.registrations[c],u=a.buildEntry(e.spec),d=uc(u),f;for(let t of o){let r=a.parse(t),o=a.getServers(r),s=o[e.spec.name];mc(s,l,i,e.spec.name);let c=s===void 0?`added`:uc(s)===d?`unchanged`:`updated`;f=Ws(f,c),c!==`unchanged`&&(o[e.spec.name]=u,n.push({path:t,original:A(t)?Wr(t,`utf8`):void 0,content:a.serialize(r)}))}let p=f??`unchanged`;r.push({agent:i,path:s,status:p}),p!==`unchanged`&&(t.registrations[c]={agent:i,name:e.spec.name,serverCode:e.spec.serverCode,transport:e.spec.transport,endpoint:e.spec.endpoint,path:s,fingerprint:d,cliVersion:e.cliVersion,updatedAt:(/* @__PURE__ */ new Date()).toISOString()})}return n.length>0&&gc(n,t,e.configDir),r}function yc(e){let t=pc(e.configDir),n=[],r=[],i=!1;for(let a of e.agents){let o=cc[a],s=o.path(e.home),c=dc(a,e.name),l=t.registrations[c];if(!l){r.push({agent:a,path:s,status:`absent`});continue}let u=!1,d=!1;for(let t of Hs(o,e.home)){let r=o.parse(t),i=o.getServers(r),s=i[e.name];s!==void 0&&(d=!0,mc(s,l,a,e.name),delete i[e.name],u=!0,n.push({path:t,original:Wr(t,`utf8`),content:o.serialize(r)}))}delete t.registrations[c],i=!0,r.push({agent:a,path:s,status:d&&u?`removed`:`absent`})}return(n.length>0||i)&&gc(n,t,e.configDir),r}function bc(e){try{return Wr(e,`utf-8`)}catch{return}}function N(e){let t=bc(e);if(t!==void 0)try{let e=JSON.parse(t);return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}catch{return}}function P(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}function xc(e){let t=/^---\s*\n([\s\S]*?)\n---/.exec(e);if(!t)return{};try{return P(ni.parse(t[1]))??{}}catch{return{}}}function Sc(e,t=500){let n=0,r=e=>{if(n>=t)return;let i;try{i=Gr(e,{withFileTypes:!0})}catch{return}for(let a of i){if(n>=t)return;let i=j(e,a.name);a.isDirectory()?r(i):n+=1}};return r(e),n}function Cc(e){return[{source:`global`,dir:j(e,`.agents`,`skills`)},{source:`claude-code`,dir:j(e,`.claude`,`skills`)},{source:`cursor`,dir:j(e,`.cursor`,`skills`)},{source:`qwen-code`,dir:j(e,`.qwen`,`skills`)},{source:`codex`,dir:j(e,`.codex`,`skills`)},{source:`opencode`,dir:j(e,`.config`,`opencode`,`skills`)},{source:`openclaw`,dir:j(e,`.openclaw`,`skills`)},{source:`openclaw`,dir:j(e,`.openclaw`,`workspace`,`skills`)},{source:`hermes`,dir:j(e,`.hermes`,`skills`)},{source:`gemini`,dir:j(e,`.gemini`,`skills`)},{source:`antigravity`,dir:j(e,`.gemini`,`antigravity`,`skills`)},{source:`windsurf`,dir:j(e,`.windsurf`,`skills`)},{source:`windsurf`,dir:j(e,`.codeium`,`windsurf`,`skills`)},{source:`qoderwork`,dir:j(e,`.qoderwork`,`skills`)},{source:`workbuddy`,dir:j(e,`.workbuddy`,`skills`)}]}function wc(e=ei()){let t=/* @__PURE__ */ new Map;for(let{source:n,dir:r}of Cc(e)){let e;try{e=Gr(r,{withFileTypes:!0})}catch{continue}for(let i of e){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let e=j(r,i.name),a=j(e,`SKILL.md`);if(!A(a))continue;let o=t.get(i.name);if(o){o.sources.includes(n)||o.sources.push(n);continue}let s=xc(bc(a)??``),c=P(s.metadata),l=typeof s.description==`string`?s.description.trim():``,u=c&&typeof c.version==`string`?c.version:typeof s.version==`string`?s.version:void 0;t.set(i.name,{id:i.name,name:typeof s.name==`string`&&s.name?s.name:i.name,description:l,version:u,fileCount:Sc(e),path:e,sources:[n],origin:`local`})}}return[...t.values()].sort((e,t)=>e.name.localeCompare(t.name))}function Tc(e,t=ei()){let n=wc(t).find(t=>t.id===e);if(!n)return null;let r=bc(j(n.path,`SKILL.md`))??``;return{...n,content:r}}const Ec=[{source:`global`,label:`All agents (~/.agents/skills)`,sub:[`.agents`,`skills`]},{source:`claude-code`,label:`Claude Code`,sub:[`.claude`,`skills`]},{source:`qwen-code`,label:`Qwen Code`,sub:[`.qwen`,`skills`]},{source:`codex`,label:`Codex`,sub:[`.codex`,`skills`]},{source:`opencode`,label:`OpenCode`,sub:[`.config`,`opencode`,`skills`]},{source:`openclaw`,label:`OpenClaw`,sub:[`.openclaw`,`skills`]},{source:`qoderwork`,label:`QoderWork`,sub:[`.qoderwork`,`skills`]},{source:`windsurf`,label:`Windsurf`,sub:[`.codeium`,`windsurf`,`skills`]},{source:`gemini`,label:`Gemini`,sub:[`.gemini`,`skills`]}];function Dc(e,t){let n=Ec.find(t=>t.source===e);return n?j(t,...n.sub):null}function Oc(e){let t=-1,n=Math.max(0,e.length-22-65535);for(let r=e.length-22;r>=n;r--)if(e.readUInt32LE(r)===101010256){t=r;break}if(t<0)throw Error(`Not a valid .zip archive.`);let r=e.readUInt16LE(t+10),i=e.readUInt32LE(t+16),a=[];for(let t=0;t<r&&!(i+46>e.length||e.readUInt32LE(i)!==33639248);t++){let t=e.readUInt16LE(i+10),n=e.readUInt32LE(i+20),r=e.readUInt16LE(i+28),o=e.readUInt16LE(i+30),s=e.readUInt16LE(i+32),c=e.readUInt32LE(i+42),l=e.toString(`utf8`,i+46,i+46+r);if(i+=46+r+o+s,l.endsWith(`/`)||c+30>e.length||e.readUInt32LE(c)!==67324752)continue;let u=e.readUInt16LE(c+26),d=e.readUInt16LE(c+28),f=c+30+u+d,p=e.subarray(f,f+n),m;if(t===0)m=Buffer.from(p);else if(t===8)m=ti(p);else throw Error(`Unsupported compression in archive (entry: `+l+`).`);a.push({name:l,data:m})}return a}function kc(e,t,n,r=ei()){let i=Dc(e,r);if(!i)throw Error(`Unknown skill install target.`);let a=Oc(t).map(e=>({name:e.name.replace(/\\/g,`/`).replace(/^\.\//,``).replace(/^\/+/,``),data:e.data})).filter(e=>e.name&&!e.name.endsWith(`/`)&&!e.name.split(`/`).includes(`..`));if(!a.length)throw Error(`The archive contains no usable files.`);let o=a.find(e=>e.name===`SKILL.md`||e.name.endsWith(`/SKILL.md`));if(!o)throw Error(`No SKILL.md found in the archive (root or a top-level folder).`);let s=o.name.lastIndexOf(`/`),c,l;if(s<0){if(c=(n||``).trim(),!c)throw Error(`SKILL.md is at the archive root — please provide a skill name.`);l=``}else l=o.name.slice(0,s+1),c=(n||``).trim()||l.split(`/`)[0];if(!/^[A-Za-z0-9._-]+$/.test(c))throw Error(`Invalid skill name: `+c);let u=j(i,c),d=M(u),f=0;for(let e of a){let t=e.name;if(l){if(!e.name.startsWith(l))continue;t=e.name.slice(l.length)}if(!t)continue;let n=M(j(u,t));(n===d||n.startsWith(d+$r))&&(Ur(Xr(n),{recursive:!0}),Jr(n,e.data),f++)}if(f===0)throw Error(`Nothing was extracted from the archive.`);return{installed:c,files:f,dir:u}}function Ac(e){if(typeof e.command==`string`){let t=Array.isArray(e.args)?e.args.join(` `):``;return{transport:`stdio`,detail:`${e.command} ${t}`.trim()}}let t=typeof e.url==`string`?e.url:void 0;if(t){let n=typeof e.type==`string`?e.type.toLowerCase():``,r=typeof e.transport==`string`?e.transport.toLowerCase():``;return n===`sse`||r===`sse`?{transport:`sse`,detail:t}:{transport:`http`,detail:t}}return{transport:`unknown`,detail:``}}function jc(e,t,n,r,i){let a=P(e);if(a)for(let[e,o]of Object.entries(a)){let a=P(o)??{},{transport:s,detail:c}=Ac(a);r.push({name:e,source:t,transport:s,detail:c,scope:n,origin:`local`,config:Gc(a),editable:i})}}function Mc(e=ei()){let t=[],n=N(j(e,`.claude.json`));if(n){jc(n.mcpServers,`claude-code`,`global`,t,!0);let e=P(n.projects);if(e)for(let[n,r]of Object.entries(e)){let e=P(r);e?.mcpServers&&jc(e.mcpServers,`claude-code`,n,t,!0)}}let r=N(j(e,`.qwen`,`settings.json`));r&&jc(r.mcpServers,`qwen-code`,`global`,t,!0);let i=N(j(e,`.config`,`opencode`,`opencode.json`));i&&jc(i.mcp,`opencode`,`global`,t,!0);let a=N(j(e,`.cursor`,`mcp.json`));a&&jc(a.mcpServers,`cursor`,`global`,t,!0);let o=N(j(e,`.qoder`,`mcp.json`));o&&jc(o.mcpServers,`qoder`,`global`,t,!0);let s=N(j(e,`.qoderwork`,`mcp.json`));s&&jc(s.mcpServers,`qoderwork`,`global`,t,!0);let c=N(Js(e));c&&jc(c.mcpServers,`qwenwork`,`global`,t,!0);let l=N(j(e,`.codeium`,`windsurf`,`mcp_config.json`));l&&jc(l.mcpServers,`windsurf`,`global`,t,!0);let u=N(j(e,`.gemini`,`settings.json`));u&&jc(u.mcpServers,`gemini`,`global`,t,!0);let d=N(j(e,`.openclaw`,`openclaw.json`));d&&jc(P(d.mcp)?.servers??d.mcpServers,`openclaw`,`global`,t,!0);let f=N(j(e,`.zcode`,`cli`,`config.json`));f&&jc(P(f.mcp)?.servers,`zcode`,`global`,t,!0);for(let n of nc(e)){let e=N(n);e&&jc(e.mcpServers,`workbuddy`,n,t,!0)}let p=bc(j(e,`.dsh`,`cordis.patch.yml`));if(p)try{let e=ni.parse(p),n=Array.isArray(e)?e:[],r={};for(let e of n){let t=P(e)?.insert,n=Array.isArray(t)?t:[e];for(let e of n){let t=P(e),n=t?P(t.config):void 0;t?.name===`@deepseek-ai/dsh-mcp-client`&&typeof n?.serverName==`string`&&(r[n.serverName]=n)}}jc(r,`deepseek-harness`,`global`,t,!1)}catch{}let m=N(Nc(e));m&&jc(m.mcpServers,`claude-desktop`,`global`,t,!0);let h=bc(j(e,`.codex`,`config.toml`));if(h)try{jc(ii(h).mcp_servers,`codex`,`global`,t,!1)}catch{}return t.sort((e,t)=>e.name.localeCompare(t.name)||e.source.localeCompare(t.source))}function Nc(e){return process.platform===`darwin`?j(e,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`):process.platform===`win32`?j(process.env.APPDATA??j(e,`AppData`,`Roaming`),`Claude`,`claude_desktop_config.json`):j(e,`.config`,`Claude`,`claude_desktop_config.json`)}function Pc(e,t,n){return e===`claude-code`?{file:j(n,`.claude.json`),mapKey:`mcpServers`,projectScoped:t!==`global`}:e===`qwen-code`?{file:j(n,`.qwen`,`settings.json`),mapKey:`mcpServers`,projectScoped:!1}:e===`opencode`?{file:j(n,`.config`,`opencode`,`opencode.json`),mapKey:`mcp`,projectScoped:!1}:e===`cursor`?{file:j(n,`.cursor`,`mcp.json`),mapKey:`mcpServers`,projectScoped:!1}:e===`windsurf`?{file:j(n,`.codeium`,`windsurf`,`mcp_config.json`),mapKey:`mcpServers`,projectScoped:!1}:e===`gemini`?{file:j(n,`.gemini`,`settings.json`),mapKey:`mcpServers`,projectScoped:!1}:e===`qoder`?{file:j(n,`.qoder`,`mcp.json`),mapKey:`mcpServers`,projectScoped:!1}:e===`qoderwork`?{file:j(n,`.qoderwork`,`mcp.json`),mapKey:`mcpServers`,projectScoped:!1}:e===`qwenwork`?{file:Js(n),mapKey:`mcpServers`,projectScoped:!1}:e===`openclaw`?{file:j(n,`.openclaw`,`openclaw.json`),mapKey:`servers`,parentKey:`mcp`,projectScoped:!1}:e===`zcode`?{file:j(n,`.zcode`,`cli`,`config.json`),mapKey:`servers`,parentKey:`mcp`,projectScoped:!1}:e===`workbuddy`?{file:nc(n)[0]??j(n,`.workbuddy-ai`,`mcp.json`),mapKey:`mcpServers`,projectScoped:!1}:e===`claude-desktop`?{file:Nc(n),mapKey:`mcpServers`,projectScoped:!1}:null}function Fc(e,t){if(typeof e==`string`){if(e.includes(`•`)){if(typeof t==`string`)return t;throw Error(`Replace masked values (•••) with the real value before saving.`)}return e}if(Array.isArray(e)){let n=Array.isArray(t)?t:[];return e.map((e,t)=>Fc(e,n[t]))}let n=P(e);if(n){let e=P(t)??{},r={};for(let[t,i]of Object.entries(n))r[t]=Fc(i,e[t]);return r}return e}function Ic(e,t,n){let r=e;if(t.projectScoped){let t=P(e.projects);r=t?P(t[n]):void 0}if(r)return t.parentKey?P(r[t.parentKey]):r}function Lc(e,t,n){let r=e;if(t.projectScoped){let t=P(e.projects)??{};e.projects=t;let i=P(t[n])??{};t[n]=i,r=i}if(t.parentKey){let e=P(r[t.parentKey])??{};return r[t.parentKey]=e,e}return r}function Rc(e,t,n,r,i=ei()){let a=Pc(e,t,i);if(!a)throw Error(`This MCP source is read-only and cannot be edited here.`);let o=n.trim();if(!o)throw Error(`Server name is required.`);let s=P(r);if(!s)throw Error(`Config must be a JSON object.`);let c=N(a.file)??{},l=Lc(c,a,t),u=P(l[a.mapKey])??{};l[a.mapKey]=u,u[o]=Fc(s,P(u[o])),Ur(Xr(a.file),{recursive:!0}),Jr(a.file,JSON.stringify(c,null,2)+`
|
|
2717
|
-
`,`utf-8`)}function
|
|
2718
|
-
`,`utf-8`)}const Bc=[{id:`claude-code`,label:`Claude Code`,paths:e=>[j(process.env.CLAUDE_CONFIG_DIR||j(e,`.claude`),`settings.json`),j(e,`.claude.json`)],detect:e=>{let t=process.env.CLAUDE_CONFIG_DIR||j(e,`.claude`),n=P(N(j(t,`settings.json`))?.env),r=n&&typeof n.ANTHROPIC_BASE_URL==`string`?n.ANTHROPIC_BASE_URL:void 0,i=n&&typeof n.ANTHROPIC_MODEL==`string`?n.ANTHROPIC_MODEL:void 0;return{configured:!!r,model:i}}},{id:`qwen-code`,label:`Qwen Code`,paths:e=>[j(e,`.qwen`,`settings.json`)],detect:e=>{let t=N(j(e,`.qwen`,`settings.json`)),n=P(t?.modelProviders),r=n?Object.values(n).some(e=>Array.isArray(e)&&e.some(e=>{let t=P(e)?.name;return typeof t==`string`&&(t===`bailian-cli`||t.startsWith(`[Bailian]`))})):!1,i=P(t?.model);return{configured:r,model:i&&typeof i.name==`string`?i.name:void 0}}},{id:`opencode`,label:`OpenCode`,paths:e=>[j(e,`.config`,`opencode`,`opencode.json`)],detect:e=>{let t=P(P(N(j(e,`.config`,`opencode`,`opencode.json`))?.provider)?.[`bailian-cli`]),n=P(t?.models);return{configured:!!t,model:n?Object.keys(n)[0]:void 0}}},{id:`openclaw`,label:`OpenClaw`,paths:e=>[j(e,`.openclaw`,`openclaw.json`)],detect:e=>{let t=P(P(P(N(j(e,`.openclaw`,`openclaw.json`))?.models)?.providers)?.[`bailian-cli`]),n=P((Array.isArray(t?.models)?t.models:[])[0]);return{configured:!!t,model:n&&typeof n.id==`string`?n.id:void 0}}},{id:`hermes`,label:`Hermes Agent`,paths:e=>[j(e,`.hermes`,`config.yaml`)],detect:e=>{let t=bc(j(e,`.hermes`,`config.yaml`));if(!t)return{configured:!1};let n;try{n=P(ni.parse(t))}catch{return{configured:!1}}let r=(Array.isArray(n?.custom_providers)?n.custom_providers:[]).some(e=>P(e)?.name===`bailian-cli`),i=P(n?.model),a=!!(i&&i.provider===`custom`&&typeof i.base_url==`string`&&i.base_url.includes(`aliyuncs.com`));return{configured:r||a,model:i&&typeof i.default==`string`?i.default:void 0}}},{id:`codex`,label:`Codex`,paths:e=>[j(e,`.codex`,`config.toml`),j(e,`.codex`,`auth.json`)],detect:e=>{let t=bc(j(e,`.codex`,`config.toml`));if(!t)return{configured:!1};let n={};try{n=ii(t)}catch{return{configured:!1}}return{configured:!!P(n.model_providers)?.[`bailian-cli`],model:typeof n.model==`string`?n.model:void 0}}}];function Vc(e=ei()){return Bc.map(t=>{let n=t.paths(e),r=n.some(e=>A(e)),{configured:i,model:a}=r?t.detect(e):{configured:!1,model:void 0};return{id:t.id,label:t.label,installed:r,configured:i,model:a,paths:n,origin:`local`}})}function F(e,t,n,r=!1){typeof n==`string`&&n.trim()&&e.push({label:t,value:n.trim(),secret:r})}function Hc(e,t){let n=[];if(e===`claude-code`){let e=P(N(j(t,`.claude`,`settings.json`))?.env);F(n,`Model`,e?.ANTHROPIC_MODEL),F(n,`Base URL`,e?.ANTHROPIC_BASE_URL),F(n,`Auth Token`,e?.ANTHROPIC_AUTH_TOKEN,!0)}else if(e===`qwen-code`){let e=N(j(t,`.qwen`,`settings.json`)),r=P(e?.model),i=P(P(e?.security)?.auth),a=P(e?.env);F(n,`Model`,r?.name),F(n,`Base URL`,i?.baseUrl??r?.baseUrl),F(n,`Protocol`,i?.selectedType),F(n,`API Key`,i?.apiKey??a?.BAILIAN_CLI_API_KEY,!0)}else if(e===`opencode`){let e=P(P(N(j(t,`.config`,`opencode`,`opencode.json`))?.provider)?.[`bailian-cli`]),r=P(e?.options),i=P(e?.models);F(n,`Model`,i?Object.keys(i)[0]:void 0),F(n,`Base URL`,r?.baseURL),F(n,`Provider`,e?.npm),F(n,`API Key`,r?.apiKey,!0)}else if(e===`openclaw`){let e=P(P(P(N(j(t,`.openclaw`,`openclaw.json`))?.models)?.providers)?.[`bailian-cli`]);F(n,`Model`,P((Array.isArray(e?.models)?e.models:[])[0])?.id),F(n,`Base URL`,e?.baseUrl),F(n,`API`,e?.api),F(n,`API Key`,e?.apiKey,!0)}else if(e===`hermes`){let e=bc(j(t,`.hermes`,`config.yaml`)),r;if(e)try{r=P(ni.parse(e))}catch{r=void 0}let i=P((Array.isArray(r?.custom_providers)?r.custom_providers:[]).find(e=>P(e)?.name===`bailian-cli`));F(n,`Model`,P((Array.isArray(i?.models)?i.models:[])[0])?.id??P(r?.model)?.default),F(n,`Base URL`,i?.base_url),F(n,`API Mode`,i?.api_mode),F(n,`API Key`,i?.api_key,!0)}else if(e===`codex`){let e=bc(j(t,`.codex`,`config.toml`)),r={};if(e)try{r=ii(e)}catch{r={}}let i=P(P(r.model_providers)?.[`bailian-cli`]),a=N(j(t,`.codex`,`auth.json`));F(n,`Model`,r.model),F(n,`Base URL`,i?.base_url),F(n,`Wire API`,i?.wire_api),F(n,`API Key`,a?.OPENAI_API_KEY,!0)}return n}function Uc(e){let t=e.trim();return t.length<=8?`•`.repeat(Math.max(t.length,4)):t.slice(0,3)+`•`.repeat(Math.min(t.length-3,16))}const Wc=/key|token|secret|password|passwd|auth|credential/i;function Gc(e,t=``){if(typeof e==`string`)return t&&Wc.test(t)&&e.trim()?Uc(e):e;if(Array.isArray(e))return e.map(e=>Gc(e));let n=P(e);if(n){let e={};for(let[t,r]of Object.entries(n))e[t]=Gc(r,t);return e}return e}function Kc(e){return e.endsWith(`.json`)?`json`:e.endsWith(`.yaml`)||e.endsWith(`.yml`)?`yaml`:e.endsWith(`.toml`)?`toml`:`text`}function qc(e,t=ei()){let n=Bc.find(t=>t.id===e);if(!n)return null;let r=n.paths(t),i=r.some(e=>A(e)),{configured:a,model:o}=i?n.detect(t):{configured:!1,model:void 0},s=i?Hc(e,t).map(e=>e.secret?{...e,raw:e.value,value:Uc(e.value)}:e):[],c=r.map(e=>({path:e,exists:A(e)})),l=i?r.filter(e=>A(e)).map(e=>({path:e,lang:Kc(e),text:bc(e)??``})).filter(e=>e.text.trim()):[];return{id:n.id,label:n.label,installed:i,configured:a,model:o,paths:r,origin:`local`,fields:s,files:c,settings:l}}const Jc={"claude-code":`claude`,"qwen-code":`qwen`,opencode:`opencode`,openclaw:`openclaw`,hermes:`hermes`,codex:`codex`};function Yc(e){return Object.prototype.hasOwnProperty.call(Jc,e)?Jc[e]:void 0}const Xc={"qwen-code":e=>[`-i`,e],"claude-code":e=>[e],codex:e=>[e]};function Zc(e){return Object.prototype.hasOwnProperty.call(Xc,e)}function Qc(e){let t=process.platform===`win32`?`where`:`which`;return new Promise(n=>{Dr(t,[e],{windowsHide:!0},e=>n(!e))})}function $c(e){let t=Yc(e);return t?Qc(t):Promise.resolve(!1)}function el(e){return`'${e.replace(/'/g,`'\\''`)}'`}function tl(e,t){let n=process.platform;return new Promise((r,i)=>{if(n===`darwin`){let n=[`-e`,`tell application "Terminal" to do script "${`cd ${el(t)} && ${e}`.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`,`-e`,`tell application "Terminal" to activate`];Dr(`osascript`,n,{windowsHide:!0},e=>e?i(e):r());return}if(n===`win32`){let n=[`/c`,`start`,``,`cmd`,`/k`,`cd /d ${t} && ${e}`];Dr(`cmd`,n,{windowsHide:!0},e=>e?i(e):r());return}let a=`cd ${el(t)} && ${e}; exec $SHELL`;Dr(`x-terminal-emulator`,[`-e`,`bash`,`-lc`,a],{windowsHide:!0},e=>e?i(/* @__PURE__ */ Error(`No supported terminal emulator was found`)):r())})}async function nl(e,t=process.cwd(),n){let r=Yc(e);if(!r)throw Error(`Unknown agent: ${e}`);if(!await Qc(r))throw Error(`\`${r}\` was not found on your PATH — install ${e} first.`);let i=r,a=(n??``).trim();if(a){let t=Xc[e];if(!t)throw Error(`${e} does not support dispatching a task prompt.`);i=[r,...t(a).map(el)].join(` `)}return await tl(i,t),{launched:!0,command:i}}const rl=[{id:`image-generate`,title:`文生图`,description:`一键生成一张示例图片并保存到输出目录。`,category:`图像`,prompt:"请使用 bl 的图像生成能力(如 `bl image generate` 命令)生成一张示例图片:一只在雨中撑伞的柯基,水彩风格,光线柔和。保存到输出目录后告诉我文件路径。"},{id:`image-describe`,title:`图片理解`,description:`从输出目录任选一张图片,详细描述内容与风格。`,category:`图像`,prompt:`请在输出目录(默认 output/images)中任选一张图片,用中文详细描述它的内容、主体、构图、色彩与风格,并推测它适合的使用场景。若目录为空请说明。`},{id:`image-alt-batch`,title:`批量 Alt 文本`,description:`为输出目录下的图片批量生成无障碍 alt 文本。`,category:`图像`,prompt:`请扫描输出目录(默认 output/images)下的所有图片,逐张生成简洁、准确的 alt 无障碍描述,最后以「文件名 → alt 文本」的表格汇总。若目录为空请说明。`},{id:`image-to-code`,title:`截图转代码`,description:`把输出目录里的界面截图还原成 HTML+CSS。`,category:`图像`,prompt:`请在输出目录(默认 output/images)中查找一张界面截图,用 HTML + CSS 尽可能还原它的布局、间距与配色,输出为一个可直接在浏览器打开的单文件,并简述还原思路。若没有找到截图请说明。`},{id:`speech-generate`,title:`文字转语音`,description:`把一句示例文字合成为自然语音。`,category:`音频`,prompt:"请使用 bl 的语音合成能力(如 `bl speech` 相关命令)把下面这句话合成为自然语音,保存到输出目录,并告诉我音频文件路径:欢迎使用阿里云百炼命令行工具,让多模态创作更简单。"},{id:`audio-summarize`,title:`音频转写总结`,description:`转写输出目录里的音频并提炼要点。`,category:`音频`,prompt:`请在输出目录(默认 output/speech)中找到一个音频文件,转写其内容,先给出完整文字,再用要点列表总结关键信息。若目录为空或缺少转写能力,请说明并尝试用可用的能力完成。`},{id:`video-generate`,title:`文生视频`,description:`一键生成一段示例短视频。`,category:`视频`,prompt:"请使用 bl 的视频生成能力(如 `bl video generate` 命令)生成一段示例短视频:日落时分海边奔跑的少年,电影质感,慢动作。保存到输出目录后告诉我视频文件路径。"},{id:`video-storyboard`,title:`视频分镜脚本`,description:`围绕示例主题产出可用于文生视频的分镜。`,category:`视频`,prompt:`围绕主题「城市清晨的第一杯咖啡」,为一支 15-30 秒的短视频撰写分镜脚本:逐镜头给出画面描述、时长、字幕或旁白,并为每个镜头附上可直接用于文生视频的英文 prompt。`},{id:`media-prompt-craft`,title:`多模态提示词`,description:`把一个示例创意扩展成图/视频/语音提示词。`,category:`多模态`,prompt:`把创意「未来赛博城市的夜市」扩展成三组高质量生成提示词:1) 文生图;2) 文生视频;3) 语音风格描述。每组给出中英对照,并简要说明关键参数建议。`},{id:`image-story-narration`,title:`图片配音文案`,description:`为输出目录里的图片写解说词并给出可合成文本。`,category:`多模态`,prompt:`请在输出目录(默认 output/images)中任选一张图片,为它撰写一段 60 秒左右的中文解说词(适合配音),语气生动。随后给出可直接用于语音合成的纯文本版本。若目录为空请说明。`},{id:`summarize-project`,title:`总结当前项目`,description:`让 agent 阅读当前目录,总结架构、技术栈与主要模块。`,category:`代码`,prompt:`请阅读当前工作目录的项目结构和关键源码,用简洁的中文总结:1) 它是做什么的;2) 技术栈;3) 主要模块及其职责;4) 值得注意的设计。先浏览再下结论,不要臆测。`},{id:`write-tests`,title:`为核心模块写单测`,description:`自动挑选缺测试的核心模块并补全单元测试。`,category:`代码`,prompt:`请在当前项目中挑选一个核心且缺少测试(或测试薄弱)的模块,为它编写全面的单元测试,覆盖主要逻辑分支和边界情况,并遵循本项目现有的测试框架与风格。先阅读相关文件及其依赖,再编写测试。`},{id:`code-review`,title:`代码审查`,description:`审查当前项目核心代码,指出问题与改进建议。`,category:`代码`,prompt:`请审查当前项目的核心源码,指出潜在的 bug、安全隐患、性能与可维护性问题,并给出具体、可操作的改进建议,按严重程度排序。先浏览项目结构,选取关键文件再审查。`},{id:`explain-code`,title:`解释核心代码`,description:`挑选入口或核心模块,解释其实现与依赖。`,category:`代码`,prompt:`请挑选当前项目的入口文件或核心模块,解释它的实现:职责是什么、关键流程如何运转、依赖了哪些模块。用清晰的中文说明,必要时给出调用关系。`},{id:`generate-readme`,title:`生成 README`,description:`阅读代码后生成结构清晰、与实现一致的 README.md。`,category:`文档`,prompt:`为当前工作目录的项目生成一个结构清晰的 README.md,包含:项目简介、安装步骤、使用示例、目录结构说明。请先阅读现有代码与配置再撰写,内容必须与实际实现一致。`}],il={"image-generate":{title:`Text to image`,description:`Generate a sample image and save it to the output directory.`,category:`Image`,prompt:"Use bl's image generation capability (such as `bl image generate`) to create a sample image: a corgi holding an umbrella in the rain, watercolor style, with soft lighting. Save it to the output directory and tell me the file path."},"image-describe":{title:`Image understanding`,description:`Pick an image from the output directory and describe its content and style.`,category:`Image`,prompt:`Pick an image from the output directory (output/images by default). Describe its subject, composition, colors, and style in detail, then suggest suitable use cases. If the directory is empty, say so.`},"image-alt-batch":{title:`Batch alt text`,description:`Generate accessible alt text for images in the output directory.`,category:`Image`,prompt:`Scan all images in the output directory (output/images by default) and write concise, accurate accessibility alt text for each one. Summarize the results in a File name -> Alt text table. If the directory is empty, say so.`},"image-to-code":{title:`Screenshot to code`,description:`Recreate a UI screenshot from the output directory with HTML and CSS.`,category:`Image`,prompt:`Find a UI screenshot in the output directory (output/images by default) and recreate its layout, spacing, and colors as closely as possible with HTML and CSS. Save it as a single file that opens directly in a browser and briefly explain your approach. If no screenshot is available, say so.`},"speech-generate":{title:`Text to speech`,description:`Turn a sample sentence into natural speech.`,category:`Audio`,prompt:"Use bl's speech synthesis capability (such as a `bl speech` command) to turn this sentence into natural speech: Welcome to Alibaba Cloud Model Studio CLI, making multimodal creation easier. Save the audio to the output directory and tell me the file path."},"audio-summarize":{title:`Transcribe and summarize audio`,description:`Transcribe an audio file from the output directory and summarize its key points.`,category:`Audio`,prompt:`Find an audio file in the output directory (output/speech by default), transcribe it, provide the full transcript, and then summarize the key points as a list. If the directory is empty or transcription is unavailable, explain that and try to complete the task with the capabilities available.`},"video-generate":{title:`Text to video`,description:`Generate a sample short video.`,category:`Video`,prompt:"Use bl's video generation capability (such as `bl video generate`) to create a sample short video: a teenager running along the beach at sunset, cinematic, in slow motion. Save it to the output directory and tell me the file path."},"video-storyboard":{title:`Video storyboard`,description:`Create a storyboard suitable for text-to-video generation.`,category:`Video`,prompt:`Create a storyboard for a 15-30 second short video themed The first cup of coffee in the city at dawn. For each shot, provide the visual description, duration, subtitles or narration, and an English prompt ready for text-to-video generation.`},"media-prompt-craft":{title:`Multimodal prompts`,description:`Expand a sample idea into image, video, and speech prompts.`,category:`Multimodal`,prompt:`Expand the idea A night market in a futuristic cyber city into three high-quality generation prompts: 1) text to image, 2) text to video, and 3) speech style. Provide each prompt in both Chinese and English, with brief parameter recommendations.`},"image-story-narration":{title:`Image narration`,description:`Write narration for an image in the output directory.`,category:`Multimodal`,prompt:`Pick an image from the output directory (output/images by default) and write an engaging English narration of about 60 seconds. Then provide a plain-text version ready for speech synthesis. If the directory is empty, say so.`},"summarize-project":{title:`Summarize this project`,description:`Read the current directory and summarize its architecture, stack, and main modules.`,category:`Code`,prompt:`Inspect the project structure and key source files in the current working directory, then concisely summarize: 1) what it does, 2) its technology stack, 3) its main modules and their responsibilities, and 4) notable design choices. Inspect the code before drawing conclusions; do not guess.`},"write-tests":{title:`Add tests for a core module`,description:`Choose an under-tested core module and add unit tests.`,category:`Code`,prompt:`Choose a core module in the current project that has no tests or weak coverage. Add comprehensive unit tests for its main branches and edge cases, following the project's existing test framework and style. Read the relevant files and dependencies before writing tests.`},"code-review":{title:`Code review`,description:`Review core project code and identify concrete improvements.`,category:`Code`,prompt:`Review the current project's core source code for potential bugs, security risks, performance issues, and maintainability problems. Give specific, actionable recommendations ordered by severity. Inspect the project structure and select the key files before reviewing them.`},"explain-code":{title:`Explain core code`,description:`Choose an entry point or core module and explain how it works.`,category:`Code`,prompt:`Choose the current project's entry point or a core module and explain its responsibilities, key execution flow, and dependencies. Use clear English and include the call relationships when useful.`},"generate-readme":{title:`Generate README`,description:`Generate a clear README.md that matches the implementation.`,category:`Documentation`,prompt:`Generate a clear README.md for the project in the current working directory. Include an overview, installation steps, usage examples, and a directory structure guide. Read the existing source code and configuration first; the content must match the actual implementation.`}};function al(e){return e===`zh-CN`?rl.map(e=>({...e})):rl.map(e=>({...e,...il[e.id]}))}function ol(e,t){return al(t).find(t=>t.id===e)}function sl(e,t){return e.prompt.replace(/\{\{(\w+)\}\}/g,(e,n)=>{let r=t[n];return typeof r==`string`?r.trim():``})}const cl=/* @__PURE__ */ new Uint8Array(512),ll=/* @__PURE__ */ new Uint8Array(256);(()=>{let e=1;for(let t=0;t<255;t++)cl[t]=e,ll[e]=t,e<<=1,e&256&&(e^=285);for(let e=255;e<512;e++)cl[e]=cl[e-255]})();function ul(e,t){return e===0||t===0?0:cl[ll[e]+ll[t]]}function dl(e){let t=[1];for(let n=0;n<e;n++){let e=Array.from({length:t.length+1},()=>0);for(let r=0;r<t.length;r++)e[r]^=t[r],e[r+1]^=ul(t[r],cl[n]);t=e}return t.map(e=>ll[e])}function fl(e,t){let n=dl(t),r=new Uint8Array(e.length+t);r.set(e,0);for(let t=0;t<e.length;t++){let e=r[t];if(e!==0){let i=ll[e];for(let e=0;e<n.length;e++)r[t+e]^=cl[(n[e]+i)%255]}}return Array.from(r.slice(e.length))}const pl=[[19,7],[34,10],[55,15],[80,20],[108,26]];function ml(e){let t=12+e*8;for(let e=0;e<pl.length;e++)if(pl[e][0]*8>=t)return e+1;throw Error(`qr: data too large for supported versions (max 108 bytes)`)}function hl(e,t){let[n]=pl[t-1],r=[],i=(e,t)=>{for(let n=t-1;n>=0;n--)r.push(e>>n&1)};i(4,4),i(e.length,8);for(let t of e)i(t,8);let a=n*8;for(i(0,Math.min(4,a-r.length));r.length%8!=0;)r.push(0);let o=[];for(let e=0;e<r.length;e+=8){let t=0;for(let n=0;n<8;n++)t=t<<1|r[e+n];o.push(t)}let s=[236,17];for(let e=0;o.length<n;e++)o.push(s[e%2]);return o.concat(fl(o,pl[t-1][1]))}function gl(e){return{size:e,mod:new Uint8Array(e*e),fn:new Uint8Array(e*e)}}function _l(e,t,n,r){e.mod[t*e.size+n]=r,e.fn[t*e.size+n]=1}function vl(e,t,n){for(let r=-1;r<=7;r++)for(let i=-1;i<=7;i++){let a=t+r,o=n+i;a<0||a>=e.size||o<0||o>=e.size||_l(e,a,o,+(r>=0&&r<=6&&i>=0&&i<=6&&(r===0||r===6||i===0||i===6||r>=2&&r<=4&&i>=2&&i<=4)))}}function yl(e,t,n){for(let r=-2;r<=2;r++)for(let i=-2;i<=2;i++){let a=Math.max(Math.abs(r),Math.abs(i));_l(e,t+r,n+i,a===1?0:1)}}function bl(e,t){let n=e.size;for(let t=0;t<n;t++)_l(e,6,t,+(t%2==0)),_l(e,t,6,+(t%2==0));if(vl(e,0,0),vl(e,0,n-7),vl(e,n-7,0),t>=2){let t=n-7;yl(e,t,t)}for(let t=0;t<9;t++)t!==6&&(e.fn[8*n+t]=1),t!==6&&(e.fn[t*n+8]=1);e.fn[8*n+6]=1,e.fn[6*n+8]=1;for(let t=0;t<8;t++)e.fn[(n-1-t)*n+8]=1;for(let t=0;t<8;t++)e.fn[8*n+(n-1-t)]=1;_l(e,n-8,8,1)}function xl(e,t){let n=e.size,r=[];for(let e of t)for(let t=7;t>=0;t--)r.push(e>>t&1);let i=0,a=!0;for(let t=n-1;t>=1;t-=2){t===6&&(t=5);for(let o=0;o<n;o++){let s=a?n-1-o:o;for(let a of[0,1]){let o=t-a;e.fn[s*n+o]||(e.mod[s*n+o]=i<r.length?r[i++]:0)}}a=!a}}const Sl=[(e,t)=>(e+t)%2==0,e=>e%2==0,(e,t)=>t%3==0,(e,t)=>(e+t)%3==0,(e,t)=>(Math.floor(e/2)+Math.floor(t/3))%2==0,(e,t)=>e*t%2+e*t%3==0,(e,t)=>(e*t%2+e*t%3)%2==0,(e,t)=>((e+t)%2+e*t%3)%2==0];function Cl(e,t){let n=Sl[t];for(let t=0;t<e.size;t++)for(let r=0;r<e.size;r++)!e.fn[t*e.size+r]&&n(t,r)&&(e.mod[t*e.size+r]^=1)}function wl(e){let t=e.size,n=(n,r)=>e.mod[n*t+r],r=0;for(let e=0;e<t;e++){let i=1,a=1;for(let o=1;o<t;o++)n(e,o)===n(e,o-1)?i++:(i>=5&&(r+=i-2),i=1),n(o,e)===n(o-1,e)?a++:(a>=5&&(r+=a-2),a=1);i>=5&&(r+=i-2),a>=5&&(r+=a-2)}for(let e=0;e<t-1;e++)for(let i=0;i<t-1;i++){let t=n(e,i);t===n(e,i+1)&&t===n(e+1,i)&&t===n(e+1,i+1)&&(r+=3)}let i=[1,0,1,1,1,0,1,0,0,0,0],a=[0,0,0,0,1,0,1,1,1,0,1],o=(e,t,n)=>{for(let r=0;r<n.length;r++)if(e(t+r)!==n[r])return!1;return!0};for(let e=0;e<t;e++)for(let s=0;s<=t-11;s++)(o(t=>n(e,t),s,i)||o(t=>n(e,t),s,a))&&(r+=40),(o(t=>n(t,e),s,i)||o(t=>n(t,e),s,a))&&(r+=40);let s=0;for(let n=0;n<t*t;n++)s+=e.mod[n];let c=s*100/(t*t),l=Math.floor(Math.abs(c-50)/5);return r+=l*10,r}function Tl(e){let t=8|e,n=t<<10;for(let e=14;e>=10;e--)n>>e&1&&(n^=1335<<e-10);return(t<<10|n)^21522}function El(e,t){let n=e.size,r=Tl(t),i=e=>r>>e&1;for(let t=0;t<=5;t++)e.mod[t*n+8]=i(t);e.mod[7*n+8]=i(6),e.mod[8*n+8]=i(7),e.mod[8*n+7]=i(8);for(let t=9;t<15;t++)e.mod[8*n+(14-t)]=i(t);for(let t=0;t<8;t++)e.mod[(n-1-t)*n+8]=i(t);for(let t=8;t<15;t++)e.mod[8*n+(n-15+t)]=i(t);e.mod[(n-8)*n+8]=1}function Dl(e){let t=new TextEncoder().encode(e),n=ml(t.length),r=hl(t,n),i=gl(17+4*n);bl(i,n),xl(i,r);let a=0,o=1/0;for(let e=0;e<8;e++){Cl(i,e),El(i,e);let t=wl(i);t<o&&(o=t,a=e),Cl(i,e)}Cl(i,a),El(i,a);let s=[];for(let e=0;e<i.size;e++){let t=[];for(let n=0;n<i.size;n++)t.push(i.mod[e*i.size+n]===1);s.push(t)}return s}function Ol(e){let t=Dl(e),n=t.length,r=n+8,i=``;for(let e=0;e<n;e++)for(let r=0;r<n;r++)t[e][r]&&(i+=`<rect x="${r+4}" y="${e+4}" width="1" height="1"/>`);return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${r} ${r}" shape-rendering="crispEdges" role="img" aria-label="QR code"><rect width="${r}" height="${r}" fill="#ffffff"/><g fill="#000000">${i}</g></svg>`}function kl(e){let{identity:t,settings:n,authStore:r}=e;return{status(){let e=r.describe(),t={apiKey:!!e.apiKey,console:!!e.console,openapi:!!e.openapi},n;e.console?n=At(e.console.token):e.apiKey?n=At(e.apiKey.token):e.openapi&&(n=At(e.openapi.accessKeyId));let i=e.console?`console`:e.apiKey?`apiKey`:e.openapi?`openapi`:null;return{authenticated:t.apiKey||t.console||t.openapi,methods:t,primary:i,region:e.console?.region,site:e.console?.site,masked:n}},startConsoleLogin(){let e=Za(r.describe().console?.site),i=!!r.stored().apiKey;po(e,{identity:t,settings:n,authStore:r},{needApiKey:!i}).catch(e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(`console login failed: ${t}\n`)})},logout(){return r.logout(`all`)}}}const Al={".png":`image`,".jpg":`image`,".jpeg":`image`,".webp":`image`,".gif":`image`,".bmp":`image`,".svg":`image`,".mp4":`video`,".mov":`video`,".webm":`video`,".mkv":`video`,".avi":`video`,".mp3":`audio`,".wav":`audio`,".m4a":`audio`,".aac":`audio`,".flac":`audio`,".ogg":`audio`},jl={".png":`image/png`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".webp":`image/webp`,".gif":`image/gif`,".bmp":`image/bmp`,".svg":`image/svg+xml`,".mp4":`video/mp4`,".mov":`video/quicktime`,".webm":`video/webm`,".mkv":`video/x-matroska`,".avi":`video/x-msvideo`,".mp3":`audio/mpeg`,".wav":`audio/wav`,".m4a":`audio/mp4`,".aac":`audio/aac`,".flac":`audio/flac`,".ogg":`audio/ogg`};function Ml(e=ei()){return j(e,`bailian-output`)}function Nl(e){return Al[e.toLowerCase()]??`other`}function Pl(e){return jl[e.toLowerCase()]??`application/octet-stream`}function Fl(e,t,n){let r;try{r=Gr(e,{withFileTypes:!0})}catch{return}for(let i of r){let r=j(e,i.name);i.isDirectory()?t>0&&Fl(r,t-1,n):(i.isFile()||i.isSymbolicLink())&&n.push(r)}}function Il(e=Ml()){let t=[];if(!A(e))return{base:e,assets:t};let n=[];Fl(e,8,n);for(let r of n){let n;try{n=Kr(r)}catch{continue}if(!n.isFile())continue;let i=Qr(e,r),a=i.split($r),o=a.length>1?a[0]:`other`,s=Zr(r);t.push({name:r.split($r).pop()??r,category:o,kind:Nl(s),relPath:i,size:n.size,mtime:n.mtimeMs,ext:s.replace(/^\./,``).toLowerCase()})}return t.sort((e,t)=>t.mtime-e.mtime),{base:e,assets:t}}function Ll(e,t){if(typeof t!=`string`||t.length===0)return null;let n=M(e),r=M(n,t);return r!==n&&!r.startsWith(n+$r)?null:r}const Rl={port:{type:`number`,valueHint:`<port>`,description:{"en-US":`Port to listen on (default: random free port)`,"zh-CN":`监听端口(默认:随机可用端口)`}},noOpen:{type:`switch`,description:{"en-US":`Do not open the browser automatically`,"zh-CN":`不自动打开浏览器`}}};function zl(e){return e instanceof n||e instanceof Error?e.message:String(e)}function I(e,t,n){e.writeHead(t,{"Content-Type":`application/json; charset=utf-8`}),e.end(JSON.stringify(n))}function Bl(e){return e.read().language??o}function Vl(e){return new Promise((t,n)=>{let r=0,i=[];e.on(`data`,t=>{if(r+=t.length,r>1048576){n(/* @__PURE__ */ Error(`payload too large`)),e.destroy();return}i.push(t)}),e.on(`end`,()=>t(Buffer.concat(i).toString(`utf8`))),e.on(`error`,n)})}function Hl(e,t){return new Promise((n,r)=>{let i=0,a=[];e.on(`data`,n=>{if(i+=n.length,i>t){r(/* @__PURE__ */ Error(`payload too large`)),e.destroy();return}a.push(n)}),e.on(`end`,()=>n(Buffer.concat(a))),e.on(`error`,r)})}function Ul(e,t){if(!e)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&Tr(n,r)}function Wl(e){let t={};for(let[n,r]of Object.entries(e)){let e=``;typeof r==`string`?e=r:typeof r==`number`||typeof r==`boolean`?e=String(r):Array.isArray(r)&&(e=JSON.stringify(r)),e!==``&&(t[us(n)]=fs(n,e))}return t}function Gl(e,t){let n=new Set(is),r={};for(let[t,i]of Object.entries(e))n.has(t)||(r[t]=i);return{...r,...t}}function Kl(e,t,n=Ml(),r){let i=null,a=()=>i===null?Bl(t):en(i==="default"?void 0:i).language??o;return Er.createServer(async(o,s)=>{try{let c=(o.headers.host||``).split(`:`)[0];if(c!==`127.0.0.1`&&c!==`localhost`){s.writeHead(403,{"Content-Type":`text/plain; charset=utf-8`}),s.end(`forbidden host
|
|
2719
|
-
`);return}let l=new URL(o.url??`/`,`http://127.0.0.1`);if(!
|
|
2720
|
-
`);return}let u=o.method??`GET`,d=l.pathname;if(d===`/`&&u===`GET`){s.writeHead(200,{"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-store`,"X-Content-Type-Options":`nosniff`,"Content-Security-Policy":`default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src 'self' data: https://img.alicdn.com https://oss.aliyuncs.com; media-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'`}),s.end(
|
|
2721
|
-
`)}catch(e){if(console.error(`[config ui] request failed:`,e),s.headersSent){s.end();return}I(s,500,{error:
|
|
2722
|
-
`);let u=
|
|
2723
|
-
`),t.dryRun){O({agent:r,label:l.label,base_url:s,api_key:
|
|
2714
|
+
`,e)}function zs(e){let t=``,n=0,r=!1;for(;n<e.length;){let i=e[n],a=e[n+1];if(r){if(t+=i,i===`\\`){t+=a??``,n+=2;continue}i===`"`&&(r=!1),n+=1;continue}if(i===`"`){r=!0,t+=i,n+=1;continue}if(i===`/`&&a===`/`){for(;n<e.length&&e[n]!==`
|
|
2715
|
+
`;)n+=1;continue}if(i===`/`&&a===`*`){for(n+=2;n<e.length&&(e[n]!==`*`||e[n+1]!==`/`);)n+=1;n+=2;continue}t+=i,n+=1}let i=``;for(n=0,r=!1;n<t.length;){let e=t[n];if(r){if(i+=e,e===`\\`){i+=t[n+1]??``,n+=2;continue}e===`"`&&(r=!1),n+=1;continue}if(e===`"`&&(r=!0),e===`,`){let e=n+1;for(;e<t.length&&/\s/.test(t[e]);)e+=1;if(t[e]===`}`||t[e]===`]`){n+=1;continue}}i+=e,n+=1}return i}function Bs(e){if(!Kr(e))return{};try{return JSON.parse(Jr(e,`utf-8`))}catch{return{}}}function Vs(e){if(!Kr(e))return{};try{return JSON.parse(zs(Jr(e,`utf-8`)))}catch{return{}}}function Hs(e,t){qr($r(e),{recursive:!0});let n=e+`.tmp`;Zr(n,JSON.stringify(t,null,2)+`
|
|
2716
|
+
`,{mode:384}),Yr(n,e)}function Us(e,t){qr($r(e),{recursive:!0});let n=e+`.tmp`;Zr(n,t,{mode:384}),Yr(n,e)}function Ws(e){if(!Kr(e))return;let t=Math.floor(Date.now()/1e3);Wr(e,`${e}.bak.${t}`)}function Gs(e){return e.includes(`/apps/anthropic`)}function Ks(e){let t=e.trim().replace(/\/+$/,``);if(Gs(t))return{url:t};if(t.includes(`/compatible-mode`))return{url:t.replace(/\/compatible-mode(?:\/v\d+)?/,`/apps/anthropic`),rewrittenFrom:e.trim()};try{let n=new URL(t),r=n.hostname;if((r.includes(`dashscope`)||r.includes(`maas.aliyuncs.com`)||r.includes(`token-plan`))&&(n.pathname===`/`||n.pathname===``))return{url:`${n.origin}/apps/anthropic`,rewrittenFrom:e.trim()}}catch{}throw new n(`Claude Code requires an Anthropic-compatible base URL, got "${e}".`,l.USAGE,`Use a URL ending in /apps/anthropic (not /compatible-mode/v1). Example: https://dashscope.aliyuncs.com/apps/anthropic`)}function qs(e){let t=e.trim();if(!/^[a-z0-9-]+$/.test(t))throw new n(`Invalid --region "${e}".`,l.USAGE,`Use a Model Studio region id, e.g. cn-beijing or ap-southeast-1.`);return`https://token-plan.${t}.maas.aliyuncs.com/compatible-mode/v1`}const Js=[`codex`,`claude-code`,`cursor`,`qoder`,`qoderwork`,`qwenwork`,`qwen-code`,`gemini`,`opencode`,`openclaw`,`deepseek-harness`,`zcode`,`workbuddy`],Ys=`@deepseek-ai/dsh-mcp-client`,Xs=`__dshOtherPatches`,Zs=`mcpServers`,Qs=[`.workbuddy-ai`,`.workbuddy`,`.codebuddy`],$s=[`.openclaw`,`.clawdbot`,`.moltbot`];function ec(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tc(e,t){if(!A(e))return{};try{let n=t(ai(e,`utf8`));if(!ec(n))throw Error(`root value is not an object`);return n}catch(t){throw new n(`Cannot update MCP configuration because ${e} is invalid.`,l.GENERAL,`Fix the existing configuration file and retry; it was not changed.`,{cause:t})}}function nc(e){return tc(e,e=>JSON.parse(zs(e)))}function rc(e){return tc(e,yi)}function ic(e,t){let r=e[t];if(r===void 0){let n={};return e[t]=n,n}if(!ec(r))throw new n(`Cannot update MCP configuration because ${t} is not an object.`,l.GENERAL);return r}function ac(e,t){let n=e;for(let e of t)n=ic(n,e);return n}function oc(e,t){let n=e.paths?.(t);return n&&n.length>0?n:[e.path(t)]}function sc(e,t,n){return e?.trim()||j(t,n)}function cc(e,t){return e===void 0||e===`unchanged`?t:t===`updated`||e===`updated`?`updated`:e}function lc(e){return new n(`${e===`codex`?`Codex`:e===`deepseek-harness`?`DeepSeek Harness`:e} does not support SSE MCP servers; use --transport streamable-http.`,l.USAGE)}const uc=[`.qwenworkcn`,`.qwenwork`];function dc(e){return uc.map(t=>j(e,t))}function fc(e){let t=dc(e);for(let e of t){let t=j(e,`mcp.json`);if(A(t))return t}for(let e of t)if(A(e))return j(e,`mcp.json`);return j(t[0],`mcp.json`)}function pc(e){return j(e,`.config`,`opencode`,`opencode.json`)}function mc(e){let t=process.env.OPENCLAW_CONFIG_PATH?.trim();if(t)return t;let n=$s.map(t=>j(e,t)).find(e=>A(e));return j(n??j(e,$s[0]),`openclaw.json`)}function hc(e){return sc(process.env.DSH_HOME,e,`.dsh`)}function gc(e){return j(hc(e),`cordis.patch.yml`)}function _c(e){return j(sc(process.env.ZCODE_HOME,e,`.zcode`),`cli`,`config.json`)}function vc(e){return Qs.map(t=>j(e,t))}function yc(e){let t=j(e,`.mcp.json`);return A(t)?t:j(e,`mcp.json`)}function bc(e){let t=vc(e).filter(e=>A(e));return(t.length>0?t:[j(e,Qs[0])]).map(e=>yc(e))}function xc(e){return ec(e)&&e.name===Ys&&ec(e.config)}function Sc(e){let t=e.config;if(ec(t)&&typeof t.serverName==`string`&&t.serverName!==``)return t.serverName}function Cc(e){if(!A(e))return{[Xs]:[],[Zs]:{}};let t;try{t=_i.parse(ai(e,`utf8`))}catch(t){throw new n(`Cannot update MCP configuration because ${e} is invalid.`,l.GENERAL,`Fix the existing configuration file and retry; it was not changed.`,{cause:t})}if(t==null)return{[Xs]:[],[Zs]:{}};if(!Array.isArray(t))throw new n(`Cannot update MCP configuration because ${e} is invalid.`,l.GENERAL,`Fix the existing configuration file and retry; it was not changed.`);let r=[],i={};for(let e of t){if(ec(e)&&Array.isArray(e.insert)){let t=[];for(let n of e.insert){if(xc(n)){let e=Sc(n);if(e){i[e]=n;continue}}t.push(n)}t.length>0&&r.push({...e,insert:t});continue}if(xc(e)){let t=Sc(e);if(t){i[t]=e;continue}}r.push(e)}return{[Xs]:r,[Zs]:i}}function wc(e){let t=Array.isArray(e[Xs])?e[Xs]:[],n=ec(e[Zs])?e[Zs]:{},r=[...t],i=Object.values(n);return i.length>0&&r.push({insert:i}),_i.stringify(r)}function Tc(e){let t=e.serverKeys??[`mcpServers`];return{path:e.path,paths:e.paths,installed:e.installed,supports:e.supports??(()=>!0),parse:nc,serialize:e=>`${JSON.stringify(e,null,2)}\n`,getServers:e=>ac(e,t),buildEntry:e.buildEntry??(t=>e.typed?{type:t.transport===`sse`?`sse`:`http`,url:t.endpoint,headers:t.headers}:{url:t.endpoint,headers:t.headers})}}const Ec={codex:{path:e=>j(process.env.CODEX_HOME||j(e,`.codex`),`config.toml`),installed:e=>A(process.env.CODEX_HOME||j(e,`.codex`))||A(j(process.env.CODEX_HOME||j(e,`.codex`),`config.toml`)),supports:e=>e===`streamable-http`,parse:rc,serialize:e=>`${bi(e)}\n`,getServers:e=>ic(e,`mcp_servers`),buildEntry:e=>({url:e.endpoint,http_headers:e.headers})},"claude-code":{path:e=>j(e,`.claude.json`),installed:e=>A(j(e,`.claude`))||A(j(e,`.claude.json`)),supports:()=>!0,parse:nc,serialize:e=>`${JSON.stringify(e,null,2)}\n`,getServers:e=>ic(e,`mcpServers`),buildEntry:e=>({type:e.transport===`sse`?`sse`:`http`,url:e.endpoint,headers:e.headers})},cursor:Tc({path:e=>j(e,`.cursor`,`mcp.json`),installed:e=>A(j(e,`.cursor`))||A(j(e,`.cursor`,`mcp.json`))}),qoder:Tc({path:e=>j(e,`.qoder`,`mcp.json`),installed:e=>A(j(e,`.qoder`))||A(j(e,`.qoder`,`mcp.json`))}),qoderwork:Tc({path:e=>j(e,`.qoderwork`,`mcp.json`),installed:e=>A(j(e,`.qoderwork`))||A(j(e,`.qoderwork`,`mcp.json`))}),qwenwork:Tc({path:fc,installed:e=>dc(e).some(e=>A(e)||A(j(e,`mcp.json`))),buildEntry:e=>({type:e.transport===`sse`?`sse`:`streamable-http`,url:e.endpoint,headers:e.headers})}),"qwen-code":{path:e=>j(e,`.qwen`,`settings.json`),installed:e=>A(j(e,`.qwen`)),supports:()=>!0,parse:nc,serialize:e=>`${JSON.stringify(e,null,2)}\n`,getServers:e=>ic(e,`mcpServers`),buildEntry:e=>e.transport===`sse`?{url:e.endpoint,headers:e.headers}:{httpUrl:e.endpoint,headers:e.headers}},gemini:{path:e=>j(e,`.gemini`,`settings.json`),installed:e=>A(j(e,`.gemini`)),supports:()=>!0,parse:nc,serialize:e=>`${JSON.stringify(e,null,2)}\n`,getServers:e=>ic(e,`mcpServers`),buildEntry:e=>e.transport===`sse`?{url:e.endpoint,headers:e.headers}:{httpUrl:e.endpoint,headers:e.headers}},opencode:Tc({path:pc,installed:e=>A(j(e,`.config`,`opencode`))||A(pc(e)),serverKeys:[`mcp`],buildEntry:e=>({type:`remote`,url:e.endpoint,enabled:!0,oauth:!1,headers:e.headers})}),openclaw:Tc({path:mc,installed:e=>!!process.env.OPENCLAW_CONFIG_PATH?.trim()||$s.some(t=>A(j(e,t)))||A(mc(e)),serverKeys:[`mcp`,`servers`],buildEntry:e=>({url:e.endpoint,transport:e.transport===`sse`?`sse`:`streamable-http`,headers:e.headers})}),"deepseek-harness":{path:gc,installed:e=>A(hc(e)),supports:e=>e===`streamable-http`,parse:Cc,serialize:wc,getServers:e=>ic(e,Zs),buildEntry:e=>({id:`mcp-bailian-${e.name}`,name:Ys,config:{serverName:e.name,transport:`streamable-http`,url:e.endpoint,headers:e.headers}})},zcode:Tc({path:_c,installed:e=>A(sc(process.env.ZCODE_HOME,e,`.zcode`)),serverKeys:[`mcp`,`servers`],buildEntry:e=>({type:e.transport===`sse`?`sse`:`http`,url:e.endpoint,enabled:!0,headers:e.headers})}),workbuddy:Tc({path:e=>bc(e)[0]??j(e,Qs[0],`mcp.json`),paths:bc,installed:e=>vc(e).some(e=>A(e)),typed:!0})};function Dc(e){return Array.isArray(e)?`[${e.map(Dc).join(`,`)}]`:ec(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Dc(e[t])}`).join(`,`)}}`:JSON.stringify(e)}function Oc(e){return Lr(`sha256`).update(Dc(e)).digest(`hex`)}function kc(e,t){return`${e}:${t}`}function Ac(e){return j(e,`mcp-registrations.json`)}function jc(e){let t=Ac(e);if(!A(t))return{version:1,registrations:{}};let r=nc(t);if(r.version!==1||!ec(r.registrations))throw new n(`Cannot update MCP registrations because ${t} has an unsupported format.`,l.GENERAL);return r}function Mc(e,t,r,i){if(e!==void 0){if(!t)throw new n(`MCP server "${i}" already exists in ${r} and is not managed by bailian-cli.`,l.GENERAL,`Choose another server name or remove the existing entry yourself.`);if(Oc(e)!==t.fingerprint)throw new n(`MCP server "${i}" in ${r} conflicts with the last bailian-cli registration.`,l.GENERAL,`The entry was changed after registration; resolve it manually before retrying.`)}}function Nc(e){for(let t of e.reverse())try{t.original===void 0?ci(t.path):Us(t.path,t.original)}catch{}}function Pc(e,t,r){let i=[];try{for(let t of e)Ws(t.path),Us(t.path,t.content),i.push(t);Hs(Ac(r),t)}catch(e){throw Nc(i),new n(`Failed to update MCP Agent configuration.`,l.GENERAL,void 0,{cause:e})}}function Fc(e,t){return e===`all`?Js.filter(e=>Ec[e].installed(t)):[e]}function Ic(e){let t=jc(e.configDir),n=[],r=[];for(let i of e.agents){let a=Ec[i];if(!a.supports(e.spec.transport))throw lc(i);let o=oc(a,e.home),s=a.path(e.home),c=kc(i,e.spec.name),l=t.registrations[c],u=a.buildEntry(e.spec),d=Oc(u),f;for(let t of o){let r=a.parse(t),o=a.getServers(r),s=o[e.spec.name];Mc(s,l,i,e.spec.name);let c=s===void 0?`added`:Oc(s)===d?`unchanged`:`updated`;f=cc(f,c),c!==`unchanged`&&(o[e.spec.name]=u,n.push({path:t,original:A(t)?ai(t,`utf8`):void 0,content:a.serialize(r)}))}let p=f??`unchanged`;r.push({agent:i,path:s,status:p}),p!==`unchanged`&&(t.registrations[c]={agent:i,name:e.spec.name,serverCode:e.spec.serverCode,transport:e.spec.transport,endpoint:e.spec.endpoint,path:s,fingerprint:d,cliVersion:e.cliVersion,updatedAt:(/* @__PURE__ */ new Date()).toISOString()})}return n.length>0&&Pc(n,t,e.configDir),r}function Lc(e){let t=jc(e.configDir),n=[],r=[],i=!1;for(let a of e.agents){let o=Ec[a],s=o.path(e.home),c=kc(a,e.name),l=t.registrations[c];if(!l){r.push({agent:a,path:s,status:`absent`});continue}let u=!1,d=!1;for(let t of oc(o,e.home)){let r=o.parse(t),i=o.getServers(r),s=i[e.name];s!==void 0&&(d=!0,Mc(s,l,a,e.name),delete i[e.name],u=!0,n.push({path:t,original:ai(t,`utf8`),content:o.serialize(r)}))}delete t.registrations[c],i=!0,r.push({agent:a,path:s,status:d&&u?`removed`:`absent`})}return(n.length>0||i)&&Pc(n,t,e.configDir),r}function Rc(e){try{return ai(e,`utf-8`)}catch{return}}function N(e){let t=Rc(e);if(t!==void 0)try{let e=JSON.parse(t);return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}catch{return}}function P(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}function zc(e){let t=/^---\s*\n([\s\S]*?)\n---/.exec(e);if(!t)return{};try{return P(_i.parse(t[1]))??{}}catch{return{}}}function Bc(e,t=500){let n=0,r=e=>{if(n>=t)return;let i;try{i=oi(e,{withFileTypes:!0})}catch{return}for(let a of i){if(n>=t)return;let i=j(e,a.name);a.isDirectory()?r(i):n+=1}};return r(e),n}function Vc(e){return[{source:`global`,dir:j(e,`.agents`,`skills`)},{source:`claude-code`,dir:j(e,`.claude`,`skills`)},{source:`cursor`,dir:j(e,`.cursor`,`skills`)},{source:`qwen-code`,dir:j(e,`.qwen`,`skills`)},{source:`codex`,dir:j(e,`.codex`,`skills`)},{source:`opencode`,dir:j(e,`.config`,`opencode`,`skills`)},{source:`openclaw`,dir:j(e,`.openclaw`,`skills`)},{source:`openclaw`,dir:j(e,`.openclaw`,`workspace`,`skills`)},{source:`hermes`,dir:j(e,`.hermes`,`skills`)},{source:`gemini`,dir:j(e,`.gemini`,`skills`)},{source:`antigravity`,dir:j(e,`.gemini`,`antigravity`,`skills`)},{source:`windsurf`,dir:j(e,`.windsurf`,`skills`)},{source:`windsurf`,dir:j(e,`.codeium`,`windsurf`,`skills`)},{source:`qoderwork`,dir:j(e,`.qoderwork`,`skills`)},{source:`workbuddy`,dir:j(e,`.workbuddy`,`skills`)}]}function Hc(e=hi()){let t=/* @__PURE__ */ new Map;for(let{source:n,dir:r}of Vc(e)){let e;try{e=oi(r,{withFileTypes:!0})}catch{continue}for(let i of e){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let e=j(r,i.name),a=j(e,`SKILL.md`);if(!A(a))continue;let o=t.get(i.name);if(o){o.sources.includes(n)||o.sources.push(n);continue}let s=zc(Rc(a)??``),c=P(s.metadata),l=typeof s.description==`string`?s.description.trim():``,u=c&&typeof c.version==`string`?c.version:typeof s.version==`string`?s.version:void 0;t.set(i.name,{id:i.name,name:typeof s.name==`string`&&s.name?s.name:i.name,description:l,version:u,fileCount:Bc(e),path:e,sources:[n],origin:`local`})}}return[...t.values()].sort((e,t)=>e.name.localeCompare(t.name))}function Uc(e,t=hi()){let n=Hc(t).find(t=>t.id===e);if(!n)return null;let r=Rc(j(n.path,`SKILL.md`))??``;return{...n,content:r}}const Wc=[{source:`global`,label:`All agents (~/.agents/skills)`,sub:[`.agents`,`skills`]},{source:`claude-code`,label:`Claude Code`,sub:[`.claude`,`skills`]},{source:`qwen-code`,label:`Qwen Code`,sub:[`.qwen`,`skills`]},{source:`codex`,label:`Codex`,sub:[`.codex`,`skills`]},{source:`opencode`,label:`OpenCode`,sub:[`.config`,`opencode`,`skills`]},{source:`openclaw`,label:`OpenClaw`,sub:[`.openclaw`,`skills`]},{source:`qoderwork`,label:`QoderWork`,sub:[`.qoderwork`,`skills`]},{source:`windsurf`,label:`Windsurf`,sub:[`.codeium`,`windsurf`,`skills`]},{source:`gemini`,label:`Gemini`,sub:[`.gemini`,`skills`]}];function Gc(e,t){let n=Wc.find(t=>t.source===e);return n?j(t,...n.sub):null}function Kc(e){let t=-1,n=Math.max(0,e.length-22-65535);for(let r=e.length-22;r>=n;r--)if(e.readUInt32LE(r)===101010256){t=r;break}if(t<0)throw Error(`Not a valid .zip archive.`);let r=e.readUInt16LE(t+10),i=e.readUInt32LE(t+16),a=[];for(let t=0;t<r&&!(i+46>e.length||e.readUInt32LE(i)!==33639248);t++){let t=e.readUInt16LE(i+10),n=e.readUInt32LE(i+20),r=e.readUInt16LE(i+28),o=e.readUInt16LE(i+30),s=e.readUInt16LE(i+32),c=e.readUInt32LE(i+42),l=e.toString(`utf8`,i+46,i+46+r);if(i+=46+r+o+s,l.endsWith(`/`)||c+30>e.length||e.readUInt32LE(c)!==67324752)continue;let u=e.readUInt16LE(c+26),d=e.readUInt16LE(c+28),f=c+30+u+d,p=e.subarray(f,f+n),m;if(t===0)m=Buffer.from(p);else if(t===8)m=gi(p);else throw Error(`Unsupported compression in archive (entry: `+l+`).`);a.push({name:l,data:m})}return a}function qc(e,t,n,r=hi()){let i=Gc(e,r);if(!i)throw Error(`Unknown skill install target.`);let a=Kc(t).map(e=>({name:e.name.replace(/\\/g,`/`).replace(/^\.\//,``).replace(/^\/+/,``),data:e.data})).filter(e=>e.name&&!e.name.endsWith(`/`)&&!e.name.split(`/`).includes(`..`));if(!a.length)throw Error(`The archive contains no usable files.`);let o=a.find(e=>e.name===`SKILL.md`||e.name.endsWith(`/SKILL.md`));if(!o)throw Error(`No SKILL.md found in the archive (root or a top-level folder).`);let s=o.name.lastIndexOf(`/`),c,l;if(s<0){if(c=(n||``).trim(),!c)throw Error(`SKILL.md is at the archive root — please provide a skill name.`);l=``}else l=o.name.slice(0,s+1),c=(n||``).trim()||l.split(`/`)[0];if(!/^[A-Za-z0-9._-]+$/.test(c))throw Error(`Invalid skill name: `+c);let u=j(i,c),d=M(u),f=0;for(let e of a){let t=e.name;if(l){if(!e.name.startsWith(l))continue;t=e.name.slice(l.length)}if(!t)continue;let n=M(j(u,t));(n===d||n.startsWith(d+mi))&&(ii(di(n),{recursive:!0}),li(n,e.data),f++)}if(f===0)throw Error(`Nothing was extracted from the archive.`);return{installed:c,files:f,dir:u}}function Jc(e){if(typeof e.command==`string`){let t=Array.isArray(e.args)?e.args.join(` `):``;return{transport:`stdio`,detail:`${e.command} ${t}`.trim()}}let t=typeof e.url==`string`?e.url:void 0;if(t){let n=typeof e.type==`string`?e.type.toLowerCase():``,r=typeof e.transport==`string`?e.transport.toLowerCase():``;return n===`sse`||r===`sse`?{transport:`sse`,detail:t}:{transport:`http`,detail:t}}return{transport:`unknown`,detail:``}}function Yc(e,t,n,r,i){let a=P(e);if(a)for(let[e,o]of Object.entries(a)){let a=P(o)??{},{transport:s,detail:c}=Jc(a);r.push({name:e,source:t,transport:s,detail:c,scope:n,origin:`local`,config:ll(a),editable:i})}}function Xc(e=hi()){let t=[],n=N(j(e,`.claude.json`));if(n){Yc(n.mcpServers,`claude-code`,`global`,t,!0);let e=P(n.projects);if(e)for(let[n,r]of Object.entries(e)){let e=P(r);e?.mcpServers&&Yc(e.mcpServers,`claude-code`,n,t,!0)}}let r=N(j(e,`.qwen`,`settings.json`));r&&Yc(r.mcpServers,`qwen-code`,`global`,t,!0);let i=N(j(e,`.config`,`opencode`,`opencode.json`));i&&Yc(i.mcp,`opencode`,`global`,t,!0);let a=N(j(e,`.cursor`,`mcp.json`));a&&Yc(a.mcpServers,`cursor`,`global`,t,!0);let o=N(j(e,`.qoder`,`mcp.json`));o&&Yc(o.mcpServers,`qoder`,`global`,t,!0);let s=N(j(e,`.qoderwork`,`mcp.json`));s&&Yc(s.mcpServers,`qoderwork`,`global`,t,!0);let c=N(fc(e));c&&Yc(c.mcpServers,`qwenwork`,`global`,t,!0);let l=N(j(e,`.codeium`,`windsurf`,`mcp_config.json`));l&&Yc(l.mcpServers,`windsurf`,`global`,t,!0);let u=N(j(e,`.gemini`,`settings.json`));u&&Yc(u.mcpServers,`gemini`,`global`,t,!0);let d=N(j(e,`.openclaw`,`openclaw.json`));d&&Yc(P(d.mcp)?.servers??d.mcpServers,`openclaw`,`global`,t,!0);let f=N(j(e,`.zcode`,`cli`,`config.json`));f&&Yc(P(f.mcp)?.servers,`zcode`,`global`,t,!0);for(let n of bc(e)){let e=N(n);e&&Yc(e.mcpServers,`workbuddy`,n,t,!0)}let p=Rc(j(e,`.dsh`,`cordis.patch.yml`));if(p)try{let e=_i.parse(p),n=Array.isArray(e)?e:[],r={};for(let e of n){let t=P(e)?.insert,n=Array.isArray(t)?t:[e];for(let e of n){let t=P(e),n=t?P(t.config):void 0;t?.name===`@deepseek-ai/dsh-mcp-client`&&typeof n?.serverName==`string`&&(r[n.serverName]=n)}}Yc(r,`deepseek-harness`,`global`,t,!1)}catch{}let m=N(Zc(e));m&&Yc(m.mcpServers,`claude-desktop`,`global`,t,!0);let h=Rc(j(e,`.codex`,`config.toml`));if(h)try{Yc(yi(h).mcp_servers,`codex`,`global`,t,!1)}catch{}return t.sort((e,t)=>e.name.localeCompare(t.name)||e.source.localeCompare(t.source))}function Zc(e){return process.platform===`darwin`?j(e,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`):process.platform===`win32`?j(process.env.APPDATA??j(e,`AppData`,`Roaming`),`Claude`,`claude_desktop_config.json`):j(e,`.config`,`Claude`,`claude_desktop_config.json`)}function Qc(e,t,n){return e===`claude-code`?{file:j(n,`.claude.json`),mapKey:`mcpServers`,projectScoped:t!==`global`}:e===`qwen-code`?{file:j(n,`.qwen`,`settings.json`),mapKey:`mcpServers`,projectScoped:!1}:e===`opencode`?{file:j(n,`.config`,`opencode`,`opencode.json`),mapKey:`mcp`,projectScoped:!1}:e===`cursor`?{file:j(n,`.cursor`,`mcp.json`),mapKey:`mcpServers`,projectScoped:!1}:e===`windsurf`?{file:j(n,`.codeium`,`windsurf`,`mcp_config.json`),mapKey:`mcpServers`,projectScoped:!1}:e===`gemini`?{file:j(n,`.gemini`,`settings.json`),mapKey:`mcpServers`,projectScoped:!1}:e===`qoder`?{file:j(n,`.qoder`,`mcp.json`),mapKey:`mcpServers`,projectScoped:!1}:e===`qoderwork`?{file:j(n,`.qoderwork`,`mcp.json`),mapKey:`mcpServers`,projectScoped:!1}:e===`qwenwork`?{file:fc(n),mapKey:`mcpServers`,projectScoped:!1}:e===`openclaw`?{file:j(n,`.openclaw`,`openclaw.json`),mapKey:`servers`,parentKey:`mcp`,projectScoped:!1}:e===`zcode`?{file:j(n,`.zcode`,`cli`,`config.json`),mapKey:`servers`,parentKey:`mcp`,projectScoped:!1}:e===`workbuddy`?{file:bc(n)[0]??j(n,`.workbuddy-ai`,`mcp.json`),mapKey:`mcpServers`,projectScoped:!1}:e===`claude-desktop`?{file:Zc(n),mapKey:`mcpServers`,projectScoped:!1}:null}function $c(e,t){if(typeof e==`string`){if(e.includes(`•`)){if(typeof t==`string`)return t;throw Error(`Replace masked values (•••) with the real value before saving.`)}return e}if(Array.isArray(e)){let n=Array.isArray(t)?t:[];return e.map((e,t)=>$c(e,n[t]))}let n=P(e);if(n){let e=P(t)??{},r={};for(let[t,i]of Object.entries(n))r[t]=$c(i,e[t]);return r}return e}function el(e,t,n){let r=e;if(t.projectScoped){let t=P(e.projects);r=t?P(t[n]):void 0}if(r)return t.parentKey?P(r[t.parentKey]):r}function tl(e,t,n){let r=e;if(t.projectScoped){let t=P(e.projects)??{};e.projects=t;let i=P(t[n])??{};t[n]=i,r=i}if(t.parentKey){let e=P(r[t.parentKey])??{};return r[t.parentKey]=e,e}return r}function nl(e,t,n,r,i=hi()){let a=Qc(e,t,i);if(!a)throw Error(`This MCP source is read-only and cannot be edited here.`);let o=n.trim();if(!o)throw Error(`Server name is required.`);let s=P(r);if(!s)throw Error(`Config must be a JSON object.`);let c=N(a.file)??{},l=tl(c,a,t),u=P(l[a.mapKey])??{};l[a.mapKey]=u,u[o]=$c(s,P(u[o])),ii(di(a.file),{recursive:!0}),li(a.file,JSON.stringify(c,null,2)+`
|
|
2717
|
+
`,`utf-8`)}function rl(e,t,n,r=hi()){let i=Qc(e,t,r);if(!i)throw Error(`This MCP source is read-only and cannot be edited here.`);let a=N(i.file);if(!a)throw Error(`Config file not found.`);let o=el(a,i,t),s=o?P(o[i.mapKey]):void 0;if(!s||!(n in s))throw Error(`Server not found: `+n);delete s[n],o&&Object.keys(s).length===0&&delete o[i.mapKey],li(i.file,JSON.stringify(a,null,2)+`
|
|
2718
|
+
`,`utf-8`)}const il=[{id:`claude-code`,label:`Claude Code`,paths:e=>[j(process.env.CLAUDE_CONFIG_DIR||j(e,`.claude`),`settings.json`),j(e,`.claude.json`)],detect:e=>{let t=process.env.CLAUDE_CONFIG_DIR||j(e,`.claude`),n=P(N(j(t,`settings.json`))?.env),r=n&&typeof n.ANTHROPIC_BASE_URL==`string`?n.ANTHROPIC_BASE_URL:void 0,i=n&&typeof n.ANTHROPIC_MODEL==`string`?n.ANTHROPIC_MODEL:void 0;return{configured:!!r,model:i}}},{id:`qwen-code`,label:`Qwen Code`,paths:e=>[j(e,`.qwen`,`settings.json`)],detect:e=>{let t=N(j(e,`.qwen`,`settings.json`)),n=P(t?.modelProviders),r=n?Object.values(n).some(e=>Array.isArray(e)&&e.some(e=>{let t=P(e)?.name;return typeof t==`string`&&(t===`bailian-cli`||t.startsWith(`[Bailian]`))})):!1,i=P(t?.model);return{configured:r,model:i&&typeof i.name==`string`?i.name:void 0}}},{id:`opencode`,label:`OpenCode`,paths:e=>[j(e,`.config`,`opencode`,`opencode.json`)],detect:e=>{let t=P(P(N(j(e,`.config`,`opencode`,`opencode.json`))?.provider)?.[`bailian-cli`]),n=P(t?.models);return{configured:!!t,model:n?Object.keys(n)[0]:void 0}}},{id:`openclaw`,label:`OpenClaw`,paths:e=>[j(e,`.openclaw`,`openclaw.json`)],detect:e=>{let t=P(P(P(N(j(e,`.openclaw`,`openclaw.json`))?.models)?.providers)?.[`bailian-cli`]),n=P((Array.isArray(t?.models)?t.models:[])[0]);return{configured:!!t,model:n&&typeof n.id==`string`?n.id:void 0}}},{id:`hermes`,label:`Hermes Agent`,paths:e=>[j(e,`.hermes`,`config.yaml`)],detect:e=>{let t=Rc(j(e,`.hermes`,`config.yaml`));if(!t)return{configured:!1};let n;try{n=P(_i.parse(t))}catch{return{configured:!1}}let r=(Array.isArray(n?.custom_providers)?n.custom_providers:[]).some(e=>P(e)?.name===`bailian-cli`),i=P(n?.model),a=!!(i&&i.provider===`custom`&&typeof i.base_url==`string`&&i.base_url.includes(`aliyuncs.com`));return{configured:r||a,model:i&&typeof i.default==`string`?i.default:void 0}}},{id:`codex`,label:`Codex`,paths:e=>[j(e,`.codex`,`config.toml`),j(e,`.codex`,`auth.json`)],detect:e=>{let t=Rc(j(e,`.codex`,`config.toml`));if(!t)return{configured:!1};let n={};try{n=yi(t)}catch{return{configured:!1}}return{configured:!!P(n.model_providers)?.[`bailian-cli`],model:typeof n.model==`string`?n.model:void 0}}}];function al(e=hi()){return il.map(t=>{let n=t.paths(e),r=n.some(e=>A(e)),{configured:i,model:a}=r?t.detect(e):{configured:!1,model:void 0};return{id:t.id,label:t.label,installed:r,configured:i,model:a,paths:n,origin:`local`}})}function F(e,t,n,r=!1){typeof n==`string`&&n.trim()&&e.push({label:t,value:n.trim(),secret:r})}function ol(e,t){let n=[];if(e===`claude-code`){let e=P(N(j(t,`.claude`,`settings.json`))?.env);F(n,`Model`,e?.ANTHROPIC_MODEL),F(n,`Base URL`,e?.ANTHROPIC_BASE_URL),F(n,`Auth Token`,e?.ANTHROPIC_AUTH_TOKEN,!0)}else if(e===`qwen-code`){let e=N(j(t,`.qwen`,`settings.json`)),r=P(e?.model),i=P(P(e?.security)?.auth),a=P(e?.env);F(n,`Model`,r?.name),F(n,`Base URL`,i?.baseUrl??r?.baseUrl),F(n,`Protocol`,i?.selectedType),F(n,`API Key`,i?.apiKey??a?.BAILIAN_CLI_API_KEY,!0)}else if(e===`opencode`){let e=P(P(N(j(t,`.config`,`opencode`,`opencode.json`))?.provider)?.[`bailian-cli`]),r=P(e?.options),i=P(e?.models);F(n,`Model`,i?Object.keys(i)[0]:void 0),F(n,`Base URL`,r?.baseURL),F(n,`Provider`,e?.npm),F(n,`API Key`,r?.apiKey,!0)}else if(e===`openclaw`){let e=P(P(P(N(j(t,`.openclaw`,`openclaw.json`))?.models)?.providers)?.[`bailian-cli`]);F(n,`Model`,P((Array.isArray(e?.models)?e.models:[])[0])?.id),F(n,`Base URL`,e?.baseUrl),F(n,`API`,e?.api),F(n,`API Key`,e?.apiKey,!0)}else if(e===`hermes`){let e=Rc(j(t,`.hermes`,`config.yaml`)),r;if(e)try{r=P(_i.parse(e))}catch{r=void 0}let i=P((Array.isArray(r?.custom_providers)?r.custom_providers:[]).find(e=>P(e)?.name===`bailian-cli`));F(n,`Model`,P((Array.isArray(i?.models)?i.models:[])[0])?.id??P(r?.model)?.default),F(n,`Base URL`,i?.base_url),F(n,`API Mode`,i?.api_mode),F(n,`API Key`,i?.api_key,!0)}else if(e===`codex`){let e=Rc(j(t,`.codex`,`config.toml`)),r={};if(e)try{r=yi(e)}catch{r={}}let i=P(P(r.model_providers)?.[`bailian-cli`]),a=N(j(t,`.codex`,`auth.json`));F(n,`Model`,r.model),F(n,`Base URL`,i?.base_url),F(n,`Wire API`,i?.wire_api),F(n,`API Key`,a?.OPENAI_API_KEY,!0)}return n}function sl(e){let t=e.trim();return t.length<=8?`•`.repeat(Math.max(t.length,4)):t.slice(0,3)+`•`.repeat(Math.min(t.length-3,16))}const cl=/key|token|secret|password|passwd|auth|credential/i;function ll(e,t=``){if(typeof e==`string`)return t&&cl.test(t)&&e.trim()?sl(e):e;if(Array.isArray(e))return e.map(e=>ll(e));let n=P(e);if(n){let e={};for(let[t,r]of Object.entries(n))e[t]=ll(r,t);return e}return e}function ul(e){return e.endsWith(`.json`)?`json`:e.endsWith(`.yaml`)||e.endsWith(`.yml`)?`yaml`:e.endsWith(`.toml`)?`toml`:`text`}function dl(e,t=hi()){let n=il.find(t=>t.id===e);if(!n)return null;let r=n.paths(t),i=r.some(e=>A(e)),{configured:a,model:o}=i?n.detect(t):{configured:!1,model:void 0},s=i?ol(e,t).map(e=>e.secret?{...e,raw:e.value,value:sl(e.value)}:e):[],c=r.map(e=>({path:e,exists:A(e)})),l=i?r.filter(e=>A(e)).map(e=>({path:e,lang:ul(e),text:Rc(e)??``})).filter(e=>e.text.trim()):[];return{id:n.id,label:n.label,installed:i,configured:a,model:o,paths:r,origin:`local`,fields:s,files:c,settings:l}}const fl={"claude-code":`claude`,"qwen-code":`qwen`,opencode:`opencode`,openclaw:`openclaw`,hermes:`hermes`,codex:`codex`};function pl(e){return Object.prototype.hasOwnProperty.call(fl,e)?fl[e]:void 0}const ml={"qwen-code":e=>[`-i`,e],"claude-code":e=>[e],codex:e=>[e]};function hl(e){return Object.prototype.hasOwnProperty.call(ml,e)}function gl(e){let t=process.platform===`win32`?`where`:`which`;return new Promise(n=>{Hr(t,[e],{windowsHide:!0},e=>n(!e))})}function _l(e){let t=pl(e);return t?gl(t):Promise.resolve(!1)}function vl(e){return`'${e.replace(/'/g,`'\\''`)}'`}function yl(e,t){let n=process.platform;return new Promise((r,i)=>{if(n===`darwin`){let n=[`-e`,`tell application "Terminal" to do script "${`cd ${vl(t)} && ${e}`.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`,`-e`,`tell application "Terminal" to activate`];Hr(`osascript`,n,{windowsHide:!0},e=>e?i(e):r());return}if(n===`win32`){let n=[`/c`,`start`,``,`cmd`,`/k`,`cd /d ${t} && ${e}`];Hr(`cmd`,n,{windowsHide:!0},e=>e?i(e):r());return}let a=`cd ${vl(t)} && ${e}; exec $SHELL`;Hr(`x-terminal-emulator`,[`-e`,`bash`,`-lc`,a],{windowsHide:!0},e=>e?i(/* @__PURE__ */ Error(`No supported terminal emulator was found`)):r())})}async function bl(e,t=process.cwd(),n){let r=pl(e);if(!r)throw Error(`Unknown agent: ${e}`);if(!await gl(r))throw Error(`\`${r}\` was not found on your PATH — install ${e} first.`);let i=r,a=(n??``).trim();if(a){let t=ml[e];if(!t)throw Error(`${e} does not support dispatching a task prompt.`);i=[r,...t(a).map(vl)].join(` `)}return await yl(i,t),{launched:!0,command:i}}const xl=[{id:`image-generate`,title:`文生图`,description:`一键生成一张示例图片并保存到输出目录。`,category:`图像`,prompt:"请使用 bl 的图像生成能力(如 `bl image generate` 命令)生成一张示例图片:一只在雨中撑伞的柯基,水彩风格,光线柔和。保存到输出目录后告诉我文件路径。"},{id:`image-describe`,title:`图片理解`,description:`从输出目录任选一张图片,详细描述内容与风格。`,category:`图像`,prompt:`请在输出目录(默认 output/images)中任选一张图片,用中文详细描述它的内容、主体、构图、色彩与风格,并推测它适合的使用场景。若目录为空请说明。`},{id:`image-alt-batch`,title:`批量 Alt 文本`,description:`为输出目录下的图片批量生成无障碍 alt 文本。`,category:`图像`,prompt:`请扫描输出目录(默认 output/images)下的所有图片,逐张生成简洁、准确的 alt 无障碍描述,最后以「文件名 → alt 文本」的表格汇总。若目录为空请说明。`},{id:`image-to-code`,title:`截图转代码`,description:`把输出目录里的界面截图还原成 HTML+CSS。`,category:`图像`,prompt:`请在输出目录(默认 output/images)中查找一张界面截图,用 HTML + CSS 尽可能还原它的布局、间距与配色,输出为一个可直接在浏览器打开的单文件,并简述还原思路。若没有找到截图请说明。`},{id:`speech-generate`,title:`文字转语音`,description:`把一句示例文字合成为自然语音。`,category:`音频`,prompt:"请使用 bl 的语音合成能力(如 `bl speech` 相关命令)把下面这句话合成为自然语音,保存到输出目录,并告诉我音频文件路径:欢迎使用阿里云百炼命令行工具,让多模态创作更简单。"},{id:`audio-summarize`,title:`音频转写总结`,description:`转写输出目录里的音频并提炼要点。`,category:`音频`,prompt:`请在输出目录(默认 output/speech)中找到一个音频文件,转写其内容,先给出完整文字,再用要点列表总结关键信息。若目录为空或缺少转写能力,请说明并尝试用可用的能力完成。`},{id:`video-generate`,title:`文生视频`,description:`一键生成一段示例短视频。`,category:`视频`,prompt:"请使用 bl 的视频生成能力(如 `bl video generate` 命令)生成一段示例短视频:日落时分海边奔跑的少年,电影质感,慢动作。保存到输出目录后告诉我视频文件路径。"},{id:`video-storyboard`,title:`视频分镜脚本`,description:`围绕示例主题产出可用于文生视频的分镜。`,category:`视频`,prompt:`围绕主题「城市清晨的第一杯咖啡」,为一支 15-30 秒的短视频撰写分镜脚本:逐镜头给出画面描述、时长、字幕或旁白,并为每个镜头附上可直接用于文生视频的英文 prompt。`},{id:`media-prompt-craft`,title:`多模态提示词`,description:`把一个示例创意扩展成图/视频/语音提示词。`,category:`多模态`,prompt:`把创意「未来赛博城市的夜市」扩展成三组高质量生成提示词:1) 文生图;2) 文生视频;3) 语音风格描述。每组给出中英对照,并简要说明关键参数建议。`},{id:`image-story-narration`,title:`图片配音文案`,description:`为输出目录里的图片写解说词并给出可合成文本。`,category:`多模态`,prompt:`请在输出目录(默认 output/images)中任选一张图片,为它撰写一段 60 秒左右的中文解说词(适合配音),语气生动。随后给出可直接用于语音合成的纯文本版本。若目录为空请说明。`},{id:`summarize-project`,title:`总结当前项目`,description:`让 agent 阅读当前目录,总结架构、技术栈与主要模块。`,category:`代码`,prompt:`请阅读当前工作目录的项目结构和关键源码,用简洁的中文总结:1) 它是做什么的;2) 技术栈;3) 主要模块及其职责;4) 值得注意的设计。先浏览再下结论,不要臆测。`},{id:`write-tests`,title:`为核心模块写单测`,description:`自动挑选缺测试的核心模块并补全单元测试。`,category:`代码`,prompt:`请在当前项目中挑选一个核心且缺少测试(或测试薄弱)的模块,为它编写全面的单元测试,覆盖主要逻辑分支和边界情况,并遵循本项目现有的测试框架与风格。先阅读相关文件及其依赖,再编写测试。`},{id:`code-review`,title:`代码审查`,description:`审查当前项目核心代码,指出问题与改进建议。`,category:`代码`,prompt:`请审查当前项目的核心源码,指出潜在的 bug、安全隐患、性能与可维护性问题,并给出具体、可操作的改进建议,按严重程度排序。先浏览项目结构,选取关键文件再审查。`},{id:`explain-code`,title:`解释核心代码`,description:`挑选入口或核心模块,解释其实现与依赖。`,category:`代码`,prompt:`请挑选当前项目的入口文件或核心模块,解释它的实现:职责是什么、关键流程如何运转、依赖了哪些模块。用清晰的中文说明,必要时给出调用关系。`},{id:`generate-readme`,title:`生成 README`,description:`阅读代码后生成结构清晰、与实现一致的 README.md。`,category:`文档`,prompt:`为当前工作目录的项目生成一个结构清晰的 README.md,包含:项目简介、安装步骤、使用示例、目录结构说明。请先阅读现有代码与配置再撰写,内容必须与实际实现一致。`}],Sl={"image-generate":{title:`Text to image`,description:`Generate a sample image and save it to the output directory.`,category:`Image`,prompt:"Use bl's image generation capability (such as `bl image generate`) to create a sample image: a corgi holding an umbrella in the rain, watercolor style, with soft lighting. Save it to the output directory and tell me the file path."},"image-describe":{title:`Image understanding`,description:`Pick an image from the output directory and describe its content and style.`,category:`Image`,prompt:`Pick an image from the output directory (output/images by default). Describe its subject, composition, colors, and style in detail, then suggest suitable use cases. If the directory is empty, say so.`},"image-alt-batch":{title:`Batch alt text`,description:`Generate accessible alt text for images in the output directory.`,category:`Image`,prompt:`Scan all images in the output directory (output/images by default) and write concise, accurate accessibility alt text for each one. Summarize the results in a File name -> Alt text table. If the directory is empty, say so.`},"image-to-code":{title:`Screenshot to code`,description:`Recreate a UI screenshot from the output directory with HTML and CSS.`,category:`Image`,prompt:`Find a UI screenshot in the output directory (output/images by default) and recreate its layout, spacing, and colors as closely as possible with HTML and CSS. Save it as a single file that opens directly in a browser and briefly explain your approach. If no screenshot is available, say so.`},"speech-generate":{title:`Text to speech`,description:`Turn a sample sentence into natural speech.`,category:`Audio`,prompt:"Use bl's speech synthesis capability (such as a `bl speech` command) to turn this sentence into natural speech: Welcome to Alibaba Cloud Model Studio CLI, making multimodal creation easier. Save the audio to the output directory and tell me the file path."},"audio-summarize":{title:`Transcribe and summarize audio`,description:`Transcribe an audio file from the output directory and summarize its key points.`,category:`Audio`,prompt:`Find an audio file in the output directory (output/speech by default), transcribe it, provide the full transcript, and then summarize the key points as a list. If the directory is empty or transcription is unavailable, explain that and try to complete the task with the capabilities available.`},"video-generate":{title:`Text to video`,description:`Generate a sample short video.`,category:`Video`,prompt:"Use bl's video generation capability (such as `bl video generate`) to create a sample short video: a teenager running along the beach at sunset, cinematic, in slow motion. Save it to the output directory and tell me the file path."},"video-storyboard":{title:`Video storyboard`,description:`Create a storyboard suitable for text-to-video generation.`,category:`Video`,prompt:`Create a storyboard for a 15-30 second short video themed The first cup of coffee in the city at dawn. For each shot, provide the visual description, duration, subtitles or narration, and an English prompt ready for text-to-video generation.`},"media-prompt-craft":{title:`Multimodal prompts`,description:`Expand a sample idea into image, video, and speech prompts.`,category:`Multimodal`,prompt:`Expand the idea A night market in a futuristic cyber city into three high-quality generation prompts: 1) text to image, 2) text to video, and 3) speech style. Provide each prompt in both Chinese and English, with brief parameter recommendations.`},"image-story-narration":{title:`Image narration`,description:`Write narration for an image in the output directory.`,category:`Multimodal`,prompt:`Pick an image from the output directory (output/images by default) and write an engaging English narration of about 60 seconds. Then provide a plain-text version ready for speech synthesis. If the directory is empty, say so.`},"summarize-project":{title:`Summarize this project`,description:`Read the current directory and summarize its architecture, stack, and main modules.`,category:`Code`,prompt:`Inspect the project structure and key source files in the current working directory, then concisely summarize: 1) what it does, 2) its technology stack, 3) its main modules and their responsibilities, and 4) notable design choices. Inspect the code before drawing conclusions; do not guess.`},"write-tests":{title:`Add tests for a core module`,description:`Choose an under-tested core module and add unit tests.`,category:`Code`,prompt:`Choose a core module in the current project that has no tests or weak coverage. Add comprehensive unit tests for its main branches and edge cases, following the project's existing test framework and style. Read the relevant files and dependencies before writing tests.`},"code-review":{title:`Code review`,description:`Review core project code and identify concrete improvements.`,category:`Code`,prompt:`Review the current project's core source code for potential bugs, security risks, performance issues, and maintainability problems. Give specific, actionable recommendations ordered by severity. Inspect the project structure and select the key files before reviewing them.`},"explain-code":{title:`Explain core code`,description:`Choose an entry point or core module and explain how it works.`,category:`Code`,prompt:`Choose the current project's entry point or a core module and explain its responsibilities, key execution flow, and dependencies. Use clear English and include the call relationships when useful.`},"generate-readme":{title:`Generate README`,description:`Generate a clear README.md that matches the implementation.`,category:`Documentation`,prompt:`Generate a clear README.md for the project in the current working directory. Include an overview, installation steps, usage examples, and a directory structure guide. Read the existing source code and configuration first; the content must match the actual implementation.`}};function Cl(e){return e===`zh-CN`?xl.map(e=>({...e})):xl.map(e=>({...e,...Sl[e.id]}))}function wl(e,t){return Cl(t).find(t=>t.id===e)}function Tl(e,t){return e.prompt.replace(/\{\{(\w+)\}\}/g,(e,n)=>{let r=t[n];return typeof r==`string`?r.trim():``})}const El=/* @__PURE__ */ new Uint8Array(512),Dl=/* @__PURE__ */ new Uint8Array(256);(()=>{let e=1;for(let t=0;t<255;t++)El[t]=e,Dl[e]=t,e<<=1,e&256&&(e^=285);for(let e=255;e<512;e++)El[e]=El[e-255]})();function Ol(e,t){return e===0||t===0?0:El[Dl[e]+Dl[t]]}function kl(e){let t=[1];for(let n=0;n<e;n++){let e=Array.from({length:t.length+1},()=>0);for(let r=0;r<t.length;r++)e[r]^=t[r],e[r+1]^=Ol(t[r],El[n]);t=e}return t.map(e=>Dl[e])}function Al(e,t){let n=kl(t),r=new Uint8Array(e.length+t);r.set(e,0);for(let t=0;t<e.length;t++){let e=r[t];if(e!==0){let i=Dl[e];for(let e=0;e<n.length;e++)r[t+e]^=El[(n[e]+i)%255]}}return Array.from(r.slice(e.length))}const jl=[[19,7],[34,10],[55,15],[80,20],[108,26]];function Ml(e){let t=12+e*8;for(let e=0;e<jl.length;e++)if(jl[e][0]*8>=t)return e+1;throw Error(`qr: data too large for supported versions (max 108 bytes)`)}function Nl(e,t){let[n]=jl[t-1],r=[],i=(e,t)=>{for(let n=t-1;n>=0;n--)r.push(e>>n&1)};i(4,4),i(e.length,8);for(let t of e)i(t,8);let a=n*8;for(i(0,Math.min(4,a-r.length));r.length%8!=0;)r.push(0);let o=[];for(let e=0;e<r.length;e+=8){let t=0;for(let n=0;n<8;n++)t=t<<1|r[e+n];o.push(t)}let s=[236,17];for(let e=0;o.length<n;e++)o.push(s[e%2]);return o.concat(Al(o,jl[t-1][1]))}function Pl(e){return{size:e,mod:new Uint8Array(e*e),fn:new Uint8Array(e*e)}}function Fl(e,t,n,r){e.mod[t*e.size+n]=r,e.fn[t*e.size+n]=1}function Il(e,t,n){for(let r=-1;r<=7;r++)for(let i=-1;i<=7;i++){let a=t+r,o=n+i;a<0||a>=e.size||o<0||o>=e.size||Fl(e,a,o,+(r>=0&&r<=6&&i>=0&&i<=6&&(r===0||r===6||i===0||i===6||r>=2&&r<=4&&i>=2&&i<=4)))}}function Ll(e,t,n){for(let r=-2;r<=2;r++)for(let i=-2;i<=2;i++){let a=Math.max(Math.abs(r),Math.abs(i));Fl(e,t+r,n+i,a===1?0:1)}}function Rl(e,t){let n=e.size;for(let t=0;t<n;t++)Fl(e,6,t,+(t%2==0)),Fl(e,t,6,+(t%2==0));if(Il(e,0,0),Il(e,0,n-7),Il(e,n-7,0),t>=2){let t=n-7;Ll(e,t,t)}for(let t=0;t<9;t++)t!==6&&(e.fn[8*n+t]=1),t!==6&&(e.fn[t*n+8]=1);e.fn[8*n+6]=1,e.fn[6*n+8]=1;for(let t=0;t<8;t++)e.fn[(n-1-t)*n+8]=1;for(let t=0;t<8;t++)e.fn[8*n+(n-1-t)]=1;Fl(e,n-8,8,1)}function zl(e,t){let n=e.size,r=[];for(let e of t)for(let t=7;t>=0;t--)r.push(e>>t&1);let i=0,a=!0;for(let t=n-1;t>=1;t-=2){t===6&&(t=5);for(let o=0;o<n;o++){let s=a?n-1-o:o;for(let a of[0,1]){let o=t-a;e.fn[s*n+o]||(e.mod[s*n+o]=i<r.length?r[i++]:0)}}a=!a}}const Bl=[(e,t)=>(e+t)%2==0,e=>e%2==0,(e,t)=>t%3==0,(e,t)=>(e+t)%3==0,(e,t)=>(Math.floor(e/2)+Math.floor(t/3))%2==0,(e,t)=>e*t%2+e*t%3==0,(e,t)=>(e*t%2+e*t%3)%2==0,(e,t)=>((e+t)%2+e*t%3)%2==0];function Vl(e,t){let n=Bl[t];for(let t=0;t<e.size;t++)for(let r=0;r<e.size;r++)!e.fn[t*e.size+r]&&n(t,r)&&(e.mod[t*e.size+r]^=1)}function Hl(e){let t=e.size,n=(n,r)=>e.mod[n*t+r],r=0;for(let e=0;e<t;e++){let i=1,a=1;for(let o=1;o<t;o++)n(e,o)===n(e,o-1)?i++:(i>=5&&(r+=i-2),i=1),n(o,e)===n(o-1,e)?a++:(a>=5&&(r+=a-2),a=1);i>=5&&(r+=i-2),a>=5&&(r+=a-2)}for(let e=0;e<t-1;e++)for(let i=0;i<t-1;i++){let t=n(e,i);t===n(e,i+1)&&t===n(e+1,i)&&t===n(e+1,i+1)&&(r+=3)}let i=[1,0,1,1,1,0,1,0,0,0,0],a=[0,0,0,0,1,0,1,1,1,0,1],o=(e,t,n)=>{for(let r=0;r<n.length;r++)if(e(t+r)!==n[r])return!1;return!0};for(let e=0;e<t;e++)for(let s=0;s<=t-11;s++)(o(t=>n(e,t),s,i)||o(t=>n(e,t),s,a))&&(r+=40),(o(t=>n(t,e),s,i)||o(t=>n(t,e),s,a))&&(r+=40);let s=0;for(let n=0;n<t*t;n++)s+=e.mod[n];let c=s*100/(t*t),l=Math.floor(Math.abs(c-50)/5);return r+=l*10,r}function Ul(e){let t=8|e,n=t<<10;for(let e=14;e>=10;e--)n>>e&1&&(n^=1335<<e-10);return(t<<10|n)^21522}function Wl(e,t){let n=e.size,r=Ul(t),i=e=>r>>e&1;for(let t=0;t<=5;t++)e.mod[t*n+8]=i(t);e.mod[7*n+8]=i(6),e.mod[8*n+8]=i(7),e.mod[8*n+7]=i(8);for(let t=9;t<15;t++)e.mod[8*n+(14-t)]=i(t);for(let t=0;t<8;t++)e.mod[(n-1-t)*n+8]=i(t);for(let t=8;t<15;t++)e.mod[8*n+(n-15+t)]=i(t);e.mod[(n-8)*n+8]=1}function Gl(e){let t=new TextEncoder().encode(e),n=Ml(t.length),r=Nl(t,n),i=Pl(17+4*n);Rl(i,n),zl(i,r);let a=0,o=1/0;for(let e=0;e<8;e++){Vl(i,e),Wl(i,e);let t=Hl(i);t<o&&(o=t,a=e),Vl(i,e)}Vl(i,a),Wl(i,a);let s=[];for(let e=0;e<i.size;e++){let t=[];for(let n=0;n<i.size;n++)t.push(i.mod[e*i.size+n]===1);s.push(t)}return s}function Kl(e){let t=Gl(e),n=t.length,r=n+8,i=``;for(let e=0;e<n;e++)for(let r=0;r<n;r++)t[e][r]&&(i+=`<rect x="${r+4}" y="${e+4}" width="1" height="1"/>`);return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${r} ${r}" shape-rendering="crispEdges" role="img" aria-label="QR code"><rect width="${r}" height="${r}" fill="#ffffff"/><g fill="#000000">${i}</g></svg>`}function ql(e){let{identity:t,settings:n,authStore:r}=e;return{status(){let e=r.describe(),t={apiKey:!!e.apiKey,console:!!e.console,openapi:!!e.openapi},n;e.console?n=Rt(e.console.token):e.apiKey?n=Rt(e.apiKey.token):e.openapi&&(n=Rt(e.openapi.accessKeyId));let i=e.console?`console`:e.apiKey?`apiKey`:e.openapi?`openapi`:null;return{authenticated:t.apiKey||t.console||t.openapi,methods:t,primary:i,region:e.console?.region,site:e.console?.site,masked:n}},startConsoleLogin(){let e=po(r.describe().console?.site),i=!!r.stored().apiKey;Oo(e,{identity:t,settings:n,authStore:r},{needApiKey:!i}).catch(e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(`console login failed: ${t}\n`)})},logout(){return r.logout(`all`)}}}const Jl={".png":`image`,".jpg":`image`,".jpeg":`image`,".webp":`image`,".gif":`image`,".bmp":`image`,".svg":`image`,".mp4":`video`,".mov":`video`,".webm":`video`,".mkv":`video`,".avi":`video`,".mp3":`audio`,".wav":`audio`,".m4a":`audio`,".aac":`audio`,".flac":`audio`,".ogg":`audio`},Yl={".png":`image/png`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".webp":`image/webp`,".gif":`image/gif`,".bmp":`image/bmp`,".svg":`image/svg+xml`,".mp4":`video/mp4`,".mov":`video/quicktime`,".webm":`video/webm`,".mkv":`video/x-matroska`,".avi":`video/x-msvideo`,".mp3":`audio/mpeg`,".wav":`audio/wav`,".m4a":`audio/mp4`,".aac":`audio/aac`,".flac":`audio/flac`,".ogg":`audio/ogg`};function Xl(e=hi()){return j(e,`bailian-output`)}function Zl(e){return Jl[e.toLowerCase()]??`other`}function Ql(e){return Yl[e.toLowerCase()]??`application/octet-stream`}function $l(e,t,n){let r;try{r=oi(e,{withFileTypes:!0})}catch{return}for(let i of r){let r=j(e,i.name);i.isDirectory()?t>0&&$l(r,t-1,n):(i.isFile()||i.isSymbolicLink())&&n.push(r)}}function eu(e=Xl()){let t=[];if(!A(e))return{base:e,assets:t};let n=[];$l(e,8,n);for(let r of n){let n;try{n=si(r)}catch{continue}if(!n.isFile())continue;let i=pi(e,r),a=i.split(mi),o=a.length>1?a[0]:`other`,s=fi(r);t.push({name:r.split(mi).pop()??r,category:o,kind:Zl(s),relPath:i,size:n.size,mtime:n.mtimeMs,ext:s.replace(/^\./,``).toLowerCase()})}return t.sort((e,t)=>t.mtime-e.mtime),{base:e,assets:t}}function tu(e,t){if(typeof t!=`string`||t.length===0)return null;let n=M(e),r=M(n,t);return r!==n&&!r.startsWith(n+mi)?null:r}const nu={port:{type:`number`,valueHint:`<port>`,description:{"en-US":`Port to listen on (default: random free port)`,"zh-CN":`监听端口(默认:随机可用端口)`}},noOpen:{type:`switch`,description:{"en-US":`Do not open the browser automatically`,"zh-CN":`不自动打开浏览器`}}};function ru(e){return e instanceof n||e instanceof Error?e.message:String(e)}function I(e,t,n){e.writeHead(t,{"Content-Type":`application/json; charset=utf-8`}),e.end(JSON.stringify(n))}function iu(e){return e.read().language??o}function au(e){return new Promise((t,n)=>{let r=0,i=[];e.on(`data`,t=>{if(r+=t.length,r>1048576){n(/* @__PURE__ */ Error(`payload too large`)),e.destroy();return}i.push(t)}),e.on(`end`,()=>t(Buffer.concat(i).toString(`utf8`))),e.on(`error`,n)})}function ou(e,t){return new Promise((n,r)=>{let i=0,a=[];e.on(`data`,n=>{if(i+=n.length,i>t){r(/* @__PURE__ */ Error(`payload too large`)),e.destroy();return}a.push(n)}),e.on(`end`,()=>n(Buffer.concat(a))),e.on(`error`,r)})}function su(e,t){if(!e)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&Br(n,r)}function cu(e){let t={};for(let[n,r]of Object.entries(e)){let e=``;typeof r==`string`?e=r:typeof r==`number`||typeof r==`boolean`?e=String(r):Array.isArray(r)&&(e=JSON.stringify(r)),e!==``&&(t[Os(n)]=As(n,e))}return t}function lu(e,t){let n=new Set(Ss),r={};for(let[t,i]of Object.entries(e))n.has(t)||(r[t]=i);return{...r,...t}}function uu(e,t,n=Xl(),r){let i=null,a=()=>i===null?iu(t):ln(i==="default"?void 0:i).language??o;return Vr.createServer(async(o,s)=>{try{let c=(o.headers.host||``).split(`:`)[0];if(c!==`127.0.0.1`&&c!==`localhost`){s.writeHead(403,{"Content-Type":`text/plain; charset=utf-8`}),s.end(`forbidden host
|
|
2719
|
+
`);return}let l=new URL(o.url??`/`,`http://127.0.0.1`);if(!su(l.searchParams.get(`token`),e)){s.writeHead(401,{"Content-Type":`text/plain; charset=utf-8`}),s.end(`unauthorized
|
|
2720
|
+
`);return}let u=o.method??`GET`,d=l.pathname;if(d===`/`&&u===`GET`){s.writeHead(200,{"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-store`,"X-Content-Type-Options":`nosniff`,"Content-Security-Policy":`default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src 'self' data: https://img.alicdn.com https://oss.aliyuncs.com; media-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'`}),s.end(Rs(a()));return}if(d===`/api/qr`&&u===`GET`){let e=(l.searchParams.get(`data`)??``).slice(0,512);if(!e){I(s,400,{error:`missing data`});return}try{let t=Kl(e);s.writeHead(200,{"Content-Type":`image/svg+xml; charset=utf-8`,"Cache-Control":`no-store`}),s.end(t)}catch(e){I(s,400,{error:ru(e)})}return}if(d===`/api/config`&&u===`GET`){let e=t.profiles();I(s,200,{configFile:t.path,keys:Ss,secretKeys:[...bs],enums:Cs,booleanKeys:[...ws],fieldDefaults:{...Ts,base_url:g.cn,output_dir:Xl(),timeout:`300`},modelCatalog:Es,activeProfile:e.active,default:e.default,named:e.named});return}if(d===`/api/skills`&&u===`GET`){I(s,200,{skills:Hc()});return}if(d===`/api/skill`&&u===`GET`){let e=Uc(l.searchParams.get(`id`)??``);if(!e){I(s,404,{error:`not found`});return}I(s,200,e);return}if(d===`/api/skill/install`&&u===`POST`){let e=l.searchParams.get(`source`)??``,t=l.searchParams.get(`name`)??``;try{I(s,200,qc(e,await ou(o,25165824),t))}catch(e){I(s,400,{error:ru(e)})}return}if(d===`/api/mcp`&&u===`GET`){I(s,200,{servers:Xc()});return}if(d===`/api/mcp`&&u===`POST`){let e=await au(o),t;try{t=JSON.parse(e)}catch{I(s,400,{error:`invalid JSON body`});return}let n=t,r=typeof n.source==`string`?n.source:``,i=typeof n.scope==`string`&&n.scope?n.scope:`global`,a=typeof n.name==`string`?n.name:``;try{nl(r,i,a,n.config),I(s,200,{saved:a.trim()})}catch(e){I(s,400,{error:ru(e)})}return}if(d===`/api/mcp`&&u===`DELETE`){let e=l.searchParams.get(`source`)??``,t=l.searchParams.get(`scope`)||`global`,n=l.searchParams.get(`name`)??``;try{rl(e,t,n),I(s,200,{deleted:n})}catch(e){I(s,400,{error:ru(e)})}return}if(d===`/api/health`&&u===`GET`){let e=Number(process.versions.node.split(`.`)[0]);I(s,200,{node:process.version,nodeOk:Number.isFinite(e)&&e>=18,platform:process.platform,cwd:process.cwd()});return}if(d===`/api/agents`&&u===`GET`){let e=al(),t=await Promise.all(e.map(e=>_l(e.id)));I(s,200,{agents:e.map((e,n)=>({...e,launchable:t[n],dispatchable:t[n]&&hl(e.id)}))});return}if(d===`/api/agent`&&u===`GET`){let e=dl(l.searchParams.get(`id`)??``);if(!e){I(s,404,{error:`not found`});return}I(s,200,e);return}if(d===`/api/agent/open`&&u===`POST`){let e=dl(l.searchParams.get(`id`)??``),t=l.searchParams.get(`path`)??``,n=e?.settings.some(e=>e.path===t)??!1;if(!e||!n||!A(t)){I(s,404,{error:`not found`});return}try{await co(t),I(s,200,{opened:t})}catch(e){I(s,400,{error:ru(e)})}return}if(d===`/api/scenarios`&&u===`GET`){let e=al(),t=await Promise.all(e.map(e=>_l(e.id))),n=e.map((e,n)=>({id:e.id,label:e.label,dispatchable:t[n]&&hl(e.id)})).filter(e=>e.dispatchable);I(s,200,{scenarios:Cl(a()),agents:n});return}if(d===`/api/auth/status`&&u===`GET`){I(s,200,r?r.status():{authenticated:!1,methods:{apiKey:!1,console:!1,openapi:!1},primary:null});return}if(d===`/api/auth/login`&&u===`POST`){if(!r){I(s,400,{error:`login unavailable`});return}r.startConsoleLogin(),I(s,200,{started:!0});return}if(d===`/api/auth/logout`&&u===`POST`){if(!r){I(s,400,{error:`logout unavailable`});return}try{I(s,200,{loggedOut:await r.logout()})}catch(e){I(s,400,{error:ru(e)})}return}if(d===`/api/assets`&&u===`GET`){I(s,200,eu(n));return}if(d===`/api/asset/file`&&u===`GET`){let e=tu(n,l.searchParams.get(`path`)??``),t=e&&A(e)?si(e):null;if(!e||!t||!t.isFile()){I(s,404,{error:`not found`});return}s.writeHead(200,{"Content-Type":Ql(fi(e)),"Content-Length":t.size,"Cache-Control":`no-store`});let r=ni(e);r.on(`error`,()=>{s.headersSent||s.writeHead(500),s.end()}),r.pipe(s);return}if(d===`/api/asset`&&u===`DELETE`){let e=l.searchParams.get(`path`)??``,t=tu(n,e);if(!t||!A(t)||!si(t).isFile()){I(s,404,{error:`not found`});return}try{ci(t),I(s,200,{deleted:e})}catch(e){I(s,400,{error:ru(e)})}return}if(d===`/api/asset/open`&&u===`POST`){let e=l.searchParams.get(`path`)??``,t=tu(n,e);if(!t||!A(t)||!si(t).isFile()){I(s,404,{error:`not found`});return}try{await co(t),I(s,200,{opened:e})}catch(e){I(s,400,{error:ru(e)})}return}if(d===`/api/agent/launch`&&u===`POST`){try{I(s,200,await bl(l.searchParams.get(`id`)??``))}catch(e){I(s,400,{error:ru(e)})}return}if(d===`/api/agent/dispatch`&&u===`POST`){let e=await au(o),t;try{t=JSON.parse(e)}catch{I(s,400,{error:`invalid JSON body`});return}let n=t,r=typeof n.agent==`string`?n.agent:``;if(!hl(r)){I(s,400,{error:`agent cannot be dispatched a prompt`});return}let i,c=n.custom;if(c&&typeof c==`object`&&!Array.isArray(c)){let e=c,t=typeof e.prompt==`string`?e.prompt.trim():``;if(!t){I(s,400,{error:`custom scenario needs a prompt`});return}let n=[];if(Array.isArray(e.inputs)){for(let t of e.inputs)if(t&&typeof t==`object`){let e=t,r=typeof e.key==`string`?e.key.trim():``;if(r){let t=typeof e.label==`string`&&e.label.trim()?e.label.trim():r;n.push({key:r,label:t})}}}i={id:`custom`,title:typeof e.title==`string`&&e.title.trim()?e.title.trim():`Custom`,description:``,category:`自定义`,prompt:t,inputs:n}}else i=typeof n.scenario==`string`?wl(n.scenario,a()):void 0;if(!i){I(s,400,{error:`unknown scenario`});return}let l={};if(n.values&&typeof n.values==`object`&&!Array.isArray(n.values))for(let[e,t]of Object.entries(n.values))typeof t==`string`&&(l[e]=t);for(let e of i.inputs??[])if(!l[e.key]||!l[e.key].trim()){I(s,400,{error:`Missing input: ${e.label}`});return}let u=Tl(i,l);try{let e=await bl(r,process.cwd(),u);I(s,200,{launched:!0,agent:r,scenario:i.id,command:e.command})}catch(e){I(s,400,{error:ru(e)})}return}if(d===`/api/active`&&u===`POST`){let e=await au(o),n;try{n=JSON.parse(e)}catch{I(s,400,{error:`invalid JSON body`});return}let r=n;try{let e=await t.activate(r.name);i=e,I(s,200,{activeProfile:e,uiLanguage:a()})}catch(e){I(s,400,{error:ru(e)})}return}if(d===`/api/profile`&&u===`POST`){let e=await au(o),t;try{t=JSON.parse(e)}catch{I(s,400,{error:`invalid JSON body`});return}let n=t;if(!n.data||typeof n.data!=`object`||Array.isArray(n.data)){I(s,400,{error:`missing or invalid 'data'`});return}let r,i;try{r=Jt(n.name),i=cu(n.data)}catch(e){I(s,400,{error:ru(e)});return}let c=lu(ln(r),i);await ir(c,r),I(s,200,{saved:c,uiLanguage:a()});return}if(d===`/api/profile`&&u===`DELETE`){try{I(s,200,{deleted:await ke(l.searchParams.get(`name`)??void 0),activeProfile:t.profiles().active})}catch(e){I(s,400,{error:ru(e)})}return}s.writeHead(404,{"Content-Type":`text/plain; charset=utf-8`}),s.end(`not found
|
|
2721
|
+
`)}catch(e){if(console.error(`[config ui] request failed:`,e),s.headersSent){s.end();return}I(s,500,{error:ru(e)})}})}var du=S({description:{"en-US":`Open a local web UI to manage config profiles`,"zh-CN":`打开用于管理配置 Profile 的本地 Web UI`},auth:`none`,usageArgs:`[--port <port>] [--no-open]`,flags:nu,exampleArgs:[``,`--port 8787`,`--no-open`],async run(e){let{settings:t,flags:r}=e,i=C(t.output);if(t.dryRun){O({host:`127.0.0.1`,port:r.port??`random free port`,config_file:e.configStore.path,routes:[`GET / -> web UI`,`GET /api/config -> read all profiles`,`GET /api/skills -> list installed agent skills`,`GET /api/skill -> read one skill's SKILL.md detail`,`POST /api/skill/install -> install a skill from an uploaded .zip into a skills root`,`GET /api/mcp -> list local MCP servers`,`POST /api/mcp -> create or update one MCP server (writes its source config)`,`DELETE /api/mcp -> remove one MCP server from its source config`,`GET /api/health -> runtime environment info (node, platform, cwd)`,`GET /api/agents -> list coding agent frameworks`,`GET /api/agent -> one agent's config detail (secrets masked)`,`POST /api/agent/open -> open one agent's config file with the OS default app`,`GET /api/auth/status -> current auth state`,`POST /api/auth/login -> start console login (opens browser)`,`POST /api/auth/logout -> clear all stored credentials`,`GET /api/assets -> list generated assets`,`GET /api/asset/file -> stream one asset file`,`POST /api/asset/open -> open one asset with the OS default app`,`POST /api/agent/launch -> launch a coding agent CLI in a new terminal`,`GET /api/scenarios -> list Playground scenarios and dispatchable agents`,`POST /api/agent/dispatch -> dispatch a scenario prompt to a connected agent`,`POST /api/profile -> save a profile`,`POST /api/active -> activate a profile`,`DELETE /api/profile -> delete a named profile`,`DELETE /api/asset -> delete one asset file`]},i);return}let a=Rr(16).toString(`hex`),o=t.outputDir||Xl(),s=uu(a,e.configStore,o,ql(e)),c;try{c=await so(s,r.port??0)}catch(e){throw new n(`Could not bind to 127.0.0.1 (no free port or permission denied): ${ru(e)}`,l.USAGE)}let u=`http://127.0.0.1:${c}/?token=${a}`;if(!r.noOpen)try{await lo(u),D(`Opened the config UI in your default browser.`)}catch{D(`Could not open the browser automatically. Open the URL below manually.`)}D(`Config UI running at ${u}`),D(`Note: credentials are shown in cleartext in the browser (localhost only).`),D(`Press Ctrl+C to stop.`),await new Promise(e=>{let t=()=>s.close(()=>e());process.once(`SIGINT`,t),process.once(`SIGTERM`,t),s.once(`close`,()=>e())})}});function fu(e,t,n){let r=e[t];(r===void 0||r.trim()===``)&&(e[t]=n)}var pu={label:`Claude Code`,write({baseUrl:e,apiKey:t,model:n}){let r=process.env.CLAUDE_CONFIG_DIR||ti(xi(),`.claude`),i=ti(r,`settings.json`),a=ti(xi(),`.claude.json`),o=[],s=Ks(e);s.rewrittenFrom&&o.push(`Rewrote base URL for Claude Code: "${s.rewrittenFrom}" → "${s.url}" (Claude Code needs /apps/anthropic, not OpenAI compatible-mode).`),Ws(i);let c=Bs(i),l=c.env??{};l.ANTHROPIC_BASE_URL=s.url,l.ANTHROPIC_AUTH_TOKEN=t,delete l.ANTHROPIC_API_KEY,l.ANTHROPIC_MODEL=n,fu(l,`ANTHROPIC_DEFAULT_HAIKU_MODEL`,n),fu(l,`ANTHROPIC_DEFAULT_SONNET_MODEL`,n),fu(l,`ANTHROPIC_DEFAULT_OPUS_MODEL`,n),fu(l,`CLAUDE_CODE_SUBAGENT_MODEL`,n),c.env=l,Hs(i,c),Ws(a);let u=Bs(a);return u.hasCompletedOnboarding=!0,Hs(a,u),{paths:[i,a],nextStep:"Run `claude` to start using Claude Code with DashScope.",warnings:o.length>0?o:void 0}}};const mu=`DASHSCOPE_API_KEY`;function hu(e){return`[Bailian] ${e}`}function gu(e){if(e.envKey===mu)return!0;let t=typeof e.name==`string`?e.name:``;return t===`bailian-cli`||t.startsWith(`[Bailian]`)}var _u={label:`Qwen Code`,write({baseUrl:e,apiKey:t,model:n}){let r=ti(xi(),`.qwen`,`settings.json`),i=Gs(e)?`anthropic`:`openai`,a=[];Ws(r);let o=Bs(r);o.$version=3;let s=o.env??{};s[mu]=t,o.env=s;let c=process.env[mu];c!==void 0&&c!==t&&a.push(`Shell/environment ${mu} is set and overrides settings.json. Unset it (e.g. \`unset ${mu}\`) so the key written here takes effect.`);let l=o.modelProviders??{},u=l[i]??[],d=u.find(e=>gu(e)&&e.id===n),f=u.find(e=>!gu(e)&&e.id===n);if(d){d.baseUrl=e,d.envKey=mu;let t=typeof d.name==`string`?d.name.trim():``;(!t||t===`bailian-cli`)&&(d.name=hu(n))}else if(f){let e=typeof f.name==`string`&&f.name.length>0?f.name:String(f.id);a.push(`Model id "${n}" already exists as "${e}"; left unchanged (Qwen Code loads only the first entry per id). Remove or rename that entry if you want bailian-cli to own this model.`)}else u.push({id:n,name:hu(n),baseUrl:e,envKey:mu});l[i]=u,o.modelProviders=l;let p=o.security??{};return p.auth={selectedType:i,apiKey:t,baseUrl:e},o.security=p,o.model={name:n,baseUrl:e},Hs(r,o),{paths:[r],nextStep:"Run `qwen` to start using Qwen Code with DashScope.",warnings:a.length>0?a:void 0}}},vu={label:`OpenCode`,write({baseUrl:e,apiKey:t,model:n}){let r=ti(xi(),`.config`,`opencode`,`opencode.json`);Ws(r);let i=Vs(r);i.$schema||=`https://opencode.ai/config.json`;let a=i.provider??{};return a[`bailian-cli`]={npm:Gs(e)?`@ai-sdk/anthropic`:`@ai-sdk/openai-compatible`,name:`Alibaba Cloud Model Studio`,options:{baseURL:e,apiKey:t,setCacheKey:!0},models:{[n]:{name:n}}},i.provider=a,Hs(r,i),{paths:[r],nextStep:"Run `opencode` then type `/models` to select your model."}}};const yu=`bailian-cli`;function bu(e){let t=e.model;if(!t||typeof t!=`object`)return;let n=t.primary;return typeof n==`string`&&n.trim()!==``?n.trim():void 0}var xu={label:`OpenClaw`,write({baseUrl:e,apiKey:t,model:n,contextWindow:r}){let i=ti(xi(),`.openclaw`,`openclaw.json`),a=[],o=`${yu}/${n}`;Ws(i);let s=Bs(i),c=s.models??{};c.mode=`merge`;let l=c.providers??{},u=Gs(e)?`anthropic-messages`:`openai-completions`;l[yu]={baseUrl:e,apiKey:t,api:u,models:[{id:n,name:n,contextWindow:r??256e3,cost:{input:0,output:0,cacheRead:0,cacheWrite:0}}]},c.providers=l,s.models=c;let d=s.agents??{},f=d.defaults??{},p=f.models??{};p[o]=p[o]??{},f.models=p;let m=bu(f);return m?m.startsWith(`${yu}/`)?f.model={primary:o}:a.push(`Left existing primary model unchanged ("${m}"). Added provider "${yu}" — switch to "${o}" in OpenClaw if you want to use it.`):f.model={primary:o},d.defaults=f,s.agents=d,Hs(i,s),{paths:[i],nextStep:"Run `openclaw gateway restart`, then `openclaw` to start using OpenClaw with DashScope.",warnings:a.length>0?a:void 0}}},Su={label:`Hermes Agent`,write({baseUrl:e,apiKey:t,model:n}){let r=ti(xi(),`.hermes`,`config.yaml`);Ws(r);let i={};if(Kr(r))try{i=_i.parse(Jr(r,`utf-8`))??{}}catch{i={}}let a={default:n,provider:`custom`,base_url:e,api_key:t};return Gs(e)&&(a.api_mode=`anthropic_messages`),i.model=a,Us(r,_i.stringify(i)),{paths:[r],nextStep:'Run `hermes chat -q "hello"` to verify.'}}};const Cu=`bailian-cli`,wu={"claude-code":pu,"qwen-code":_u,opencode:vu,openclaw:xu,hermes:Su,codex:{label:`Codex`,write({baseUrl:e,apiKey:t,model:n,wireApi:r}){let i=ti(xi(),`.codex`,`config.toml`),a=[];Ws(i);let o={};if(Kr(i))try{o=yi(Jr(i,`utf-8`))}catch{o={}}o.model_provider=Cu,o.model=n;let s=r===`chat`?`chat`:`responses`;s===`chat`&&a.push('Current Codex releases refuse to load `wire_api = "chat"`; only use --wire-api chat with legacy Codex <= 0.80.0 (e.g. `npm install -g @openai/codex@0.80.0`).');let c=o.model_providers??{},l=c[Cu]??{};c[Cu]={...l,name:Cu,base_url:e,env_key:`OPENAI_API_KEY`,wire_api:s,requires_openai_auth:!0},o.model_providers=c,Us(i,bi(o)+`
|
|
2722
|
+
`);let u=ti(xi(),`.codex`,`auth.json`);Ws(u);let d=Bs(u);return d.OPENAI_API_KEY=t,Hs(u,d),{paths:[i,u],nextStep:"Run `codex` to start using Codex with DashScope.",warnings:a.length>0?a:void 0}}}},Tu=Object.keys(wu),Eu=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.`,Du=new Map(Eu.split(``).map((e,t)=>[e,t])),Ou=/^[A-Za-z0-9._-]+$/;function ku(){return new n(`Invalid obfuscated API key.`,l.USAGE,`--key expects the obfuscated key copied from the web console (starts with "o1_").`)}function Au(e){let t=[];for(let n of e){let e=Du.get(n);if(e===void 0)throw ku();t.push(e)}return t}function ju(e){return e.map(e=>Eu[e]).join(``)}function Mu(e,t){return Math.imul((e^t)>>>0,16777619)>>>0}function Nu(e){let t=e>>>0;return t^=t<<13,t^=t>>>17,t^=t<<5,t>>>0}function Pu(e,t,n,r){let i=(2166136261^Math.imul(n+1,2654435761))>>>0;i=Mu(i,e.length),i=Mu(i,r);for(let e of t)i=Mu(i,(Du.get(e)??-1)+1);for(let t of e)i=Mu(i,t+1);i^=i>>>16,i=Math.imul(i,2246822507)>>>0,i^=i>>>13,i=Math.imul(i,3266489909)>>>0,i^=i>>>16,i=i>>>0||1831565813;let a=[];for(let e=0;e<r;e+=1)i=i+Math.imul(e+1,2654435761)>>>0,i=Nu(i),a.push(i%65);return a}function Fu(e,t){let n=Au(e),r=Math.floor(n.length/2),i=n.slice(0,r),a=n.slice(r);for(let e=7;e>=0;--e){let n=i,r=Pu(n,t,e,a.length);i=a.map((e,t)=>(e-r[t]+65)%65),a=n}return ju([...i,...a])}function Iu(e){let t=4294967295;for(let n=0;n<e.length;n+=1){t^=e.charCodeAt(n);for(let e=0;e<8;e+=1){let e=-(t&1);t=t>>>1^3988292384&e}}return(t^4294967295)>>>0}function Lu(e,t){let n=e>>>0,r=Array(t).fill(Eu[0]);for(let e=t-1;e>=0;--e)r[e]=Eu[n%65],n=Math.floor(n/65);if(n!==0)throw ku();return r.join(``)}function Ru(e){if(e.length!==6||!Ou.test(e))throw ku()}function zu(e){if(e.length<16||!e.startsWith(`o1_`))throw ku();let t=e.slice(3);if(!Ou.test(t))throw ku();let n=t.slice(0,6),r=t.slice(6,-6),i=t.slice(-6);if(Ru(n),!r)throw ku();let a=Fu(r,n);if(!Ou.test(a)||i!==Lu(Iu(a),6))throw ku();return a}const Bu={agent:{type:`string`,valueHint:`<name>`,description:{"en-US":`Target agent: ${Tu.join(`, `)}`,"zh-CN":`目标 Agent:${Tu.join(`, `)}`},required:!0,choices:Tu},baseUrl:{type:`string`,valueHint:`<url>`,description:{"en-US":`API base URL`,"zh-CN":`API Base URL`}},region:{type:`string`,valueHint:`<region>`,description:{"en-US":`Model Studio region (e.g. cn-beijing, ap-southeast-1); converted into --base-url. Token Plan only`,"zh-CN":`模型服务地域(例如 cn-beijing、ap-southeast-1);将转换为 --base-url。仅用于 Token Plan`}},apiKey:{type:`string`,valueHint:`<key>`,description:{"en-US":`API key`,"zh-CN":`API Key`}},key:{type:`string`,valueHint:`<encoded>`,description:{"en-US":`Obfuscated API key from the web console (starts with "o1_"); decoded into --api-key`,"zh-CN":`来自 Web 控制台的混淆 API Key(以 "o1_" 开头);将解码为 --api-key`}},model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Default model name`,"zh-CN":`默认模型名称`},required:!0},contextWindow:{type:`number`,valueHint:`<tokens>`,description:{"en-US":`OpenClaw only: model context window in tokens (default: 256000)`,"zh-CN":`仅 OpenClaw:模型上下文窗口 Token 数(默认:256000)`}},wireApi:{type:`string`,valueHint:`<api>`,description:{"en-US":`Codex only: wire protocol (default: responses). "chat" only works with legacy Codex <= 0.80.0`,"zh-CN":`仅 Codex:通信协议(默认:responses)。"chat" 仅适用于旧版 Codex <= 0.80.0`},choices:[`chat`,`responses`]}};var Vu=S({description:{"en-US":`Configure a coding agent to use DashScope API`,"zh-CN":`配置编程 Agent 使用 DashScope API`},auth:`none`,usageArgs:`--agent <name> (--base-url <url> | --region <region>) (--api-key <key> | --key <encoded>) --model <model>`,flags:Bu,exampleArgs:[`--agent claude-code --base-url https://dashscope.aliyuncs.com/apps/anthropic --api-key sk-xxxxx --model qwen3-max`,`--agent qwen-code --base-url https://dashscope.aliyuncs.com/compatible-mode/v1 --api-key sk-xxxxx --model qwen3-coder-plus`,`--agent codex --base-url https://dashscope.aliyuncs.com/compatible-mode/v1 --api-key sk-xxxxx --model qwen3-coder-plus`],validate(e){if(!e.baseUrl&&!e.region)return`one of --base-url or --region is required`;if(e.baseUrl&&e.region)return`--base-url and --region are mutually exclusive`;if(!e.apiKey&&!e.key)return`one of --api-key or --key is required`;if(e.apiKey&&e.key)return`--api-key and --key are mutually exclusive`},async run(e){let{settings:t,flags:n}=e,r=n.agent,{model:i,contextWindow:a,wireApi:o}=n,s=n.region?qs(n.region):n.baseUrl,c=n.key?zu(n.key):n.apiKey,l=wu[r],u=C(t.output);if(r===`hermes`&&Si()===`win32`&&process.stderr.write(`Warning: Hermes Agent does not support native Windows. Please use WSL2.
|
|
2723
|
+
`),t.dryRun){O({agent:r,label:l.label,base_url:s,api_key:Rt(c),model:i},u);return}let d={baseUrl:s,apiKey:c,model:i,contextWindow:a,wireApi:o},f=l.write(d);if(!t.quiet){D(`${l.label} configured successfully.`);for(let e of f.paths)D(` Written: ${e}`);D(` ${f.nextStep}`);for(let e of f.warnings??[])process.stderr.write(`Warning: ${e}\n`)}}});const Hu=`bl skill update`;function Uu(e){process.stderr.write(`
|
|
2724
2724
|
Updating agent skill...
|
|
2725
|
-
`);try{
|
|
2726
|
-
`),s===`brew`||s===`winget`){let e=s===`brew`?`brew upgrade bailian-cli`:`winget upgrade Aliyun.BailianCLI`;process.stderr.write(`${o.yellow(`This CLI was installed via ${s}. Update with:`)}\n ${e}\n`),l&&process.stderr.write(`${o.dim(`Note: --to is not supported for ${s} installs.`)}\n`);return}let u=l??await
|
|
2725
|
+
`);try{Ci(Hu,{stdio:`inherit`}),process.stderr.write(`${e.green(`✓ Agent skill updated.`)}\n`)}catch{process.stderr.write(`${e.yellow(`Agent skill update skipped. Run manually: ${Hu}`)}\n`)}}function Wu(e){try{let t=ti(rt(),`update-state.json`);Zr(t,JSON.stringify({lastChecked:Date.now(),latestVersion:e}))}catch{}}async function Gu(e,t){return e===`binary`?await yr(`latest`,5e3)??await br(5e3,t):br(5e3,t)}function Ku(){return process.platform===`win32`?` irm ${i} | iex\n`:` curl -fsSL ${a} | bash\n`}var qu=S({description:{"en-US":`Update the CLI to the latest or a specified version`,"zh-CN":`将 CLI 更新到最新版本或指定版本`},auth:`none`,usageArgs:`[--to <version>]`,flags:{to:{type:`string`,valueHint:`<version>`,description:{"en-US":`Install this exact version instead of the latest`,"zh-CN":`安装指定版本,而不是最新版本`}}},exampleArgs:[``,`--to 0.1.14`],validate(e){if(e.to!==void 0){if(!e.to.trim())return`--to requires a non-empty version`;if(!Tr(e.to))return`--to must be a semver version (e.g. 1.13.0, v1.13.0, 0.0.0-beta-<sha>-<YYYYMMDDHHMM>), got: ${e.to.trim()}`}},async run(e){let{identity:t}=e,r=t.npmPackage,i=t.binName,a=t.version,o=E(process.stderr),s=pt(t),c=e.flags.to?.trim(),l=c?Dr(c):void 0;if(process.stderr.write(`Current version: ${o.yellow(a)}\n`),process.stderr.write(`Install method: ${o.dim(s)}\n`),l?process.stderr.write(`Target version: ${o.green(l)}\n`):process.stderr.write(`Checking for updates...
|
|
2726
|
+
`),s===`brew`||s===`winget`){let e=s===`brew`?`brew upgrade bailian-cli`:`winget upgrade Aliyun.BailianCLI`;process.stderr.write(`${o.yellow(`This CLI was installed via ${s}. Update with:`)}\n ${e}\n`),l&&process.stderr.write(`${o.dim(`Note: --to is not supported for ${s} installs.`)}\n`);return}let u=l??await Gu(s,r);if(!u){process.stderr.write(`${o.yellow(`Could not determine the latest version.`)}\n`);return}if(u===a){let e=l?`\u2713 Already at ${a}.`:`\u2713 Already up to date (${a}).`;process.stderr.write(`${o.green(e)}\n`),s===`npm`&&Uu(o);return}if(l?process.stderr.write(`
|
|
2727
2727
|
`):process.stderr.write(`Latest version: ${o.green(u)}\n\n`),s===`binary`){process.stderr.write(`Updating via binary channel...
|
|
2728
2728
|
|
|
2729
|
-
`);try{let e=await
|
|
2730
|
-
`),process.stderr.write(` ${r}\n\n`)}return}let d=`npm install -g ${l?`${r}@${l}`:`${r}@latest`}`;process.stderr.write(`Updating ${r} via npm...\n\n`);try{
|
|
2729
|
+
`);try{let e=await Or(u);process.stderr.write(`\n${o.green(`\u2713 Update complete: ${a} \u2192 ${e}`)}\n`),Wu(e),Uu(o)}catch(e){let t=e instanceof Error?e.message:String(e),r=e instanceof n&&e.hint?e.hint.replace(/^Re-run:\s*/i,``):Ku().trim();process.stderr.write(`\nAutomatic binary update failed: ${t}\n`),process.stderr.write(`Re-run the install script:
|
|
2730
|
+
`),process.stderr.write(` ${r}\n\n`)}return}let d=`npm install -g ${l?`${r}@${l}`:`${r}@latest`}`;process.stderr.write(`Updating ${r} via npm...\n\n`);try{Ci(d,{stdio:`inherit`});try{let e=Ci(`${i} --version 2>/dev/null`,{encoding:`utf-8`}).trim().replace(RegExp(`^${i}\\s+`),``);process.stderr.write(`\n${o.green(`\u2713 Update complete: ${a} \u2192 ${e}`)}\n`),Wu(e)}catch{process.stderr.write(`\n${o.green(`✓ Update complete.`)}\n`)}Uu(o)}catch{process.stderr.write(`
|
|
2731
2731
|
Automatic update failed. Please run manually:
|
|
2732
|
-
`),process.stderr.write(` ${d}\n\n`)}}}),
|
|
2733
|
-
`)}else{let n=await e.client.requestJson({path:ae(r),method:`POST`,body:s}),i=n.output?.text??``;t.quiet||o===`text`?D(i):O(n,o)}}});const ju=`zeldaEasy.broadscope-bailian.app-control.list`;var Mu=S({description:{"en-US":`List Bailian applications`,"zh-CN":`列出百炼应用`},auth:`console`,usageArgs:`[flags]`,flags:{name:{type:`string`,valueHint:`<name>`,description:{"en-US":`Filter by app name (keyword search)`,"zh-CN":`按应用名称筛选(关键词搜索)`}},page:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Results per page (default: 30)`,"zh-CN":`每页结果数(默认:30)`}}},exampleArgs:[``,{"en-US":`--name customer service`,"zh-CN":`--name 客户服务`},`--page 2 --page-size 10`,`--output json`],async run(e){let{settings:t,flags:n}=e,r=n.name||``,i=n.page||1,a=n.pageSize||30,o=C(t.output),s={reqDTO:{name:r,notInTypes:[10],type:5,statuses:[1,4],page_no:i,page_size:a}};if(t.dryRun){O({api:ju,data:s},o);return}let c=await e.client.console(ju,s),l=c?.data?.DataV2?.data?.data?.list??[],u=c?.data?.DataV2?.data?.data?.total??0,d=l.map(e=>({code:e.code,name:e.name,user_prompt_params:e.config?.user_prompt_params??[]}));O({total:u,apps:d},o)}}),Nu=S({description:{"en-US":`Add memory from messages or custom content`,"zh-CN":`从消息或自定义内容添加记忆`},auth:`apiKey`,usageArgs:`--user-id <id> [--messages <json>] [--content <text>] [flags]`,flags:{userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},messages:{type:`string`,valueHint:`<json>`,description:{"en-US":`Messages JSON array: [{"role":"user","content":"..."},...]`,"zh-CN":`消息 JSON 数组:[{"role":"user","content":"..."},...]`}},content:{type:`string`,valueHint:`<text>`,description:{"en-US":`Custom content text to memorize`,"zh-CN":`要记忆的自定义内容文本`}},profileSchema:{type:`string`,valueHint:`<id>`,description:{"en-US":`Profile schema ID for user profiling`,"zh-CN":`用于用户画像的 Profile Schema ID`}},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID (isolate memory space)`,"zh-CN":`记忆库 ID(用于隔离记忆空间)`}}},exampleArgs:[{"en-US":`--user-id user1 --content "The user likes Python programming"`,"zh-CN":`--user-id user1 --content "用户喜欢使用 Python 编程"`},{"en-US":`--user-id user1 --messages '[{"role":"user","content":"I like traveling"}]'`,"zh-CN":`--user-id user1 --messages '[{"role":"user","content":"我喜欢旅行"}]'`},{"en-US":`--user-id user1 --content "Lives in Beijing" --profile-schema schema_xxx`,"zh-CN":`--user-id user1 --content "居住在北京" --profile-schema schema_xxx`}],validate:e=>!e.messages&&!e.content?`Provide --messages or --content.`:void 0,async run(e){let{settings:t,flags:n}=e,r={user_id:n.userId};if(n.messages)try{r.messages=JSON.parse(n.messages)}catch{throw new x(`--messages must be valid JSON array`)}n.content&&(r.custom_content=n.content),n.profileSchema&&(r.profile_schema=n.profileSchema),n.memoryLibraryId&&(r.memory_library_id=n.memoryLibraryId);let i=C(t.output);if(t.dryRun){O({endpoint:e.client.url(Nt()),request:r},i);return}let a=await e.client.requestJson({path:Nt(),method:`POST`,body:r});if(t.quiet||i===`text`){let e=a.memory_ids?.join(`, `)||`none`;D(`Memory added. IDs: ${e}`)}else O(a,i)}}),Pu=S({description:{"en-US":`Search memory nodes by query or messages`,"zh-CN":`通过查询文本或消息搜索记忆节点`},auth:`apiKey`,usageArgs:`--user-id <id> [--query <text>] [flags]`,flags:{userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},query:{type:`string`,valueHint:`<text>`,description:{"en-US":`Search query text`,"zh-CN":`搜索查询文本`}},messages:{type:`string`,valueHint:`<json>`,description:{"en-US":`Messages JSON array for context-based search`,"zh-CN":`用于上下文搜索的消息 JSON 数组`}},topK:{type:`number`,valueHint:`<n>`,description:{"en-US":`Number of results to return (default: 10)`,"zh-CN":`返回结果数量(默认:10)`}},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID`,"zh-CN":`记忆库 ID`}}},exampleArgs:[{"en-US":`--user-id user1 --query "programming preferences"`,"zh-CN":`--user-id user1 --query "编程偏好"`},{"en-US":`--user-id user1 --messages '[{"role":"user","content":"recommend a book"}]' --top-k 5`,"zh-CN":`--user-id user1 --messages '[{"role":"user","content":"推荐一本书"}]' --top-k 5`}],validate:e=>!e.query&&!e.messages?`Provide --query or --messages.`:void 0,async run(e){let{settings:t,flags:n}=e,r={user_id:n.userId};if(n.query&&(r.query=n.query),n.messages)try{r.messages=JSON.parse(n.messages)}catch{throw new x(`--messages must be valid JSON array`)}!r.messages&&r.query&&(r.messages=[{role:`user`,content:r.query}]),n.topK!==void 0&&(r.top_k=n.topK),n.memoryLibraryId&&(r.memory_library_id=n.memoryLibraryId);let i=C(t.output);if(t.dryRun){O({endpoint:e.client.url(It()),request:r},i);return}let a=await e.client.requestJson({path:It(),method:`POST`,body:r});if(t.quiet||i===`text`){if(!a.memory_nodes||a.memory_nodes.length===0)D(`No memory nodes found.`);else for(let e of a.memory_nodes)D(`[${e.memory_node_id}] ${e.content}`)}else O(a,i)}}),Fu=S({description:{"en-US":`List memory nodes for a user`,"zh-CN":`列出用户的记忆节点`},auth:`apiKey`,usageArgs:`--user-id <id> [flags]`,flags:{userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Results per page (default: 10)`,"zh-CN":`每页结果数(默认:10)`}},page:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID`,"zh-CN":`记忆库 ID`}}},exampleArgs:[`--user-id user1`,`--user-id user1 --page-size 20 --page 2`],async run(e){let{settings:t,flags:n}=e,r=n.userId,i=C(t.output),a=new URLSearchParams;a.set(`user_id`,r),n.pageSize!==void 0&&a.set(`page_size`,String(n.pageSize)),n.page!==void 0&&a.set(`page_num`,String(n.page)),n.memoryLibraryId&&a.set(`memory_library_id`,n.memoryLibraryId);let o=`${Pt()}?${a.toString()}`;if(t.dryRun){O({endpoint:e.client.url(o),method:`GET`},i);return}let s=await e.client.requestJson({path:o,method:`GET`});if(t.quiet||i===`text`){if(!s.memory_nodes||s.memory_nodes.length===0)D(`No memory nodes found.`);else{for(let e of s.memory_nodes)D(`[${e.memory_node_id}] ${e.content}`);s.total!==void 0&&D(`\nTotal: ${s.total}`)}}else O(s,i)}}),Iu=S({description:{"en-US":`Update a memory node content`,"zh-CN":`更新记忆节点内容`},auth:`apiKey`,usageArgs:`--node-id <id> --user-id <id> --content <text>`,flags:{nodeId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory node ID (required)`,"zh-CN":`记忆节点 ID(必填)`},required:!0},userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},content:{type:`string`,valueHint:`<text>`,description:{"en-US":`New content for the memory node (required)`,"zh-CN":`记忆节点的新内容(必填)`},required:!0},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID (non-default library)`,"zh-CN":`记忆库 ID(非默认记忆库)`}}},exampleArgs:[{"en-US":`--node-id node_xxx --user-id user1 --content "updated memory content"`,"zh-CN":`--node-id node_xxx --user-id user1 --content "更新后的记忆内容"`}],async run(e){let{settings:t,flags:n}=e,r=n.nodeId,i={user_id:n.userId,custom_content:n.content};n.memoryLibraryId&&(i.memory_library_id=n.memoryLibraryId);let a=C(t.output);if(t.dryRun){O({endpoint:e.client.url(Ft(r)),method:`PATCH`,request:i},a);return}let o=await e.client.requestJson({path:Ft(r),method:`PATCH`,body:i});t.quiet||a===`text`?D(`Memory node ${r} updated.`):O(o,a)}}),Lu=S({description:{"en-US":`Delete a memory node`,"zh-CN":`删除记忆节点`},auth:`apiKey`,usageArgs:`--node-id <id> --user-id <id>`,flags:{nodeId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory node ID (required)`,"zh-CN":`记忆节点 ID(必填)`},required:!0},userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID (non-default library)`,"zh-CN":`记忆库 ID(非默认记忆库)`}}},exampleArgs:[`--node-id node_xxx --user-id user1`],async run(e){let{settings:t,flags:n}=e,r=n.nodeId,i=n.userId,a=C(t.output),o=new URLSearchParams({user_id:i});n.memoryLibraryId&&o.set(`memory_library_id`,n.memoryLibraryId);let s=`${Ft(r)}?${o.toString()}`;if(t.dryRun){O({endpoint:e.client.url(s),method:`DELETE`},a);return}let c=await e.client.requestJson({path:s,method:`DELETE`});t.quiet||a===`text`?D(`Memory node ${r} deleted.`):O(c,a)}}),Ru=S({description:{"en-US":`Create a user profile schema for memory profiling`,"zh-CN":`创建用于记忆画像的用户 Profile Schema`},auth:`apiKey`,usageArgs:`--name <name> --attributes <json> [flags]`,flags:{name:{type:`string`,valueHint:`<name>`,description:{"en-US":`Schema name (required)`,"zh-CN":`Schema 名称(必填)`},required:!0},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`Schema description`,"zh-CN":`Schema 描述`}},attributes:{type:`string`,valueHint:`<json>`,description:{"en-US":`Attributes JSON array: [{"name":"age","description":"age"}]`,"zh-CN":`属性 JSON 数组:[{"name":"age","description":"age"}]`},required:!0}},exampleArgs:[{"en-US":`--name "user_basic" --attributes '[{"name":"age","description":"age"},{"name":"hobby","description":"hobby"}]'`,"zh-CN":`--name "user_basic" --attributes '[{"name":"age","description":"年龄"},{"name":"hobby","description":"爱好"}]'`}],async run(e){let{settings:t,flags:n}=e,r=n.name,i=n.attributes,a;try{a=JSON.parse(i)}catch{throw new x(`--attributes must be valid JSON array`)}let o={name:r,attributes:a};n.description&&(o.description=n.description);let s=C(t.output);if(t.dryRun){O({endpoint:e.client.url(Zt()),request:o},s);return}let c=await e.client.requestJson({path:Zt(),method:`POST`,body:o});t.quiet||s===`text`?D(`Profile schema created: ${c.profile_schema_id}`):O(c,s)}}),zu=S({description:{"en-US":`Get user profile by schema ID and user ID`,"zh-CN":`通过 Schema ID 和用户 ID 获取用户画像`},auth:`apiKey`,usageArgs:`--schema-id <id> --user-id <id>`,flags:{schemaId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Profile schema ID (required)`,"zh-CN":`Profile Schema ID(必填)`},required:!0},userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0}},exampleArgs:[`--schema-id schema_xxx --user-id user1`],async run(e){let{settings:t,flags:n}=e,r=n.schemaId,i=n.userId,a=C(t.output),o=new URLSearchParams({user_id:i}),s=`${Vn(r)}?${o.toString()}`;if(t.dryRun){O({endpoint:e.client.url(s),method:`GET`},a);return}let c=await e.client.requestJson({path:s,method:`GET`});if(t.quiet||a===`text`){if(c.profile?.attributes)for(let e of c.profile.attributes)D(`${e.name}: ${e.value??`(empty)`}`);else D(`No profile data found.`)}else O(c,a)}}),Bu=S({description:{"en-US":"Retrieve from a Bailian knowledge base (deprecated, use `search` instead)","zh-CN":"从百炼知识库检索(已废弃,请改用 `search`)"},auth:`apiKey`,usageArgs:`--index-id <id> --query <text> [flags]`,flags:{indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base index ID (required)`,"zh-CN":`知识库索引 ID(必填)`},required:!0},query:{type:`string`,valueHint:`<text>`,description:{"en-US":`Search query (required)`,"zh-CN":`搜索查询(必填)`},required:!0},denseSimilarityTopK:{type:`number`,valueHint:`<n>`,description:{"en-US":`Dense retrieval top K`,"zh-CN":`稠密检索 Top K`}},sparseSimilarityTopK:{type:`number`,valueHint:`<n>`,description:{"en-US":`Sparse retrieval top K`,"zh-CN":`稀疏检索 Top K`}},rerank:{type:`switch`,description:{"en-US":`Enable reranking`,"zh-CN":`启用重排序`}},rerankTopN:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rerank top N results`,"zh-CN":`重排序前 N 个结果`}},rerankModel:{type:`string`,valueHint:`<name>`,description:{"en-US":`Rerank model, e.g. qwen3-rerank-hybrid`,"zh-CN":`重排序模型,例如 qwen3-rerank-hybrid`}},rerankMode:{type:`string`,valueHint:`<mode>`,description:{"en-US":`Rerank mode: qa, similar, or custom`,"zh-CN":`重排序模式:qa、similar 或 custom`}},rerankInstruct:{type:`string`,valueHint:`<text>`,description:{"en-US":`Custom rerank instruction, when mode=custom`,"zh-CN":`自定义重排序指令,仅在 mode=custom 时使用`}},topK:{type:`number`,valueHint:`<n>`,description:{"en-US":`Number of results (deprecated, use --rerank-top-n)`,"zh-CN":`结果数量(已废弃,请使用 --rerank-top-n)`}}},notes:[{"en-US":`--rerank-model requires the target knowledge base to already have a rerank model configured; otherwise every value is rejected.`,"zh-CN":`--rerank-model 要求目标知识库已配置重排序模型,否则任何取值都会被拒绝。`}],exampleArgs:[{"en-US":`--index-id idx_xxx --query "How to use Alibaba Cloud Bailian"`,"zh-CN":`--index-id idx_xxx --query "如何使用阿里云百炼"`},{"en-US":`--index-id idx_xxx --query "RAG retrieval" --rerank --rerank-model qwen3-rerank-hybrid`,"zh-CN":`--index-id idx_xxx --query "RAG 检索" --rerank --rerank-model qwen3-rerank-hybrid`}],async run(e){let{settings:t,flags:n}=e,r=C(t.output);n.topK!==void 0&&n.rerankTopN===void 0&&(process.stderr.write(`Warning: --top-k is deprecated. Use --rerank-top-n instead.
|
|
2734
|
-
`),n.rerankTopN=n.topK);let i={index_id:n.indexId,query:n.query,search_filters:[]};if(n.denseSimilarityTopK!==void 0&&(i.dense_similarity_top_k=n.denseSimilarityTopK),n.sparseSimilarityTopK!==void 0&&(i.sparse_similarity_top_k=n.sparseSimilarityTopK),n.rerank&&(i.enable_reranking=!0),n.rerankTopN!==void 0&&(i.rerank_top_n=n.rerankTopN),n.rerankModel){let e={model_name:n.rerankModel};n.rerankMode&&(e.rerank_mode=n.rerankMode),n.rerankInstruct&&(e.rerank_instruct=n.rerankInstruct),i.rerank=[e]}if(t.dryRun){O({endpoint:e.client.url(_t()),request:i},r);return}let a=await e.client.requestJson({path:_t(),method:`POST`,body:i}),o=a.data?.nodes||[];t.quiet||r===`text`?Vu(o.map(e=>({text:e.text,score:e.score}))):O(a,r)}});function Vu(e){if(e.length===0)D(`No results found.`);else for(let t=0;t<e.length;t++){let n=e[t];D(`[${t+1}] (score: ${n.score.toFixed(4)})`),D(n.text),D(``)}}const L={workspaceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID)`,"zh-CN":`API Endpoint URL 使用的 Workspace ID(也可设置 BAILIAN_WORKSPACE_ID)`}}},Hu={pageNumber:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page size per request`,"zh-CN":`每次请求的分页大小`}}};function R(e){let t=e.flags.workspaceId||e.settings.workspaceId;if(!t)throw new n(`Workspace ID is required.`,l.USAGE,`Pass --workspace-id, set BAILIAN_WORKSPACE_ID env, or configure: ${e.identity.binName} config set workspace_id <id>`);return t}function Uu(e){if(!process.stdout.isTTY)return e;let t=process.stdout.columns??120;return e.length>t?`${e.slice(0,Math.max(0,t-1))}…`:e}function Wu(e){return e.data?.ingestion_status??`UNKNOWN`}function Gu(e){return(e.data?.rows??[]).filter(e=>[e.code,e.status].some(e=>typeof e==`string`&&e.includes(`FAILED`)))}function Ku(e){let t=e.data?.rows??[];if(t.length===0)return!1;let n=e.data?.total_count;return typeof n==`number`&&t.length<n?!1:t.every(e=>{let t=e.code??e.status??``;return t===`FINISH`||t.includes(`FAILED`)})}function qu(e,t){let n=e.data?.rows??[],r=Gu(e),i=new Set(r.map(e=>e.doc_id)),a=n.filter(e=>!i.has(e.doc_id)),o=r.map(e=>`${e.doc_name??e.doc_id??`?`}: ${e.message??e.code??`unknown`}`).join(`; `),s=a.map(e=>e.doc_name??e.doc_id??`?`).join(`, `),c=[];return o&&c.push(`failed: ${o}`),s&&c.push(`succeeded: ${s}`),c.length>0?`${t} (${c.join(`; `)})`:t}function Ju(e,t,n){let r=new URL(T(e,h.indexJobStatus));return r.searchParams.set(`index_id`,t),r.searchParams.set(`job_id`,n),r}async function Yu(e,t,n){return hr(e,t,{url:n.statusUrl,intervalSec:n.intervalSec,timeoutSec:t.timeout,isComplete:e=>{let t=e;return Wu(t)===`COMPLETED`||Ku(t)},isFailed:()=>!1,getStatus:e=>{let t=e,n=Wu(t),r=Gu(t).length,i=t.data?.total_count;return typeof i==`number`&&i>0?`${n} (${r}/${i} failed)`:r>0?`${n} (${r} failed)`:n}})}function Xu(e,t){return!(e instanceof n)||e.hint?e:new n(e.message,e.exitCode,t,{cause:e,api:e.api,rawResponse:e.rawResponse})}function Zu(e,t){let n=e.data?.[t];if(typeof n==`string`)return n;let r=e[t];return typeof r==`string`?r:void 0}const Qu={query:{type:`string`,valueHint:`<text>`,description:{"en-US":`Search query text (required, cannot be empty)`,"zh-CN":`搜索查询文本(必填且不能为空)`},required:!0},agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Retrieval service ID (find in console knowledge retrieval page)`,"zh-CN":`检索服务 ID(可在控制台知识库检索页面查看)`},required:!0},...L,agentVersion:{type:`string`,valueHint:`<version>`,description:{"en-US":`Service version to call: beta (draft for debugging) or a published number; default is the latest published version`,"zh-CN":`要调用的服务版本:beta(用于调试的草稿)或已发布版本号;默认使用最新发布版本`}},image:{type:`array`,valueHint:`<url>`,description:{"en-US":`Image URL for multimodal retrieval (repeatable)`,"zh-CN":`多模态检索使用的图片 URL(可重复)`}}};var $u=S({description:{"en-US":`Search a Bailian knowledge base (RAG semantic retrieval)`,"zh-CN":`搜索百炼知识库(RAG 语义检索)`},auth:`apiKey`,usageArgs:`--query <text> --agent-id <id> [flags]`,flags:Qu,notes:[{"en-US":`Retrieval scope and strategy (multi-index weighting, routing, reranking, etc.) are driven by the agent_id service config. Only query and agent_id are required.`,"zh-CN":`检索范围与策略(多索引权重、路由、重排序等)由 agent_id 服务配置决定。仅 query 和 agent_id 必填。`},{"en-US":`Auth: uses DashScope API Key (Bearer token). Get yours from the console API Key page.`,"zh-CN":`鉴权:使用 DashScope API Key(Bearer Token)。可在控制台 API Key 页面获取。`},{"en-US":"`--workspace-id` can be set via BAILIAN_WORKSPACE_ID env or `kscli config set workspace_id <id>`.","zh-CN":"`--workspace-id` 可通过 BAILIAN_WORKSPACE_ID 环境变量或 `kscli config set workspace_id <id>` 设置。"},{"en-US":"`--agent-version beta` calls the draft config for debugging before it is deployed.","zh-CN":"`--agent-version beta` 会调用尚未部署的草稿配置,便于发布前调试。"}],exampleArgs:[{"en-US":`--query "What is RAG?" --agent-id aid-xxx --workspace-id ws-xxx`,"zh-CN":`--query "什么是 RAG?" --agent-id aid-xxx --workspace-id ws-xxx`},{"en-US":`--api-key $DASHSCOPE_API_KEY --query "test search" --agent-id aid-xxx --workspace-id ws-xxx --image https://example.com/img.jpg`,"zh-CN":`--api-key $DASHSCOPE_API_KEY --query "测试搜索" --agent-id aid-xxx --workspace-id ws-xxx --image https://example.com/img.jpg`}],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={query:n.query,agent_id:n.agentId};n.agentVersion&&(a.agent_version=n.agentVersion),n.image&&n.image.length>0&&(a.images=n.image);let o=vt(r);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.nodes||[];if(t.quiet||i===`text`){if(c.length===0)D(`No results found.`);else for(let e=0;e<c.length;e++){let t=c[e];D(`[${e+1}] (score: ${t.score.toFixed(4)})`),D(t.text),D(``)}}else O(s,i)}});const ed={message:{type:`array`,valueHint:`<text>`,description:{"en-US":`Message text (repeatable). Supports role:content prefix to set role (e.g. user:hello), defaults to user. Follows OpenAI message format`,"zh-CN":`消息文本(可重复)。支持使用 role:content 前缀指定角色(例如 user:hello),默认为 user。遵循 OpenAI 消息格式`}},agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Q&A service ID (find in console knowledge Q&A page)`,"zh-CN":`问答服务 ID(可在控制台知识库问答页面查看)`},required:!0},...L,agentVersion:{type:`string`,valueHint:`<version>`,description:{"en-US":`Service version to call: beta (draft for debugging) or a published number; default is the latest published version`,"zh-CN":`要调用的服务版本:beta(用于调试的草稿)或已发布版本号;默认使用最新发布版本`}},image:{type:`array`,valueHint:`<url>`,description:{"en-US":`Image URL (repeatable). Attached to the last user message as multimodal content`,"zh-CN":`图片 URL(可重复)。将作为多模态内容附加到最后一条用户消息`}}};function td(e){let t=[];if(e.message){let n=/* @__PURE__ */ new Set([`user`,`assistant`]);for(let r of e.message){if(r.startsWith(`{`))try{let e=JSON.parse(r);if(e.role&&n.has(e.role)&&e.content!==void 0){t.push(e);continue}}catch{}let e=r.indexOf(`:`),i=e===-1?``:r.slice(0,e);n.has(i)?t.push({role:i,content:r.slice(e+1)}):t.push({role:`user`,content:r})}}return t}function nd(e){for(let t of e)if(Array.isArray(t.content)&&t.content.some(e=>e.type===`image_url`))return!0;return!1}function rd(e,t){let n=-1;for(let t=e.length-1;t>=0;t--)if(e[t].role===`user`){n=t;break}n===-1&&(e.push({role:`user`,content:``}),n=e.length-1);let r=e[n],i=[];typeof r.content==`string`?i.push({type:`text`,text:r.content}):i.push(...r.content);for(let e of t)i.push({type:`image_url`,image_url:{url:e}});r.content=i}const id={tool_calling:`🔍 Retrieving...`,plan_start:`🤔 Planning...`,generation_start:`✍️ Generating...`};var ad=S({description:{"en-US":`Chat with a Bailian knowledge base (RAG Q&A with streaming)`,"zh-CN":`与百炼知识库对话(支持流式输出的 RAG 问答)`},auth:`apiKey`,usageArgs:`--message <text> --agent-id <id> [flags]`,flags:ed,notes:[{"en-US":`Response is returned as SSE stream events. Event lifecycle: tool_calling → tool_return → plan_start → planning → plan_end → generation_start → generating → generation_end. tool_calling → tool_return may loop multiple times.`,"zh-CN":`响应以 SSE 流事件返回。事件生命周期:tool_calling → tool_return → plan_start → planning → plan_end → generation_start → generating → generation_end。tool_calling → tool_return 可能循环多次。`},{"en-US":`Auth: uses DashScope API Key (Bearer token). Get yours from the console API Key page.`,"zh-CN":`鉴权:使用 DashScope API Key(Bearer Token)。可在控制台 API Key 页面获取。`},{"en-US":"`--workspace-id` can be set via BAILIAN_WORKSPACE_ID env or `kscli config set workspace_id <id>`.","zh-CN":"`--workspace-id` 可通过 BAILIAN_WORKSPACE_ID 环境变量或 `kscli config set workspace_id <id>` 设置。"},{"en-US":`Multi-turn: use --message "user:..." and --message "assistant:..." to pass conversation history.`,"zh-CN":`多轮对话:使用 --message "user:..." 和 --message "assistant:..." 传入对话历史。`},{"en-US":"`--agent-version beta` calls the draft config for debugging before it is deployed.","zh-CN":"`--agent-version beta` 会调用尚未部署的草稿配置,便于发布前调试。"}],exampleArgs:[{"en-US":`--message "What is RAG?" --agent-id aid-xxx --workspace-id ws-xxx`,"zh-CN":`--message "什么是 RAG?" --agent-id aid-xxx --workspace-id ws-xxx`},{"en-US":`--message "user:What is RAG?" --message "assistant:RAG is..." --message "How does it work?" --agent-id aid-xxx --workspace-id ws-xxx`,"zh-CN":`--message "user:什么是 RAG?" --message "assistant:RAG 是……" --message "它是如何工作的?" --agent-id aid-xxx --workspace-id ws-xxx`},{"en-US":`--message "Describe these images" --image https://example.com/a.png --image https://example.com/b.png --agent-id aid-xxx --workspace-id ws-xxx`,"zh-CN":`--message "描述这些图片" --image https://example.com/a.png --image https://example.com/b.png --agent-id aid-xxx --workspace-id ws-xxx`}],validate:e=>e.message&&e.message.length>0||e.image&&e.image.length>0?void 0:`Provide --message (or --image for a pure image query).`,async run(e){let{settings:t,flags:r}=e,i=td(r),a=r.image,o=!!a&&a.length>0;i.length===0&&o&&(i=[{role:`user`,content:``}]);let s=R(e),c=C(t.output),u=c===`text`&&!!process.stdout.isTTY;if(o){if(nd(i))throw new n(`Cannot use --image when messages already contain embedded image_url content parts. Use one approach or the other.`,l.USAGE);rd(i,a)}let d={input:{messages:i},parameters:{agent_options:{agent_id:r.agentId,...r.agentVersion?{agent_version:r.agentVersion}:{}}},stream:!0},f=gt(s);if(t.dryRun){O({endpoint:f,request:d},c);return}let p=await e.client.request({path:f,method:`POST`,body:d,stream:!0});if(u){let e=E(process.stdout),r=t.verbose;for await(let t of Gt(p)){if(t.data===`[DONE]`)break;if(t.event===`error`){let e=`Chat API error`,r;try{let n=JSON.parse(t.data);e=n.message||e,r=n.code}catch{}throw new n(e,l.GENERAL,r?`API error: ${r}`:void 0)}try{let n=JSON.parse(t.data);for(let t of n.output?.choices??[]){let n=t.message;if(n.extra?.step_change){let t=id[n.extra.step_change];t&&process.stdout.write(`${e.dim(t)}\n`)}if(r&&n.extra?.step_change&&process.stderr.write(E(process.stderr).dim(`[event] step_change=${n.extra.step_change} step=${n.extra?.step??``} group=${n.extra?.group??``}`)+`
|
|
2732
|
+
`),process.stderr.write(` ${d}\n\n`)}}}),Ju=S({description:{"en-US":`Call a Bailian application (agent or workflow)`,"zh-CN":`调用百炼应用(智能体或工作流)`},auth:`apiKey`,usageArgs:`--app-id <id> --prompt <text> [flags]`,flags:{appId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Application ID (required)`,"zh-CN":`应用 ID(必填)`},required:!0},prompt:{type:`string`,valueHint:`<text>`,description:{"en-US":`Input prompt text`,"zh-CN":`输入提示词文本`},required:!0},image:{type:`array`,valueHint:`<url>`,description:{"en-US":`Image URL(s) to pass to the app (repeatable)`,"zh-CN":`传给应用的图片 URL(可重复)`}},fileId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Pre-uploaded file ID(s) (repeatable)`,"zh-CN":`已上传的文件 ID(可重复)`}},sessionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Session ID for multi-turn conversation`,"zh-CN":`多轮对话的 Session ID`}},stream:{type:`switch`,description:{"en-US":`Stream response (default: on in TTY)`,"zh-CN":`流式输出响应(TTY 中默认开启)`}},pipelineIds:{type:`string`,valueHint:`<ids>`,description:{"en-US":`Knowledge base pipeline IDs (comma-separated)`,"zh-CN":`知识库 Pipeline ID(以逗号分隔)`}},memoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory ID for long-term memory`,"zh-CN":`长期记忆使用的 Memory ID`}},bizParams:{type:`string`,valueHint:`<json>`,description:{"en-US":`Business parameters JSON (workflow variables)`,"zh-CN":`业务参数 JSON(工作流变量)`}},hasThoughts:{type:`switch`,description:{"en-US":`Show agent thinking process`,"zh-CN":`显示智能体思考过程`}}},exampleArgs:[{"en-US":`--app-id abc123 --prompt "Hello"`,"zh-CN":`--app-id abc123 --prompt "你好"`},{"en-US":`--app-id abc123 --prompt "Describe this image" --image https://example.com/photo.jpg`,"zh-CN":`--app-id abc123 --prompt "描述这张图片" --image https://example.com/photo.jpg`},{"en-US":`--app-id abc123 --prompt "Analyze the image" --image img1.jpg --image img2.jpg`,"zh-CN":`--app-id abc123 --prompt "分析这些图片" --image img1.jpg --image img2.jpg`},{"en-US":`--app-id abc123 --prompt "Continue" --session-id sess_xxx --stream`,"zh-CN":`--app-id abc123 --prompt "继续" --session-id sess_xxx --stream`},{"en-US":`--app-id abc123 --prompt "Search for materials" --pipeline-ids pipe1,pipe2`,"zh-CN":`--app-id abc123 --prompt "搜索资料" --pipeline-ids pipe1,pipe2`},{"en-US":`--app-id abc123 --prompt "Start" --biz-params '{"key":"value"}'`,"zh-CN":`--app-id abc123 --prompt "开始" --biz-params '{"key":"value"}'`}],async run(e){let{settings:t,flags:n}=e,r=n.appId,i=n.prompt,a=n.stream||process.stdout.isTTY,o=C(t.output),s={input:{prompt:i},parameters:{incremental_output:a}};n.sessionId&&(s.input.session_id=n.sessionId);let c=n.image;c&&c.length>0&&(s.input.image_list=c);let l=n.fileId;if(l&&l.length>0&&(s.input.file_ids=l),n.hasThoughts&&(s.parameters.has_thoughts=!0),n.pipelineIds){let e=n.pipelineIds.split(`,`).map(e=>e.trim()).filter(Boolean);s.parameters.rag_options={pipeline_ids:e}}if(n.memoryId&&(s.parameters.memory_id=n.memoryId),n.bizParams)try{s.input.biz_params=JSON.parse(n.bizParams)}catch{throw new x(`--biz-params must be valid JSON`)}if(t.dryRun){O({endpoint:e.client.url(ae(r)),request:s},o);return}if(a){let i=await e.client.request({path:ae(r),method:`POST`,body:s,headers:{"X-DashScope-SSE":`enable`},stream:!0}),a=``,c=``,l=o===`text`,u=E(process.stderr);for await(let e of $t(i)){if(e.data===`[DONE]`)break;try{let t=JSON.parse(e.data),r=t.output?.text;if(r&&(l&&process.stdout.write(r),a+=r),t.output?.session_id&&(c=t.output.session_id),t.output?.thoughts&&n.hasThoughts)for(let e of t.output.thoughts)e.thought&&process.stderr.write(`${u.dim(`[Thinking] ${e.thought}`)}\n`),e.action_name&&process.stderr.write(`${u.dim(`[Action] ${e.action_name}: ${e.action_input||``}`)}\n`),e.observation&&process.stderr.write(`${u.dim(`[Observation] ${e.observation}`)}\n`)}catch{}}c&&!t.quiet&&process.stderr.write(`${u.dim(`Session ID: ${c}`)}\n`),o===`json`?O({text:a,session_id:c},o):process.stdout.write(`
|
|
2733
|
+
`)}else{let n=await e.client.requestJson({path:ae(r),method:`POST`,body:s}),i=n.output?.text??``;t.quiet||o===`text`?D(i):O(n,o)}}});const Yu=`zeldaEasy.broadscope-bailian.app-control.list`;var Xu=S({description:{"en-US":`List Bailian applications`,"zh-CN":`列出百炼应用`},auth:`console`,usageArgs:`[flags]`,flags:{name:{type:`string`,valueHint:`<name>`,description:{"en-US":`Filter by app name (keyword search)`,"zh-CN":`按应用名称筛选(关键词搜索)`}},page:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Results per page (default: 30)`,"zh-CN":`每页结果数(默认:30)`}}},exampleArgs:[``,{"en-US":`--name customer service`,"zh-CN":`--name 客户服务`},`--page 2 --page-size 10`,`--output json`],async run(e){let{settings:t,flags:n}=e,r=n.name||``,i=n.page||1,a=n.pageSize||30,o=C(t.output),s={reqDTO:{name:r,notInTypes:[10],type:5,statuses:[1,4],page_no:i,page_size:a}};if(t.dryRun){O({api:Yu,data:s},o);return}let c=await e.client.console(Yu,s),l=c?.data?.DataV2?.data?.data?.list??[],u=c?.data?.DataV2?.data?.data?.total??0,d=l.map(e=>({code:e.code,name:e.name,user_prompt_params:e.config?.user_prompt_params??[]}));O({total:u,apps:d},o)}}),Zu=S({description:{"en-US":`Add memory from messages or custom content`,"zh-CN":`从消息或自定义内容添加记忆`},auth:`apiKey`,usageArgs:`--user-id <id> [--messages <json>] [--content <text>] [flags]`,flags:{userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},messages:{type:`string`,valueHint:`<json>`,description:{"en-US":`Messages JSON array: [{"role":"user","content":"..."},...]`,"zh-CN":`消息 JSON 数组:[{"role":"user","content":"..."},...]`}},content:{type:`string`,valueHint:`<text>`,description:{"en-US":`Custom content text to memorize`,"zh-CN":`要记忆的自定义内容文本`}},profileSchema:{type:`string`,valueHint:`<id>`,description:{"en-US":`Profile schema ID for user profiling`,"zh-CN":`用于用户画像的 Profile Schema ID`}},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID (isolate memory space)`,"zh-CN":`记忆库 ID(用于隔离记忆空间)`}}},exampleArgs:[{"en-US":`--user-id user1 --content "The user likes Python programming"`,"zh-CN":`--user-id user1 --content "用户喜欢使用 Python 编程"`},{"en-US":`--user-id user1 --messages '[{"role":"user","content":"I like traveling"}]'`,"zh-CN":`--user-id user1 --messages '[{"role":"user","content":"我喜欢旅行"}]'`},{"en-US":`--user-id user1 --content "Lives in Beijing" --profile-schema schema_xxx`,"zh-CN":`--user-id user1 --content "居住在北京" --profile-schema schema_xxx`}],validate:e=>!e.messages&&!e.content?`Provide --messages or --content.`:void 0,async run(e){let{settings:t,flags:n}=e,r={user_id:n.userId};if(n.messages)try{r.messages=JSON.parse(n.messages)}catch{throw new x(`--messages must be valid JSON array`)}n.content&&(r.custom_content=n.content),n.profileSchema&&(r.profile_schema=n.profileSchema),n.memoryLibraryId&&(r.memory_library_id=n.memoryLibraryId);let i=C(t.output);if(t.dryRun){O({endpoint:e.client.url(Vt()),request:r},i);return}let a=await e.client.requestJson({path:Vt(),method:`POST`,body:r});if(t.quiet||i===`text`){let e=a.memory_ids?.join(`, `)||`none`;D(`Memory added. IDs: ${e}`)}else O(a,i)}}),Qu=S({description:{"en-US":`Search memory nodes by query or messages`,"zh-CN":`通过查询文本或消息搜索记忆节点`},auth:`apiKey`,usageArgs:`--user-id <id> [--query <text>] [flags]`,flags:{userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},query:{type:`string`,valueHint:`<text>`,description:{"en-US":`Search query text`,"zh-CN":`搜索查询文本`}},messages:{type:`string`,valueHint:`<json>`,description:{"en-US":`Messages JSON array for context-based search`,"zh-CN":`用于上下文搜索的消息 JSON 数组`}},topK:{type:`number`,valueHint:`<n>`,description:{"en-US":`Number of results to return (default: 10)`,"zh-CN":`返回结果数量(默认:10)`}},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID`,"zh-CN":`记忆库 ID`}}},exampleArgs:[{"en-US":`--user-id user1 --query "programming preferences"`,"zh-CN":`--user-id user1 --query "编程偏好"`},{"en-US":`--user-id user1 --messages '[{"role":"user","content":"recommend a book"}]' --top-k 5`,"zh-CN":`--user-id user1 --messages '[{"role":"user","content":"推荐一本书"}]' --top-k 5`}],validate:e=>!e.query&&!e.messages?`Provide --query or --messages.`:void 0,async run(e){let{settings:t,flags:n}=e,r={user_id:n.userId};if(n.query&&(r.query=n.query),n.messages)try{r.messages=JSON.parse(n.messages)}catch{throw new x(`--messages must be valid JSON array`)}!r.messages&&r.query&&(r.messages=[{role:`user`,content:r.query}]),n.topK!==void 0&&(r.top_k=n.topK),n.memoryLibraryId&&(r.memory_library_id=n.memoryLibraryId);let i=C(t.output);if(t.dryRun){O({endpoint:e.client.url(Wt()),request:r},i);return}let a=await e.client.requestJson({path:Wt(),method:`POST`,body:r});if(t.quiet||i===`text`){if(!a.memory_nodes||a.memory_nodes.length===0)D(`No memory nodes found.`);else for(let e of a.memory_nodes)D(`[${e.memory_node_id}] ${e.content}`)}else O(a,i)}}),$u=S({description:{"en-US":`List memory nodes for a user`,"zh-CN":`列出用户的记忆节点`},auth:`apiKey`,usageArgs:`--user-id <id> [flags]`,flags:{userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Results per page (default: 10)`,"zh-CN":`每页结果数(默认:10)`}},page:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID`,"zh-CN":`记忆库 ID`}}},exampleArgs:[`--user-id user1`,`--user-id user1 --page-size 20 --page 2`],async run(e){let{settings:t,flags:n}=e,r=n.userId,i=C(t.output),a=new URLSearchParams;a.set(`user_id`,r),n.pageSize!==void 0&&a.set(`page_size`,String(n.pageSize)),n.page!==void 0&&a.set(`page_num`,String(n.page)),n.memoryLibraryId&&a.set(`memory_library_id`,n.memoryLibraryId);let o=`${Ht()}?${a.toString()}`;if(t.dryRun){O({endpoint:e.client.url(o),method:`GET`},i);return}let s=await e.client.requestJson({path:o,method:`GET`});if(t.quiet||i===`text`){if(!s.memory_nodes||s.memory_nodes.length===0)D(`No memory nodes found.`);else{for(let e of s.memory_nodes)D(`[${e.memory_node_id}] ${e.content}`);s.total!==void 0&&D(`\nTotal: ${s.total}`)}}else O(s,i)}}),ed=S({description:{"en-US":`Update a memory node content`,"zh-CN":`更新记忆节点内容`},auth:`apiKey`,usageArgs:`--node-id <id> --user-id <id> --content <text>`,flags:{nodeId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory node ID (required)`,"zh-CN":`记忆节点 ID(必填)`},required:!0},userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},content:{type:`string`,valueHint:`<text>`,description:{"en-US":`New content for the memory node (required)`,"zh-CN":`记忆节点的新内容(必填)`},required:!0},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID (non-default library)`,"zh-CN":`记忆库 ID(非默认记忆库)`}}},exampleArgs:[{"en-US":`--node-id node_xxx --user-id user1 --content "updated memory content"`,"zh-CN":`--node-id node_xxx --user-id user1 --content "更新后的记忆内容"`}],async run(e){let{settings:t,flags:n}=e,r=n.nodeId,i={user_id:n.userId,custom_content:n.content};n.memoryLibraryId&&(i.memory_library_id=n.memoryLibraryId);let a=C(t.output);if(t.dryRun){O({endpoint:e.client.url(Ut(r)),method:`PATCH`,request:i},a);return}let o=await e.client.requestJson({path:Ut(r),method:`PATCH`,body:i});t.quiet||a===`text`?D(`Memory node ${r} updated.`):O(o,a)}}),td=S({description:{"en-US":`Delete a memory node`,"zh-CN":`删除记忆节点`},auth:`apiKey`,usageArgs:`--node-id <id> --user-id <id>`,flags:{nodeId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory node ID (required)`,"zh-CN":`记忆节点 ID(必填)`},required:!0},userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0},memoryLibraryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Memory library ID (non-default library)`,"zh-CN":`记忆库 ID(非默认记忆库)`}}},exampleArgs:[`--node-id node_xxx --user-id user1`],async run(e){let{settings:t,flags:n}=e,r=n.nodeId,i=n.userId,a=C(t.output),o=new URLSearchParams({user_id:i});n.memoryLibraryId&&o.set(`memory_library_id`,n.memoryLibraryId);let s=`${Ut(r)}?${o.toString()}`;if(t.dryRun){O({endpoint:e.client.url(s),method:`DELETE`},a);return}let c=await e.client.requestJson({path:s,method:`DELETE`});t.quiet||a===`text`?D(`Memory node ${r} deleted.`):O(c,a)}}),nd=S({description:{"en-US":`Create a user profile schema for memory profiling`,"zh-CN":`创建用于记忆画像的用户 Profile Schema`},auth:`apiKey`,usageArgs:`--name <name> --attributes <json> [flags]`,flags:{name:{type:`string`,valueHint:`<name>`,description:{"en-US":`Schema name (required)`,"zh-CN":`Schema 名称(必填)`},required:!0},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`Schema description`,"zh-CN":`Schema 描述`}},attributes:{type:`string`,valueHint:`<json>`,description:{"en-US":`Attributes JSON array: [{"name":"age","description":"age"}]`,"zh-CN":`属性 JSON 数组:[{"name":"age","description":"age"}]`},required:!0}},exampleArgs:[{"en-US":`--name "user_basic" --attributes '[{"name":"age","description":"age"},{"name":"hobby","description":"hobby"}]'`,"zh-CN":`--name "user_basic" --attributes '[{"name":"age","description":"年龄"},{"name":"hobby","description":"爱好"}]'`}],async run(e){let{settings:t,flags:n}=e,r=n.name,i=n.attributes,a;try{a=JSON.parse(i)}catch{throw new x(`--attributes must be valid JSON array`)}let o={name:r,attributes:a};n.description&&(o.description=n.description);let s=C(t.output);if(t.dryRun){O({endpoint:e.client.url(on()),request:o},s);return}let c=await e.client.requestJson({path:on(),method:`POST`,body:o});t.quiet||s===`text`?D(`Profile schema created: ${c.profile_schema_id}`):O(c,s)}}),rd=S({description:{"en-US":`Get user profile by schema ID and user ID`,"zh-CN":`通过 Schema ID 和用户 ID 获取用户画像`},auth:`apiKey`,usageArgs:`--schema-id <id> --user-id <id>`,flags:{schemaId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Profile schema ID (required)`,"zh-CN":`Profile Schema ID(必填)`},required:!0},userId:{type:`string`,valueHint:`<id>`,description:{"en-US":`User ID (required)`,"zh-CN":`用户 ID(必填)`},required:!0}},exampleArgs:[`--schema-id schema_xxx --user-id user1`],async run(e){let{settings:t,flags:n}=e,r=n.schemaId,i=n.userId,a=C(t.output),o=new URLSearchParams({user_id:i}),s=`${Qn(r)}?${o.toString()}`;if(t.dryRun){O({endpoint:e.client.url(s),method:`GET`},a);return}let c=await e.client.requestJson({path:s,method:`GET`});if(t.quiet||a===`text`){if(c.profile?.attributes)for(let e of c.profile.attributes)D(`${e.name}: ${e.value??`(empty)`}`);else D(`No profile data found.`)}else O(c,a)}}),id=S({description:{"en-US":"Retrieve from a Bailian knowledge base (deprecated, use `search` instead)","zh-CN":"从百炼知识库检索(已废弃,请改用 `search`)"},auth:`apiKey`,usageArgs:`--index-id <id> --query <text> [flags]`,flags:{indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base index ID (required)`,"zh-CN":`知识库索引 ID(必填)`},required:!0},query:{type:`string`,valueHint:`<text>`,description:{"en-US":`Search query (required)`,"zh-CN":`搜索查询(必填)`},required:!0},denseSimilarityTopK:{type:`number`,valueHint:`<n>`,description:{"en-US":`Dense retrieval top K`,"zh-CN":`稠密检索 Top K`}},sparseSimilarityTopK:{type:`number`,valueHint:`<n>`,description:{"en-US":`Sparse retrieval top K`,"zh-CN":`稀疏检索 Top K`}},rerank:{type:`switch`,description:{"en-US":`Enable reranking`,"zh-CN":`启用重排序`}},rerankTopN:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rerank top N results`,"zh-CN":`重排序前 N 个结果`}},rerankModel:{type:`string`,valueHint:`<name>`,description:{"en-US":`Rerank model, e.g. qwen3-rerank-hybrid`,"zh-CN":`重排序模型,例如 qwen3-rerank-hybrid`}},rerankMode:{type:`string`,valueHint:`<mode>`,description:{"en-US":`Rerank mode: qa, similar, or custom`,"zh-CN":`重排序模式:qa、similar 或 custom`}},rerankInstruct:{type:`string`,valueHint:`<text>`,description:{"en-US":`Custom rerank instruction, when mode=custom`,"zh-CN":`自定义重排序指令,仅在 mode=custom 时使用`}},topK:{type:`number`,valueHint:`<n>`,description:{"en-US":`Number of results (deprecated, use --rerank-top-n)`,"zh-CN":`结果数量(已废弃,请使用 --rerank-top-n)`}}},notes:[{"en-US":`--rerank-model requires the target knowledge base to already have a rerank model configured; otherwise every value is rejected.`,"zh-CN":`--rerank-model 要求目标知识库已配置重排序模型,否则任何取值都会被拒绝。`}],exampleArgs:[{"en-US":`--index-id idx_xxx --query "How to use Alibaba Cloud Bailian"`,"zh-CN":`--index-id idx_xxx --query "如何使用阿里云百炼"`},{"en-US":`--index-id idx_xxx --query "RAG retrieval" --rerank --rerank-model qwen3-rerank-hybrid`,"zh-CN":`--index-id idx_xxx --query "RAG 检索" --rerank --rerank-model qwen3-rerank-hybrid`}],async run(e){let{settings:t,flags:n}=e,r=C(t.output);n.topK!==void 0&&n.rerankTopN===void 0&&(process.stderr.write(`Warning: --top-k is deprecated. Use --rerank-top-n instead.
|
|
2734
|
+
`),n.rerankTopN=n.topK);let i={index_id:n.indexId,query:n.query,search_filters:[]};if(n.denseSimilarityTopK!==void 0&&(i.dense_similarity_top_k=n.denseSimilarityTopK),n.sparseSimilarityTopK!==void 0&&(i.sparse_similarity_top_k=n.sparseSimilarityTopK),n.rerank&&(i.enable_reranking=!0),n.rerankTopN!==void 0&&(i.rerank_top_n=n.rerankTopN),n.rerankModel){let e={model_name:n.rerankModel};n.rerankMode&&(e.rerank_mode=n.rerankMode),n.rerankInstruct&&(e.rerank_instruct=n.rerankInstruct),i.rerank=[e]}if(t.dryRun){O({endpoint:e.client.url(wt()),request:i},r);return}let a=await e.client.requestJson({path:wt(),method:`POST`,body:i}),o=a.data?.nodes||[];t.quiet||r===`text`?ad(o.map(e=>({text:e.text,score:e.score}))):O(a,r)}});function ad(e){if(e.length===0)D(`No results found.`);else for(let t=0;t<e.length;t++){let n=e[t];D(`[${t+1}] (score: ${n.score.toFixed(4)})`),D(n.text),D(``)}}const L={workspaceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID)`,"zh-CN":`API Endpoint URL 使用的 Workspace ID(也可设置 BAILIAN_WORKSPACE_ID)`}}},od={pageNumber:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page size per request`,"zh-CN":`每次请求的分页大小`}}};function R(e){let t=e.flags.workspaceId||e.settings.workspaceId;if(!t)throw new n(`Workspace ID is required.`,l.USAGE,`Pass --workspace-id, set BAILIAN_WORKSPACE_ID env, or configure: ${e.identity.binName} config set workspace_id <id>`);return t}function sd(e){if(!process.stdout.isTTY)return e;let t=process.stdout.columns??120;return e.length>t?`${e.slice(0,Math.max(0,t-1))}…`:e}function cd(e){return e.data?.ingestion_status??`UNKNOWN`}function ld(e){return(e.data?.rows??[]).filter(e=>[e.code,e.status].some(e=>typeof e==`string`&&e.includes(`FAILED`)))}function ud(e){let t=e.data?.rows??[];if(t.length===0)return!1;let n=e.data?.total_count;return typeof n==`number`&&t.length<n?!1:t.every(e=>{let t=e.code??e.status??``;return t===`FINISH`||t.includes(`FAILED`)})}function dd(e,t){let n=e.data?.rows??[],r=ld(e),i=new Set(r.map(e=>e.doc_id)),a=n.filter(e=>!i.has(e.doc_id)),o=r.map(e=>`${e.doc_name??e.doc_id??`?`}: ${e.message??e.code??`unknown`}`).join(`; `),s=a.map(e=>e.doc_name??e.doc_id??`?`).join(`, `),c=[];return o&&c.push(`failed: ${o}`),s&&c.push(`succeeded: ${s}`),c.length>0?`${t} (${c.join(`; `)})`:t}function fd(e,t,n){let r=new URL(T(e,h.indexJobStatus));return r.searchParams.set(`index_id`,t),r.searchParams.set(`job_id`,n),r}async function pd(e,t,n){return kr(e,t,{url:n.statusUrl,intervalSec:n.intervalSec,timeoutSec:t.timeout,isComplete:e=>{let t=e;return cd(t)===`COMPLETED`||ud(t)},isFailed:()=>!1,getStatus:e=>{let t=e,n=cd(t),r=ld(t).length,i=t.data?.total_count;return typeof i==`number`&&i>0?`${n} (${r}/${i} failed)`:r>0?`${n} (${r} failed)`:n}})}function md(e,t){return!(e instanceof n)||e.hint?e:new n(e.message,e.exitCode,t,{cause:e,api:e.api,rawResponse:e.rawResponse})}function hd(e,t){let n=e.data?.[t];if(typeof n==`string`)return n;let r=e[t];return typeof r==`string`?r:void 0}const gd={query:{type:`string`,valueHint:`<text>`,description:{"en-US":`Search query text (required, cannot be empty)`,"zh-CN":`搜索查询文本(必填且不能为空)`},required:!0},agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Retrieval service ID (find in console knowledge retrieval page)`,"zh-CN":`检索服务 ID(可在控制台知识库检索页面查看)`},required:!0},...L,agentVersion:{type:`string`,valueHint:`<version>`,description:{"en-US":`Service version to call: beta (draft for debugging) or a published number; default is the latest published version`,"zh-CN":`要调用的服务版本:beta(用于调试的草稿)或已发布版本号;默认使用最新发布版本`}},image:{type:`array`,valueHint:`<url>`,description:{"en-US":`Image URL for multimodal retrieval (repeatable)`,"zh-CN":`多模态检索使用的图片 URL(可重复)`}}};var _d=S({description:{"en-US":`Search a Bailian knowledge base (RAG semantic retrieval)`,"zh-CN":`搜索百炼知识库(RAG 语义检索)`},auth:`apiKey`,usageArgs:`--query <text> --agent-id <id> [flags]`,flags:gd,notes:[{"en-US":`Retrieval scope and strategy (multi-index weighting, routing, reranking, etc.) are driven by the agent_id service config. Only query and agent_id are required.`,"zh-CN":`检索范围与策略(多索引权重、路由、重排序等)由 agent_id 服务配置决定。仅 query 和 agent_id 必填。`},{"en-US":`Auth: uses DashScope API Key (Bearer token). Get yours from the console API Key page.`,"zh-CN":`鉴权:使用 DashScope API Key(Bearer Token)。可在控制台 API Key 页面获取。`},{"en-US":"`--workspace-id` can be set via BAILIAN_WORKSPACE_ID env or `kscli config set workspace_id <id>`.","zh-CN":"`--workspace-id` 可通过 BAILIAN_WORKSPACE_ID 环境变量或 `kscli config set workspace_id <id>` 设置。"},{"en-US":"`--agent-version beta` calls the draft config for debugging before it is deployed.","zh-CN":"`--agent-version beta` 会调用尚未部署的草稿配置,便于发布前调试。"}],exampleArgs:[{"en-US":`--query "What is RAG?" --agent-id aid-xxx --workspace-id ws-xxx`,"zh-CN":`--query "什么是 RAG?" --agent-id aid-xxx --workspace-id ws-xxx`},{"en-US":`--api-key $DASHSCOPE_API_KEY --query "test search" --agent-id aid-xxx --workspace-id ws-xxx --image https://example.com/img.jpg`,"zh-CN":`--api-key $DASHSCOPE_API_KEY --query "测试搜索" --agent-id aid-xxx --workspace-id ws-xxx --image https://example.com/img.jpg`}],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={query:n.query,agent_id:n.agentId};n.agentVersion&&(a.agent_version=n.agentVersion),n.image&&n.image.length>0&&(a.images=n.image);let o=Tt(r);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.nodes||[];if(t.quiet||i===`text`){if(c.length===0)D(`No results found.`);else for(let e=0;e<c.length;e++){let t=c[e];D(`[${e+1}] (score: ${t.score.toFixed(4)})`),D(t.text),D(``)}}else O(s,i)}});const vd={message:{type:`array`,valueHint:`<text>`,description:{"en-US":`Message text (repeatable). Supports role:content prefix to set role (e.g. user:hello), defaults to user. Follows OpenAI message format`,"zh-CN":`消息文本(可重复)。支持使用 role:content 前缀指定角色(例如 user:hello),默认为 user。遵循 OpenAI 消息格式`}},agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Q&A service ID (find in console knowledge Q&A page)`,"zh-CN":`问答服务 ID(可在控制台知识库问答页面查看)`},required:!0},...L,agentVersion:{type:`string`,valueHint:`<version>`,description:{"en-US":`Service version to call: beta (draft for debugging) or a published number; default is the latest published version`,"zh-CN":`要调用的服务版本:beta(用于调试的草稿)或已发布版本号;默认使用最新发布版本`}},image:{type:`array`,valueHint:`<url>`,description:{"en-US":`Image URL (repeatable). Attached to the last user message as multimodal content`,"zh-CN":`图片 URL(可重复)。将作为多模态内容附加到最后一条用户消息`}}};function yd(e){let t=[];if(e.message){let n=/* @__PURE__ */ new Set([`user`,`assistant`]);for(let r of e.message){if(r.startsWith(`{`))try{let e=JSON.parse(r);if(e.role&&n.has(e.role)&&e.content!==void 0){t.push(e);continue}}catch{}let e=r.indexOf(`:`),i=e===-1?``:r.slice(0,e);n.has(i)?t.push({role:i,content:r.slice(e+1)}):t.push({role:`user`,content:r})}}return t}function bd(e){for(let t of e)if(Array.isArray(t.content)&&t.content.some(e=>e.type===`image_url`))return!0;return!1}function xd(e,t){let n=-1;for(let t=e.length-1;t>=0;t--)if(e[t].role===`user`){n=t;break}n===-1&&(e.push({role:`user`,content:``}),n=e.length-1);let r=e[n],i=[];typeof r.content==`string`?i.push({type:`text`,text:r.content}):i.push(...r.content);for(let e of t)i.push({type:`image_url`,image_url:{url:e}});r.content=i}const Sd={tool_calling:`🔍 Retrieving...`,plan_start:`🤔 Planning...`,generation_start:`✍️ Generating...`};var Cd=S({description:{"en-US":`Chat with a Bailian knowledge base (RAG Q&A with streaming)`,"zh-CN":`与百炼知识库对话(支持流式输出的 RAG 问答)`},auth:`apiKey`,usageArgs:`--message <text> --agent-id <id> [flags]`,flags:vd,notes:[{"en-US":`Response is returned as SSE stream events. Event lifecycle: tool_calling → tool_return → plan_start → planning → plan_end → generation_start → generating → generation_end. tool_calling → tool_return may loop multiple times.`,"zh-CN":`响应以 SSE 流事件返回。事件生命周期:tool_calling → tool_return → plan_start → planning → plan_end → generation_start → generating → generation_end。tool_calling → tool_return 可能循环多次。`},{"en-US":`Auth: uses DashScope API Key (Bearer token). Get yours from the console API Key page.`,"zh-CN":`鉴权:使用 DashScope API Key(Bearer Token)。可在控制台 API Key 页面获取。`},{"en-US":"`--workspace-id` can be set via BAILIAN_WORKSPACE_ID env or `kscli config set workspace_id <id>`.","zh-CN":"`--workspace-id` 可通过 BAILIAN_WORKSPACE_ID 环境变量或 `kscli config set workspace_id <id>` 设置。"},{"en-US":`Multi-turn: use --message "user:..." and --message "assistant:..." to pass conversation history.`,"zh-CN":`多轮对话:使用 --message "user:..." 和 --message "assistant:..." 传入对话历史。`},{"en-US":"`--agent-version beta` calls the draft config for debugging before it is deployed.","zh-CN":"`--agent-version beta` 会调用尚未部署的草稿配置,便于发布前调试。"}],exampleArgs:[{"en-US":`--message "What is RAG?" --agent-id aid-xxx --workspace-id ws-xxx`,"zh-CN":`--message "什么是 RAG?" --agent-id aid-xxx --workspace-id ws-xxx`},{"en-US":`--message "user:What is RAG?" --message "assistant:RAG is..." --message "How does it work?" --agent-id aid-xxx --workspace-id ws-xxx`,"zh-CN":`--message "user:什么是 RAG?" --message "assistant:RAG 是……" --message "它是如何工作的?" --agent-id aid-xxx --workspace-id ws-xxx`},{"en-US":`--message "Describe these images" --image https://example.com/a.png --image https://example.com/b.png --agent-id aid-xxx --workspace-id ws-xxx`,"zh-CN":`--message "描述这些图片" --image https://example.com/a.png --image https://example.com/b.png --agent-id aid-xxx --workspace-id ws-xxx`}],validate:e=>e.message&&e.message.length>0||e.image&&e.image.length>0?void 0:`Provide --message (or --image for a pure image query).`,async run(e){let{settings:t,flags:r}=e,i=yd(r),a=r.image,o=!!a&&a.length>0;i.length===0&&o&&(i=[{role:`user`,content:``}]);let s=R(e),c=C(t.output),u=c===`text`&&!!process.stdout.isTTY;if(o){if(bd(i))throw new n(`Cannot use --image when messages already contain embedded image_url content parts. Use one approach or the other.`,l.USAGE);xd(i,a)}let d={input:{messages:i},parameters:{agent_options:{agent_id:r.agentId,...r.agentVersion?{agent_version:r.agentVersion}:{}}},stream:!0},f=Ct(s);if(t.dryRun){O({endpoint:f,request:d},c);return}let p=await e.client.request({path:f,method:`POST`,body:d,stream:!0});if(u){let e=E(process.stdout),r=t.verbose;for await(let t of $t(p)){if(t.data===`[DONE]`)break;if(t.event===`error`){let e=`Chat API error`,r;try{let n=JSON.parse(t.data);e=n.message||e,r=n.code}catch{}throw new n(e,l.GENERAL,r?`API error: ${r}`:void 0)}try{let n=JSON.parse(t.data);for(let t of n.output?.choices??[]){let n=t.message;if(n.extra?.step_change){let t=Sd[n.extra.step_change];t&&process.stdout.write(`${e.dim(t)}\n`)}if(r&&n.extra?.step_change&&process.stderr.write(E(process.stderr).dim(`[event] step_change=${n.extra.step_change} step=${n.extra?.step??``} group=${n.extra?.group??``}`)+`
|
|
2735
2735
|
`),n.content&&process.stdout.write(n.content),t.finish_reason===`stop`)break}}catch{}}process.stdout.write(`
|
|
2736
|
-
`)}else{let e=``,r=``;for await(let t of Gt(p)){if(t.data===`[DONE]`)break;if(t.event===`error`){let e=`Chat API error`,r;try{let n=JSON.parse(t.data);e=n.message||e,r=n.code}catch{}throw new n(e,l.GENERAL,r?`API error: ${r}`:void 0)}try{let n=JSON.parse(t.data);n.request_id&&(r=n.request_id);for(let t of n.output?.choices??[])if(t.message?.content&&(e+=t.message.content),t.finish_reason===`stop`)break}catch{}}t.quiet||c===`text`?D(e):O({answer:e,request_id:r},c)}}});const od={name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by knowledge base name (fuzzy match, 1-20 chars)`,"zh-CN":`按知识库名称筛选(模糊匹配,1–20 个字符)`}},...Hu,...L};var sd=S({description:{"en-US":`List knowledge bases in the workspace`,"zh-CN":`列出 Workspace 中的知识库`},auth:`apiKey`,usageArgs:`[flags]`,flags:od,notes:[{"en-US":`Auth: uses DashScope API Key (Bearer token).`,"zh-CN":`鉴权:使用 DashScope API Key(Bearer Token)。`},{"en-US":"`--workspace-id` can be set via BAILIAN_WORKSPACE_ID env or config workspace_id.","zh-CN":"`--workspace-id` 可通过 BAILIAN_WORKSPACE_ID 环境变量或配置项 workspace_id 设置。"},{"en-US":`Use the returned id as --index-id in knowledge base / document management commands.`,"zh-CN":`在知识库/文档管理命令中,将返回的 ID 作为 --index-id 使用。`}],exampleArgs:[`--workspace-id ws-xxx`,`--name demo --page-number 2 --page-size 50`],validate(e){if(e.name!==void 0&&(e.name.length<1||e.name.length>20))return`--name must be 1-20 characters`;if(e.pageSize!==void 0&&(e.pageSize<1||e.pageSize>100))return`--page-size must be between 1 and 100`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a=new URL(T(r,h.indexList));n.name&&a.searchParams.set(`pipeline_name`,n.name),a.searchParams.set(`page_number`,String(n.pageNumber??1)),a.searchParams.set(`page_size`,String(n.pageSize??20));let o=a.toString();if(t.dryRun){O({endpoint:o,request:null},i);return}let s=await e.client.requestJson({path:o,method:`GET`}),c=s.data?.rows??[];if(t.quiet){for(let e of c)D(e.id);return}if(i===`text`){if(c.length===0)D(`No knowledge bases found.`);else for(let e of c)D(Uu([e.id,e.name,e.embeddingModelName??`-`,e.chunkSize??`-`,e.description??``].join(` `)));D(`total: ${s.data?.total??c.length}`)}else O(s,i)}});const cd={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},...L};function ld(e,t){let n=new URL(T(e,h.indexList));return n.searchParams.set(`pipeline_id`,t),n.searchParams.set(`page_number`,`1`),n.searchParams.set(`page_size`,`1`),n.toString()}async function ud(e,t,r){let i=(await e.requestJson({path:ld(t,r),method:`GET`})).data?.rows?.[0];if(!i)throw new n(`Knowledge base not found: ${r}`,l.GENERAL,`Check the id — list knowledge bases in this workspace to verify it.`);return i}function z(e,t){return` ${e}: ${t??`-`}`}var dd=S({description:{"en-US":`Show knowledge base configuration details`,"zh-CN":`查看知识库配置详情`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:cd,notes:[{"en-US":`Indexing settings are immutable; changing them requires recreating the knowledge base.`,"zh-CN":`索引设置不可修改;如需更改,必须重新创建知识库。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output);if(t.dryRun){O({endpoint:ld(r,n.indexId),request:null},i);return}let a=await ud(e.client,r,n.indexId);if(t.quiet){D(a.id??``);return}if(i!==`text`){O(a,i);return}D(`Basic:`),D(z(`id`,a.id)),D(z(`name`,a.name)),D(z(`description`,a.description)),D(z(`dataType`,a.dataType)),D(`Indexing: [immutable — recreate required to change]`),D(z(`embeddingModelName`,a.embeddingModelName)),D(z(`embeddingDimension`,a.embeddingDimension)),D(z(`chunkSize`,a.chunkSize)),D(z(`overlapSize`,a.overlapSize)),D(z(`chunkMode`,a.chunkMode)),D(z(`separator`,a.separator)),D(`Retrieval:`),D(z(`rerankModelName`,a.rerankModelName)),D(z(`rerankMinScore`,a.rerankMinScore)),D(z(`rerankTopN`,a.rerankTopN)),D(z(`rerankMode`,a.rerankMode)),D(z(`enableRewrite`,a.enableRewrite)),D(z(`denseSimilarityTopK`,a.denseSimilarityTopK)),D(z(`sparseSimilarityTopK`,a.sparseSimilarityTopK)),D(`Data:`),D(z(`sourceType`,a.sourceType)),D(z(`connectorId`,a.connectorId))}});const fd={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},...Hu,...L};var pd=S({description:{"en-US":`List documents in a knowledge base with parse/index status`,"zh-CN":`列出知识库文档及其解析/索引状态`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:fd,notes:[{"en-US":`Documents with status FAILED are highlighted in text mode — use the import job status command to inspect failures.`,"zh-CN":`文本模式会突出显示状态为 FAILED 的文档——请使用导入任务状态命令检查失败详情。`},{"en-US":`Page size defaults to 10 (server default), max 100.`,"zh-CN":`分页大小默认为 10(服务端默认值),最大为 100。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --page-size 100`],validate(e){if(e.pageSize!==void 0&&(e.pageSize<1||e.pageSize>100))return`--page-size must be between 1 and 100`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a=new URL(T(r,h.indexFiles));a.searchParams.set(`index_id`,n.indexId),a.searchParams.set(`page_num`,String(n.pageNumber??1)),a.searchParams.set(`page_size`,String(n.pageSize??10));let o=a.toString();if(t.dryRun){O({endpoint:o,request:null},i);return}let s=await e.client.requestJson({path:o,method:`GET`}),c=s.data?.rows??[];if(t.quiet){for(let e of c)D(e.doc_id??``);return}if(i===`text`){let e=E(process.stdout);if(c.length===0)D(`No documents found.`);else for(let t of c){let n=Uu([t.doc_id,t.status,t.doc_name,t.doc_type??`-`,t.size??`-`].join(` `));D(t.status===`FAILED`?e.red(n):n)}D(`total: ${s.data?.total_count??c.length}`)}else O(s,i)}});const md={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},jobId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Import job ID (ingestionId returned by import commands)`,"zh-CN":`导入任务 ID(导入命令返回的 ingestionId)`},required:!0},...Hu,wait:{type:`switch`,description:{"en-US":`Poll until the job reaches a terminal state`,"zh-CN":`轮询直到任务进入终态`}},pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 5)`,"zh-CN":`等待时的轮询间隔(默认:5)`}},...L};function hd(e){let t=E(process.stdout);D(`status: ${e.data?.ingestion_status??`UNKNOWN`}`);for(let n of e.data?.rows??[]){let e=n.code??n.status??`?`,r=` ${n.doc_id??`?`} ${e} ${n.doc_name??``}`;D(e.includes(`FAILED`)?t.red(r):r)}}var gd=S({description:{"en-US":`Check knowledge base import job status`,"zh-CN":`检查知识库导入任务状态`},auth:`apiKey`,usageArgs:`--index-id <id> --job-id <id> [flags]`,flags:md,notes:[{"en-US":`Both --index-id and --job-id are required (passing only one returns SystemError).`,"zh-CN":`--index-id 和 --job-id 均为必填(只传其中一个会返回 SystemError)。`},{"en-US":`If you see a SystemError, the job may not exist — check the ingestion id in the document list output.`,"zh-CN":`如果出现 SystemError,任务可能不存在——请检查文档列表输出中的 ingestion ID。`},{"en-US":`Overall job states are PENDING / RUNNING / COMPLETED; per-document failures (for example PARSE_FAILED) exit non-zero with the error message passed through.`,"zh-CN":`任务整体状态为 PENDING / RUNNING / COMPLETED;单个文档失败(例如 PARSE_FAILED)时会以非零状态退出,并原样透传错误信息。`}],exampleArgs:[`--index-id idx-xxx --job-id job-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --job-id job-xxx --wait --poll-interval 10`],async run(e){let{settings:t,flags:r}=e,i=R(e),a=C(t.output),o=new URL(T(i,h.indexJobStatus));o.searchParams.set(`index_id`,r.indexId),o.searchParams.set(`job_id`,r.jobId),r.pageNumber!==void 0&&o.searchParams.set(`page_number`,String(r.pageNumber)),r.pageSize!==void 0&&o.searchParams.set(`page_size`,String(r.pageSize));let s=o.toString();if(t.dryRun){O({endpoint:s,request:null},a);return}let c;if(c=r.wait?await Yu(e.client,t,{statusUrl:s,intervalSec:r.pollInterval??5}):await e.client.requestJson({path:s,method:`GET`}),Gu(c).length>0)throw new n(qu(c,`Import job reported document failures.`),l.GENERAL);if(t.quiet){D(c.data?.ingestion_status??`UNKNOWN`);return}a===`text`?hd(c):O(c,a)}});const _d=1048576,vd={".doc":{maxBytes:150*_d,enforce:`block`},".docx":{maxBytes:150*_d,enforce:`block`},".ppt":{maxBytes:150*_d,enforce:`block`},".pptx":{maxBytes:150*_d,enforce:`block`},".pdf":{maxBytes:150*_d,enforce:`block`},".png":{maxBytes:20*_d,enforce:`block`},".jpg":{maxBytes:20*_d,enforce:`block`},".jpeg":{maxBytes:20*_d,enforce:`block`},".bmp":{maxBytes:20*_d,enforce:`block`},".gif":{maxBytes:20*_d,enforce:`block`},".xls":{maxBytes:10*_d,enforce:`warn`},".xlsx":{maxBytes:10*_d,enforce:`warn`},".csv":{maxBytes:10*_d,enforce:`warn`},".md":{maxBytes:10*_d,enforce:`warn`},".txt":{maxBytes:10*_d,enforce:`warn`},".html":{maxBytes:10*_d,enforce:`warn`}};function yd(e){return Zr(e).toLowerCase()in vd}const bd=/* @__PURE__ */ new Set([`node_modules`,`.git`,`.svn`,`.hg`,`__pycache__`,`.venv`,`venv`,`.env`,`.tox`,`dist`,`build`,`.cache`,`.next`,`.nuxt`]);function xd(e){let t=[],r=[];function i(e){let a;try{a=Gr(e,{withFileTypes:!0})}catch(t){let r=t.code??`unknown`;throw new n(`Cannot read directory: ${e}`,l.GENERAL,`File system error (${r}) — check the path and permissions.`)}for(let n of a){let a=j(e,n.name);if(n.isDirectory()){bd.has(n.name)||i(a);continue}n.isFile()&&(yd(n.name)?t.push(a):r.push(a))}}for(let r of e){let e;try{e=Kr(r)}catch(e){let t=e.code??`unknown`;throw new n(`Cannot read path: ${r}`,l.GENERAL,`File system error (${t}) — check the path and permissions.`)}e.isDirectory()?i(r):e.isFile()&&t.push(r)}return{files:t,skipped:r}}function Sd(e){let t=Zr(e).toLowerCase(),r=vd[t];if(!r)throw new n(`Unsupported file type: ${t||Yr(e)}`,l.USAGE,`Supported formats: ${Object.keys(vd).join(` `)}`);let i;try{i=Kr(e).size}catch(t){let r=t.code??`unknown`;throw new n(`Cannot read file: ${e}`,l.GENERAL,`File system error (${r}) — check the path and permissions.`)}if(i>r.maxBytes){let a=r.maxBytes/_d;if(r.enforce===`block`)throw new n(`File exceeds the ${a} MB limit for ${t}: ${Yr(e)}`,l.USAGE);return{sizeBytes:i,warning:`${Yr(e)} exceeds the recommended 10 MB for ${t}; the server may reject or truncate it.`}}return{sizeBytes:i}}const Cd=/* @__PURE__ */ new Set([`.doc`,`.docx`,`.ppt`,`.pptx`,`.pdf`,`.xls`,`.xlsx`,`.png`,`.jpg`,`.jpeg`,`.bmp`,`.gif`]);function wd(e,t){let r;try{r=Wr(e)}catch(r){let i=r.code??`unknown`,a=`File system error (${i}) — check the path and permissions.`;throw t&&i===`ENOENT`&&!Zr(e)&&!e.includes(`/`)&&!e.includes(`\\`)&&(a+=` If you meant to pass text content directly, use ${t} instead of --content-file.`),new n(`Cannot read file: ${e}`,l.GENERAL,a)}try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(r)}catch{let t=Zr(e).toLowerCase(),r=Cd.has(t)?`Document formats cannot be used as chunk content. Upload documents via the document upload command; to edit a chunk, save the text as .md/.txt first.`:`Convert the file to UTF-8 encoding and retry.`;throw new n(`File is not valid UTF-8 plain text: ${Yr(e)}`,l.USAGE,r)}}const Td={file:{type:`array`,valueHint:`<path>`,description:{"en-US":`Local file or directory path (repeatable). Directories are scanned recursively; unsupported formats are skipped`,"zh-CN":`本地文件或目录路径(可重复)。目录会递归扫描,不支持的格式将被跳过`},required:!0},indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Import into this knowledge base after registration (one job for all files)`,"zh-CN":`文件注册后导入该知识库(所有文件共用一个任务)`}},categoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Target data-center category; defaults to the workspace default category`,"zh-CN":`目标数据中心类目;默认为 Workspace 的默认类目`}},tag:{type:`array`,valueHint:`<text>`,description:{"en-US":`File tag (repeatable), applied to every uploaded file`,"zh-CN":`文件标签(可重复),应用于每个上传文件`}},wait:{type:`switch`,description:{"en-US":`Poll the import job to a terminal state (needs --index-id)`,"zh-CN":`轮询导入任务直到进入终态(需要 --index-id)`}},pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 5)`,"zh-CN":`等待时的轮询间隔(默认:5)`}},...L};var Ed=S({description:{"en-US":`Upload local files or directories to the data center and optionally import into a knowledge base`,"zh-CN":`上传本地文件或目录到数据中心,并可选择导入知识库`},auth:`apiKey`,usageArgs:`--file <path> [flags]`,flags:Td,notes:[{"en-US":`Pipeline: apply upload lease → PUT to OSS → register file → (with --index-id) create import job.`,"zh-CN":`处理流程:申请上传凭证 → PUT 到 OSS → 注册文件 →(传入 --index-id 时)创建导入任务。`},{"en-US":`Without --category-id the workspace default category is resolved automatically.`,"zh-CN":`未传入 --category-id 时,会自动解析 Workspace 的默认类目。`},{"en-US":`Directories are scanned recursively; node_modules, .git, and similar are skipped automatically.`,"zh-CN":`目录会递归扫描;node_modules、.git 等目录会被自动跳过。`},{"en-US":`Multiple files are processed sequentially; on failure, already-registered file ids are listed in the error hint.`,"zh-CN":`多个文件会依次处理;失败时,错误提示会列出已经注册成功的文件 ID。`}],exampleArgs:[`--file ./a.md --workspace-id ws-xxx`,`--file ./a.md --file ./b.pdf --index-id idx-xxx --wait`,`--file ./docs/ --workspace-id ws-xxx`,`--file ./docs/ --dry-run --verbose`],validate(e){if(e.wait&&!e.indexId)return`--wait requires --index-id`},async run(e){let{settings:t,flags:r}=e,i=R(e),a=C(t.output),{files:o,skipped:s}=xd(r.file);if(o.length===0)throw new n(`No supported files found`,l.USAGE,`Supported formats: .pdf .doc .docx .ppt .pptx .xls .xlsx .csv .md .txt .html .png .jpg .jpeg .bmp .gif`);let c=o.map(e=>{let t=Sd(e);return t.warning&&process.stderr.write(`Warning: ${t.warning}\n`),{filePath:e,sizeBytes:t.sizeBytes}});if(t.dryRun){let e=r.categoryId??`default`,t=c.flatMap(t=>[{step:`applyFileUploadLease`,endpoint:T(i,h.applyFileUploadLease),request:{category:e,fileName:Yr(t.filePath),sizeBytes:String(t.sizeBytes),contentMd5:`<md5-base64>`}},{step:`ossPut`,endpoint:`<lease.param.url>`,request:{method:`PUT`,headers:`<lease.param.headers>`}},{step:`addFile`,endpoint:T(i,h.addFile),request:{leaseId:`<leaseId>`,category:e,parser:`AUTO_SELECT`,...r.tag?.length?{tags:r.tag}:{}}}]);r.indexId&&t.push({step:`createImportJob`,endpoint:T(i,h.indexJobCreate),request:{indexId:r.indexId,sourceType:`DATA_CENTER_FILE`,docIds:[`<fileId>`]}}),O({steps:t,skipped:s},a);return}let u=r.categoryId??`default`,d=[];for(let t of c)try{let a=Wr(t.filePath),o=Sr(`md5`).update(a).digest(`base64`),s=await e.client.requestJson({path:T(i,h.applyFileUploadLease),method:`POST`,body:{category:u,fileName:Yr(t.filePath),sizeBytes:String(t.sizeBytes),contentMd5:o}}),c=s.data?.leaseId,f=s.data?.param;if(!c||!f?.url)throw new n(`Upload lease response missing leaseId/url for ${t.filePath}`,l.GENERAL);let p;try{p=await fetch(f.url,{method:f.method??`PUT`,headers:f.headers,body:a})}catch(e){let r=e.cause?.code;throw new n(`OSS upload failed for ${Yr(t.filePath)}`,l.NETWORK,r?`Network error (${r}).`:void 0,{cause:e})}if(!p.ok){let e=await p.text().catch(()=>``);throw new n(`OSS upload rejected (HTTP ${p.status}) for ${Yr(t.filePath)}${e?`: ${e.slice(0,300)}`:``}`,l.GENERAL)}let m=(await e.client.requestJson({path:T(i,h.addFile),method:`POST`,body:{leaseId:c,category:u,parser:`AUTO_SELECT`,...r.tag?.length?{tags:r.tag}:{}}})).data?.fileId;if(!m)throw new n(`addFile response missing fileId for ${t.filePath}`,l.GENERAL);d.push({path:t.filePath,fileId:m})}catch(e){throw d.length>0?Xu(e,`Already registered: ${d.map(e=>e.fileId).join(`, `)}`):e}let f,p;if(r.indexId&&(f=(await e.client.requestJson({path:T(i,h.indexJobCreate),method:`POST`,body:{indexId:r.indexId,sourceType:`DATA_CENTER_FILE`,docIds:d.map(e=>e.fileId)}})).data?.ingestionId,r.wait&&f)){let a=await Yu(e.client,t,{statusUrl:Ju(i,r.indexId,f).toString(),intervalSec:r.pollInterval??5});if(p=Wu(a),Gu(a).length>0)throw new n(qu(a,`Import job reported document failures.`),l.GENERAL,`Registered file ids: ${d.map(e=>e.fileId).join(`, `)}`)}if(t.quiet){for(let e of d)D(e.fileId);return}if(a===`text`){for(let e of d)D(`${Yr(e.path)} ${e.fileId} registered`);f&&D(`job: ${f}`),p&&D(`status: ${p}`);let e=[`Uploaded ${d.length} file${d.length===1?``:`s`}`];if(s.length>0&&e.push(`skipped ${s.length} unsupported`),D(`\n${e.join(`, `)}.`),t.verbose&&s.length>0){D(`Skipped files:`);for(let e of s)D(` ${Yr(e)}`)}return}O({files:d.map(e=>({path:e.path,fileId:e.fileId})),skipped:s,...r.indexId?{index_id:r.indexId}:{},...f?{ingestion_id:f}:{},...p?{final_status:p}:{}},a)}});const Dd={name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Knowledge base name (1-20 chars, unique in workspace)`,"zh-CN":`知识库名称(1–20 个字符,在 Workspace 中唯一)`},required:!0},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`What this knowledge base holds and what it is for — tells bases apart in the workspace list (1-500 chars)`,"zh-CN":`知识库装了什么内容、给谁用,用于在 Workspace 列表中区分同类知识库(1–500 个字符)`},required:!0},docId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Data-center file id to import (repeatable); mutually exclusive with --category-id`,"zh-CN":`要导入的数据中心文件 ID(可重复);不能与 --category-id 同时使用`}},categoryId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Import every file under this category (repeatable); mutually exclusive with --doc-id`,"zh-CN":`导入该类目下的所有文件(可重复);不能与 --doc-id 同时使用`}},embeddingModel:{type:`string`,valueHint:`<name>`,description:{"en-US":`Embedding model name (default: text-embedding-v4)`,"zh-CN":`Embedding 模型名称(默认:text-embedding-v4)`}},chunkSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Chunk size in characters (default: 600, recommended 300-800)`,"zh-CN":`Chunk 字符数(默认:600,建议:300–800)`}},wait:{type:`switch`,description:{"en-US":`Poll the initial import job to a terminal state`,"zh-CN":`轮询初始导入任务直到进入终态`}},pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 5)`,"zh-CN":`等待时的轮询间隔(默认:5)`}},...L};function Od(e){return e.docId?.length?{sourceType:`DATA_CENTER_FILE`,docIds:e.docId,dataSources:[{sourceType:`DATA_CENTER_FILE`}]}:{sourceType:`DATA_CENTER_CATEGORY`,categoryIds:e.categoryId,dataSources:[{sourceType:`DATA_CENTER_CATEGORY`}]}}var kd=S({description:{"en-US":`Create a knowledge base and import data-center files or categories`,"zh-CN":`创建知识库并导入数据中心文件或类目`},auth:`apiKey`,usageArgs:`--name <text> --description <text> (--doc-id <id> | --category-id <id>) [flags]`,flags:Dd,notes:[{"en-US":`Structure/sink types are fixed to the default document knowledge base (unstructured, BUILT_IN storage).`,"zh-CN":`结构和存储类型固定为默认文档知识库(unstructured、BUILT_IN 存储)。`},{"en-US":`Returns the knowledge base id (pipelineId) and the initial import job id (ingestionId).`,"zh-CN":`返回知识库 ID(pipelineId)和初始导入任务 ID(ingestionId)。`},{"en-US":`Use the import job status command (or --wait) to track the initial import.`,"zh-CN":`使用导入任务状态命令(或 --wait)跟踪初始导入。`}],exampleArgs:[{"en-US":`--name demo --description 'product docs' --doc-id file-xxx --workspace-id ws-xxx`,"zh-CN":`--name demo --description '产品文档' --doc-id file-xxx --workspace-id ws-xxx`},{"en-US":`--name demo --description 'product docs' --category-id cate-xxx --wait`,"zh-CN":`--name demo --description '产品文档' --category-id cate-xxx --wait`}],validate(e){if(e.name.length<1||e.name.length>20)return`--name must be 1-20 characters`;if(e.description.length<1||e.description.length>500)return`--description must be 1-500 characters`;let t=!!e.docId?.length,n=!!e.categoryId?.length;if(t&&n)return`Use either --doc-id or --category-id, not both`;if(!t&&!n)return`Provide --doc-id or --category-id as the data source`},async run(e){let{settings:t,flags:r}=e,i=R(e),a=C(t.output),o={name:r.name,description:r.description,structureType:`unstructured`,sinkType:`BUILT_IN`,embeddingModelName:r.embeddingModel??`text-embedding-v4`,chunkSize:r.chunkSize??600,...Od(r)},s=T(i,h.indexCreateV2);if(t.dryRun){O({endpoint:s,request:o},a);return}let c=await e.client.requestJson({path:s,method:`POST`,body:o}),u=c.data?.pipelineId,d=c.data?.ingestionId,f;if(r.wait&&u&&d){let a=await Yu(e.client,t,{statusUrl:Ju(i,u,d).toString(),intervalSec:r.pollInterval??5});if(f=Wu(a),Gu(a).length>0)throw new n(qu(a,`Initial import reported document failures.`),l.GENERAL,`Knowledge base created: ${u}`,{api:{requestId:a.request_id}})}if(t.quiet){D(u??``);return}if(a===`text`){D(`index_id: ${u??`-`}`),d&&D(`ingestion_id: ${d}`),f&&D(`status: ${f}`),D(`Next: check the import job status, then search against this knowledge base.`);return}O(f?{...c,final_status:f}:c,a)}});const Ad={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`New knowledge base name (1-20 chars)`,"zh-CN":`新的知识库名称(1–20 个字符)`}},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`New knowledge base description`,"zh-CN":`新的知识库描述`}},rerankMinScore:{type:`number`,valueHint:`<score>`,description:{"en-US":`Rerank minimum score threshold, range 0-1 (chunks below are filtered)`,"zh-CN":`Rerank 最低分数阈值,范围 0–1(低于阈值的 Chunk 会被过滤)`}},...L};var jd=S({description:{"en-US":`Update knowledge base name, description or rerank threshold`,"zh-CN":`更新知识库名称、描述或 Rerank 阈值`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:Ad,notes:[{"en-US":`Indexing settings (embedding model, chunk size, etc.) are immutable — recreate the knowledge base to change them.`,"zh-CN":`索引设置(Embedding 模型、Chunk 大小等)不可修改——如需更改,请重新创建知识库。`}],exampleArgs:[{"en-US":`--index-id idx-xxx --description 'product docs v2' --workspace-id ws-xxx`,"zh-CN":`--index-id idx-xxx --description '产品文档 v2' --workspace-id ws-xxx`},`--index-id idx-xxx --rerank-min-score 0.3`],validate(e){if(e.name===void 0&&e.description===void 0&&e.rerankMinScore===void 0)return`Nothing to update — pass --name, --description or --rerank-min-score`;if(e.name!==void 0&&(e.name.length<1||e.name.length>20))return`--name must be 1-20 characters`;if(e.rerankMinScore!==void 0&&(e.rerankMinScore<0||e.rerankMinScore>1))return`--rerank-min-score must be between 0 and 1`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={id:n.indexId,...n.name===void 0?{}:{name:n.name},...n.description===void 0?{}:{description:n.description},...n.rerankMinScore===void 0?{}:{rerankMinScore:n.rerankMinScore}},o=T(r,h.indexUpdate);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){D(`updated: ${n.indexId}`);return}O(s,i)}}});const Md={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},...L};var Nd=S({description:{"en-US":`Delete a knowledge base with all its documents and chunks`,"zh-CN":`删除知识库及其所有文档和 Chunk`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the knowledge base and all of its documents and chunks. Data-center files are not deleted.`,"zh-CN":`该操作会永久删除知识库及其全部文档和 Chunk,但不会删除数据中心文件。`}},usageArgs:`--index-id <id> [flags]`,flags:Md,notes:[{"en-US":`Irreversible — the knowledge base and all indexed content are permanently removed.`,"zh-CN":`该操作不可撤销——知识库及所有已索引内容将被永久删除。`},{"en-US":`Files in the data center are not affected; only the knowledge base index is deleted.`,"zh-CN":`数据中心中的文件不受影响;仅删除知识库索引。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={index_id:n.indexId},o=T(r,h.indexDelete);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){D(`deleted: ${n.indexId}`);return}O(s,i)}}});const Pd={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},docId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Document ID to delete (repeatable)`,"zh-CN":`要删除的文档 ID(可重复)`},required:!0},...L};var Fd=S({description:{"en-US":`Delete documents and their chunks from a knowledge base`,"zh-CN":`从知识库中删除文档及其 Chunk`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the selected documents and all of their chunks.`,"zh-CN":`该操作会永久删除所选文档及其全部 Chunk,且无法撤销。`}},usageArgs:`--index-id <id> --doc-id <id> [flags]`,flags:Pd,notes:[{"en-US":`Removes documents from the knowledge base index only; the source files remain in the data center.`,"zh-CN":`仅从知识库索引中移除文档;源文件仍保留在数据中心。`},{"en-US":"Use the doc_id from `knowledge doc list --quiet`, not the fileId from `knowledge doc upload`. For documents created via `knowledge create --doc-id`, the doc_id equals the fileId; for documents imported via `knowledge doc upload --index-id`, the doc_id may include a workspace suffix.","zh-CN":"请使用 `knowledge doc list --quiet` 返回的 doc_id,而不是 `knowledge doc upload` 返回的 fileId。通过 `knowledge create --doc-id` 创建的文档,其 doc_id 等于 fileId;通过 `knowledge doc upload --index-id` 导入的文档,其 doc_id 可能带有 Workspace 后缀。"},{"en-US":`Deletion may take up to ~30s to propagate — the document may still appear in the doc list briefly.`,"zh-CN":`删除结果最多可能需要约 30 秒才会生效——文档可能会短暂地继续出现在列表中。`},{"en-US":`The output lists the ids actually deleted.`,"zh-CN":`输出会列出实际删除的 ID。`}],exampleArgs:[`--index-id idx-xxx --doc-id file-xxx --workspace-id ws-xxx --dry-run`,`--index-id idx-xxx --doc-id file-a --doc-id file-b --yes`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={index_id:n.indexId,doc_ids:n.docId},o=T(r,h.indexDeleteFile);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.deleted??[];if(t.quiet){for(let e of c)D(e);return}if(i===`text`){D(`deleted: ${c.length} document(s)`);for(let e of c)D(` ${e}`);c.length!==n.docId.length&&process.stderr.write(`Warning: requested ${n.docId.length} deletion(s) but the server reported ${c.length}.\n`);return}O(s,i)}});const Id={docId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Data-center file ID to tag (repeatable, 1-20 per call)`,"zh-CN":`要添加标签的数据中心文件 ID(可重复,每次调用 1–20 个)`},required:!0},tag:{type:`array`,valueHint:`<text>`,description:{"en-US":`Tag applied to every --doc-id (repeatable, each up to 32 chars)`,"zh-CN":`应用于每个 --doc-id 的标签(可重复,每个最多 32 个字符)`},required:!0},mode:{type:`string`,valueHint:`<mode>`,description:{"en-US":`Update mode: append (default) or overwrite`,"zh-CN":`更新模式:append(默认)或 overwrite`}},...L};var Ld=S({description:{"en-US":`Batch update tags on data-center files`,"zh-CN":`批量更新数据中心文件标签`},auth:`apiKey`,usageArgs:`--doc-id <id> --tag <text> [flags]`,flags:Id,notes:[{"en-US":`The same tag set is applied to every --doc-id; run the command multiple times for different tag sets.`,"zh-CN":`同一组标签会应用于每个 --doc-id;若需应用不同标签组,请多次运行该命令。`},{"en-US":`Server limits: up to 100 tags per file, total tag length up to 700 chars, tag up to 32 chars.`,"zh-CN":`服务端限制:每个文件最多 100 个标签,标签总长度最多 700 个字符,单个标签最多 32 个字符。`}],exampleArgs:[`--doc-id file-xxx --tag project-a --tag draft --workspace-id ws-xxx`,`--doc-id file-a --doc-id file-b --tag final --mode overwrite`],validate(e){if(e.docId.length>20)return`--doc-id accepts at most 20 ids per call`;if(e.mode!==void 0&&e.mode!==`append`&&e.mode!==`overwrite`)return`--mode must be append or overwrite`;if(e.tag.length>100)return`At most 100 tags per file`;let t=e.tag.find(e=>e.length>32);if(t)return`Tag exceeds 32 characters: ${t}`;if(e.tag.reduce((e,t)=>e+t.length,0)>700)return`Total tag length exceeds 700 characters`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={fileInfos:n.docId.map(e=>({fileId:e,tags:n.tag})),updateMode:(n.mode??`append`).toUpperCase()},o=T(r,h.batchUpdateFileTag);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){D(`tagged: ${n.docId.length} file(s) with [${n.tag.join(`, `)}]`);return}O(s,i)}}});const Rd={scene:{type:`string`,valueHint:`<scene>`,description:{"en-US":`Service scene: chat (Q&A) or search (retrieval)`,"zh-CN":`服务场景:chat(问答)或 search(检索)`},required:!0},status:{type:`string`,valueHint:`<status>`,description:{"en-US":`Filter by status: draft, deployed (includes edited) or deleted`,"zh-CN":`按状态筛选:draft、deployed(包含 edited)或 deleted`}},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by service name (fuzzy match)`,"zh-CN":`按服务名称模糊筛选`}},agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by exact agent ID`,"zh-CN":`按 Agent ID 精确筛选`}},indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by exact linked knowledge base (pipeline) ID`,"zh-CN":`按关联的知识库(Pipeline)ID 精确筛选`}},...Hu,...L},zd=[`chat`,`search`],Bd=[`draft`,`deployed`,`deleted`];var Vd=S({description:{"en-US":`List retrieval / Q&A services (agents) in the workspace`,"zh-CN":`列出 Workspace 中的检索/问答服务(Agent)`},auth:`apiKey`,usageArgs:`--scene <chat|search> [flags]`,flags:Rd,notes:[{"en-US":`A scene (chat or search) is required — run once per scene to see both.`,"zh-CN":`必须指定场景(chat 或 search)——要查看两类服务,请分别运行一次。`},{"en-US":`Use the returned agent_id with the search or chat commands, or with service management commands.`,"zh-CN":`将返回的 agent_id 用于 search/chat 命令或服务管理命令。`}],exampleArgs:[`--scene chat --workspace-id ws-xxx`,`--scene search --status deployed`],validate(e){if(!zd.includes(e.scene))return`--scene must be chat or search`;if(e.status!==void 0&&!Bd.includes(e.status))return`--status must be draft, deployed or deleted`;if(e.pageSize!==void 0&&(e.pageSize<1||e.pageSize>100))return`--page-size must be between 1 and 100`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={agent_scene:n.scene,...n.status?{agent_status:n.status}:{},...n.name?{agent_name:n.name}:{},...n.agentId?{agent_id:n.agentId}:{},...n.indexId?{pipeline_id:n.indexId}:{},page_number:n.pageNumber??1,page_size:n.pageSize??10},o=T(r,h.agentList);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.rows??[];if(t.quiet){for(let e of c)D(e.agent_id??``);return}if(i===`text`){if(c.length===0)D(`No services found.`);else for(let e of c){let t=(e.pipeline_list??[]).map(e=>e.pipeline_name).filter(Boolean).join(`,`);D(Uu([e.agent_id,e.agent_status,e.agent_version,e.agent_name,t?`(kb: ${t})`:``].filter(Boolean).join(` `)))}D(`total: ${s.data?.total_count??c.length}`),D(n.scene===`search`?`Use an agent_id above with the knowledge search command.`:`Use an agent_id above with the knowledge chat command.`)}else O(s,i)}});const Hd={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Service (agent) ID`,"zh-CN":`服务(Agent)ID`},required:!0},agentVersion:{type:`string`,valueHint:`<version>`,description:{"en-US":`Specific version to inspect (beta or a published number); omit for all versions`,"zh-CN":`要查看的指定版本(beta 或已发布版本号);省略则返回全部版本`}},...L};function Ud(e){D(`Version ${e.agent_version??`?`}:`),e.agent_version_desc&&D(` desc: ${e.agent_version_desc}`),e.publish_time!==void 0&&D(` published: ${e.publish_time}`);let t=e.agent_config;if(t){t.agent_policy&&D(` policy: ${t.agent_policy}`),t.agent_model&&D(` model: ${t.agent_model}`),t.temperature!==void 0&&D(` temperature: ${t.temperature}`);for(let e of t.kb_search_configs??[]){let t=typeof e.id==`string`?e.id:`?`,n=typeof e.name==`string`?` (${e.name})`:``;D(` kb: ${t}${n}`)}}}var Wd=S({description:{"en-US":`Show service (agent) details including per-version configuration`,"zh-CN":`查看服务(Agent)详情及各版本配置`},auth:`apiKey`,usageArgs:`--agent-id <id> [flags]`,flags:Hd,notes:[{"en-US":`Without --agent-version all versions are returned (beta draft plus published numbers).`,"zh-CN":`未传入 --agent-version 时,会返回所有版本(beta 草稿和已发布版本号)。`},{"en-US":`The version value is passed through as-is; the valid set is server-side state.`,"zh-CN":`版本值将原样传递;有效版本集合由服务端状态决定。`}],exampleArgs:[`--agent-id aid-xxx --workspace-id ws-xxx`,`--agent-id aid-xxx --agent-version beta`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={agent_id:n.agentId,...n.agentVersion?{agent_version:n.agentVersion}:{}},o=T(r,h.agentGet);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data;if(t.quiet){D(c?.agent_id??``);return}if(i!==`text`){O(s,i);return}D(`Basic:`),D(` id: ${c?.agent_id??`-`}`),D(` name: ${c?.agent_name??`-`}`),D(` desc: ${c?.agent_desc??`-`}`),D(` scene: ${c?.agent_scene??`-`}`),D(` status: ${c?.agent_status??`-`}`);for(let e of c?.agent_details??[])Ud(e)}});const Gd={name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Service name (up to 200 chars, unique per scene in the workspace)`,"zh-CN":`服务名称(最多 200 个字符,在 Workspace 的同一场景中唯一)`},required:!0},scene:{type:`string`,valueHint:`<scene>`,description:{"en-US":`Service scene: chat (Q&A) or search (retrieval)`,"zh-CN":`服务场景:chat(问答)或 search(检索)`},required:!0},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`What this service answers and who it serves — recommended: agents read it to pick the right service (up to 1000 chars)`,"zh-CN":`这个服务能回答什么、给谁用 —— 建议填写:agent 靠它判断该调用哪个服务(最多 1000 个字符)`}},indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Bind this knowledge base; other settings use server defaults`,"zh-CN":`绑定该知识库;其他设置使用服务端默认值`}},...L};var Kd=S({description:{"en-US":`Create a retrieval / Q&A service (initial status: draft, version: beta)`,"zh-CN":`创建检索/问答服务(初始状态:draft,版本:beta)`},auth:`apiKey`,usageArgs:`--name <text> --scene <chat|search> [flags]`,flags:Gd,notes:[{"en-US":`Without an explicit configuration the server applies its default agent settings.`,"zh-CN":`未显式提供配置时,服务端会应用默认 Agent 设置。`},{"en-US":`The draft (beta) version can be tested via --agent-version beta on search/chat before deploying.`,"zh-CN":`部署前,可在 search/chat 命令中使用 --agent-version beta 测试草稿(beta)版本。`},{"en-US":`Requires the knowledge-base create permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库创建权限。`}],exampleArgs:[{"en-US":`--name my-qa --scene chat --description 'answers product FAQs' --workspace-id ws-xxx`,"zh-CN":`--name my-qa --scene chat --description '回答产品常见问题' --workspace-id ws-xxx`},`--name my-search --scene search --index-id idx-xxx`],validate(e){if(e.name.length>200)return`--name must be at most 200 characters`;if(e.scene!==`chat`&&e.scene!==`search`)return`--scene must be chat or search`;if(e.description!==void 0&&e.description.length>1e3)return`--description must be at most 1000 characters`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={agent_name:n.name,agent_scene:n.scene,...n.description?{agent_desc:n.description}:{},...n.indexId?{agent_config:{kb_search_configs:[{id:n.indexId}]}}:{}},o=T(r,h.agentCreate);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=Zu(s,`agent_id`);if(t.quiet){D(c??``);return}if(i===`text`){D(`created: ${c??`-`} (status: ${Zu(s,`agent_status`)??`draft`}, version: ${Zu(s,`agent_version`)??`beta`})`),D(`Test the draft with --agent-version beta on search/chat, then deploy it to publish.`);return}O(s,i)}});const qd=[`true`,`false`],Jd={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Service (agent) ID`,"zh-CN":`服务(Agent)ID`},required:!0},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`New service name (up to 200 chars)`,"zh-CN":`新服务名称(最多 200 个字符)`}},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`New service description (up to 1000 chars)`,"zh-CN":`新服务描述(最多 1000 个字符)`}},agentVersion:{type:`string`,valueHint:`<version>`,description:{"en-US":`Target version (default: beta draft). Published versions only accept --version-desc`,"zh-CN":`目标版本(默认:beta 草稿)。已发布版本只接受 --version-desc`}},versionDesc:{type:`string`,valueHint:`<text>`,description:{"en-US":`Version description`,"zh-CN":`版本描述`}},policy:{type:`string`,valueHint:`<policy>`,description:{"en-US":`Agent policy: turbo (fast) or agentic (multi-turn)`,"zh-CN":`Agent 策略:turbo(快速)或 agentic(多轮)`}},model:{type:`string`,valueHint:`<name>`,description:{"en-US":`Generation model code (must be in the platform allowlist)`,"zh-CN":`生成模型代码(必须在平台白名单中)`}},temperature:{type:`number`,valueHint:`<n>`,description:{"en-US":`Sampling temperature, range 0-2`,"zh-CN":`采样温度,范围 0–2`}},maxLlmCalls:{type:`number`,valueHint:`<n>`,description:{"en-US":`Max LLM calls per request, range 1-30`,"zh-CN":`每次请求最大 LLM 调用次数,范围 1–30`}},enableSessionFile:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable session files: true or false`,"zh-CN":`启用会话文件:true 或 false`}},enableRefusal:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable refusal answers: true or false`,"zh-CN":`启用拒答:true 或 false`}},enableAntiLeak:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable anti prompt-leak: true or false`,"zh-CN":`启用防提示词泄露:true 或 false`}},enableRichText:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable rich text output: true or false`,"zh-CN":`启用富文本输出:true 或 false`}},enableCitation:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable citations: true or false`,"zh-CN":`启用引用:true 或 false`}},configFile:{type:`string`,valueHint:`<path>`,description:{"en-US":`JSON file replacing the whole agent_config (for nested settings like kb_search_configs); mutually exclusive with scalar config flags`,"zh-CN":`替换整个 agent_config 的 JSON 文件(用于 kb_search_configs 等嵌套设置);不能与标量配置选项同时使用`}},...L};function Yd(e){let t={};return e.policy!==void 0&&(t.agent_policy=e.policy),e.model!==void 0&&(t.agent_model=e.model),e.temperature!==void 0&&(t.temperature=e.temperature),e.maxLlmCalls!==void 0&&(t.max_num_llm_calls=e.maxLlmCalls),e.enableSessionFile!==void 0&&(t.enable_session_file=e.enableSessionFile),e.enableRefusal!==void 0&&(t.enable_refusal=e.enableRefusal),e.enableAntiLeak!==void 0&&(t.enable_anti_leak=e.enableAntiLeak),e.enableRichText!==void 0&&(t.enable_rich_text=e.enableRichText),e.enableCitation!==void 0&&(t.enable_citation=e.enableCitation),t}function Xd(e){let t;try{t=Wr(e,`utf-8`)}catch(t){let r=t.code??`unknown`;throw new n(`Cannot read config file: ${e}`,l.GENERAL,`File system error (${r}) — check the path and permissions.`)}let r;try{r=JSON.parse(t)}catch{throw new n(`--config-file must contain valid JSON.`,l.USAGE)}if(typeof r!=`object`||!r||Array.isArray(r))throw new n(`--config-file must contain a JSON object.`,l.USAGE);let i=r;return Qd(i),i}const Zd=/* @__PURE__ */ new Set([`agent_policy`,`agent_model`,`enable_session_file`,`enable_refusal`,`enable_anti_leak`,`enable_rich_text`,`enable_citation`,`temperature`,`max_num_llm_calls`,`max_completion_tokens`,`session_file_max_parse_length`,`enable_kb_router`,`kb_router_model`,`user_system_prompt`,`anti_leak_prompt`,`refusal_prompt`,`credibility_prompt`,`enable_thinking`,`enable_temperature`,`enable_credibility`,`enable_max_completion_tokens`,`session_file_parse_mode`,`rerank_top_n`,`hybrid_rerank`,`kb_search_configs`]);function Qd(e){if(e.agent_policy!==void 0&&![`turbo`,`agentic`].includes(e.agent_policy))throw new n(`agent_policy must be turbo or agentic`,l.USAGE);if(e.temperature!==void 0&&(e.temperature<0||e.temperature>2))throw new n(`temperature must be between 0 and 2`,l.USAGE);if(e.max_num_llm_calls!==void 0&&(e.max_num_llm_calls<1||e.max_num_llm_calls>30))throw new n(`max_num_llm_calls must be between 1 and 30`,l.USAGE);if(e.rerank_top_n!==void 0&&(e.rerank_top_n<1||e.rerank_top_n>20))throw new n(`rerank_top_n must be between 1 and 20`,l.USAGE);for(let t of e.kb_search_configs??[]){let e=t.rerank;e?.rerank_instruct&&e.rerank_mode!==`custom`&&process.stderr.write(`Warning: rerank_instruct is only effective with rerank_mode=custom; the server clears it otherwise.
|
|
2737
|
-
`)}for(let t of Object.keys(e))Zd.has(t)||process.stderr.write(`Warning: unknown agent_config field passed through: ${t}\n`)}async function $d(e,t,n){return((await e.requestJson({path:T(t,h.agentGet),method:`POST`,body:{agent_id:n,agent_version:`beta`}})).data?.agent_details??[]).find(e=>e.agent_version===`beta`)?.agent_config??{}}var ef=S({description:{"en-US":`Update service name, description or draft configuration`,"zh-CN":`更新服务名称、描述或草稿配置`},auth:`apiKey`,usageArgs:`--agent-id <id> [flags]`,flags:Jd,notes:[{"en-US":`Configuration changes only apply to the beta draft; published versions accept --version-desc only.`,"zh-CN":`配置修改只应用于 beta 草稿;已发布版本只接受 --version-desc。`},{"en-US":`To change the configuration of a published version, first update the beta draft (this command without --agent-version or with --agent-version beta), then run service deploy to publish a new version.`,"zh-CN":`要修改已发布版本的配置,请先更新 beta 草稿(不传 --agent-version,或传 --agent-version beta),然后运行 service deploy 发布新版本。`},{"en-US":`Scalar config flags merge into the current draft config (read-merge-write); --config-file replaces the whole config and is mutually exclusive with them.`,"zh-CN":`标量配置选项会合并到当前草稿配置(读取-合并-写入);--config-file 会替换整个配置,且不能与标量配置选项同时使用。`},{"en-US":`After updating the draft, verify with --agent-version beta on search/chat, then deploy.`,"zh-CN":`更新草稿后,先在 search/chat 命令中使用 --agent-version beta 验证,再部署。`},{"en-US":`Requires the knowledge-base modify permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库修改权限。`}],exampleArgs:[`--agent-id aid-xxx --temperature 0.7 --workspace-id ws-xxx`,`--agent-id aid-xxx --config-file ./agent-config.json`,{"en-US":`--agent-id aid-xxx --agent-version 1 --version-desc 'first stable release'`,"zh-CN":`--agent-id aid-xxx --agent-version 1 --version-desc '首个稳定版本'`}],validate(e){let t=Object.keys(Yd(e)).length>0;if(!(e.name!==void 0||e.description!==void 0||e.versionDesc!==void 0||e.configFile!==void 0||t))return`Nothing to update — pass a name/description/version-desc or config flags`;if(e.configFile!==void 0&&t)return`--config-file is mutually exclusive with scalar config flags`;if(e.agentVersion!==void 0&&e.agentVersion!==`beta`&&(t||e.configFile!==void 0))return`Published versions only accept --version-desc; update the beta draft to change config`;if(e.name!==void 0&&e.name.length>200)return`--name must be at most 200 characters`;if(e.description!==void 0&&e.description.length>1e3)return`--description must be at most 1000 characters`;if(e.policy!==void 0&&![`turbo`,`agentic`].includes(e.policy))return`--policy must be turbo or agentic`;if(e.temperature!==void 0&&(e.temperature<0||e.temperature>2))return`--temperature must be between 0 and 2`;if(e.maxLlmCalls!==void 0&&(e.maxLlmCalls<1||e.maxLlmCalls>30))return`--max-llm-calls must be between 1 and 30`;for(let[t,n]of[[`--enable-session-file`,e.enableSessionFile],[`--enable-refusal`,e.enableRefusal],[`--enable-anti-leak`,e.enableAntiLeak],[`--enable-rich-text`,e.enableRichText],[`--enable-citation`,e.enableCitation]])if(n!==void 0&&!qd.includes(n))return`${t} must be true or false`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a=Yd(n),o=n.configFile!==void 0||Object.keys(a).length>0,s;n.configFile===void 0?Object.keys(a).length>0&&(t.dryRun?s={...a}:(s={...await $d(e.client,r,n.agentId),...a},Qd(s))):s=Xd(n.configFile);let c={agent_id:n.agentId,...n.name===void 0?{}:{agent_name:n.name},...n.description===void 0?{}:{agent_desc:n.description},...n.agentVersion===void 0?{}:{agent_version:n.agentVersion},...n.versionDesc===void 0?{}:{agent_version_desc:n.versionDesc},...s===void 0?{}:{agent_config:s}},l=T(r,h.agentUpdate);if(t.dryRun){O({endpoint:l,request:c,...o&&n.configFile===void 0?{note:`scalar config flags are merged into the current beta config at run time`}:{}},i);return}let u=await e.client.requestJson({path:l,method:`POST`,body:c});if(!t.quiet){if(i===`text`){D(`updated: ${n.agentId}`),o&&D(`Draft config changed — verify with --agent-version beta, then deploy.`);return}O(u,i)}}});const tf={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Service (agent) ID`,"zh-CN":`服务(Agent)ID`},required:!0},versionDesc:{type:`string`,valueHint:`<text>`,description:{"en-US":`Description for the newly published version`,"zh-CN":`新发布版本的描述`}},...L};var nf=S({description:{"en-US":`Publish the beta draft of a service as a new version`,"zh-CN":`将服务的 beta 草稿发布为新版本`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This publishes the current draft as a new version and changes the behavior seen by live callers.`,"zh-CN":`该操作会将当前草稿发布为新版本,并改变线上调用方使用的服务行为。`}},usageArgs:`--agent-id <id> [flags]`,flags:tf,notes:[{"en-US":`The version number auto-increments; status becomes deployed.`,"zh-CN":`版本号会自动递增;状态将变为 deployed。`},{"en-US":`Publishing affects live callers — the confirmation prompt guards against accidents.`,"zh-CN":`发布会影响线上调用方——确认提示用于避免误操作。`},{"en-US":`Requires the knowledge-base modify permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库修改权限。`}],exampleArgs:[`--agent-id aid-xxx --workspace-id ws-xxx`,{"en-US":`--agent-id aid-xxx --version-desc 'tuned rerank params' --yes`,"zh-CN":`--agent-id aid-xxx --version-desc '已调优 Rerank 参数' --yes`}],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={agent_id:n.agentId,...n.versionDesc?{agent_version_desc:n.versionDesc}:{}},o=T(r,h.agentDeploy);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=Zu(s,`agent_version`);if(t.quiet){D(c??``);return}if(i===`text`){D(`deployed: ${n.agentId} version ${c??`-`}`);return}O(s,i)}});const rf={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Service (agent) ID`,"zh-CN":`服务(Agent)ID`},required:!0},...L};var af=S({description:{"en-US":`Delete a retrieval / Q&A service (soft delete, idempotent)`,"zh-CN":`删除检索/问答服务(软删除,幂等)`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This deletes the service and makes its agent ID unavailable for search and chat calls. The operation cannot be undone.`,"zh-CN":`该操作会删除服务,使其 Agent ID 无法再用于搜索和对话调用,且无法撤销。`}},usageArgs:`--agent-id <id> [flags]`,flags:rf,notes:[{"en-US":`Deletion cannot be undone; the agent_id becomes unusable for search and chat calls.`,"zh-CN":`删除无法撤销;该 agent_id 将不能再用于 search 和 chat 调用。`},{"en-US":`Idempotent — deleting an already-deleted service does not fail.`,"zh-CN":`该操作具有幂等性——重复删除已删除的服务不会失败。`},{"en-US":`Requires the knowledge-base delete permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库删除权限。`}],exampleArgs:[`--agent-id aid-xxx --workspace-id ws-xxx`,`--agent-id aid-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={agent_id:n.agentId},o=T(r,h.agentDelete);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){D(`deleted: ${n.agentId} (status: ${Zu(s,`agent_status`)??`deleted`})`);return}O(s,i)}}});const of={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Source service (agent) ID to copy`,"zh-CN":`要复制的源服务(Agent)ID`},required:!0},...L};var sf=S({description:{"en-US":`Copy a service into a new draft (name gets a copy_ prefix)`,"zh-CN":`将服务复制为新草稿(名称会添加 copy_ 前缀)`},auth:`apiKey`,usageArgs:`--agent-id <id> [flags]`,flags:of,notes:[{"en-US":`The copy starts as a beta draft; test it with --agent-version beta, then deploy to publish.`,"zh-CN":`副本初始为 beta 草稿;请使用 --agent-version beta 测试,然后部署发布。`},{"en-US":`Requires the knowledge-base create permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库创建权限。`}],exampleArgs:[`--agent-id aid-xxx --workspace-id ws-xxx`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={agent_id:n.agentId},o=T(r,h.agentCopy);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=Zu(s,`agent_id`);if(t.quiet){D(c??``);return}if(i===`text`){D(`new agent_id: ${c??`-`} (name: ${Zu(s,`agent_name`)??`-`}, status: ${Zu(s,`agent_status`)??`draft`})`),D(`Test the draft with --agent-version beta on search/chat, then deploy it to publish.`);return}O(s,i)}});const cf={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},docId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Owning document ID from the doc list command; required in practice for all knowledge base types`,"zh-CN":`来自文档列表命令的所属文档 ID;实际使用时所有知识库类型都需要提供`}},content:{type:`string`,valueHint:`<text>`,description:{"en-US":`Chunk body text, up to 6000 chars (document-type); alternative to --content-file`,"zh-CN":`Chunk 正文,最多 6000 个字符(文档型);与 --content-file 二选一`}},contentFile:{type:`string`,valueHint:`<path>`,description:{"en-US":`Read chunk body from a UTF-8 plain text file (.md/.txt etc.)`,"zh-CN":`从 UTF-8 纯文本文件(.md/.txt 等)读取 Chunk 正文`}},title:{type:`string`,valueHint:`<text>`,description:{"en-US":`Chunk title, up to 50 chars (document-type)`,"zh-CN":`Chunk 标题,最多 50 个字符(文档型)`}},imageUrl:{type:`array`,valueHint:`<url>`,description:{"en-US":`Chunk image URL (repeatable, up to 10; document-type)`,"zh-CN":`Chunk 图片 URL(可重复,最多 10 个;文档型)`}},field:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Arbitrary field entry (repeatable) for table/image knowledge bases where keys are Excel column headers; mutually exclusive with content/title/image flags`,"zh-CN":`表格/图片知识库的自定义字段(可重复),键为 Excel 列标题;不能与 content/title/image 相关选项同时使用`}},...L};function lf(e){let t={};for(let r of e){let e=r.indexOf(`=`);if(e<=0)throw new n(`--field must be key=value, got: ${r}`,l.USAGE);t[r.slice(0,e)]=r.slice(e+1)}return t}var uf=S({description:{"en-US":`Add a chunk directly to a knowledge base`,"zh-CN":`直接向知识库添加 Chunk`},auth:`apiKey`,usageArgs:`--index-id <id> (--content <text> | --field <k=v>) [flags]`,flags:cf,notes:[{"en-US":`Document / table / image knowledge bases are supported; audio-video ones are not.`,"zh-CN":`支持文档、表格和图片知识库;不支持音视频知识库。`},{"en-US":`--doc-id is required in practice for all knowledge base types. Use the document-level id from the doc list command; the per-row doc_id in chunk list output is not accepted.`,"zh-CN":`实际使用时,所有知识库类型都需要 --doc-id。请使用文档列表命令返回的文档级 ID;Chunk 列表每行返回的 doc_id 不被接受。`},{"en-US":`Image-type documents do not support text chunks. Target a text-type document (docx/pdf/txt) instead.`,"zh-CN":`图片型文档不支持文本 Chunk;请改为操作文本型文档(docx/pdf/txt)。`},{"en-US":`The API is idempotent but rate-limited to 10 calls per second — throttle batch scripts.`,"zh-CN":`该 API 具有幂等性,但限流为每秒 10 次调用——批处理脚本需要控制速率。`},{"en-US":`The response carries no chunk id; list chunks afterwards to find the new one.`,"zh-CN":`响应不包含 Chunk ID;添加后请列出 Chunk 以查找新条目。`},{"en-US":`For table/image knowledge bases use --field with Excel column headers as keys; values are passed through as strings.`,"zh-CN":`表格/图片知识库请使用 --field,并以 Excel 列标题作为键;值将按字符串原样传递。`}],exampleArgs:[{"en-US":`--index-id idx-xxx --content "chunk text" --title intro --workspace-id ws-xxx`,"zh-CN":`--index-id idx-xxx --content "Chunk 文本" --title 简介 --workspace-id ws-xxx`},{"en-US":`--index-id idx-xxx --field columnA=v1 --field columnB=v2`,"zh-CN":`--index-id idx-xxx --field 列A=v1 --field 列B=v2`}],validate(e){let t=e.content!==void 0||e.contentFile!==void 0||e.title!==void 0||!!e.imageUrl?.length,n=!!e.field?.length;if(t&&n)return`--field is mutually exclusive with --content/--content-file/--title/--image-url`;if(!t&&!n)return`Provide chunk content via --content/--content-file or --field entries`;if(e.content!==void 0&&e.contentFile!==void 0)return`Use either --content or --content-file, not both`;if(e.content!==void 0&&e.content.length>6e3)return`--content must be at most 6000 characters`;if(e.title!==void 0&&e.title.length>50)return`--title must be at most 50 characters`;if(e.imageUrl!==void 0&&e.imageUrl.length>10)return`--image-url accepts at most 10 entries`},async run(e){let{settings:t,flags:r}=e,i=R(e),a=C(t.output),o;if(r.field?.length)o=lf(r.field);else{let e=r.contentFile===void 0?r.content:wd(r.contentFile,`--content`);if(typeof e==`string`&&e.length>6e3)throw new n(`Chunk content must be at most 6000 characters`,l.USAGE);o={...e===void 0?{}:{content:e},...r.title===void 0?{}:{title:r.title},...r.imageUrl?.length?{image_urls:r.imageUrl}:{}}}let s={pipelineId:r.indexId,...r.docId?{dataId:r.docId}:{},field:o},c=T(i,h.chunkCreate);if(t.dryRun){O({endpoint:c,request:s},a);return}let u=await e.client.requestJson({path:c,method:`POST`,body:s});if(!t.quiet){if(a===`text`){D(`chunk created (pipeline: ${r.indexId})`),D(`List chunks to find the new chunk id.`);return}O(u,a)}}});const df={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},docId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Only show chunks belonging to this document`,"zh-CN":`仅显示属于该文档的 Chunk`}},...Hu,...L};var ff=S({description:{"en-US":`List chunks in a knowledge base with content and status`,"zh-CN":`列出知识库中的 Chunk 及其内容和状态`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:df,notes:[{"en-US":`Use metadata._id as the chunk id and metadata.doc_id as the document id in chunk update/delete commands.`,"zh-CN":`在 Chunk 更新/删除命令中,使用 metadata._id 作为 Chunk ID,使用 metadata.doc_id 作为文档 ID。`},{"en-US":`Page size defaults to 20 (server default), max 100.`,"zh-CN":`分页大小默认为 20(服务端默认值),最大为 100。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --doc-id file-xxx --page-size 50`],validate(e){if(e.pageSize!==void 0&&(e.pageSize<1||e.pageSize>100))return`--page-size must be between 1 and 100`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={indexId:n.indexId,pageNum:n.pageNumber??1,pageSize:n.pageSize??20,...n.docId?{docId:n.docId}:{}},o=T(r,h.chunkList);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.nodes??[];if(t.quiet){for(let e of c)D(e.metadata?._id??``);return}if(i===`text`){if(c.length===0)D(`No chunks found.`);else for(let e of c){let t=e.metadata??{},n=t._chunk_status_message?` status: ${t._chunk_status_message}`:``,r=t.is_displayed_chunk_content===!1?` [excluded from retrieval]`:``;D(`[chunk] ${t._id??`?`} (doc: ${t.doc_name??`?`}, doc_id: ${t.doc_id??`?`})${n}${r}`);let i=t.content??e.text??``;D(` ${i.length>200?`${i.slice(0,200)}…`:i}`)}D(`total: ${s.data?.total??c.length}`)}else O(s,i)}});const pf={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},chunkId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Chunk ID (metadata._id from the chunk list output)`,"zh-CN":`Chunk ID(来自 Chunk 列表输出的 metadata._id)`},required:!0},docId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Document ID owning the chunk (metadata.doc_id from the chunk list output)`,"zh-CN":`Chunk 所属文档 ID(来自 Chunk 列表输出的 metadata.doc_id)`},required:!0},content:{type:`string`,valueHint:`<text>`,description:{"en-US":`New chunk content, 10-6000 chars; alternative to --content-file`,"zh-CN":`新的 Chunk 内容,10–6000 个字符;与 --content-file 二选一`}},contentFile:{type:`string`,valueHint:`<path>`,description:{"en-US":`Read new content from a UTF-8 plain text file (.md/.txt etc.)`,"zh-CN":`从 UTF-8 纯文本文件(.md/.txt 等)读取新内容`}},title:{type:`string`,valueHint:`<text>`,description:{"en-US":`Chunk title, 0-50 chars (empty string clears it; omit to keep unchanged)`,"zh-CN":`Chunk 标题,0–50 个字符(空字符串表示清除;省略则保持不变)`}},exclude:{type:`switch`,description:{"en-US":`Exclude this chunk from retrieval`,"zh-CN":`在检索中排除该 Chunk`}},include:{type:`switch`,description:{"en-US":`Include this chunk in retrieval (default)`,"zh-CN":`在检索中包含该 Chunk(默认)`}},...L};async function mf(e,t,r,i,a){for(let n=1;n<=10;n++){let o=(await e.requestJson({path:T(t,h.chunkList),method:`POST`,body:{indexId:r,docId:a,pageNum:n,pageSize:100}})).data?.nodes??[],s=o.find(e=>e.metadata?._id===i),c=s?.metadata?.content??s?.text;if(typeof c==`string`)return c;if(o.length<100)break}throw new n(`Chunk not found: ${i}`,l.GENERAL,`Check the chunk id via the chunk list command.`)}var hf=S({description:{"en-US":`Update chunk content or toggle its retrieval visibility`,"zh-CN":`更新 Chunk 内容或切换其检索可见性`},auth:`apiKey`,usageArgs:`--index-id <id> --chunk-id <id> --doc-id <id> [flags]`,flags:pf,notes:[{"en-US":`Content must be 10-6000 characters and within the knowledge base's max chunk size.`,"zh-CN":`内容必须为 10–6000 个字符,且不能超过知识库的最大 Chunk 大小。`},{"en-US":`--content-file expects a UTF-8 plain text file; document formats (.docx/.pdf) are not parsed here.`,"zh-CN":`--content-file 需要 UTF-8 纯文本文件;此处不会解析 .docx/.pdf 等文档格式。`},{"en-US":`Toggling --exclude/--include without new content re-submits the existing content automatically.`,"zh-CN":`仅切换 --exclude/--include 而不提供新内容时,会自动重新提交现有内容。`}],exampleArgs:[{"en-US":`--index-id idx-xxx --chunk-id chunk-xxx --doc-id file-xxx --content "corrected text"`,"zh-CN":`--index-id idx-xxx --chunk-id chunk-xxx --doc-id file-xxx --content "修正后的文本"`},`--index-id idx-xxx --chunk-id chunk-xxx --doc-id file-xxx --exclude`],validate(e){if(e.content!==void 0&&e.contentFile!==void 0)return`Use either --content or --content-file, not both`;if(e.exclude&&e.include)return`--exclude and --include are mutually exclusive`;if(e.content===void 0&&e.contentFile===void 0&&!e.exclude&&!e.include&&e.title===void 0)return`Nothing to update — pass --content/--content-file, --title, --exclude or --include`;if(e.content!==void 0&&(e.content.length<10||e.content.length>6e3))return`--content must be 10-6000 characters`;if(e.title!==void 0&&e.title.length>50)return`--title must be at most 50 characters`},async run(e){let{settings:t,flags:r}=e,i=R(e),a=C(t.output),o=r.contentFile===void 0?r.content:wd(r.contentFile,`--content`);if(o!==void 0&&(o.length<10||o.length>6e3))throw new n(`Chunk content must be 10-6000 characters`,l.USAGE);o===void 0&&(o=t.dryRun?`<current-content (fetched at run time)>`:await mf(e.client,i,r.indexId,r.chunkId,r.docId));let s={pipelineId:r.indexId,chunkId:r.chunkId,dataId:r.docId,content:o,isDisplayedChunkContent:!r.exclude,...r.title===void 0?{}:{title:r.title}},c=T(i,h.chunkUpdate);if(t.dryRun){O({endpoint:c,request:s},a);return}let u=await e.client.requestJson({path:c,method:`POST`,body:s});if(!t.quiet){if(a===`text`){D(`updated: ${r.chunkId}`);return}O(u,a)}}});const gf={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},chunkId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Chunk ID to delete (repeatable; batches of 10 are sent automatically)`,"zh-CN":`要删除的 Chunk ID(可重复;每 10 个自动分批发送)`},required:!0},...L};function _f(e,t=10){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}var vf=S({description:{"en-US":`Delete chunks from a knowledge base (irreversible)`,"zh-CN":`从知识库中删除 Chunk(不可撤销)`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the selected chunks and cannot be undone.`,"zh-CN":`该操作会永久删除所选 Chunk,且无法撤销。`}},usageArgs:`--index-id <id> --chunk-id <id> [flags]`,flags:gf,notes:[{"en-US":`Accepts at most 10 chunk ids per call; larger sets are batched automatically.`,"zh-CN":`每次调用最多接受 10 个 Chunk ID;更多 ID 会自动分批处理。`}],exampleArgs:[`--index-id idx-xxx --chunk-id chunk-a --chunk-id chunk-b --workspace-id ws-xxx`,`--index-id idx-xxx --chunk-id chunk-a --yes`],async run(e){let{settings:t,flags:r}=e,i=R(e),a=C(t.output),o=_f(r.chunkId),s=T(i,h.chunkDelete);if(t.dryRun){O({endpoint:s,batches:o.map(e=>({request:{pipelineId:r.indexId,chunkIds:e}}))},a);return}let c=0;for(let t of o)try{await e.client.requestJson({path:s,method:`POST`,body:{pipelineId:r.indexId,chunkIds:t}}),c+=t.length}catch(e){throw c>0&&e instanceof n&&!e.hint?new n(e.message,e.exitCode,`${c} chunk(s) in earlier batches were already deleted.`,{cause:e,api:e.api,rawResponse:e.rawResponse}):e}if(!t.quiet){if(a===`text`){D(`deleted: ${c} chunk(s) in ${o.length} batch(es)`);return}O({deleted_count:c,batches:o.length},a)}}});const yf={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},start:{type:`string`,valueHint:`<time>`,description:{"en-US":`Range start: Unix seconds or ISO date, must be in the past (default: 24 hours ago)`,"zh-CN":`范围开始时间:Unix 秒或 ISO 日期,必须是过去时间(默认:24 小时前)`}},end:{type:`string`,valueHint:`<time>`,description:{"en-US":`Range end: Unix seconds or ISO date, must be in the past (default: now)`,"zh-CN":`范围结束时间:Unix 秒或 ISO 日期,必须是过去时间(默认:当前时间)`}},...L};function bf(e){if(/^\d+$/.test(e))return e.length>=13?String(Math.floor(Number(e)/1e3)):e;let t=/^\d{4}-\d{2}-\d{2}([T ].*)?$/.test(e)?Date.parse(e):NaN;if(Number.isNaN(t))throw new n(`Invalid time value: ${e}`,l.USAGE,`Pass Unix seconds (e.g. 1780900000) or an ISO date (e.g. 2026-07-30T00:00:00Z).`);return String(Math.floor(t/1e3))}var xf=S({description:{"en-US":`Show knowledge base storage and QPS monitoring data`,"zh-CN":`查看知识库存储和 QPS 监控数据`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:yf,notes:[{"en-US":`Defaults to the last 24 hours when --start/--end are omitted.`,"zh-CN":`省略 --start/--end 时,默认查询最近 24 小时。`},{"en-US":`Timestamps are normalized to epoch seconds as required by the server.`,"zh-CN":`时间戳会按服务端要求归一化为 Epoch 秒。`},{"en-US":`Future timestamps are rejected for --start and clamped to now for --end, since the monitor API only returns past data.`,"zh-CN":`监控 API 只返回历史数据,因此未来的 --start 会被拒绝,未来的 --end 会被截断为当前时间。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --start 2026-07-30 --end 2026-07-31`],async run(e){let{settings:t,flags:r}=e,i=R(e),a=C(t.output),o=Math.floor(Date.now()/1e3),s=r.start?bf(r.start):String(o-86400),c=r.end?bf(r.end):String(o);if(Number(s)>o)throw new n(`Start time is in the future; the monitor API only accepts past or current timestamps.`,l.USAGE,`Use a start date/time at or before now, or omit --start to default to 24 hours ago.`);let u=Number(c)>o;u&&(c=String(o));let d={indexId:r.indexId,startTimestamp:s,endTimestamp:c},f=T(i,h.indexMonitor);if(t.dryRun){O({endpoint:f,request:d},a);return}let p=await e.client.requestJson({path:f,method:`POST`,body:d});if(a!==`text`){O(p,a);return}u&&D(`note: end time was in the future, clamped to now.`);let m=p.data?.storageMonitorData,g=p.data?.qpsMonitorData;D(`plan: ${p.data?.pipelineCommercialType??`-`}`),D(`storage: ${m?.indexStorageUsage??`-`} / ${m?.indexStorageLimit??`-`}`),D(`peak qps: ${g?.peakQps??`-`}`),D(`qps windows: ${g?.monitorData?.length??0} data point(s)`)}});const Sf={collectionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by exact collection ID`,"zh-CN":`按数据集合 ID 精确筛选`}},parentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`List sub-categories of this exact parent category`,"zh-CN":`列出该父类目下的子类目`}},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by category name (exact match, unlike the knowledge base list)`,"zh-CN":`按类目名称筛选(精确匹配,与知识库列表不同)`}},nextToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Cursor for the next page (from previous output)`,"zh-CN":`下一页游标(来自上一次输出)`}},maxResult:{type:`number`,valueHint:`<n>`,description:{"en-US":`Items per page (default: 20)`,"zh-CN":`每页条目数(默认:20)`}},...L};var Cf=S({description:{"en-US":`List data-center categories`,"zh-CN":`列出数据中心类目`},auth:`apiKey`,usageArgs:`[flags]`,flags:Sf,notes:[{"en-US":`Categories marked [default] are where files land when no category is specified.`,"zh-CN":`未指定类目时,文件会进入标记为 [default] 的类目。`},{"en-US":`Pagination is cursor-based: reuse the printed next token to continue.`,"zh-CN":`分页使用游标:复用输出中的 next token 继续查询。`}],exampleArgs:[`--workspace-id ws-xxx`,`--name my-category`,`--next-token <token>`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={type:`UNSTRUCTURED`,...n.collectionId?{connectorId:n.collectionId}:{},...n.parentId?{parentId:n.parentId}:{},...n.name?{categoryName:n.name}:{},...n.nextToken?{nextToken:n.nextToken}:{},...n.maxResult===void 0?{}:{maxResult:n.maxResult}},o=T(r,h.listCategory);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.categoryList??[];if(t.quiet){for(let e of c)D(e.categoryId??``);return}if(i===`text`){if(c.length===0)D(`No categories found.`);else for(let e of c){let t=e.isDefault?` [default]`:``;D(Uu(`${e.categoryId} ${e.categoryName}${t}`))}let e=s.data?.nextToken;e&&D(`next: --next-token ${e}`)}else O(s,i)}});const wf={name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Category name (1-20 chars)`,"zh-CN":`类目名称(1–20 个字符)`},required:!0},parentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Create as a sub-category of this category`,"zh-CN":`创建为该类目的子类目`}},collectionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Create under this collection (defaults to the platform collection)`,"zh-CN":`在该数据集合下创建(默认为平台数据集合)`}},...L};var Tf=S({description:{"en-US":`Create a data-center category`,"zh-CN":`创建数据中心类目`},auth:`apiKey`,usageArgs:`--name <text> [flags]`,flags:wf,notes:[{"en-US":`Use categories to organize data-center files by business domain.`,"zh-CN":`使用类目按业务领域组织数据中心文件。`}],exampleArgs:[`--name product-docs --workspace-id ws-xxx`,`--name sub --parent-id cate-xxx`],validate(e){if(e.name.length<1||e.name.length>20)return`--name must be 1-20 characters`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={categoryName:n.name,categoryType:`UNSTRUCTURED`,...n.parentId?{parentCategoryId:n.parentId}:{},...n.collectionId?{connectorId:n.collectionId}:{}},o=T(r,h.addCategory);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.categoryId;if(t.quiet){D(c??``);return}if(i===`text`){D(`created: ${c??`-`} (${n.name})`);return}O(s,i)}});const Ef={categoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Category ID to delete`,"zh-CN":`要删除的类目 ID`},required:!0},...L};var Df=S({description:{"en-US":`Delete a data-center category`,"zh-CN":`删除数据中心类目`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This deletes the selected data-center category and cannot be undone.`,"zh-CN":`该操作会删除所选数据中心类目,且无法撤销。`}},usageArgs:`--category-id <id> [flags]`,flags:Ef,notes:[{"en-US":`Behavior for categories containing files or sub-categories is server-defined — the server error is passed through as-is.`,"zh-CN":`包含文件或子类目时的处理行为由服务端定义——服务端返回的错误将原样透传。`}],exampleArgs:[`--category-id cate-xxx --workspace-id ws-xxx`,`--category-id cate-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={categoryId:n.categoryId},o=T(r,h.deleteCategory);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){D(`deleted: ${n.categoryId}`);return}O(s,i)}}});const Of={categoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Category to list (find ids via the category list command); exact match`,"zh-CN":`要列出文件的类目(通过类目列表命令查找 ID);精确匹配`},required:!0},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by exact file name without its extension (a.md → pass a)`,"zh-CN":`按不含扩展名的文件名精确筛选(a.md 应传入 a)`}},fileId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Filter by exact file ID (repeatable)`,"zh-CN":`按文件 ID 精确筛选(可重复)`}},nextToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Cursor for the next page (from previous output)`,"zh-CN":`下一页游标(来自上一次输出)`}},maxResult:{type:`number`,valueHint:`<n>`,description:{"en-US":`Items per page`,"zh-CN":`每页条目数`}},...L};var kf=S({description:{"en-US":`List files in a data-center category`,"zh-CN":`列出数据中心类目中的文件`},auth:`apiKey`,usageArgs:`--category-id <id> [flags]`,flags:Of,notes:[{"en-US":`A real category id is required — the default value is not resolved here. Find the id via the category list command.`,"zh-CN":`必须提供真实的类目 ID——此处不会解析 default 值。请通过类目列表命令查找 ID。`},{"en-US":`--name matches the exact file name without its extension (for a.md pass a); partial keywords return no results.`,"zh-CN":`--name 精确匹配不含扩展名的文件名(a.md 应传入 a);部分关键字不会返回结果。`},{"en-US":`Pagination is cursor-based: reuse the printed next token to continue.`,"zh-CN":`分页使用游标:复用输出中的 next token 继续查询。`}],exampleArgs:[`--category-id cate-xxx --workspace-id ws-xxx`,{"en-US":`--category-id cate-xxx --name report`,"zh-CN":`--category-id cate-xxx --name 报告`}],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={categoryId:n.categoryId,...n.name?{fileName:n.name}:{},...n.fileId?.length?{fileIds:n.fileId}:{},...n.nextToken?{nextToken:n.nextToken}:{},...n.maxResult===void 0?{}:{maxResult:n.maxResult}},o=T(r,h.listFile);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.fileList??[];if(t.quiet){for(let e of c)D(e.fileId??``);return}if(i===`text`){if(c.length===0)D(`No files found.`);else for(let e of c)D(Uu([e.fileId,e.status??`-`,e.fileName,e.sizeBytes??`-`].join(` `)));let e=s.data?.nextToken;e&&D(`next: --next-token ${e}`)}else O(s,i)}});const Af={fileId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Data-center file ID`,"zh-CN":`数据中心文件 ID`},required:!0},...L};var jf=S({description:{"en-US":`Show data-center file details (size, MD5, tags, timestamps)`,"zh-CN":`查看数据中心文件详情(大小、MD5、标签、时间戳)`},auth:`apiKey`,usageArgs:`--file-id <id> [flags]`,flags:Af,exampleArgs:[`--file-id file-xxx --workspace-id ws-xxx`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={fileId:n.fileId},o=T(r,h.describeFile);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data;if(t.quiet){D(c?.fileId??``);return}if(i!==`text`){O(s,i);return}D(`id: ${c?.fileId??`-`}`),D(`name: ${c?.fileName??`-`}`),D(`type: ${c?.fileType??`-`}`),D(`size: ${c?.sizeBytes??`-`}`),D(`status: ${c?.status??`-`}`),D(`parser: ${c?.parser??`-`}`),D(`category: ${c?.category??`-`}`),D(`uploaded: ${c?.uploadTime??`-`}`);let l=Array.isArray(c?.tags)?c.tags.join(`, `):c?.tags??`-`;D(`tags: ${l||`-`}`)}});const Mf={fileId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Data-center file ID to delete`,"zh-CN":`要删除的数据中心文件 ID`},required:!0},...L};var Nf=S({description:{"en-US":`Permanently delete a file from the data center`,"zh-CN":`从数据中心永久删除文件`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the data-center file. Knowledge-base document indexes that reference it may become invalid.`,"zh-CN":`该操作会永久删除数据中心文件;引用该文件的知识库文档索引可能失效。`}},usageArgs:`--file-id <id> [flags]`,flags:Mf,notes:[{"en-US":`Irreversible. If knowledge bases reference this file, their related document indexes become invalid.`,"zh-CN":`该操作不可撤销。如果知识库引用了此文件,其相关文档索引将失效。`},{"en-US":`To remove a document from a single knowledge base only, use the document delete command instead.`,"zh-CN":`如果只需从单个知识库中移除文档,请改用文档删除命令。`}],exampleArgs:[`--file-id file-xxx --workspace-id ws-xxx`,`--file-id file-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={fileId:n.fileId},o=T(r,h.deleteFile);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){D(`deleted: ${n.fileId}`);return}O(s,i)}}});const Pf={name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Collection name`,"zh-CN":`数据集合名称`},required:!0},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`What this collection holds and what it is for — tells collections apart in the list`,"zh-CN":`数据集合装了什么内容、给谁用,用于在列表中区分同类集合`},required:!0},storeType:{type:`string`,valueHint:`<type>`,description:{"en-US":`Storage: platform (managed) or custom (your own OSS bucket)`,"zh-CN":`存储类型:platform(托管)或 custom(自有 OSS Bucket)`}},ossRegion:{type:`string`,valueHint:`<id>`,description:{"en-US":`OSS region id (required with --store-type custom)`,"zh-CN":`OSS Region ID(使用 --store-type custom 时必填)`}},ossBucket:{type:`string`,valueHint:`<name>`,description:{"en-US":`OSS bucket name (required with --store-type custom)`,"zh-CN":`OSS Bucket 名称(使用 --store-type custom 时必填)`}},...L};var Ff=S({description:{"en-US":`Create a FILE data collection`,"zh-CN":`创建 FILE 数据集合`},auth:`apiKey`,usageArgs:`--name <text> --description <text> [flags]`,flags:Pf,notes:[{"en-US":`Store type defaults to platform (managed storage); custom uses your authorized OSS bucket.`,"zh-CN":`存储类型默认为 platform(托管存储);custom 使用已授权的自有 OSS Bucket。`},{"en-US":`Custom buckets must carry the bucket tag bailian-connector-access=ReadAndWrite (Bailian's tag-based access control); without it the server rejects creation with a misleading 'setBucketCORS failed' error.`,"zh-CN":`自定义 Bucket 必须带有 bailian-connector-access=ReadAndWrite 标签(百炼基于标签的访问控制);缺少该标签时,服务端会以容易误解的 'setBucketCORS failed' 错误拒绝创建。`},{"en-US":`There is no collection delete API — create collections deliberately.`,"zh-CN":`目前没有删除数据集合的 API——请谨慎创建。`}],exampleArgs:[{"en-US":`--name my-collection --description 'team docs' --workspace-id ws-xxx`,"zh-CN":`--name my-collection --description '团队文档' --workspace-id ws-xxx`},{"en-US":`--name oss-coll --description 'own bucket' --store-type custom --oss-region cn-beijing --oss-bucket my-bucket`,"zh-CN":`--name oss-coll --description '自有 Bucket' --store-type custom --oss-region cn-beijing --oss-bucket my-bucket`}],validate(e){if(e.name.length<1||e.name.length>20)return`--name must be 1-20 characters`;let t=e.storeType??`platform`;if(t!==`platform`&&t!==`custom`)return`--store-type must be platform or custom`;if(t===`custom`&&(!e.ossRegion||!e.ossBucket))return`--store-type custom requires --oss-region and --oss-bucket`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a=(n.storeType??`platform`).toUpperCase(),o={connectorType:`FILE`,connectorName:n.name,description:n.description,fileConnectorConfig:{storeType:a,...a===`CUSTOM`?{regionId:n.ossRegion,bucketName:n.ossBucket}:{}}},s=T(r,h.addConnector);if(t.dryRun){O({endpoint:s,request:o},i);return}let c=await e.client.requestJson({path:s,method:`POST`,body:o}),l=c.data?.connectorId;if(t.quiet){D(l??``);return}if(i===`text`){D(`created: ${l??`-`} (${n.name}, ${a})`);return}O(c,i)}});const If={collectionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Collection ID; alternative to --name`,"zh-CN":`数据集合 ID;与 --name 二选一`}},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Collection name; alternative to --collection-id`,"zh-CN":`数据集合名称;与 --collection-id 二选一`}},...L};var Lf=S({description:{"en-US":`Show data collection details`,"zh-CN":`查看数据集合详情`},auth:`apiKey`,usageArgs:`(--collection-id <id> | --name <text>) [flags]`,flags:If,exampleArgs:[`--collection-id conn-xxx --workspace-id ws-xxx`,`--name my-collection`],validate(e){if(!e.collectionId&&!e.name)return`Pass --collection-id or --name`;if(e.collectionId&&e.name)return`Use either --collection-id or --name, not both`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={...n.collectionId?{connectorId:n.collectionId}:{},...n.name?{connectorName:n.name}:{}},o=T(r,h.getConnector);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data;if(t.quiet){D(c?.connectorId??``);return}if(i===`text`){D(`id: ${c?.connectorId??`-`}`),D(`name: ${c?.connectorName??`-`}`),D(`description: ${c?.description??`-`}`);return}O(s,i)}});const Rf={bucket:{type:`string`,valueHint:`<name>`,description:{"en-US":`Authorized OSS bucket name`,"zh-CN":`已授权的 OSS Bucket 名称`},required:!0},region:{type:`string`,valueHint:`<id>`,description:{"en-US":`OSS region id (e.g. cn-beijing)`,"zh-CN":`OSS Region ID(例如 cn-beijing)`},required:!0},ossKey:{type:`array`,valueHint:`<key>`,description:{"en-US":`OSS object key to import (repeatable, 1-10 per call)`,"zh-CN":`要导入的 OSS Object Key(可重复,每次调用 1–10 个)`},required:!0},categoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Target data-center category (default: the default category)`,"zh-CN":`目标数据中心类目(默认:默认类目)`}},tag:{type:`array`,valueHint:`<text>`,description:{"en-US":`File tag applied to every imported file (repeatable, up to 10)`,"zh-CN":`应用于每个导入文件的标签(可重复,最多 10 个)`}},overwrite:{type:`switch`,description:{"en-US":`Overwrite files previously imported from the same OSS keys`,"zh-CN":`覆盖此前从相同 OSS Key 导入的文件`}},...L};var zf=S({description:{"en-US":`Batch import files from an authorized OSS bucket into the data center`,"zh-CN":`从已授权的 OSS Bucket 批量导入文件到数据中心`},auth:`apiKey`,usageArgs:`--bucket <name> --region <id> --oss-key <key> [flags]`,flags:Rf,notes:[{"en-US":`The bucket must be authorized to the platform service role beforehand; permission errors from the server are passed through with a pointer to check AliyunServiceRoleForBailian in the RAM console.`,"zh-CN":`必须预先将 Bucket 授权给平台服务角色;服务端权限错误将原样透传,并提示在 RAM 控制台检查 AliyunServiceRoleForBailian。`},{"en-US":`File names are derived from the OSS key basename.`,"zh-CN":`文件名取自 OSS Key 的 basename。`},{"en-US":`--overwrite replaces the previously imported file and issues a NEW fileId (the old one becomes invalid) — verified live.`,"zh-CN":`--overwrite 会替换此前导入的文件并生成新的 fileId(旧 fileId 将失效)——已通过真实环境验证。`}],exampleArgs:[`--bucket my-bucket --region cn-beijing --oss-key docs/a.pdf --workspace-id ws-xxx`,`--bucket my-bucket --region cn-beijing --oss-key docs/a.pdf --oss-key docs/b.docx --overwrite`],validate(e){if(e.ossKey.length>10)return`--oss-key accepts at most 10 entries per call`;if(e.tag!==void 0&&e.tag.length>10)return`--tag accepts at most 10 entries`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={categoryId:n.categoryId??`default`,categoryType:`UNSTRUCTURED`,ossBucket:n.bucket,ossRegionId:n.region,fileDetails:n.ossKey.map(e=>({fileName:Yr(e),ossKey:e})),...n.tag?.length?{tags:n.tag}:{},...n.overwrite?{overWriteFileByOssKey:!0}:{}},o=T(r,h.addFilesFromAuthorizedOss);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.addFileResultList??[],l=c.map(e=>e.fileId).filter(e=>!!e);if(t.quiet){for(let e of l)D(e);return}if(i===`text`){D(`imported: ${l.length} file(s)`);for(let e of c)D(` ${e.fileId??`-`} ${e.status??`-`} ${e.ossKey??``}`);return}O(s,i)}});function Bf(e){if(!(e instanceof n))return!1;let t=e.message;return/^MCP request failed:\s*404\b/i.test(t)?/未开通|MCP不存在|MCP_IS_INVALID/i.test(t):!1}function Vf(e){let t=[`Activate (or re-activate) the ${e} MCP in the Bailian MCP marketplace, then retry.`];return e===`WebSearch`&&t.push(`If it was previously on SSE, cancel and activate again to upgrade to Streamable HTTP.`),t.push(`Open: ${fr(e)}`),t.join(`
|
|
2738
|
-
`)}function
|
|
2739
|
-
`);throw new n(`Tool error: ${e}`)}O(s,c)}catch(e){throw r.url||
|
|
2740
|
-
`);throw new n(`Search error: ${e}`)}if(t.quiet||s.stop(`Done.`),i===`json`)O(c,i);else for(let e of c.content)if(e.type===`text`&&e.text)try{let t=JSON.parse(e.text);t.pages&&Array.isArray(t.pages)?O({pages:t.pages,total:t.pages.length},i):O(t,i)}catch{O({text:e.text},i)}}catch(e){s.stop(`Failed.`),
|
|
2741
|
-
`),process.stdout.write(`See: ${
|
|
2742
|
-
`));else if(p.length===1){let e=s[0].output?.audio?.expires_at;O({saved:p[0],audio_url:c[0],model:r.model,voice:r.input.voice,...e?{url_expires_at:e}:{}},a)}else O({saved:p,audio_urls:c,total:p.length,model:r.model,voice:r.input.voice},a)}async function
|
|
2743
|
-
Hint: Add --diarization flag to enable speaker separation.`,l.USAGE);let s=r.model||t.defaultSpeechRecognitionModel||`fun-asr`,c=
|
|
2744
|
-
`)?d:`${d}\n`):D(JSON.stringify(u)),n.out&&(
|
|
2745
|
-
`),t.quiet||process.stderr.write(`Full result saved to: ${n.out}\n`))}async function
|
|
2736
|
+
`)}else{let e=``,r=``;for await(let t of $t(p)){if(t.data===`[DONE]`)break;if(t.event===`error`){let e=`Chat API error`,r;try{let n=JSON.parse(t.data);e=n.message||e,r=n.code}catch{}throw new n(e,l.GENERAL,r?`API error: ${r}`:void 0)}try{let n=JSON.parse(t.data);n.request_id&&(r=n.request_id);for(let t of n.output?.choices??[])if(t.message?.content&&(e+=t.message.content),t.finish_reason===`stop`)break}catch{}}t.quiet||c===`text`?D(e):O({answer:e,request_id:r},c)}}});const wd={name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by knowledge base name (fuzzy match, 1-20 chars)`,"zh-CN":`按知识库名称筛选(模糊匹配,1–20 个字符)`}},...od,...L};var Td=S({description:{"en-US":`List knowledge bases in the workspace`,"zh-CN":`列出 Workspace 中的知识库`},auth:`apiKey`,usageArgs:`[flags]`,flags:wd,notes:[{"en-US":`Auth: uses DashScope API Key (Bearer token).`,"zh-CN":`鉴权:使用 DashScope API Key(Bearer Token)。`},{"en-US":"`--workspace-id` can be set via BAILIAN_WORKSPACE_ID env or config workspace_id.","zh-CN":"`--workspace-id` 可通过 BAILIAN_WORKSPACE_ID 环境变量或配置项 workspace_id 设置。"},{"en-US":`Use the returned id as --index-id in knowledge base / document management commands.`,"zh-CN":`在知识库/文档管理命令中,将返回的 ID 作为 --index-id 使用。`}],exampleArgs:[`--workspace-id ws-xxx`,`--name demo --page-number 2 --page-size 50`],validate(e){if(e.name!==void 0&&(e.name.length<1||e.name.length>20))return`--name must be 1-20 characters`;if(e.pageSize!==void 0&&(e.pageSize<1||e.pageSize>100))return`--page-size must be between 1 and 100`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a=new URL(T(r,h.indexList));n.name&&a.searchParams.set(`pipeline_name`,n.name),a.searchParams.set(`page_number`,String(n.pageNumber??1)),a.searchParams.set(`page_size`,String(n.pageSize??20));let o=a.toString();if(t.dryRun){O({endpoint:o,request:null},i);return}let s=await e.client.requestJson({path:o,method:`GET`}),c=s.data?.rows??[];if(t.quiet){for(let e of c)D(e.id);return}if(i===`text`){if(c.length===0)D(`No knowledge bases found.`);else for(let e of c)D(sd([e.id,e.name,e.embeddingModelName??`-`,e.chunkSize??`-`,e.description??``].join(` `)));D(`total: ${s.data?.total??c.length}`)}else O(s,i)}});const Ed={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},...L};function Dd(e,t){let n=new URL(T(e,h.indexList));return n.searchParams.set(`pipeline_id`,t),n.searchParams.set(`page_number`,`1`),n.searchParams.set(`page_size`,`1`),n.toString()}async function Od(e,t,r){let i=(await e.requestJson({path:Dd(t,r),method:`GET`})).data?.rows?.[0];if(!i)throw new n(`Knowledge base not found: ${r}`,l.GENERAL,`Check the id — list knowledge bases in this workspace to verify it.`);return i}function z(e,t){return` ${e}: ${t??`-`}`}var kd=S({description:{"en-US":`Show knowledge base configuration details`,"zh-CN":`查看知识库配置详情`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:Ed,notes:[{"en-US":`Indexing settings are immutable; changing them requires recreating the knowledge base.`,"zh-CN":`索引设置不可修改;如需更改,必须重新创建知识库。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output);if(t.dryRun){O({endpoint:Dd(r,n.indexId),request:null},i);return}let a=await Od(e.client,r,n.indexId);if(t.quiet){D(a.id??``);return}if(i!==`text`){O(a,i);return}D(`Basic:`),D(z(`id`,a.id)),D(z(`name`,a.name)),D(z(`description`,a.description)),D(z(`dataType`,a.dataType)),D(`Indexing: [immutable — recreate required to change]`),D(z(`embeddingModelName`,a.embeddingModelName)),D(z(`embeddingDimension`,a.embeddingDimension)),D(z(`chunkSize`,a.chunkSize)),D(z(`overlapSize`,a.overlapSize)),D(z(`chunkMode`,a.chunkMode)),D(z(`separator`,a.separator)),D(`Retrieval:`),D(z(`rerankModelName`,a.rerankModelName)),D(z(`rerankMinScore`,a.rerankMinScore)),D(z(`rerankTopN`,a.rerankTopN)),D(z(`rerankMode`,a.rerankMode)),D(z(`enableRewrite`,a.enableRewrite)),D(z(`denseSimilarityTopK`,a.denseSimilarityTopK)),D(z(`sparseSimilarityTopK`,a.sparseSimilarityTopK)),D(`Data:`),D(z(`sourceType`,a.sourceType)),D(z(`connectorId`,a.connectorId))}});const Ad={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},...od,...L};var jd=S({description:{"en-US":`List documents in a knowledge base with parse/index status`,"zh-CN":`列出知识库文档及其解析/索引状态`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:Ad,notes:[{"en-US":`Documents with status FAILED are highlighted in text mode — use the import job status command to inspect failures.`,"zh-CN":`文本模式会突出显示状态为 FAILED 的文档——请使用导入任务状态命令检查失败详情。`},{"en-US":`Page size defaults to 10 (server default), max 100.`,"zh-CN":`分页大小默认为 10(服务端默认值),最大为 100。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --page-size 100`],validate(e){if(e.pageSize!==void 0&&(e.pageSize<1||e.pageSize>100))return`--page-size must be between 1 and 100`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a=new URL(T(r,h.indexFiles));a.searchParams.set(`index_id`,n.indexId),a.searchParams.set(`page_num`,String(n.pageNumber??1)),a.searchParams.set(`page_size`,String(n.pageSize??10));let o=a.toString();if(t.dryRun){O({endpoint:o,request:null},i);return}let s=await e.client.requestJson({path:o,method:`GET`}),c=s.data?.rows??[];if(t.quiet){for(let e of c)D(e.doc_id??``);return}if(i===`text`){let e=E(process.stdout);if(c.length===0)D(`No documents found.`);else for(let t of c){let n=sd([t.doc_id,t.status,t.doc_name,t.doc_type??`-`,t.size??`-`].join(` `));D(t.status===`FAILED`?e.red(n):n)}D(`total: ${s.data?.total_count??c.length}`)}else O(s,i)}});const Md={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},jobId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Import job ID (ingestionId returned by import commands)`,"zh-CN":`导入任务 ID(导入命令返回的 ingestionId)`},required:!0},...od,wait:{type:`switch`,description:{"en-US":`Poll until the job reaches a terminal state`,"zh-CN":`轮询直到任务进入终态`}},pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 5)`,"zh-CN":`等待时的轮询间隔(默认:5)`}},...L};function Nd(e){let t=E(process.stdout);D(`status: ${e.data?.ingestion_status??`UNKNOWN`}`);for(let n of e.data?.rows??[]){let e=n.code??n.status??`?`,r=` ${n.doc_id??`?`} ${e} ${n.doc_name??``}`;D(e.includes(`FAILED`)?t.red(r):r)}}var Pd=S({description:{"en-US":`Check knowledge base import job status`,"zh-CN":`检查知识库导入任务状态`},auth:`apiKey`,usageArgs:`--index-id <id> --job-id <id> [flags]`,flags:Md,notes:[{"en-US":`Both --index-id and --job-id are required (passing only one returns SystemError).`,"zh-CN":`--index-id 和 --job-id 均为必填(只传其中一个会返回 SystemError)。`},{"en-US":`If you see a SystemError, the job may not exist — check the ingestion id in the document list output.`,"zh-CN":`如果出现 SystemError,任务可能不存在——请检查文档列表输出中的 ingestion ID。`},{"en-US":`Overall job states are PENDING / RUNNING / COMPLETED; per-document failures (for example PARSE_FAILED) exit non-zero with the error message passed through.`,"zh-CN":`任务整体状态为 PENDING / RUNNING / COMPLETED;单个文档失败(例如 PARSE_FAILED)时会以非零状态退出,并原样透传错误信息。`}],exampleArgs:[`--index-id idx-xxx --job-id job-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --job-id job-xxx --wait --poll-interval 10`],async run(e){let{settings:t,flags:r}=e,i=R(e),a=C(t.output),o=new URL(T(i,h.indexJobStatus));o.searchParams.set(`index_id`,r.indexId),o.searchParams.set(`job_id`,r.jobId),r.pageNumber!==void 0&&o.searchParams.set(`page_number`,String(r.pageNumber)),r.pageSize!==void 0&&o.searchParams.set(`page_size`,String(r.pageSize));let s=o.toString();if(t.dryRun){O({endpoint:s,request:null},a);return}let c;if(c=r.wait?await pd(e.client,t,{statusUrl:s,intervalSec:r.pollInterval??5}):await e.client.requestJson({path:s,method:`GET`}),ld(c).length>0)throw new n(dd(c,`Import job reported document failures.`),l.GENERAL);if(t.quiet){D(c.data?.ingestion_status??`UNKNOWN`);return}a===`text`?Nd(c):O(c,a)}});const Fd=1048576,Id={".doc":{maxBytes:150*Fd,enforce:`block`},".docx":{maxBytes:150*Fd,enforce:`block`},".ppt":{maxBytes:150*Fd,enforce:`block`},".pptx":{maxBytes:150*Fd,enforce:`block`},".pdf":{maxBytes:150*Fd,enforce:`block`},".png":{maxBytes:20*Fd,enforce:`block`},".jpg":{maxBytes:20*Fd,enforce:`block`},".jpeg":{maxBytes:20*Fd,enforce:`block`},".bmp":{maxBytes:20*Fd,enforce:`block`},".gif":{maxBytes:20*Fd,enforce:`block`},".xls":{maxBytes:10*Fd,enforce:`warn`},".xlsx":{maxBytes:10*Fd,enforce:`warn`},".csv":{maxBytes:10*Fd,enforce:`warn`},".md":{maxBytes:10*Fd,enforce:`warn`},".txt":{maxBytes:10*Fd,enforce:`warn`},".html":{maxBytes:10*Fd,enforce:`warn`}};function Ld(e){return fi(e).toLowerCase()in Id}const Rd=/* @__PURE__ */ new Set([`node_modules`,`.git`,`.svn`,`.hg`,`__pycache__`,`.venv`,`venv`,`.env`,`.tox`,`dist`,`build`,`.cache`,`.next`,`.nuxt`]);function zd(e){let t=[],r=[];function i(e){let a;try{a=oi(e,{withFileTypes:!0})}catch(t){let r=t.code??`unknown`;throw new n(`Cannot read directory: ${e}`,l.GENERAL,`File system error (${r}) — check the path and permissions.`)}for(let n of a){let a=j(e,n.name);if(n.isDirectory()){Rd.has(n.name)||i(a);continue}n.isFile()&&(Ld(n.name)?t.push(a):r.push(a))}}for(let r of e){let e;try{e=si(r)}catch(e){let t=e.code??`unknown`;throw new n(`Cannot read path: ${r}`,l.GENERAL,`File system error (${t}) — check the path and permissions.`)}e.isDirectory()?i(r):e.isFile()&&t.push(r)}return{files:t,skipped:r}}function Bd(e){let t=fi(e).toLowerCase(),r=Id[t];if(!r)throw new n(`Unsupported file type: ${t||ui(e)}`,l.USAGE,`Supported formats: ${Object.keys(Id).join(` `)}`);let i;try{i=si(e).size}catch(t){let r=t.code??`unknown`;throw new n(`Cannot read file: ${e}`,l.GENERAL,`File system error (${r}) — check the path and permissions.`)}if(i>r.maxBytes){let a=r.maxBytes/Fd;if(r.enforce===`block`)throw new n(`File exceeds the ${a} MB limit for ${t}: ${ui(e)}`,l.USAGE);return{sizeBytes:i,warning:`${ui(e)} exceeds the recommended 10 MB for ${t}; the server may reject or truncate it.`}}return{sizeBytes:i}}const Vd=/* @__PURE__ */ new Set([`.doc`,`.docx`,`.ppt`,`.pptx`,`.pdf`,`.xls`,`.xlsx`,`.png`,`.jpg`,`.jpeg`,`.bmp`,`.gif`]);function Hd(e,t){let r;try{r=ai(e)}catch(r){let i=r.code??`unknown`,a=`File system error (${i}) — check the path and permissions.`;throw t&&i===`ENOENT`&&!fi(e)&&!e.includes(`/`)&&!e.includes(`\\`)&&(a+=` If you meant to pass text content directly, use ${t} instead of --content-file.`),new n(`Cannot read file: ${e}`,l.GENERAL,a)}try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(r)}catch{let t=fi(e).toLowerCase(),r=Vd.has(t)?`Document formats cannot be used as chunk content. Upload documents via the document upload command; to edit a chunk, save the text as .md/.txt first.`:`Convert the file to UTF-8 encoding and retry.`;throw new n(`File is not valid UTF-8 plain text: ${ui(e)}`,l.USAGE,r)}}const Ud={file:{type:`array`,valueHint:`<path>`,description:{"en-US":`Local file or directory path (repeatable). Directories are scanned recursively; unsupported formats are skipped`,"zh-CN":`本地文件或目录路径(可重复)。目录会递归扫描,不支持的格式将被跳过`},required:!0},indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Import into this knowledge base after registration (one job for all files)`,"zh-CN":`文件注册后导入该知识库(所有文件共用一个任务)`}},categoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Target data-center category; defaults to the workspace default category`,"zh-CN":`目标数据中心类目;默认为 Workspace 的默认类目`}},tag:{type:`array`,valueHint:`<text>`,description:{"en-US":`File tag (repeatable), applied to every uploaded file`,"zh-CN":`文件标签(可重复),应用于每个上传文件`}},wait:{type:`switch`,description:{"en-US":`Poll the import job to a terminal state (needs --index-id)`,"zh-CN":`轮询导入任务直到进入终态(需要 --index-id)`}},pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 5)`,"zh-CN":`等待时的轮询间隔(默认:5)`}},...L};var Wd=S({description:{"en-US":`Upload local files or directories to the data center and optionally import into a knowledge base`,"zh-CN":`上传本地文件或目录到数据中心,并可选择导入知识库`},auth:`apiKey`,usageArgs:`--file <path> [flags]`,flags:Ud,notes:[{"en-US":`Pipeline: apply upload lease → PUT to OSS → register file → (with --index-id) create import job.`,"zh-CN":`处理流程:申请上传凭证 → PUT 到 OSS → 注册文件 →(传入 --index-id 时)创建导入任务。`},{"en-US":`Without --category-id the workspace default category is resolved automatically.`,"zh-CN":`未传入 --category-id 时,会自动解析 Workspace 的默认类目。`},{"en-US":`Directories are scanned recursively; node_modules, .git, and similar are skipped automatically.`,"zh-CN":`目录会递归扫描;node_modules、.git 等目录会被自动跳过。`},{"en-US":`Multiple files are processed sequentially; on failure, already-registered file ids are listed in the error hint.`,"zh-CN":`多个文件会依次处理;失败时,错误提示会列出已经注册成功的文件 ID。`}],exampleArgs:[`--file ./a.md --workspace-id ws-xxx`,`--file ./a.md --file ./b.pdf --index-id idx-xxx --wait`,`--file ./docs/ --workspace-id ws-xxx`,`--file ./docs/ --dry-run --verbose`],validate(e){if(e.wait&&!e.indexId)return`--wait requires --index-id`},async run(e){let{settings:t,flags:r}=e,i=R(e),a=C(t.output),{files:o,skipped:s}=zd(r.file);if(o.length===0)throw new n(`No supported files found`,l.USAGE,`Supported formats: .pdf .doc .docx .ppt .pptx .xls .xlsx .csv .md .txt .html .png .jpg .jpeg .bmp .gif`);let c=o.map(e=>{let t=Bd(e);return t.warning&&process.stderr.write(`Warning: ${t.warning}\n`),{filePath:e,sizeBytes:t.sizeBytes}});if(t.dryRun){let e=r.categoryId??`default`,t=c.flatMap(t=>[{step:`applyFileUploadLease`,endpoint:T(i,h.applyFileUploadLease),request:{category:e,fileName:ui(t.filePath),sizeBytes:String(t.sizeBytes),contentMd5:`<md5-base64>`}},{step:`ossPut`,endpoint:`<lease.param.url>`,request:{method:`PUT`,headers:`<lease.param.headers>`}},{step:`addFile`,endpoint:T(i,h.addFile),request:{leaseId:`<leaseId>`,category:e,parser:`AUTO_SELECT`,...r.tag?.length?{tags:r.tag}:{}}}]);r.indexId&&t.push({step:`createImportJob`,endpoint:T(i,h.indexJobCreate),request:{indexId:r.indexId,sourceType:`DATA_CENTER_FILE`,docIds:[`<fileId>`]}}),O({steps:t,skipped:s},a);return}let u=r.categoryId??`default`,d=[];for(let t of c)try{let a=ai(t.filePath),o=Lr(`md5`).update(a).digest(`base64`),s=await e.client.requestJson({path:T(i,h.applyFileUploadLease),method:`POST`,body:{category:u,fileName:ui(t.filePath),sizeBytes:String(t.sizeBytes),contentMd5:o}}),c=s.data?.leaseId,f=s.data?.param;if(!c||!f?.url)throw new n(`Upload lease response missing leaseId/url for ${t.filePath}`,l.GENERAL);let p;try{p=await fetch(f.url,{method:f.method??`PUT`,headers:f.headers,body:a})}catch(e){let r=e.cause?.code;throw new n(`OSS upload failed for ${ui(t.filePath)}`,l.NETWORK,r?`Network error (${r}).`:void 0,{cause:e})}if(!p.ok){let e=await p.text().catch(()=>``);throw new n(`OSS upload rejected (HTTP ${p.status}) for ${ui(t.filePath)}${e?`: ${e.slice(0,300)}`:``}`,l.GENERAL)}let m=(await e.client.requestJson({path:T(i,h.addFile),method:`POST`,body:{leaseId:c,category:u,parser:`AUTO_SELECT`,...r.tag?.length?{tags:r.tag}:{}}})).data?.fileId;if(!m)throw new n(`addFile response missing fileId for ${t.filePath}`,l.GENERAL);d.push({path:t.filePath,fileId:m})}catch(e){throw d.length>0?md(e,`Already registered: ${d.map(e=>e.fileId).join(`, `)}`):e}let f,p;if(r.indexId&&(f=(await e.client.requestJson({path:T(i,h.indexJobCreate),method:`POST`,body:{indexId:r.indexId,sourceType:`DATA_CENTER_FILE`,docIds:d.map(e=>e.fileId)}})).data?.ingestionId,r.wait&&f)){let a=await pd(e.client,t,{statusUrl:fd(i,r.indexId,f).toString(),intervalSec:r.pollInterval??5});if(p=cd(a),ld(a).length>0)throw new n(dd(a,`Import job reported document failures.`),l.GENERAL,`Registered file ids: ${d.map(e=>e.fileId).join(`, `)}`)}if(t.quiet){for(let e of d)D(e.fileId);return}if(a===`text`){for(let e of d)D(`${ui(e.path)} ${e.fileId} registered`);f&&D(`job: ${f}`),p&&D(`status: ${p}`);let e=[`Uploaded ${d.length} file${d.length===1?``:`s`}`];if(s.length>0&&e.push(`skipped ${s.length} unsupported`),D(`\n${e.join(`, `)}.`),t.verbose&&s.length>0){D(`Skipped files:`);for(let e of s)D(` ${ui(e)}`)}return}O({files:d.map(e=>({path:e.path,fileId:e.fileId})),skipped:s,...r.indexId?{index_id:r.indexId}:{},...f?{ingestion_id:f}:{},...p?{final_status:p}:{}},a)}});const Gd={name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Knowledge base name (1-20 chars, unique in workspace)`,"zh-CN":`知识库名称(1–20 个字符,在 Workspace 中唯一)`},required:!0},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`What this knowledge base holds and what it is for — tells bases apart in the workspace list (1-500 chars)`,"zh-CN":`知识库装了什么内容、给谁用,用于在 Workspace 列表中区分同类知识库(1–500 个字符)`},required:!0},docId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Data-center file id to import (repeatable); mutually exclusive with --category-id`,"zh-CN":`要导入的数据中心文件 ID(可重复);不能与 --category-id 同时使用`}},categoryId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Import every file under this category (repeatable); mutually exclusive with --doc-id`,"zh-CN":`导入该类目下的所有文件(可重复);不能与 --doc-id 同时使用`}},embeddingModel:{type:`string`,valueHint:`<name>`,description:{"en-US":`Embedding model name (default: text-embedding-v4)`,"zh-CN":`Embedding 模型名称(默认:text-embedding-v4)`}},chunkSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Chunk size in characters (default: 600, recommended 300-800)`,"zh-CN":`Chunk 字符数(默认:600,建议:300–800)`}},wait:{type:`switch`,description:{"en-US":`Poll the initial import job to a terminal state`,"zh-CN":`轮询初始导入任务直到进入终态`}},pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval when waiting (default: 5)`,"zh-CN":`等待时的轮询间隔(默认:5)`}},...L};function Kd(e){return e.docId?.length?{sourceType:`DATA_CENTER_FILE`,docIds:e.docId,dataSources:[{sourceType:`DATA_CENTER_FILE`}]}:{sourceType:`DATA_CENTER_CATEGORY`,categoryIds:e.categoryId,dataSources:[{sourceType:`DATA_CENTER_CATEGORY`}]}}var qd=S({description:{"en-US":`Create a knowledge base and import data-center files or categories`,"zh-CN":`创建知识库并导入数据中心文件或类目`},auth:`apiKey`,usageArgs:`--name <text> --description <text> (--doc-id <id> | --category-id <id>) [flags]`,flags:Gd,notes:[{"en-US":`Structure/sink types are fixed to the default document knowledge base (unstructured, BUILT_IN storage).`,"zh-CN":`结构和存储类型固定为默认文档知识库(unstructured、BUILT_IN 存储)。`},{"en-US":`Returns the knowledge base id (pipelineId) and the initial import job id (ingestionId).`,"zh-CN":`返回知识库 ID(pipelineId)和初始导入任务 ID(ingestionId)。`},{"en-US":`Use the import job status command (or --wait) to track the initial import.`,"zh-CN":`使用导入任务状态命令(或 --wait)跟踪初始导入。`}],exampleArgs:[{"en-US":`--name demo --description 'product docs' --doc-id file-xxx --workspace-id ws-xxx`,"zh-CN":`--name demo --description '产品文档' --doc-id file-xxx --workspace-id ws-xxx`},{"en-US":`--name demo --description 'product docs' --category-id cate-xxx --wait`,"zh-CN":`--name demo --description '产品文档' --category-id cate-xxx --wait`}],validate(e){if(e.name.length<1||e.name.length>20)return`--name must be 1-20 characters`;if(e.description.length<1||e.description.length>500)return`--description must be 1-500 characters`;let t=!!e.docId?.length,n=!!e.categoryId?.length;if(t&&n)return`Use either --doc-id or --category-id, not both`;if(!t&&!n)return`Provide --doc-id or --category-id as the data source`},async run(e){let{settings:t,flags:r}=e,i=R(e),a=C(t.output),o={name:r.name,description:r.description,structureType:`unstructured`,sinkType:`BUILT_IN`,embeddingModelName:r.embeddingModel??`text-embedding-v4`,chunkSize:r.chunkSize??600,...Kd(r)},s=T(i,h.indexCreateV2);if(t.dryRun){O({endpoint:s,request:o},a);return}let c=await e.client.requestJson({path:s,method:`POST`,body:o}),u=c.data?.pipelineId,d=c.data?.ingestionId,f;if(r.wait&&u&&d){let a=await pd(e.client,t,{statusUrl:fd(i,u,d).toString(),intervalSec:r.pollInterval??5});if(f=cd(a),ld(a).length>0)throw new n(dd(a,`Initial import reported document failures.`),l.GENERAL,`Knowledge base created: ${u}`,{api:{requestId:a.request_id}})}if(t.quiet){D(u??``);return}if(a===`text`){D(`index_id: ${u??`-`}`),d&&D(`ingestion_id: ${d}`),f&&D(`status: ${f}`),D(`Next: check the import job status, then search against this knowledge base.`);return}O(f?{...c,final_status:f}:c,a)}});const Jd={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`New knowledge base name (1-20 chars)`,"zh-CN":`新的知识库名称(1–20 个字符)`}},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`New knowledge base description`,"zh-CN":`新的知识库描述`}},rerankMinScore:{type:`number`,valueHint:`<score>`,description:{"en-US":`Rerank minimum score threshold, range 0-1 (chunks below are filtered)`,"zh-CN":`Rerank 最低分数阈值,范围 0–1(低于阈值的 Chunk 会被过滤)`}},...L};var Yd=S({description:{"en-US":`Update knowledge base name, description or rerank threshold`,"zh-CN":`更新知识库名称、描述或 Rerank 阈值`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:Jd,notes:[{"en-US":`Indexing settings (embedding model, chunk size, etc.) are immutable — recreate the knowledge base to change them.`,"zh-CN":`索引设置(Embedding 模型、Chunk 大小等)不可修改——如需更改,请重新创建知识库。`}],exampleArgs:[{"en-US":`--index-id idx-xxx --description 'product docs v2' --workspace-id ws-xxx`,"zh-CN":`--index-id idx-xxx --description '产品文档 v2' --workspace-id ws-xxx`},`--index-id idx-xxx --rerank-min-score 0.3`],validate(e){if(e.name===void 0&&e.description===void 0&&e.rerankMinScore===void 0)return`Nothing to update — pass --name, --description or --rerank-min-score`;if(e.name!==void 0&&(e.name.length<1||e.name.length>20))return`--name must be 1-20 characters`;if(e.rerankMinScore!==void 0&&(e.rerankMinScore<0||e.rerankMinScore>1))return`--rerank-min-score must be between 0 and 1`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={id:n.indexId,...n.name===void 0?{}:{name:n.name},...n.description===void 0?{}:{description:n.description},...n.rerankMinScore===void 0?{}:{rerankMinScore:n.rerankMinScore}},o=T(r,h.indexUpdate);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){D(`updated: ${n.indexId}`);return}O(s,i)}}});const Xd={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},...L};var Zd=S({description:{"en-US":`Delete a knowledge base with all its documents and chunks`,"zh-CN":`删除知识库及其所有文档和 Chunk`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the knowledge base and all of its documents and chunks. Data-center files are not deleted.`,"zh-CN":`该操作会永久删除知识库及其全部文档和 Chunk,但不会删除数据中心文件。`}},usageArgs:`--index-id <id> [flags]`,flags:Xd,notes:[{"en-US":`Irreversible — the knowledge base and all indexed content are permanently removed.`,"zh-CN":`该操作不可撤销——知识库及所有已索引内容将被永久删除。`},{"en-US":`Files in the data center are not affected; only the knowledge base index is deleted.`,"zh-CN":`数据中心中的文件不受影响;仅删除知识库索引。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={index_id:n.indexId},o=T(r,h.indexDelete);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){D(`deleted: ${n.indexId}`);return}O(s,i)}}});const Qd={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},docId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Document ID to delete (repeatable)`,"zh-CN":`要删除的文档 ID(可重复)`},required:!0},...L};var $d=S({description:{"en-US":`Delete documents and their chunks from a knowledge base`,"zh-CN":`从知识库中删除文档及其 Chunk`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the selected documents and all of their chunks.`,"zh-CN":`该操作会永久删除所选文档及其全部 Chunk,且无法撤销。`}},usageArgs:`--index-id <id> --doc-id <id> [flags]`,flags:Qd,notes:[{"en-US":`Removes documents from the knowledge base index only; the source files remain in the data center.`,"zh-CN":`仅从知识库索引中移除文档;源文件仍保留在数据中心。`},{"en-US":"Use the doc_id from `knowledge doc list --quiet`, not the fileId from `knowledge doc upload`. For documents created via `knowledge create --doc-id`, the doc_id equals the fileId; for documents imported via `knowledge doc upload --index-id`, the doc_id may include a workspace suffix.","zh-CN":"请使用 `knowledge doc list --quiet` 返回的 doc_id,而不是 `knowledge doc upload` 返回的 fileId。通过 `knowledge create --doc-id` 创建的文档,其 doc_id 等于 fileId;通过 `knowledge doc upload --index-id` 导入的文档,其 doc_id 可能带有 Workspace 后缀。"},{"en-US":`Deletion may take up to ~30s to propagate — the document may still appear in the doc list briefly.`,"zh-CN":`删除结果最多可能需要约 30 秒才会生效——文档可能会短暂地继续出现在列表中。`},{"en-US":`The output lists the ids actually deleted.`,"zh-CN":`输出会列出实际删除的 ID。`}],exampleArgs:[`--index-id idx-xxx --doc-id file-xxx --workspace-id ws-xxx --dry-run`,`--index-id idx-xxx --doc-id file-a --doc-id file-b --yes`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={index_id:n.indexId,doc_ids:n.docId},o=T(r,h.indexDeleteFile);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.deleted??[];if(t.quiet){for(let e of c)D(e);return}if(i===`text`){D(`deleted: ${c.length} document(s)`);for(let e of c)D(` ${e}`);c.length!==n.docId.length&&process.stderr.write(`Warning: requested ${n.docId.length} deletion(s) but the server reported ${c.length}.\n`);return}O(s,i)}});const ef={docId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Data-center file ID to tag (repeatable, 1-20 per call)`,"zh-CN":`要添加标签的数据中心文件 ID(可重复,每次调用 1–20 个)`},required:!0},tag:{type:`array`,valueHint:`<text>`,description:{"en-US":`Tag applied to every --doc-id (repeatable, each up to 32 chars)`,"zh-CN":`应用于每个 --doc-id 的标签(可重复,每个最多 32 个字符)`},required:!0},mode:{type:`string`,valueHint:`<mode>`,description:{"en-US":`Update mode: append (default) or overwrite`,"zh-CN":`更新模式:append(默认)或 overwrite`}},...L};var tf=S({description:{"en-US":`Batch update tags on data-center files`,"zh-CN":`批量更新数据中心文件标签`},auth:`apiKey`,usageArgs:`--doc-id <id> --tag <text> [flags]`,flags:ef,notes:[{"en-US":`The same tag set is applied to every --doc-id; run the command multiple times for different tag sets.`,"zh-CN":`同一组标签会应用于每个 --doc-id;若需应用不同标签组,请多次运行该命令。`},{"en-US":`Server limits: up to 100 tags per file, total tag length up to 700 chars, tag up to 32 chars.`,"zh-CN":`服务端限制:每个文件最多 100 个标签,标签总长度最多 700 个字符,单个标签最多 32 个字符。`}],exampleArgs:[`--doc-id file-xxx --tag project-a --tag draft --workspace-id ws-xxx`,`--doc-id file-a --doc-id file-b --tag final --mode overwrite`],validate(e){if(e.docId.length>20)return`--doc-id accepts at most 20 ids per call`;if(e.mode!==void 0&&e.mode!==`append`&&e.mode!==`overwrite`)return`--mode must be append or overwrite`;if(e.tag.length>100)return`At most 100 tags per file`;let t=e.tag.find(e=>e.length>32);if(t)return`Tag exceeds 32 characters: ${t}`;if(e.tag.reduce((e,t)=>e+t.length,0)>700)return`Total tag length exceeds 700 characters`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={fileInfos:n.docId.map(e=>({fileId:e,tags:n.tag})),updateMode:(n.mode??`append`).toUpperCase()},o=T(r,h.batchUpdateFileTag);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){D(`tagged: ${n.docId.length} file(s) with [${n.tag.join(`, `)}]`);return}O(s,i)}}});const nf={scene:{type:`string`,valueHint:`<scene>`,description:{"en-US":`Service scene: chat (Q&A) or search (retrieval)`,"zh-CN":`服务场景:chat(问答)或 search(检索)`},required:!0},status:{type:`string`,valueHint:`<status>`,description:{"en-US":`Filter by status: draft, deployed (includes edited) or deleted`,"zh-CN":`按状态筛选:draft、deployed(包含 edited)或 deleted`}},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by service name (fuzzy match)`,"zh-CN":`按服务名称模糊筛选`}},agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by exact agent ID`,"zh-CN":`按 Agent ID 精确筛选`}},indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by exact linked knowledge base (pipeline) ID`,"zh-CN":`按关联的知识库(Pipeline)ID 精确筛选`}},...od,...L},rf=[`chat`,`search`],af=[`draft`,`deployed`,`deleted`];var of=S({description:{"en-US":`List retrieval / Q&A services (agents) in the workspace`,"zh-CN":`列出 Workspace 中的检索/问答服务(Agent)`},auth:`apiKey`,usageArgs:`--scene <chat|search> [flags]`,flags:nf,notes:[{"en-US":`A scene (chat or search) is required — run once per scene to see both.`,"zh-CN":`必须指定场景(chat 或 search)——要查看两类服务,请分别运行一次。`},{"en-US":`Use the returned agent_id with the search or chat commands, or with service management commands.`,"zh-CN":`将返回的 agent_id 用于 search/chat 命令或服务管理命令。`}],exampleArgs:[`--scene chat --workspace-id ws-xxx`,`--scene search --status deployed`],validate(e){if(!rf.includes(e.scene))return`--scene must be chat or search`;if(e.status!==void 0&&!af.includes(e.status))return`--status must be draft, deployed or deleted`;if(e.pageSize!==void 0&&(e.pageSize<1||e.pageSize>100))return`--page-size must be between 1 and 100`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={agent_scene:n.scene,...n.status?{agent_status:n.status}:{},...n.name?{agent_name:n.name}:{},...n.agentId?{agent_id:n.agentId}:{},...n.indexId?{pipeline_id:n.indexId}:{},page_number:n.pageNumber??1,page_size:n.pageSize??10},o=T(r,h.agentList);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.rows??[];if(t.quiet){for(let e of c)D(e.agent_id??``);return}if(i===`text`){if(c.length===0)D(`No services found.`);else for(let e of c){let t=(e.pipeline_list??[]).map(e=>e.pipeline_name).filter(Boolean).join(`,`);D(sd([e.agent_id,e.agent_status,e.agent_version,e.agent_name,t?`(kb: ${t})`:``].filter(Boolean).join(` `)))}D(`total: ${s.data?.total_count??c.length}`),D(n.scene===`search`?`Use an agent_id above with the knowledge search command.`:`Use an agent_id above with the knowledge chat command.`)}else O(s,i)}});const sf={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Service (agent) ID`,"zh-CN":`服务(Agent)ID`},required:!0},agentVersion:{type:`string`,valueHint:`<version>`,description:{"en-US":`Specific version to inspect (beta or a published number); omit for all versions`,"zh-CN":`要查看的指定版本(beta 或已发布版本号);省略则返回全部版本`}},...L};function cf(e){D(`Version ${e.agent_version??`?`}:`),e.agent_version_desc&&D(` desc: ${e.agent_version_desc}`),e.publish_time!==void 0&&D(` published: ${e.publish_time}`);let t=e.agent_config;if(t){t.agent_policy&&D(` policy: ${t.agent_policy}`),t.agent_model&&D(` model: ${t.agent_model}`),t.temperature!==void 0&&D(` temperature: ${t.temperature}`);for(let e of t.kb_search_configs??[]){let t=typeof e.id==`string`?e.id:`?`,n=typeof e.name==`string`?` (${e.name})`:``;D(` kb: ${t}${n}`)}}}var lf=S({description:{"en-US":`Show service (agent) details including per-version configuration`,"zh-CN":`查看服务(Agent)详情及各版本配置`},auth:`apiKey`,usageArgs:`--agent-id <id> [flags]`,flags:sf,notes:[{"en-US":`Without --agent-version all versions are returned (beta draft plus published numbers).`,"zh-CN":`未传入 --agent-version 时,会返回所有版本(beta 草稿和已发布版本号)。`},{"en-US":`The version value is passed through as-is; the valid set is server-side state.`,"zh-CN":`版本值将原样传递;有效版本集合由服务端状态决定。`}],exampleArgs:[`--agent-id aid-xxx --workspace-id ws-xxx`,`--agent-id aid-xxx --agent-version beta`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={agent_id:n.agentId,...n.agentVersion?{agent_version:n.agentVersion}:{}},o=T(r,h.agentGet);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data;if(t.quiet){D(c?.agent_id??``);return}if(i!==`text`){O(s,i);return}D(`Basic:`),D(` id: ${c?.agent_id??`-`}`),D(` name: ${c?.agent_name??`-`}`),D(` desc: ${c?.agent_desc??`-`}`),D(` scene: ${c?.agent_scene??`-`}`),D(` status: ${c?.agent_status??`-`}`);for(let e of c?.agent_details??[])cf(e)}});const uf={name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Service name (up to 200 chars, unique per scene in the workspace)`,"zh-CN":`服务名称(最多 200 个字符,在 Workspace 的同一场景中唯一)`},required:!0},scene:{type:`string`,valueHint:`<scene>`,description:{"en-US":`Service scene: chat (Q&A) or search (retrieval)`,"zh-CN":`服务场景:chat(问答)或 search(检索)`},required:!0},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`What this service answers and who it serves — recommended: agents read it to pick the right service (up to 1000 chars)`,"zh-CN":`这个服务能回答什么、给谁用 —— 建议填写:agent 靠它判断该调用哪个服务(最多 1000 个字符)`}},indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Bind this knowledge base; other settings use server defaults`,"zh-CN":`绑定该知识库;其他设置使用服务端默认值`}},...L};var df=S({description:{"en-US":`Create a retrieval / Q&A service (initial status: draft, version: beta)`,"zh-CN":`创建检索/问答服务(初始状态:draft,版本:beta)`},auth:`apiKey`,usageArgs:`--name <text> --scene <chat|search> [flags]`,flags:uf,notes:[{"en-US":`Without an explicit configuration the server applies its default agent settings.`,"zh-CN":`未显式提供配置时,服务端会应用默认 Agent 设置。`},{"en-US":`The draft (beta) version can be tested via --agent-version beta on search/chat before deploying.`,"zh-CN":`部署前,可在 search/chat 命令中使用 --agent-version beta 测试草稿(beta)版本。`},{"en-US":`Requires the knowledge-base create permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库创建权限。`}],exampleArgs:[{"en-US":`--name my-qa --scene chat --description 'answers product FAQs' --workspace-id ws-xxx`,"zh-CN":`--name my-qa --scene chat --description '回答产品常见问题' --workspace-id ws-xxx`},`--name my-search --scene search --index-id idx-xxx`],validate(e){if(e.name.length>200)return`--name must be at most 200 characters`;if(e.scene!==`chat`&&e.scene!==`search`)return`--scene must be chat or search`;if(e.description!==void 0&&e.description.length>1e3)return`--description must be at most 1000 characters`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={agent_name:n.name,agent_scene:n.scene,...n.description?{agent_desc:n.description}:{},...n.indexId?{agent_config:{kb_search_configs:[{id:n.indexId}]}}:{}},o=T(r,h.agentCreate);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=hd(s,`agent_id`);if(t.quiet){D(c??``);return}if(i===`text`){D(`created: ${c??`-`} (status: ${hd(s,`agent_status`)??`draft`}, version: ${hd(s,`agent_version`)??`beta`})`),D(`Test the draft with --agent-version beta on search/chat, then deploy it to publish.`);return}O(s,i)}});const ff=[`true`,`false`],pf={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Service (agent) ID`,"zh-CN":`服务(Agent)ID`},required:!0},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`New service name (up to 200 chars)`,"zh-CN":`新服务名称(最多 200 个字符)`}},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`New service description (up to 1000 chars)`,"zh-CN":`新服务描述(最多 1000 个字符)`}},agentVersion:{type:`string`,valueHint:`<version>`,description:{"en-US":`Target version (default: beta draft). Published versions only accept --version-desc`,"zh-CN":`目标版本(默认:beta 草稿)。已发布版本只接受 --version-desc`}},versionDesc:{type:`string`,valueHint:`<text>`,description:{"en-US":`Version description`,"zh-CN":`版本描述`}},policy:{type:`string`,valueHint:`<policy>`,description:{"en-US":`Agent policy: turbo (fast) or agentic (multi-turn)`,"zh-CN":`Agent 策略:turbo(快速)或 agentic(多轮)`}},model:{type:`string`,valueHint:`<name>`,description:{"en-US":`Generation model code (must be in the platform allowlist)`,"zh-CN":`生成模型代码(必须在平台白名单中)`}},temperature:{type:`number`,valueHint:`<n>`,description:{"en-US":`Sampling temperature, range 0-2`,"zh-CN":`采样温度,范围 0–2`}},maxLlmCalls:{type:`number`,valueHint:`<n>`,description:{"en-US":`Max LLM calls per request, range 1-30`,"zh-CN":`每次请求最大 LLM 调用次数,范围 1–30`}},enableSessionFile:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable session files: true or false`,"zh-CN":`启用会话文件:true 或 false`}},enableRefusal:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable refusal answers: true or false`,"zh-CN":`启用拒答:true 或 false`}},enableAntiLeak:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable anti prompt-leak: true or false`,"zh-CN":`启用防提示词泄露:true 或 false`}},enableRichText:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable rich text output: true or false`,"zh-CN":`启用富文本输出:true 或 false`}},enableCitation:{type:`string`,valueHint:`<bool>`,description:{"en-US":`Enable citations: true or false`,"zh-CN":`启用引用:true 或 false`}},configFile:{type:`string`,valueHint:`<path>`,description:{"en-US":`JSON file replacing the whole agent_config (for nested settings like kb_search_configs); mutually exclusive with scalar config flags`,"zh-CN":`替换整个 agent_config 的 JSON 文件(用于 kb_search_configs 等嵌套设置);不能与标量配置选项同时使用`}},...L};function mf(e){let t={};return e.policy!==void 0&&(t.agent_policy=e.policy),e.model!==void 0&&(t.agent_model=e.model),e.temperature!==void 0&&(t.temperature=e.temperature),e.maxLlmCalls!==void 0&&(t.max_num_llm_calls=e.maxLlmCalls),e.enableSessionFile!==void 0&&(t.enable_session_file=e.enableSessionFile),e.enableRefusal!==void 0&&(t.enable_refusal=e.enableRefusal),e.enableAntiLeak!==void 0&&(t.enable_anti_leak=e.enableAntiLeak),e.enableRichText!==void 0&&(t.enable_rich_text=e.enableRichText),e.enableCitation!==void 0&&(t.enable_citation=e.enableCitation),t}function hf(e){let t;try{t=ai(e,`utf-8`)}catch(t){let r=t.code??`unknown`;throw new n(`Cannot read config file: ${e}`,l.GENERAL,`File system error (${r}) — check the path and permissions.`)}let r;try{r=JSON.parse(t)}catch{throw new n(`--config-file must contain valid JSON.`,l.USAGE)}if(typeof r!=`object`||!r||Array.isArray(r))throw new n(`--config-file must contain a JSON object.`,l.USAGE);let i=r;return _f(i),i}const gf=/* @__PURE__ */ new Set([`agent_policy`,`agent_model`,`enable_session_file`,`enable_refusal`,`enable_anti_leak`,`enable_rich_text`,`enable_citation`,`temperature`,`max_num_llm_calls`,`max_completion_tokens`,`session_file_max_parse_length`,`enable_kb_router`,`kb_router_model`,`user_system_prompt`,`anti_leak_prompt`,`refusal_prompt`,`credibility_prompt`,`enable_thinking`,`enable_temperature`,`enable_credibility`,`enable_max_completion_tokens`,`session_file_parse_mode`,`rerank_top_n`,`hybrid_rerank`,`kb_search_configs`]);function _f(e){if(e.agent_policy!==void 0&&![`turbo`,`agentic`].includes(e.agent_policy))throw new n(`agent_policy must be turbo or agentic`,l.USAGE);if(e.temperature!==void 0&&(e.temperature<0||e.temperature>2))throw new n(`temperature must be between 0 and 2`,l.USAGE);if(e.max_num_llm_calls!==void 0&&(e.max_num_llm_calls<1||e.max_num_llm_calls>30))throw new n(`max_num_llm_calls must be between 1 and 30`,l.USAGE);if(e.rerank_top_n!==void 0&&(e.rerank_top_n<1||e.rerank_top_n>20))throw new n(`rerank_top_n must be between 1 and 20`,l.USAGE);for(let t of e.kb_search_configs??[]){let e=t.rerank;e?.rerank_instruct&&e.rerank_mode!==`custom`&&process.stderr.write(`Warning: rerank_instruct is only effective with rerank_mode=custom; the server clears it otherwise.
|
|
2737
|
+
`)}for(let t of Object.keys(e))gf.has(t)||process.stderr.write(`Warning: unknown agent_config field passed through: ${t}\n`)}async function vf(e,t,n){return((await e.requestJson({path:T(t,h.agentGet),method:`POST`,body:{agent_id:n,agent_version:`beta`}})).data?.agent_details??[]).find(e=>e.agent_version===`beta`)?.agent_config??{}}var yf=S({description:{"en-US":`Update service name, description or draft configuration`,"zh-CN":`更新服务名称、描述或草稿配置`},auth:`apiKey`,usageArgs:`--agent-id <id> [flags]`,flags:pf,notes:[{"en-US":`Configuration changes only apply to the beta draft; published versions accept --version-desc only.`,"zh-CN":`配置修改只应用于 beta 草稿;已发布版本只接受 --version-desc。`},{"en-US":`To change the configuration of a published version, first update the beta draft (this command without --agent-version or with --agent-version beta), then run service deploy to publish a new version.`,"zh-CN":`要修改已发布版本的配置,请先更新 beta 草稿(不传 --agent-version,或传 --agent-version beta),然后运行 service deploy 发布新版本。`},{"en-US":`Scalar config flags merge into the current draft config (read-merge-write); --config-file replaces the whole config and is mutually exclusive with them.`,"zh-CN":`标量配置选项会合并到当前草稿配置(读取-合并-写入);--config-file 会替换整个配置,且不能与标量配置选项同时使用。`},{"en-US":`After updating the draft, verify with --agent-version beta on search/chat, then deploy.`,"zh-CN":`更新草稿后,先在 search/chat 命令中使用 --agent-version beta 验证,再部署。`},{"en-US":`Requires the knowledge-base modify permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库修改权限。`}],exampleArgs:[`--agent-id aid-xxx --temperature 0.7 --workspace-id ws-xxx`,`--agent-id aid-xxx --config-file ./agent-config.json`,{"en-US":`--agent-id aid-xxx --agent-version 1 --version-desc 'first stable release'`,"zh-CN":`--agent-id aid-xxx --agent-version 1 --version-desc '首个稳定版本'`}],validate(e){let t=Object.keys(mf(e)).length>0;if(!(e.name!==void 0||e.description!==void 0||e.versionDesc!==void 0||e.configFile!==void 0||t))return`Nothing to update — pass a name/description/version-desc or config flags`;if(e.configFile!==void 0&&t)return`--config-file is mutually exclusive with scalar config flags`;if(e.agentVersion!==void 0&&e.agentVersion!==`beta`&&(t||e.configFile!==void 0))return`Published versions only accept --version-desc; update the beta draft to change config`;if(e.name!==void 0&&e.name.length>200)return`--name must be at most 200 characters`;if(e.description!==void 0&&e.description.length>1e3)return`--description must be at most 1000 characters`;if(e.policy!==void 0&&![`turbo`,`agentic`].includes(e.policy))return`--policy must be turbo or agentic`;if(e.temperature!==void 0&&(e.temperature<0||e.temperature>2))return`--temperature must be between 0 and 2`;if(e.maxLlmCalls!==void 0&&(e.maxLlmCalls<1||e.maxLlmCalls>30))return`--max-llm-calls must be between 1 and 30`;for(let[t,n]of[[`--enable-session-file`,e.enableSessionFile],[`--enable-refusal`,e.enableRefusal],[`--enable-anti-leak`,e.enableAntiLeak],[`--enable-rich-text`,e.enableRichText],[`--enable-citation`,e.enableCitation]])if(n!==void 0&&!ff.includes(n))return`${t} must be true or false`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a=mf(n),o=n.configFile!==void 0||Object.keys(a).length>0,s;n.configFile===void 0?Object.keys(a).length>0&&(t.dryRun?s={...a}:(s={...await vf(e.client,r,n.agentId),...a},_f(s))):s=hf(n.configFile);let c={agent_id:n.agentId,...n.name===void 0?{}:{agent_name:n.name},...n.description===void 0?{}:{agent_desc:n.description},...n.agentVersion===void 0?{}:{agent_version:n.agentVersion},...n.versionDesc===void 0?{}:{agent_version_desc:n.versionDesc},...s===void 0?{}:{agent_config:s}},l=T(r,h.agentUpdate);if(t.dryRun){O({endpoint:l,request:c,...o&&n.configFile===void 0?{note:`scalar config flags are merged into the current beta config at run time`}:{}},i);return}let u=await e.client.requestJson({path:l,method:`POST`,body:c});if(!t.quiet){if(i===`text`){D(`updated: ${n.agentId}`),o&&D(`Draft config changed — verify with --agent-version beta, then deploy.`);return}O(u,i)}}});const bf={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Service (agent) ID`,"zh-CN":`服务(Agent)ID`},required:!0},versionDesc:{type:`string`,valueHint:`<text>`,description:{"en-US":`Description for the newly published version`,"zh-CN":`新发布版本的描述`}},...L};var xf=S({description:{"en-US":`Publish the beta draft of a service as a new version`,"zh-CN":`将服务的 beta 草稿发布为新版本`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This publishes the current draft as a new version and changes the behavior seen by live callers.`,"zh-CN":`该操作会将当前草稿发布为新版本,并改变线上调用方使用的服务行为。`}},usageArgs:`--agent-id <id> [flags]`,flags:bf,notes:[{"en-US":`The version number auto-increments; status becomes deployed.`,"zh-CN":`版本号会自动递增;状态将变为 deployed。`},{"en-US":`Publishing affects live callers — the confirmation prompt guards against accidents.`,"zh-CN":`发布会影响线上调用方——确认提示用于避免误操作。`},{"en-US":`Requires the knowledge-base modify permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库修改权限。`}],exampleArgs:[`--agent-id aid-xxx --workspace-id ws-xxx`,{"en-US":`--agent-id aid-xxx --version-desc 'tuned rerank params' --yes`,"zh-CN":`--agent-id aid-xxx --version-desc '已调优 Rerank 参数' --yes`}],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={agent_id:n.agentId,...n.versionDesc?{agent_version_desc:n.versionDesc}:{}},o=T(r,h.agentDeploy);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=hd(s,`agent_version`);if(t.quiet){D(c??``);return}if(i===`text`){D(`deployed: ${n.agentId} version ${c??`-`}`);return}O(s,i)}});const Sf={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Service (agent) ID`,"zh-CN":`服务(Agent)ID`},required:!0},...L};var Cf=S({description:{"en-US":`Delete a retrieval / Q&A service (soft delete, idempotent)`,"zh-CN":`删除检索/问答服务(软删除,幂等)`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This deletes the service and makes its agent ID unavailable for search and chat calls. The operation cannot be undone.`,"zh-CN":`该操作会删除服务,使其 Agent ID 无法再用于搜索和对话调用,且无法撤销。`}},usageArgs:`--agent-id <id> [flags]`,flags:Sf,notes:[{"en-US":`Deletion cannot be undone; the agent_id becomes unusable for search and chat calls.`,"zh-CN":`删除无法撤销;该 agent_id 将不能再用于 search 和 chat 调用。`},{"en-US":`Idempotent — deleting an already-deleted service does not fail.`,"zh-CN":`该操作具有幂等性——重复删除已删除的服务不会失败。`},{"en-US":`Requires the knowledge-base delete permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库删除权限。`}],exampleArgs:[`--agent-id aid-xxx --workspace-id ws-xxx`,`--agent-id aid-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={agent_id:n.agentId},o=T(r,h.agentDelete);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){D(`deleted: ${n.agentId} (status: ${hd(s,`agent_status`)??`deleted`})`);return}O(s,i)}}});const wf={agentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Source service (agent) ID to copy`,"zh-CN":`要复制的源服务(Agent)ID`},required:!0},...L};var Tf=S({description:{"en-US":`Copy a service into a new draft (name gets a copy_ prefix)`,"zh-CN":`将服务复制为新草稿(名称会添加 copy_ 前缀)`},auth:`apiKey`,usageArgs:`--agent-id <id> [flags]`,flags:wf,notes:[{"en-US":`The copy starts as a beta draft; test it with --agent-version beta, then deploy to publish.`,"zh-CN":`副本初始为 beta 草稿;请使用 --agent-version beta 测试,然后部署发布。`},{"en-US":`Requires the knowledge-base create permission in the workspace.`,"zh-CN":`需要 Workspace 中的知识库创建权限。`}],exampleArgs:[`--agent-id aid-xxx --workspace-id ws-xxx`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={agent_id:n.agentId},o=T(r,h.agentCopy);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=hd(s,`agent_id`);if(t.quiet){D(c??``);return}if(i===`text`){D(`new agent_id: ${c??`-`} (name: ${hd(s,`agent_name`)??`-`}, status: ${hd(s,`agent_status`)??`draft`})`),D(`Test the draft with --agent-version beta on search/chat, then deploy it to publish.`);return}O(s,i)}});const Ef={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},docId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Owning document ID from the doc list command; required in practice for all knowledge base types`,"zh-CN":`来自文档列表命令的所属文档 ID;实际使用时所有知识库类型都需要提供`}},content:{type:`string`,valueHint:`<text>`,description:{"en-US":`Chunk body text, up to 6000 chars (document-type); alternative to --content-file`,"zh-CN":`Chunk 正文,最多 6000 个字符(文档型);与 --content-file 二选一`}},contentFile:{type:`string`,valueHint:`<path>`,description:{"en-US":`Read chunk body from a UTF-8 plain text file (.md/.txt etc.)`,"zh-CN":`从 UTF-8 纯文本文件(.md/.txt 等)读取 Chunk 正文`}},title:{type:`string`,valueHint:`<text>`,description:{"en-US":`Chunk title, up to 50 chars (document-type)`,"zh-CN":`Chunk 标题,最多 50 个字符(文档型)`}},imageUrl:{type:`array`,valueHint:`<url>`,description:{"en-US":`Chunk image URL (repeatable, up to 10; document-type)`,"zh-CN":`Chunk 图片 URL(可重复,最多 10 个;文档型)`}},field:{type:`array`,valueHint:`<key=value>`,description:{"en-US":`Arbitrary field entry (repeatable) for table/image knowledge bases where keys are Excel column headers; mutually exclusive with content/title/image flags`,"zh-CN":`表格/图片知识库的自定义字段(可重复),键为 Excel 列标题;不能与 content/title/image 相关选项同时使用`}},...L};function Df(e){let t={};for(let r of e){let e=r.indexOf(`=`);if(e<=0)throw new n(`--field must be key=value, got: ${r}`,l.USAGE);t[r.slice(0,e)]=r.slice(e+1)}return t}var Of=S({description:{"en-US":`Add a chunk directly to a knowledge base`,"zh-CN":`直接向知识库添加 Chunk`},auth:`apiKey`,usageArgs:`--index-id <id> (--content <text> | --field <k=v>) [flags]`,flags:Ef,notes:[{"en-US":`Document / table / image knowledge bases are supported; audio-video ones are not.`,"zh-CN":`支持文档、表格和图片知识库;不支持音视频知识库。`},{"en-US":`--doc-id is required in practice for all knowledge base types. Use the document-level id from the doc list command; the per-row doc_id in chunk list output is not accepted.`,"zh-CN":`实际使用时,所有知识库类型都需要 --doc-id。请使用文档列表命令返回的文档级 ID;Chunk 列表每行返回的 doc_id 不被接受。`},{"en-US":`Image-type documents do not support text chunks. Target a text-type document (docx/pdf/txt) instead.`,"zh-CN":`图片型文档不支持文本 Chunk;请改为操作文本型文档(docx/pdf/txt)。`},{"en-US":`The API is idempotent but rate-limited to 10 calls per second — throttle batch scripts.`,"zh-CN":`该 API 具有幂等性,但限流为每秒 10 次调用——批处理脚本需要控制速率。`},{"en-US":`The response carries no chunk id; list chunks afterwards to find the new one.`,"zh-CN":`响应不包含 Chunk ID;添加后请列出 Chunk 以查找新条目。`},{"en-US":`For table/image knowledge bases use --field with Excel column headers as keys; values are passed through as strings.`,"zh-CN":`表格/图片知识库请使用 --field,并以 Excel 列标题作为键;值将按字符串原样传递。`}],exampleArgs:[{"en-US":`--index-id idx-xxx --content "chunk text" --title intro --workspace-id ws-xxx`,"zh-CN":`--index-id idx-xxx --content "Chunk 文本" --title 简介 --workspace-id ws-xxx`},{"en-US":`--index-id idx-xxx --field columnA=v1 --field columnB=v2`,"zh-CN":`--index-id idx-xxx --field 列A=v1 --field 列B=v2`}],validate(e){let t=e.content!==void 0||e.contentFile!==void 0||e.title!==void 0||!!e.imageUrl?.length,n=!!e.field?.length;if(t&&n)return`--field is mutually exclusive with --content/--content-file/--title/--image-url`;if(!t&&!n)return`Provide chunk content via --content/--content-file or --field entries`;if(e.content!==void 0&&e.contentFile!==void 0)return`Use either --content or --content-file, not both`;if(e.content!==void 0&&e.content.length>6e3)return`--content must be at most 6000 characters`;if(e.title!==void 0&&e.title.length>50)return`--title must be at most 50 characters`;if(e.imageUrl!==void 0&&e.imageUrl.length>10)return`--image-url accepts at most 10 entries`},async run(e){let{settings:t,flags:r}=e,i=R(e),a=C(t.output),o;if(r.field?.length)o=Df(r.field);else{let e=r.contentFile===void 0?r.content:Hd(r.contentFile,`--content`);if(typeof e==`string`&&e.length>6e3)throw new n(`Chunk content must be at most 6000 characters`,l.USAGE);o={...e===void 0?{}:{content:e},...r.title===void 0?{}:{title:r.title},...r.imageUrl?.length?{image_urls:r.imageUrl}:{}}}let s={pipelineId:r.indexId,...r.docId?{dataId:r.docId}:{},field:o},c=T(i,h.chunkCreate);if(t.dryRun){O({endpoint:c,request:s},a);return}let u=await e.client.requestJson({path:c,method:`POST`,body:s});if(!t.quiet){if(a===`text`){D(`chunk created (pipeline: ${r.indexId})`),D(`List chunks to find the new chunk id.`);return}O(u,a)}}});const kf={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},docId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Only show chunks belonging to this document`,"zh-CN":`仅显示属于该文档的 Chunk`}},...od,...L};var Af=S({description:{"en-US":`List chunks in a knowledge base with content and status`,"zh-CN":`列出知识库中的 Chunk 及其内容和状态`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:kf,notes:[{"en-US":`Use metadata._id as the chunk id and metadata.doc_id as the document id in chunk update/delete commands.`,"zh-CN":`在 Chunk 更新/删除命令中,使用 metadata._id 作为 Chunk ID,使用 metadata.doc_id 作为文档 ID。`},{"en-US":`Page size defaults to 20 (server default), max 100.`,"zh-CN":`分页大小默认为 20(服务端默认值),最大为 100。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --doc-id file-xxx --page-size 50`],validate(e){if(e.pageSize!==void 0&&(e.pageSize<1||e.pageSize>100))return`--page-size must be between 1 and 100`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={indexId:n.indexId,pageNum:n.pageNumber??1,pageSize:n.pageSize??20,...n.docId?{docId:n.docId}:{}},o=T(r,h.chunkList);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.nodes??[];if(t.quiet){for(let e of c)D(e.metadata?._id??``);return}if(i===`text`){if(c.length===0)D(`No chunks found.`);else for(let e of c){let t=e.metadata??{},n=t._chunk_status_message?` status: ${t._chunk_status_message}`:``,r=t.is_displayed_chunk_content===!1?` [excluded from retrieval]`:``;D(`[chunk] ${t._id??`?`} (doc: ${t.doc_name??`?`}, doc_id: ${t.doc_id??`?`})${n}${r}`);let i=t.content??e.text??``;D(` ${i.length>200?`${i.slice(0,200)}…`:i}`)}D(`total: ${s.data?.total??c.length}`)}else O(s,i)}});const jf={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},chunkId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Chunk ID (metadata._id from the chunk list output)`,"zh-CN":`Chunk ID(来自 Chunk 列表输出的 metadata._id)`},required:!0},docId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Document ID owning the chunk (metadata.doc_id from the chunk list output)`,"zh-CN":`Chunk 所属文档 ID(来自 Chunk 列表输出的 metadata.doc_id)`},required:!0},content:{type:`string`,valueHint:`<text>`,description:{"en-US":`New chunk content, 10-6000 chars; alternative to --content-file`,"zh-CN":`新的 Chunk 内容,10–6000 个字符;与 --content-file 二选一`}},contentFile:{type:`string`,valueHint:`<path>`,description:{"en-US":`Read new content from a UTF-8 plain text file (.md/.txt etc.)`,"zh-CN":`从 UTF-8 纯文本文件(.md/.txt 等)读取新内容`}},title:{type:`string`,valueHint:`<text>`,description:{"en-US":`Chunk title, 0-50 chars (empty string clears it; omit to keep unchanged)`,"zh-CN":`Chunk 标题,0–50 个字符(空字符串表示清除;省略则保持不变)`}},exclude:{type:`switch`,description:{"en-US":`Exclude this chunk from retrieval`,"zh-CN":`在检索中排除该 Chunk`}},include:{type:`switch`,description:{"en-US":`Include this chunk in retrieval (default)`,"zh-CN":`在检索中包含该 Chunk(默认)`}},...L};async function Mf(e,t,r,i,a){for(let n=1;n<=10;n++){let o=(await e.requestJson({path:T(t,h.chunkList),method:`POST`,body:{indexId:r,docId:a,pageNum:n,pageSize:100}})).data?.nodes??[],s=o.find(e=>e.metadata?._id===i),c=s?.metadata?.content??s?.text;if(typeof c==`string`)return c;if(o.length<100)break}throw new n(`Chunk not found: ${i}`,l.GENERAL,`Check the chunk id via the chunk list command.`)}var Nf=S({description:{"en-US":`Update chunk content or toggle its retrieval visibility`,"zh-CN":`更新 Chunk 内容或切换其检索可见性`},auth:`apiKey`,usageArgs:`--index-id <id> --chunk-id <id> --doc-id <id> [flags]`,flags:jf,notes:[{"en-US":`Content must be 10-6000 characters and within the knowledge base's max chunk size.`,"zh-CN":`内容必须为 10–6000 个字符,且不能超过知识库的最大 Chunk 大小。`},{"en-US":`--content-file expects a UTF-8 plain text file; document formats (.docx/.pdf) are not parsed here.`,"zh-CN":`--content-file 需要 UTF-8 纯文本文件;此处不会解析 .docx/.pdf 等文档格式。`},{"en-US":`Toggling --exclude/--include without new content re-submits the existing content automatically.`,"zh-CN":`仅切换 --exclude/--include 而不提供新内容时,会自动重新提交现有内容。`}],exampleArgs:[{"en-US":`--index-id idx-xxx --chunk-id chunk-xxx --doc-id file-xxx --content "corrected text"`,"zh-CN":`--index-id idx-xxx --chunk-id chunk-xxx --doc-id file-xxx --content "修正后的文本"`},`--index-id idx-xxx --chunk-id chunk-xxx --doc-id file-xxx --exclude`],validate(e){if(e.content!==void 0&&e.contentFile!==void 0)return`Use either --content or --content-file, not both`;if(e.exclude&&e.include)return`--exclude and --include are mutually exclusive`;if(e.content===void 0&&e.contentFile===void 0&&!e.exclude&&!e.include&&e.title===void 0)return`Nothing to update — pass --content/--content-file, --title, --exclude or --include`;if(e.content!==void 0&&(e.content.length<10||e.content.length>6e3))return`--content must be 10-6000 characters`;if(e.title!==void 0&&e.title.length>50)return`--title must be at most 50 characters`},async run(e){let{settings:t,flags:r}=e,i=R(e),a=C(t.output),o=r.contentFile===void 0?r.content:Hd(r.contentFile,`--content`);if(o!==void 0&&(o.length<10||o.length>6e3))throw new n(`Chunk content must be 10-6000 characters`,l.USAGE);o===void 0&&(o=t.dryRun?`<current-content (fetched at run time)>`:await Mf(e.client,i,r.indexId,r.chunkId,r.docId));let s={pipelineId:r.indexId,chunkId:r.chunkId,dataId:r.docId,content:o,isDisplayedChunkContent:!r.exclude,...r.title===void 0?{}:{title:r.title}},c=T(i,h.chunkUpdate);if(t.dryRun){O({endpoint:c,request:s},a);return}let u=await e.client.requestJson({path:c,method:`POST`,body:s});if(!t.quiet){if(a===`text`){D(`updated: ${r.chunkId}`);return}O(u,a)}}});const Pf={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},chunkId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Chunk ID to delete (repeatable; batches of 10 are sent automatically)`,"zh-CN":`要删除的 Chunk ID(可重复;每 10 个自动分批发送)`},required:!0},...L};function Ff(e,t=10){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}var If=S({description:{"en-US":`Delete chunks from a knowledge base (irreversible)`,"zh-CN":`从知识库中删除 Chunk(不可撤销)`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the selected chunks and cannot be undone.`,"zh-CN":`该操作会永久删除所选 Chunk,且无法撤销。`}},usageArgs:`--index-id <id> --chunk-id <id> [flags]`,flags:Pf,notes:[{"en-US":`Accepts at most 10 chunk ids per call; larger sets are batched automatically.`,"zh-CN":`每次调用最多接受 10 个 Chunk ID;更多 ID 会自动分批处理。`}],exampleArgs:[`--index-id idx-xxx --chunk-id chunk-a --chunk-id chunk-b --workspace-id ws-xxx`,`--index-id idx-xxx --chunk-id chunk-a --yes`],async run(e){let{settings:t,flags:r}=e,i=R(e),a=C(t.output),o=Ff(r.chunkId),s=T(i,h.chunkDelete);if(t.dryRun){O({endpoint:s,batches:o.map(e=>({request:{pipelineId:r.indexId,chunkIds:e}}))},a);return}let c=0;for(let t of o)try{await e.client.requestJson({path:s,method:`POST`,body:{pipelineId:r.indexId,chunkIds:t}}),c+=t.length}catch(e){throw c>0&&e instanceof n&&!e.hint?new n(e.message,e.exitCode,`${c} chunk(s) in earlier batches were already deleted.`,{cause:e,api:e.api,rawResponse:e.rawResponse}):e}if(!t.quiet){if(a===`text`){D(`deleted: ${c} chunk(s) in ${o.length} batch(es)`);return}O({deleted_count:c,batches:o.length},a)}}});const Lf={indexId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Knowledge base ID`,"zh-CN":`知识库 ID`},required:!0},start:{type:`string`,valueHint:`<time>`,description:{"en-US":`Range start: Unix seconds or ISO date, must be in the past (default: 24 hours ago)`,"zh-CN":`范围开始时间:Unix 秒或 ISO 日期,必须是过去时间(默认:24 小时前)`}},end:{type:`string`,valueHint:`<time>`,description:{"en-US":`Range end: Unix seconds or ISO date, must be in the past (default: now)`,"zh-CN":`范围结束时间:Unix 秒或 ISO 日期,必须是过去时间(默认:当前时间)`}},...L};function Rf(e){if(/^\d+$/.test(e))return e.length>=13?String(Math.floor(Number(e)/1e3)):e;let t=/^\d{4}-\d{2}-\d{2}([T ].*)?$/.test(e)?Date.parse(e):NaN;if(Number.isNaN(t))throw new n(`Invalid time value: ${e}`,l.USAGE,`Pass Unix seconds (e.g. 1780900000) or an ISO date (e.g. 2026-07-30T00:00:00Z).`);return String(Math.floor(t/1e3))}var zf=S({description:{"en-US":`Show knowledge base storage and QPS monitoring data`,"zh-CN":`查看知识库存储和 QPS 监控数据`},auth:`apiKey`,usageArgs:`--index-id <id> [flags]`,flags:Lf,notes:[{"en-US":`Defaults to the last 24 hours when --start/--end are omitted.`,"zh-CN":`省略 --start/--end 时,默认查询最近 24 小时。`},{"en-US":`Timestamps are normalized to epoch seconds as required by the server.`,"zh-CN":`时间戳会按服务端要求归一化为 Epoch 秒。`},{"en-US":`Future timestamps are rejected for --start and clamped to now for --end, since the monitor API only returns past data.`,"zh-CN":`监控 API 只返回历史数据,因此未来的 --start 会被拒绝,未来的 --end 会被截断为当前时间。`}],exampleArgs:[`--index-id idx-xxx --workspace-id ws-xxx`,`--index-id idx-xxx --start 2026-07-30 --end 2026-07-31`],async run(e){let{settings:t,flags:r}=e,i=R(e),a=C(t.output),o=Math.floor(Date.now()/1e3),s=r.start?Rf(r.start):String(o-86400),c=r.end?Rf(r.end):String(o);if(Number(s)>o)throw new n(`Start time is in the future; the monitor API only accepts past or current timestamps.`,l.USAGE,`Use a start date/time at or before now, or omit --start to default to 24 hours ago.`);let u=Number(c)>o;u&&(c=String(o));let d={indexId:r.indexId,startTimestamp:s,endTimestamp:c},f=T(i,h.indexMonitor);if(t.dryRun){O({endpoint:f,request:d},a);return}let p=await e.client.requestJson({path:f,method:`POST`,body:d});if(a!==`text`){O(p,a);return}u&&D(`note: end time was in the future, clamped to now.`);let m=p.data?.storageMonitorData,g=p.data?.qpsMonitorData;D(`plan: ${p.data?.pipelineCommercialType??`-`}`),D(`storage: ${m?.indexStorageUsage??`-`} / ${m?.indexStorageLimit??`-`}`),D(`peak qps: ${g?.peakQps??`-`}`),D(`qps windows: ${g?.monitorData?.length??0} data point(s)`)}});const Bf={collectionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by exact collection ID`,"zh-CN":`按数据集合 ID 精确筛选`}},parentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`List sub-categories of this exact parent category`,"zh-CN":`列出该父类目下的子类目`}},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by category name (exact match, unlike the knowledge base list)`,"zh-CN":`按类目名称筛选(精确匹配,与知识库列表不同)`}},nextToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Cursor for the next page (from previous output)`,"zh-CN":`下一页游标(来自上一次输出)`}},maxResult:{type:`number`,valueHint:`<n>`,description:{"en-US":`Items per page (default: 20)`,"zh-CN":`每页条目数(默认:20)`}},...L};var Vf=S({description:{"en-US":`List data-center categories`,"zh-CN":`列出数据中心类目`},auth:`apiKey`,usageArgs:`[flags]`,flags:Bf,notes:[{"en-US":`Categories marked [default] are where files land when no category is specified.`,"zh-CN":`未指定类目时,文件会进入标记为 [default] 的类目。`},{"en-US":`Pagination is cursor-based: reuse the printed next token to continue.`,"zh-CN":`分页使用游标:复用输出中的 next token 继续查询。`}],exampleArgs:[`--workspace-id ws-xxx`,`--name my-category`,`--next-token <token>`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={type:`UNSTRUCTURED`,...n.collectionId?{connectorId:n.collectionId}:{},...n.parentId?{parentId:n.parentId}:{},...n.name?{categoryName:n.name}:{},...n.nextToken?{nextToken:n.nextToken}:{},...n.maxResult===void 0?{}:{maxResult:n.maxResult}},o=T(r,h.listCategory);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.categoryList??[];if(t.quiet){for(let e of c)D(e.categoryId??``);return}if(i===`text`){if(c.length===0)D(`No categories found.`);else for(let e of c){let t=e.isDefault?` [default]`:``;D(sd(`${e.categoryId} ${e.categoryName}${t}`))}let e=s.data?.nextToken;e&&D(`next: --next-token ${e}`)}else O(s,i)}});const Hf={name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Category name (1-20 chars)`,"zh-CN":`类目名称(1–20 个字符)`},required:!0},parentId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Create as a sub-category of this category`,"zh-CN":`创建为该类目的子类目`}},collectionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Create under this collection (defaults to the platform collection)`,"zh-CN":`在该数据集合下创建(默认为平台数据集合)`}},...L};var Uf=S({description:{"en-US":`Create a data-center category`,"zh-CN":`创建数据中心类目`},auth:`apiKey`,usageArgs:`--name <text> [flags]`,flags:Hf,notes:[{"en-US":`Use categories to organize data-center files by business domain.`,"zh-CN":`使用类目按业务领域组织数据中心文件。`}],exampleArgs:[`--name product-docs --workspace-id ws-xxx`,`--name sub --parent-id cate-xxx`],validate(e){if(e.name.length<1||e.name.length>20)return`--name must be 1-20 characters`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={categoryName:n.name,categoryType:`UNSTRUCTURED`,...n.parentId?{parentCategoryId:n.parentId}:{},...n.collectionId?{connectorId:n.collectionId}:{}},o=T(r,h.addCategory);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.categoryId;if(t.quiet){D(c??``);return}if(i===`text`){D(`created: ${c??`-`} (${n.name})`);return}O(s,i)}});const Wf={categoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Category ID to delete`,"zh-CN":`要删除的类目 ID`},required:!0},...L};var Gf=S({description:{"en-US":`Delete a data-center category`,"zh-CN":`删除数据中心类目`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This deletes the selected data-center category and cannot be undone.`,"zh-CN":`该操作会删除所选数据中心类目,且无法撤销。`}},usageArgs:`--category-id <id> [flags]`,flags:Wf,notes:[{"en-US":`Behavior for categories containing files or sub-categories is server-defined — the server error is passed through as-is.`,"zh-CN":`包含文件或子类目时的处理行为由服务端定义——服务端返回的错误将原样透传。`}],exampleArgs:[`--category-id cate-xxx --workspace-id ws-xxx`,`--category-id cate-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={categoryId:n.categoryId},o=T(r,h.deleteCategory);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){D(`deleted: ${n.categoryId}`);return}O(s,i)}}});const Kf={categoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Category to list (find ids via the category list command); exact match`,"zh-CN":`要列出文件的类目(通过类目列表命令查找 ID);精确匹配`},required:!0},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by exact file name without its extension (a.md → pass a)`,"zh-CN":`按不含扩展名的文件名精确筛选(a.md 应传入 a)`}},fileId:{type:`array`,valueHint:`<id>`,description:{"en-US":`Filter by exact file ID (repeatable)`,"zh-CN":`按文件 ID 精确筛选(可重复)`}},nextToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Cursor for the next page (from previous output)`,"zh-CN":`下一页游标(来自上一次输出)`}},maxResult:{type:`number`,valueHint:`<n>`,description:{"en-US":`Items per page`,"zh-CN":`每页条目数`}},...L};var qf=S({description:{"en-US":`List files in a data-center category`,"zh-CN":`列出数据中心类目中的文件`},auth:`apiKey`,usageArgs:`--category-id <id> [flags]`,flags:Kf,notes:[{"en-US":`A real category id is required — the default value is not resolved here. Find the id via the category list command.`,"zh-CN":`必须提供真实的类目 ID——此处不会解析 default 值。请通过类目列表命令查找 ID。`},{"en-US":`--name matches the exact file name without its extension (for a.md pass a); partial keywords return no results.`,"zh-CN":`--name 精确匹配不含扩展名的文件名(a.md 应传入 a);部分关键字不会返回结果。`},{"en-US":`Pagination is cursor-based: reuse the printed next token to continue.`,"zh-CN":`分页使用游标:复用输出中的 next token 继续查询。`}],exampleArgs:[`--category-id cate-xxx --workspace-id ws-xxx`,{"en-US":`--category-id cate-xxx --name report`,"zh-CN":`--category-id cate-xxx --name 报告`}],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={categoryId:n.categoryId,...n.name?{fileName:n.name}:{},...n.fileId?.length?{fileIds:n.fileId}:{},...n.nextToken?{nextToken:n.nextToken}:{},...n.maxResult===void 0?{}:{maxResult:n.maxResult}},o=T(r,h.listFile);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.fileList??[];if(t.quiet){for(let e of c)D(e.fileId??``);return}if(i===`text`){if(c.length===0)D(`No files found.`);else for(let e of c)D(sd([e.fileId,e.status??`-`,e.fileName,e.sizeBytes??`-`].join(` `)));let e=s.data?.nextToken;e&&D(`next: --next-token ${e}`)}else O(s,i)}});const Jf={fileId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Data-center file ID`,"zh-CN":`数据中心文件 ID`},required:!0},...L};var Yf=S({description:{"en-US":`Show data-center file details (size, MD5, tags, timestamps)`,"zh-CN":`查看数据中心文件详情(大小、MD5、标签、时间戳)`},auth:`apiKey`,usageArgs:`--file-id <id> [flags]`,flags:Jf,exampleArgs:[`--file-id file-xxx --workspace-id ws-xxx`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={fileId:n.fileId},o=T(r,h.describeFile);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data;if(t.quiet){D(c?.fileId??``);return}if(i!==`text`){O(s,i);return}D(`id: ${c?.fileId??`-`}`),D(`name: ${c?.fileName??`-`}`),D(`type: ${c?.fileType??`-`}`),D(`size: ${c?.sizeBytes??`-`}`),D(`status: ${c?.status??`-`}`),D(`parser: ${c?.parser??`-`}`),D(`category: ${c?.category??`-`}`),D(`uploaded: ${c?.uploadTime??`-`}`);let l=Array.isArray(c?.tags)?c.tags.join(`, `):c?.tags??`-`;D(`tags: ${l||`-`}`)}});const Xf={fileId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Data-center file ID to delete`,"zh-CN":`要删除的数据中心文件 ID`},required:!0},...L};var Zf=S({description:{"en-US":`Permanently delete a file from the data center`,"zh-CN":`从数据中心永久删除文件`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the data-center file. Knowledge-base document indexes that reference it may become invalid.`,"zh-CN":`该操作会永久删除数据中心文件;引用该文件的知识库文档索引可能失效。`}},usageArgs:`--file-id <id> [flags]`,flags:Xf,notes:[{"en-US":`Irreversible. If knowledge bases reference this file, their related document indexes become invalid.`,"zh-CN":`该操作不可撤销。如果知识库引用了此文件,其相关文档索引将失效。`},{"en-US":`To remove a document from a single knowledge base only, use the document delete command instead.`,"zh-CN":`如果只需从单个知识库中移除文档,请改用文档删除命令。`}],exampleArgs:[`--file-id file-xxx --workspace-id ws-xxx`,`--file-id file-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={fileId:n.fileId},o=T(r,h.deleteFile);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a});if(!t.quiet){if(i===`text`){D(`deleted: ${n.fileId}`);return}O(s,i)}}});const Qf={name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Collection name`,"zh-CN":`数据集合名称`},required:!0},description:{type:`string`,valueHint:`<text>`,description:{"en-US":`What this collection holds and what it is for — tells collections apart in the list`,"zh-CN":`数据集合装了什么内容、给谁用,用于在列表中区分同类集合`},required:!0},storeType:{type:`string`,valueHint:`<type>`,description:{"en-US":`Storage: platform (managed) or custom (your own OSS bucket)`,"zh-CN":`存储类型:platform(托管)或 custom(自有 OSS Bucket)`}},ossRegion:{type:`string`,valueHint:`<id>`,description:{"en-US":`OSS region id (required with --store-type custom)`,"zh-CN":`OSS Region ID(使用 --store-type custom 时必填)`}},ossBucket:{type:`string`,valueHint:`<name>`,description:{"en-US":`OSS bucket name (required with --store-type custom)`,"zh-CN":`OSS Bucket 名称(使用 --store-type custom 时必填)`}},...L};var $f=S({description:{"en-US":`Create a FILE data collection`,"zh-CN":`创建 FILE 数据集合`},auth:`apiKey`,usageArgs:`--name <text> --description <text> [flags]`,flags:Qf,notes:[{"en-US":`Store type defaults to platform (managed storage); custom uses your authorized OSS bucket.`,"zh-CN":`存储类型默认为 platform(托管存储);custom 使用已授权的自有 OSS Bucket。`},{"en-US":`Custom buckets must carry the bucket tag bailian-connector-access=ReadAndWrite (Bailian's tag-based access control); without it the server rejects creation with a misleading 'setBucketCORS failed' error.`,"zh-CN":`自定义 Bucket 必须带有 bailian-connector-access=ReadAndWrite 标签(百炼基于标签的访问控制);缺少该标签时,服务端会以容易误解的 'setBucketCORS failed' 错误拒绝创建。`},{"en-US":`There is no collection delete API — create collections deliberately.`,"zh-CN":`目前没有删除数据集合的 API——请谨慎创建。`}],exampleArgs:[{"en-US":`--name my-collection --description 'team docs' --workspace-id ws-xxx`,"zh-CN":`--name my-collection --description '团队文档' --workspace-id ws-xxx`},{"en-US":`--name oss-coll --description 'own bucket' --store-type custom --oss-region cn-beijing --oss-bucket my-bucket`,"zh-CN":`--name oss-coll --description '自有 Bucket' --store-type custom --oss-region cn-beijing --oss-bucket my-bucket`}],validate(e){if(e.name.length<1||e.name.length>20)return`--name must be 1-20 characters`;let t=e.storeType??`platform`;if(t!==`platform`&&t!==`custom`)return`--store-type must be platform or custom`;if(t===`custom`&&(!e.ossRegion||!e.ossBucket))return`--store-type custom requires --oss-region and --oss-bucket`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a=(n.storeType??`platform`).toUpperCase(),o={connectorType:`FILE`,connectorName:n.name,description:n.description,fileConnectorConfig:{storeType:a,...a===`CUSTOM`?{regionId:n.ossRegion,bucketName:n.ossBucket}:{}}},s=T(r,h.addConnector);if(t.dryRun){O({endpoint:s,request:o},i);return}let c=await e.client.requestJson({path:s,method:`POST`,body:o}),l=c.data?.connectorId;if(t.quiet){D(l??``);return}if(i===`text`){D(`created: ${l??`-`} (${n.name}, ${a})`);return}O(c,i)}});const ep={collectionId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Collection ID; alternative to --name`,"zh-CN":`数据集合 ID;与 --name 二选一`}},name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Collection name; alternative to --collection-id`,"zh-CN":`数据集合名称;与 --collection-id 二选一`}},...L};var tp=S({description:{"en-US":`Show data collection details`,"zh-CN":`查看数据集合详情`},auth:`apiKey`,usageArgs:`(--collection-id <id> | --name <text>) [flags]`,flags:ep,exampleArgs:[`--collection-id conn-xxx --workspace-id ws-xxx`,`--name my-collection`],validate(e){if(!e.collectionId&&!e.name)return`Pass --collection-id or --name`;if(e.collectionId&&e.name)return`Use either --collection-id or --name, not both`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={...n.collectionId?{connectorId:n.collectionId}:{},...n.name?{connectorName:n.name}:{}},o=T(r,h.getConnector);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data;if(t.quiet){D(c?.connectorId??``);return}if(i===`text`){D(`id: ${c?.connectorId??`-`}`),D(`name: ${c?.connectorName??`-`}`),D(`description: ${c?.description??`-`}`);return}O(s,i)}});const np={bucket:{type:`string`,valueHint:`<name>`,description:{"en-US":`Authorized OSS bucket name`,"zh-CN":`已授权的 OSS Bucket 名称`},required:!0},region:{type:`string`,valueHint:`<id>`,description:{"en-US":`OSS region id (e.g. cn-beijing)`,"zh-CN":`OSS Region ID(例如 cn-beijing)`},required:!0},ossKey:{type:`array`,valueHint:`<key>`,description:{"en-US":`OSS object key to import (repeatable, 1-10 per call)`,"zh-CN":`要导入的 OSS Object Key(可重复,每次调用 1–10 个)`},required:!0},categoryId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Target data-center category (default: the default category)`,"zh-CN":`目标数据中心类目(默认:默认类目)`}},tag:{type:`array`,valueHint:`<text>`,description:{"en-US":`File tag applied to every imported file (repeatable, up to 10)`,"zh-CN":`应用于每个导入文件的标签(可重复,最多 10 个)`}},overwrite:{type:`switch`,description:{"en-US":`Overwrite files previously imported from the same OSS keys`,"zh-CN":`覆盖此前从相同 OSS Key 导入的文件`}},...L};var rp=S({description:{"en-US":`Batch import files from an authorized OSS bucket into the data center`,"zh-CN":`从已授权的 OSS Bucket 批量导入文件到数据中心`},auth:`apiKey`,usageArgs:`--bucket <name> --region <id> --oss-key <key> [flags]`,flags:np,notes:[{"en-US":`The bucket must be authorized to the platform service role beforehand; permission errors from the server are passed through with a pointer to check AliyunServiceRoleForBailian in the RAM console.`,"zh-CN":`必须预先将 Bucket 授权给平台服务角色;服务端权限错误将原样透传,并提示在 RAM 控制台检查 AliyunServiceRoleForBailian。`},{"en-US":`File names are derived from the OSS key basename.`,"zh-CN":`文件名取自 OSS Key 的 basename。`},{"en-US":`--overwrite replaces the previously imported file and issues a NEW fileId (the old one becomes invalid) — verified live.`,"zh-CN":`--overwrite 会替换此前导入的文件并生成新的 fileId(旧 fileId 将失效)——已通过真实环境验证。`}],exampleArgs:[`--bucket my-bucket --region cn-beijing --oss-key docs/a.pdf --workspace-id ws-xxx`,`--bucket my-bucket --region cn-beijing --oss-key docs/a.pdf --oss-key docs/b.docx --overwrite`],validate(e){if(e.ossKey.length>10)return`--oss-key accepts at most 10 entries per call`;if(e.tag!==void 0&&e.tag.length>10)return`--tag accepts at most 10 entries`},async run(e){let{settings:t,flags:n}=e,r=R(e),i=C(t.output),a={categoryId:n.categoryId??`default`,categoryType:`UNSTRUCTURED`,ossBucket:n.bucket,ossRegionId:n.region,fileDetails:n.ossKey.map(e=>({fileName:ui(e),ossKey:e})),...n.tag?.length?{tags:n.tag}:{},...n.overwrite?{overWriteFileByOssKey:!0}:{}},o=T(r,h.addFilesFromAuthorizedOss);if(t.dryRun){O({endpoint:o,request:a},i);return}let s=await e.client.requestJson({path:o,method:`POST`,body:a}),c=s.data?.addFileResultList??[],l=c.map(e=>e.fileId).filter(e=>!!e);if(t.quiet){for(let e of l)D(e);return}if(i===`text`){D(`imported: ${l.length} file(s)`);for(let e of c)D(` ${e.fileId??`-`} ${e.status??`-`} ${e.ossKey??``}`);return}O(s,i)}});function ip(e){if(!(e instanceof n))return!1;let t=e.message;return/^MCP request failed:\s*404\b/i.test(t)?/未开通|MCP不存在|MCP_IS_INVALID/i.test(t):!1}function ap(e){let t=[`Activate (or re-activate) the ${e} MCP in the Bailian MCP marketplace, then retry.`];return e===`WebSearch`&&t.push(`If it was previously on SSE, cancel and activate again to upgrade to Streamable HTTP.`),t.push(`Open: ${Er(e)}`),t.join(`
|
|
2738
|
+
`)}function op(e,t){throw!(e instanceof n)||e.hint?e:ip(e)||t===`WebSearch`&&xt(e)?new n(e.message,e.exitCode,ap(t),{cause:e,api:e.api,rawResponse:e.rawResponse}):e}const sp={target:{type:`string`,valueHint:`<server.tool>`,description:{"en-US":`Server code and tool name joined by a dot, e.g. market-cmapi00073529.SmartStockSelection`,"zh-CN":`由点号连接的 Server Code 和工具名称,例如 market-cmapi00073529.SmartStockSelection`},required:!0},arg:{type:`array`,valueHint:`<kv>`,description:{"en-US":`Tool argument (repeatable). Values parsed as JSON if possible, else string.`,"zh-CN":`工具参数(可重复)。值会优先按 JSON 解析,否则作为字符串。`}},json:{type:`string`,valueHint:`<obj>`,description:{"en-US":`Full arguments object as JSON; merged with --arg (arg wins).`,"zh-CN":`完整的 JSON 参数对象;与 --arg 合并(--arg 优先)。`}},query:{type:`string`,valueHint:`<text>`,description:{"en-US":`Shortcut for --arg query=<text> (mirrors many DashScope MCP tools).`,"zh-CN":`--arg query=<text> 的快捷方式(与许多 DashScope MCP 工具一致)。`}},url:{type:`string`,valueHint:`<url>`,description:{"en-US":`Override the MCP endpoint URL (non-Bailian). Tries Streamable HTTP first, then classic SSE on the same URL.`,"zh-CN":`覆盖 MCP Endpoint URL(非百炼)。先尝试 Streamable HTTP,再在同一 URL 上回退到传统 SSE。`}}};function cp(e){let t=e.indexOf(`.`);if(t<=0||t===e.length-1)throw new x(`target must be <server-code>.<tool>, got "${e}".`);return{serverCode:e.slice(0,t),toolName:e.slice(t+1)}}function lp(e){let t={};for(let n of e){let e=n.indexOf(`=`);if(e<=0)throw new x(`--arg must be in K=V form, got: ${n}`);let r=n.slice(0,e).trim(),i=n.slice(e+1);try{t[r]=JSON.parse(i)}catch{t[r]=i}}return t}function up(e){let t;try{t=JSON.parse(e)}catch(e){throw new x(`--json is not valid JSON — ${e.message}`)}if(!t||typeof t!=`object`||Array.isArray(t))throw new x(`--json must decode to an object.`);return t}function dp(e){let t=e.json?up(e.json):{};return Object.assign(t,lp(e.arg??[])),e.query!==void 0&&(t.query=e.query),t}function fp(e){try{cp(e.target),dp(e)}catch(e){if(e instanceof x)return e.message;throw e}}var pp=S({description:{"en-US":`Call a tool on an MCP server (tools/call)`,"zh-CN":`调用 MCP 服务器上的工具(tools/call)`},auth:`apiKey`,usageArgs:`--target <server.tool> [--arg k=v ...] [--json '{...}'] [--url <url>]`,flags:sp,exampleArgs:[{"en-US":`--target market-cmapi00073529.SmartStockSelection --query "Screen consumer stocks with ROE > 15%"`,"zh-CN":`--target market-cmapi00073529.SmartStockSelection --query "筛选 ROE 大于 15% 的消费股"`},{"en-US":`--target market-cmapi00073529.FinQuery --json '{"q":"Guizhou Maotai","limit":5}'`,"zh-CN":`--target market-cmapi00073529.FinQuery --json '{"q":"贵州茅台","limit":5}'`},`--target market-cmapi00073529.SmartFundSelection --arg riskLevel=R3 --arg minScale=10`],validate:fp,async run(e){let{settings:t,flags:r}=e,{serverCode:i,toolName:a}=cp(r.target),o=dp(r),s=r.url||e.client.url(oe(i)),c=C(t.output);if(t.dryRun){O({server:i,url:s,tool:a,arguments:o},c);return}let l;try{let t=await e.client.connectBailianMcp(i,r.url);l=t.client;let s=await t.client.callTool(a,o);if(s.isError){let e=s.content.map(e=>e.text||``).join(`
|
|
2739
|
+
`);throw new n(`Tool error: ${e}`)}O(s,c)}catch(e){throw r.url||op(e,i),e}finally{l?.close?.()}}});const mp=[...Js,`all`],hp={server:{type:`string`,valueHint:`<code>`,description:{"en-US":`Bailian MCP Server Code, such as TextGenerateImage`,"zh-CN":`百炼 MCP Server Code,例如 TextGenerateImage`},required:!0},transport:{type:`string`,valueHint:`<transport>`,choices:[`streamable-http`,`sse`],description:{"en-US":`MCP transport exposed by the server: streamable-http or sse`,"zh-CN":`服务端提供的 MCP 传输协议:streamable-http 或 sse`},required:!0},agent:{type:`string`,valueHint:`<agent>`,choices:mp,description:{"en-US":`Target Agent: ${mp.join(`, `)}`,"zh-CN":`目标 Agent:${mp.join(`, `)}`},required:!0}};var gp=S({description:{"en-US":`Register a Bailian MCP server in an Agent's native configuration`,"zh-CN":`将百炼 MCP 服务注册到 Agent 的原生配置中`},auth:`apiKey`,usageArgs:`--server <code> --transport <streamable-http|sse> --agent <agent|all>`,flags:hp,notes:[{"en-US":`This release registers the official China-site MCP endpoint; the model API --base-url does not change the MCP endpoint.`,"zh-CN":`本期固定注册中国站官方 MCP 地址;模型 API 的 --base-url 不会改变 MCP 地址。`},{"en-US":`The resolved API key is written to the selected Agent's private local configuration. Existing unmanaged entries are never overwritten.`,"zh-CN":`解析出的 API Key 会写入所选 Agent 的本地私有配置;CLI 不会覆盖非其管理的同名条目。`},{"en-US":`qoder, qoderwork, and qwenwork are independent products. qwenwork is QwenWork (千问办公); qoderwork is Qoder Work.`,"zh-CN":`qoder、qoderwork、qwenwork 是彼此独立的产品。qwenwork 是千问办公(QwenWork);qoderwork 是 Qoder Work。`},{"en-US":`workbuddy covers CodeBuddy / WorkBuddy. deepseek-harness is DeepSeek Harness and only accepts streamable-http.`,"zh-CN":`workbuddy 覆盖 CodeBuddy / WorkBuddy。deepseek-harness 是 DeepSeek Harness,仅支持 streamable-http。`}],exampleArgs:[`--server TextGenerateImage --transport streamable-http --agent cursor`,`--server VideoGenerate --transport sse --agent claude-code`,`--server TextGenerateImage --transport streamable-http --agent all`],async run(e){let{flags:t,settings:r}=e,i=t.transport,a=t.agent,o=Fc(a,hi());if(o.length===0)throw new n(`No supported installed Agent was found for --agent all.`,l.USAGE);let s=i===`sse`?se(t.server):oe(t.server),c=`${g.cn}${s}`,u=Wn(e.identity),d=[`Authorization`,...Object.keys(u)],f=C(r.output);if(r.dryRun){O({server:t.server,transport:i,endpoint:c,agents:o,header_names:d},f);return}let p=Ic({agents:o,spec:{name:t.server,serverCode:t.server,transport:i,endpoint:c,headers:e.client.bailianMcpRegistrationHeaders()},cliVersion:e.identity.version,home:hi(),configDir:rt()});O({server:t.server,transport:i,endpoint:c,results:p},f)}});const _p=[...Js,`all`],vp={server:{type:`string`,valueHint:`<code>`,description:{"en-US":`Bailian MCP Server Code used during connect`,"zh-CN":`connect 时使用的百炼 MCP Server Code`},required:!0},agent:{type:`string`,valueHint:`<agent>`,choices:_p,description:{"en-US":`Target Agent: ${_p.join(`, `)}`,"zh-CN":`目标 Agent:${_p.join(`, `)}`},required:!0}};var yp=S({description:{"en-US":`Remove an unchanged MCP registration previously managed by bailian-cli`,"zh-CN":`移除此前由 bailian-cli 管理且未被修改的 MCP 注册`},auth:`none`,usageArgs:`--server <code> --agent <agent|all>`,flags:vp,notes:[{"en-US":`A registration changed after connect is left untouched and reported as a conflict.`,"zh-CN":`如果注册项在 connect 后被修改,CLI 会保留该配置并报告冲突。`}],exampleArgs:[`--server TextGenerateImage --agent cursor`,`--server TextGenerateImage --agent all`],async run(e){let{flags:t,settings:r}=e,i=t.agent,a=Fc(i,hi());if(a.length===0)throw new n(`No supported installed Agent was found for --agent all.`,l.USAGE);let o=C(r.output);if(r.dryRun){O({server:t.server,agents:a,action:`disconnect`},o);return}let s=Lc({agents:a,name:t.server,home:hi(),configDir:rt()});O({server:t.server,results:s},o)}});const bp=`zeldaEasy.broadscope-bailian.mcp-server.PageList`;var xp=S({description:{"en-US":`List MCP servers activated under your Bailian account`,"zh-CN":`列出百炼账号下已激活的 MCP 服务器`},auth:`console`,usageArgs:`[flags]`,flags:{name:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by server name (substring match)`,"zh-CN":`按服务器名称筛选(子字符串匹配)`}},type:{type:`string`,valueHint:`<type>`,description:{"en-US":`Server type: OFFICIAL | PRIVATE (default: OFFICIAL)`,"zh-CN":`服务器类型:OFFICIAL | PRIVATE(默认:OFFICIAL)`}},page:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Results per page (default: 30)`,"zh-CN":`每页结果数(默认:30)`}}},exampleArgs:[``,`--name finance`,`--output json`],async run(e){let{settings:t,identity:r,flags:i}=e,a=i.name||``,o=i.type||`OFFICIAL`,s=i.page||1,c=i.pageSize||30,u=C(t.output),d={reqDTO:{type:o,displayTools:!1,activated:1,pageNo:s,pageSize:c,serverName:a}};if(t.dryRun){O({api:bp,data:d,...w(t)},u);return}let f=(await e.client.console(bp,d))?.data??{};if(f.success===!1){let e=f.errorCode??`UnknownError`,t=f.errorMsg??e,i=e===`BailianGateway.Login.NotLogined`?`Run \`${r.binName} auth login --console\` to refresh your console session.`:void 0;throw new n(`Console gateway: ${t}`,l.AUTH,i)}let p=(f.DataV2??{}).data?.data??{},m=p.mcpServerDetailList??[],h=p.total??0,g=m.map(e=>({code:e.serverCode??``,name:e.serverName??``,description:e.description,type:e.type??``,source:e.source,bizType:e.bizType,installType:e.installType,streamable:e.streamable===!0}));O({total:h,servers:g},u)}}),Sp=S({description:{"en-US":`List tools exposed by an MCP server (tools/list)`,"zh-CN":`列出 MCP 服务器提供的工具(tools/list)`},auth:`apiKey`,usageArgs:`--server <code> [--url <url>]`,flags:{server:{type:`string`,valueHint:`<code>`,description:{"en-US":"Server code from `mcp list` (e.g. market-cmapi00073529)","zh-CN":"来自 `mcp list` 的 Server Code(例如 market-cmapi00073529)"},required:!0},url:{type:`string`,valueHint:`<url>`,description:{"en-US":`Override the MCP endpoint URL (non-Bailian). Tries Streamable HTTP first, then classic SSE on the same URL.`,"zh-CN":`覆盖 MCP Endpoint URL(非百炼)。先尝试 Streamable HTTP,再在同一 URL 上回退到传统 SSE。`}}},exampleArgs:[`--server market-cmapi00073529`,`--server market-cmapi00073529 --output json`,`--server my-server --url https://example.com/mcp`],async run(e){let{settings:t,flags:n}=e,r=n.server,i=n.url||e.client.url(oe(r)),a=C(t.output);if(t.dryRun){O({server:r,url:i,action:`tools/list`},a);return}let o;try{let t=await e.client.connectBailianMcp(r,n.url);o=t.client;let i=await t.client.listTools();O({server:r,url:t.url,tools:i},a)}catch(e){throw n.url||op(e,r),e}finally{o?.close?.()}}});function Cp(e){op(e,`WebSearch`)}var wp=S({description:{"en-US":`Search the web using DashScope MCP WebSearch service`,"zh-CN":`使用 DashScope MCP WebSearch 服务搜索互联网`},auth:`apiKey`,usageArgs:`--query <text> [flags]`,flags:{query:{type:`string`,valueHint:`<text>`,description:{"en-US":`Search query text`,"zh-CN":`搜索查询文本`}},count:{type:`number`,valueHint:`<n>`,description:{"en-US":`Number of search results (default: 10)`,"zh-CN":`搜索结果数量(默认:10)`}},listTools:{type:`switch`,description:{"en-US":`List available MCP tools and exit`,"zh-CN":`列出可用的 MCP 工具并退出`}}},exampleArgs:[{"en-US":`--query "Alibaba Cloud Bailian latest features"`,"zh-CN":`--query "阿里云百炼最新功能"`},{"en-US":`--query "TypeScript 5.9 new features" --count 5`,"zh-CN":`--query "TypeScript 5.9 新功能" --count 5`},{"en-US":`--query "Today's news"`,"zh-CN":`--query "今日新闻"`},`--list-tools`],validate:e=>!e.listTools&&!e.query?`Missing required flag: --query`:void 0,async run(e){let{settings:t,flags:r}=e,i=C(t.output);if(r.listTools){if(t.dryRun){O({endpoint:e.client.url(Bt()),action:`tools/list`},i);return}try{let t=e.client.mcp(Bt());await t.initialize();let n=await t.listTools();O({tools:n},i)}catch(e){Cp(e)}return}let a=r.query;if(t.dryRun){O({endpoint:e.client.url(Bt()),action:`tools/call`,tool:`bailian_web_search`,arguments:{query:a,count:r.count||void 0}},i);return}let o=e.client.mcp(Bt()),s=mr(`Initializing search...`);t.quiet||s.start();try{await o.initialize(),t.quiet||s.update(`Searching...`);let e={query:a};r.count&&(e.count=r.count);let c=await o.callTool(`bailian_web_search`,e);if(c.isError){let e=c.content.map(e=>e.text||``).join(`
|
|
2740
|
+
`);throw new n(`Search error: ${e}`)}if(t.quiet||s.stop(`Done.`),i===`json`)O(c,i);else for(let e of c.content)if(e.type===`text`&&e.text)try{let t=JSON.parse(e.text);t.pages&&Array.isArray(t.pages)?O({pages:t.pages,total:t.pages.length},i):O(t,i)}catch{O({text:e.text},i)}}catch(e){s.stop(`Failed.`),Cp(e)}}});const Tp=`${c.cn}/cosyvoice-clone-design-api`,Ep=`${c.cn}/qwen-audio-tts-voice-list`,Dp=[{voice:`longanlingxin`,name:`龙安灵心`,desc:`知心温暖音`,lang:`中文/英文`},{voice:`longanlufeng`,name:`龙安鲁风`,desc:`明亮开朗音`,lang:`中文/英文`}],Op=[{voice:`longanfengyue`,name:`龙安风悦`,desc:`自然亲切音`,lang:`中文/英文`},{voice:`longanyuanfei`,name:`龙安元妃`,desc:`高傲妃子音`,lang:`中文/英文`},{voice:`longanlingxi`,name:`龙安灵希`,desc:`可爱甜美音`,lang:`中文/英文`},{voice:`longanxiaoxin`,name:`龙安小昕`,desc:`亲切活泼音`,lang:`中文/英文`},{voice:`longanhuan_v3.6`,name:`龙安欢`,desc:`欢脱元气女`,lang:`中文/英文`},{voice:`longjielidou_v3.6`,name:`龙杰力豆`,desc:`天真男童`,lang:`中文/英文`},{voice:`longpaopao_v3.6`,name:`龙泡泡`,desc:`软糯可爱音`,lang:`中文/英文`},{voice:`longhuohuo_v3.6`,name:`龙火火`,desc:`顽皮少年音`,lang:`中文/英文`},{voice:`longchuanshu_v3.6`,name:`龙川叔`,desc:`川普大叔音`,lang:`中文/英文`},{voice:`loongmary`,name:`loongmary`,desc:`温暖英音`,lang:`英文`},{voice:`loongeva_v3.6`,name:`loongeva`,desc:`高智美音`,lang:`英文`},{voice:`loongjohn`,name:`loongJohn`,desc:`沉稳亲切美音`,lang:`英文`}],kp=[{voice:`longanyang`,name:`龙安洋`,desc:`阳光大男孩`,lang:`中文/英文`},{voice:`longanhuan_v3`,name:`龙安欢`,desc:`欢脱元气女`,lang:`中文/英文`},{voice:`longantai_v3`,name:`龙安台`,desc:`嗲甜台湾女`,lang:`中文/英文`},{voice:`longhua_v3`,name:`龙华`,desc:`元气甜美女`,lang:`中文/英文`},{voice:`longcheng_v3`,name:`龙橙`,desc:`智慧青年男`,lang:`中文/英文`},{voice:`longze_v3`,name:`龙泽`,desc:`温暖元气男`,lang:`中文/英文`},{voice:`longzhe_v3`,name:`龙哲`,desc:`呆板大暖男`,lang:`中文/英文`},{voice:`longyan_v3`,name:`龙颜`,desc:`温暖春风女`,lang:`中文/英文`},{voice:`longxing_v3`,name:`龙星`,desc:`温婉邻家女`,lang:`中文/英文`},{voice:`longtian_v3`,name:`龙天`,desc:`磁性理智男`,lang:`中文/英文`},{voice:`longwan_v3`,name:`龙婉`,desc:`细腻柔声女`,lang:`中文/英文`},{voice:`longqiang_v3`,name:`龙嫱`,desc:`浪漫风情女`,lang:`中文/英文`},{voice:`longfeifei_v3`,name:`龙菲菲`,desc:`甜美娇气女`,lang:`中文/英文`},{voice:`longhao_v3`,name:`龙浩`,desc:`多情忧郁男`,lang:`中文/英文`},{voice:`longanrou_v3`,name:`龙安柔`,desc:`温柔娴静女`,lang:`中文/英文`},{voice:`longxiaochun_v3`,name:`龙小淳`,desc:`知性积极女`,lang:`中文/英文`},{voice:`longxiaoxia_v3`,name:`龙小夏`,desc:`沉稳权威女`,lang:`中文/英文`},{voice:`longyumi_v3`,name:`YUMI`,desc:`正经青年女`,lang:`中文/英文`},{voice:`longanyun_v3`,name:`龙安昀`,desc:`居家暖男`,lang:`中文/英文`},{voice:`longanwen_v3`,name:`龙安温`,desc:`优雅知性女`,lang:`中文/英文`},{voice:`longanli_v3`,name:`龙安莉`,desc:`利落从容女`,lang:`中文/英文`},{voice:`longanlang_v3`,name:`龙安朗`,desc:`清爽利落男`,lang:`中文/英文`},{voice:`longyingmu_v3`,name:`龙应沐`,desc:`优雅知性女`,lang:`中文/英文`},{voice:`longyingxun_v3`,name:`龙应询`,desc:`年轻青涩男`,lang:`中文/英文`},{voice:`longyingjing_v3`,name:`龙应静`,desc:`低调冷静女`,lang:`中文/英文`},{voice:`longyingling_v3`,name:`龙应聆`,desc:`温和共情女`,lang:`中文/英文`},{voice:`longyingtao_v3`,name:`龙应桃`,desc:`温柔淡定女`,lang:`中文/英文`},{voice:`longyingxiao_v3`,name:`龙应笑`,desc:`清甜推销女`,lang:`中文/英文`},{voice:`longfei_v3`,name:`龙飞`,desc:`热血磁性男`,lang:`中文/英文`},{voice:`longhuhu_v3`,name:`龙呼呼`,desc:`天真烂漫女童`,lang:`中文/英文`},{voice:`longpaopao_v3`,name:`龙泡泡`,desc:`飞天泡泡音`,lang:`中文/英文`},{voice:`longjielidou_v3`,name:`龙杰力豆`,desc:`阳光顽皮男`,lang:`中文/英文`},{voice:`longxian_v3`,name:`龙仙`,desc:`豪放可爱女`,lang:`中文/英文`},{voice:`longling_v3`,name:`龙铃`,desc:`稚气呆板女`,lang:`中文/英文`},{voice:`longshanshan_v3`,name:`龙闪闪`,desc:`戏剧化童声`,lang:`中文/英文`},{voice:`longniuniu_v3`,name:`龙牛牛`,desc:`阳光男童声`,lang:`中文/英文`},{voice:`longjiaxin_v3`,name:`龙嘉欣`,desc:`优雅粤语女`,lang:`粤语/英文`},{voice:`longjiayi_v3`,name:`龙嘉怡`,desc:`知性粤语女`,lang:`粤语/英文`},{voice:`longanyue_v3`,name:`龙安粤`,desc:`欢脱粤语男`,lang:`粤语/英文`},{voice:`longlaotie_v3`,name:`龙老铁`,desc:`东北直率男`,lang:`东北话/英文`},{voice:`longshange_v3`,name:`龙陕哥`,desc:`原味陕北男`,lang:`陕西话/英文`},{voice:`longanmin_v3`,name:`龙安闽`,desc:`清纯萝莉女`,lang:`闽南话/英文`},{voice:`loongabby_v3`,name:`loongabby`,desc:`美式英文女`,lang:`美式英语`},{voice:`loongandy_v3`,name:`loongandy`,desc:`美式英文男`,lang:`美式英语`},{voice:`loongannie_v3`,name:`loongannie`,desc:`美式英文女`,lang:`美式英语`},{voice:`loongava_v3`,name:`loongava`,desc:`美式英文女`,lang:`美式英语`},{voice:`loongbeth_v3`,name:`loongbeth`,desc:`美式英文女`,lang:`美式英语`},{voice:`loongbetty_v3`,name:`loongbetty`,desc:`美式英文女`,lang:`美式英语`},{voice:`loongcally_v3`,name:`loongcally`,desc:`美式英文女`,lang:`美式英语`},{voice:`loongcindy_v3`,name:`loongcindy`,desc:`美式英文女`,lang:`美式英语`},{voice:`loongdavid_v3`,name:`loongdavid`,desc:`美式英文男`,lang:`美式英语`},{voice:`loongdonna_v3`,name:`loongdonna`,desc:`美式英文女`,lang:`美式英语`},{voice:`loongemily_v3`,name:`loongemily`,desc:`英式英文女`,lang:`英式英语`},{voice:`loongeric_v3`,name:`loongeric`,desc:`英式英文男`,lang:`英式英语`},{voice:`loongluna_v3`,name:`loongluna`,desc:`英式英文女`,lang:`英式英语`},{voice:`loongluca_v3`,name:`loongluca`,desc:`英式英文男`,lang:`英式英语`},{voice:`loongriko_v3`,name:`Riko`,desc:`二次元霓虹女`,lang:`日语`},{voice:`loongtomoka_v3`,name:`loongtomoka`,desc:`日语女`,lang:`日语`},{voice:`loongtomoya_v3`,name:`loongtomoya`,desc:`日语男`,lang:`日语`},{voice:`loongyuuna_v3`,name:`Yuuna`,desc:`日语女`,lang:`日语`},{voice:`loongyuuma_v3`,name:`Yuuma`,desc:`日语男`,lang:`日语`},{voice:`loongkyong_v3`,name:`loongkyong`,desc:`韩语女`,lang:`韩语`},{voice:`loongjihun_v3`,name:`Jihun`,desc:`韩语男`,lang:`韩语`},{voice:`loongindah_v3`,name:`loongindah`,desc:`印尼女`,lang:`印尼语`}],Ap={"qwen-audio-3.0-tts-plus":Dp,"qwen-audio-3.0-tts-flash":Op,"cosyvoice-v3-flash":kp,"cosyvoice-v3-plus":kp,"cosyvoice-v3.5-flash":[],"cosyvoice-v3.5-plus":[],"cosyvoice-v2":[]};function jp(e){return e.startsWith(`qwen-audio-`)?Ep:dr}function Mp(e){let t=Ap[e],n=jp(e);if(!t){process.stdout.write(`No built-in voice list available for model: ${e}\n`),process.stdout.write(`See official voice list: ${n}\n`);return}if(t.length===0){process.stdout.write(`Model ${e} has no system voices.\n`),process.stdout.write(`Use clone or design voices created via the CosyVoice API.
|
|
2741
|
+
`),process.stdout.write(`See: ${Tp}\n`),process.stdout.write(`Browse voices in the console: ${dr}\n`);return}let r=(e,t)=>e.padEnd(t);process.stdout.write(`\nSystem voices for ${e}:\n`),process.stdout.write(`${r(`VOICE ID`,26)} ${r(`NAME`,10)} ${r(`DESCRIPTION`,16)} LANGUAGE\n`),process.stdout.write(`${`-`.repeat(26)} ${`-`.repeat(10)} ${`-`.repeat(16)} ${`-`.repeat(12)}\n`);for(let e of t)process.stdout.write(`${r(e.voice,26)} ${r(e.name,10)} ${r(e.desc,16)} ${e.lang}\n`);process.stdout.write(`\nTotal: ${t.length} voices\n`),process.stdout.write(`Preview and browse more voices: \n${n}\n`)}const Np={text:{type:`string`,valueHint:`<text>`,description:{"en-US":`Text to synthesize into speech (or use --text-file)`,"zh-CN":`要合成为语音的文本(也可使用 --text-file)`}},textFile:{type:`string`,valueHint:`<path>`,description:{"en-US":`Read text from a file instead of --text`,"zh-CN":`从文件读取文本,而非使用 --text`}},model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model ID (default: configured Profile TTS model, otherwise cosyvoice-v3-flash). System voices vary by model`,"zh-CN":`模型 ID(默认:Profile 配置的 TTS 模型,否则为 cosyvoice-v3-flash)。系统音色因模型而异`}},voice:{type:`string`,valueHint:`<voice>`,description:{"en-US":`Voice ID. Use --list-voices for the selected model (e.g. qwen-audio-3.0-tts-plus/flash, cosyvoice-v3-flash); for v3.5-flash provide a clone/design voice ID`,"zh-CN":`音色 ID。使用 --list-voices 查看所选模型的内置音色(如 qwen-audio-3.0-tts-plus/flash、cosyvoice-v3-flash);使用 v3.5-flash 时需提供复刻/设计音色 ID`}},listVoices:{type:`switch`,description:{"en-US":`List built-in system voices for the selected model and exit (console link shown in output)`,"zh-CN":`列出所选模型的内置系统音色并退出(输出中会显示控制台链接)`}},format:{type:`string`,valueHint:`<format>`,description:{"en-US":`Audio format: mp3, pcm, wav, opus (default: mp3; streaming default: pcm)`,"zh-CN":`音频格式:mp3、pcm、wav、opus(默认:mp3;流式模式默认:pcm)`},choices:[`mp3`,`pcm`,`wav`,`opus`]},sampleRate:{type:`string`,valueHint:`<rate>`,description:{"en-US":`Audio sample rate in Hz (e.g. 24000)`,"zh-CN":`音频采样率,单位为 Hz(例如 24000)`}},volume:{type:`string`,valueHint:`<volume>`,description:{"en-US":`Volume 0-100 (default: 50)`,"zh-CN":`音量 0–100(默认:50)`}},rate:{type:`string`,valueHint:`<rate>`,description:{"en-US":`Speech rate 0.5-2.0 (default: 1.0)`,"zh-CN":`语速 0.5–2.0(默认:1.0)`}},pitch:{type:`string`,valueHint:`<pitch>`,description:{"en-US":`Pitch multiplier 0.5-2.0 (default: 1.0)`,"zh-CN":`音高倍数 0.5–2.0(默认:1.0)`}},seed:{type:`string`,valueHint:`<seed>`,description:{"en-US":`Random seed 0-65535 for reproducible synthesis`,"zh-CN":`用于复现合成结果的随机种子 0–65535`}},language:{type:`string`,valueHint:`<lang>`,description:{"en-US":`Language hint (e.g. zh, en, ja, ko, fr, de)`,"zh-CN":`语言提示(例如 zh、en、ja、ko、fr、de)`}},instruction:{type:`string`,valueHint:`<text>`,description:{"en-US":`Natural language instruction to control speech style (e.g. "Use a gentle tone")`,"zh-CN":`用于控制语音风格的自然语言指令(例如“使用温柔的语气”)`}},enableSsml:{type:`switch`,description:{"en-US":`Enable SSML markup parsing in input text`,"zh-CN":`解析输入文本中的 SSML 标记`}},out:{type:`string`,valueHint:`<path>`,description:{"en-US":`Save audio to file (default: auto-generate in temp dir)`,"zh-CN":`将音频保存到文件(默认:在临时目录中自动生成路径)`}},stream:{type:`switch`,description:{"en-US":`Stream raw PCM audio to stdout (pipe to player)`,"zh-CN":`将原始 PCM 音频流式输出到 stdout(可通过管道传给播放器)`}},...r};var Pp=S({description:{"en-US":`Synthesize speech from text`,"zh-CN":`将文本合成为语音`},auth:`apiKey`,usageArgs:`--text <text> [flags]`,flags:Np,exampleArgs:[`--list-voices --model qwen-audio-3.0-tts-plus`,`--list-voices --model cosyvoice-v3-flash`,{"en-US":`--text "Hello, I am Qwen" --model qwen-audio-3.0-tts-plus --voice longanlingxin`,"zh-CN":`--text "你好,我是通义千问" --model qwen-audio-3.0-tts-plus --voice longanlingxin`},{"en-US":`--text "Hello world" --voice <voice_id> --language en`,"zh-CN":`--text "你好,世界" --voice <voice_id> --language zh`},`--text-file script.txt --out speech.wav --voice <voice_id>`,{"en-US":`--text "Today is a good day" --voice <voice_id> --instruction "Use a gentle tone"`,"zh-CN":`--text "今天天气很好" --voice <voice_id> --instruction "使用温柔的语气"`},{"en-US":`--text "Hello" --voice <voice_id> --format wav --sample-rate 24000`,"zh-CN":`--text "你好" --voice <voice_id> --format wav --sample-rate 24000`},{"en-US":`# Stream to audio player (macOS)`,"zh-CN":`# 流式传输到音频播放器(macOS)`},{"en-US":`--text "Hello" --voice <voice_id> --stream | afplay -`,"zh-CN":`--text "你好" --voice <voice_id> --stream | afplay -`},{"en-US":`# Pipe to ffplay`,"zh-CN":`# 通过管道传输到 ffplay`},{"en-US":`--text "Hello" --voice <voice_id> --stream | ffplay -nodisp -autoexit -f s16le -ar 24000 -ac 1 -`,"zh-CN":`--text "你好" --voice <voice_id> --stream | ffplay -nodisp -autoexit -f s16le -ar 24000 -ac 1 -`}],validate:e=>{if(!e.listVoices){if(!e.text&&!e.textFile)return`Provide --text or --text-file.`;if(!e.voice)return`Missing required flag: --voice (use --list-voices; browse more voices: ${dr})`}},async run(e){let{settings:t,flags:r}=e,i=r.model||t.defaultSpeechModel||`cosyvoice-v3-flash`;if(r.listVoices){Mp(i);return}let a=r.text||``;if(!a&&r.textFile){let e=r.textFile;try{a=Jr(e,`utf-8`).trim()}catch{throw new n(`Cannot read text file: ${e}`,l.USAGE)}}let o=r.voice,s=r.language||void 0,c=r.instruction||void 0,u=r.stream===!0,d=r.format||(u?`pcm`:`mp3`),f=r.sampleRate===void 0?void 0:Number(r.sampleRate),p=r.volume===void 0?void 0:Number(r.volume),m=r.rate===void 0?void 0:Number(r.rate),h=r.pitch===void 0?void 0:Number(r.pitch),g=r.seed===void 0?void 0:Number(r.seed),_=r.enableSsml===!0||void 0,v=C(t.output),y={model:i,input:{text:a,voice:o,format:d,sample_rate:f,volume:p,rate:m,pitch:h,seed:g,language_hints:s?[s]:void 0,instruction:c,enable_ssml:_}};if(Hn(y.input),t.dryRun){O({request:y},v);return}t.quiet||process.stderr.write(`[Model: ${i}] [Voice: ${o}]\n`),u?await Ip(e.client,t,y,r,v):await Fp(e.client,t,y,r,v)}});async function Fp(e,t,r,i,a){let o=Cr(i),s=await Pr(o,t,()=>e.requestJson({path:Rn(),method:`POST`,body:r})),c=s.map(e=>e.output?.audio?.url).filter(Boolean);if(c.length===0)throw new n(`API returned no audio URL.`,l.GENERAL);let u=await import(`path`),d=Sn(t,{subDir:`speech`}),f=c.map((e,t)=>{let n=i.out;if(!(n&&c.length===1)){let e=Date.now(),i=c.length>1?`_${String(t+1).padStart(3,`0`)}`:``,a=r.input.format??`mp3`;n=u.join(d,`tts_${e}${i}.${a}`)}return{url:e,destPath:n}}),p=await _r(f,gr,{quiet:t.quiet});if(t.quiet)D(p.join(`
|
|
2742
|
+
`));else if(p.length===1){let e=s[0].output?.audio?.expires_at;O({saved:p[0],audio_url:c[0],model:r.model,voice:r.input.voice,...e?{url_expires_at:e}:{}},a)}else O({saved:p,audio_urls:c,total:p.length,model:r.model,voice:r.input.voice},a)}async function Ip(e,t,n,r,i){let a=await e.request({path:Rn(),method:`POST`,body:n,stream:!0,headers:{Accept:`text/event-stream`,"X-DashScope-SSE":`enable`}}),o=r.out,s=o?Gr(o):null,c;try{for await(let e of $t(a)){if(!e.data||e.data===`[DONE]`)continue;let n;try{n=JSON.parse(e.data)}catch{continue}let r=n.output?.audio?.data;if(r){let e=Buffer.from(r,`base64`);s?s.write(e)||await new Promise(e=>s.once(`drain`,()=>e())):process.stdout.write(e)}if(n.output?.finish_reason===`stop`){c=n.output?.audio?.url,c&&!t.quiet&&process.stderr.write(`\nFull audio URL: ${c}\n`);break}}}finally{s&&(await new Promise((e,t)=>{s.on(`finish`,e),s.on(`error`,t),s.end()}),!t.quiet&&o&&process.stderr.write(`Saved: ${o}\n`))}o&&O({saved:o,...c?{audio_url:c}:{},model:n.model,voice:n.input.voice},i)}const Lp={url:{type:`array`,valueHint:`<url>`,description:{"en-US":`Audio file URL or local file path (repeatable, max 100)`,"zh-CN":`音频文件 URL 或本地文件路径(可重复,最多 100 个)`},required:!0},model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model ID (default: configured Profile ASR model, otherwise fun-asr). Async: fun-asr / *-filetrans / paraformer-*; sync: qwen3-asr-flash* / fun-asr-flash* / qwen-audio-*-asr-flash`,"zh-CN":`模型 ID(默认:Profile 配置的 ASR 模型,否则为 fun-asr)。异步:fun-asr / *-filetrans / paraformer-*;同步:qwen3-asr-flash* / fun-asr-flash* / qwen-audio-*-asr-flash`}},language:{type:`string`,valueHint:`<lang>`,description:{"en-US":`Language hint (e.g. zh, en, ja). Classic async/input-audio: language_hints; qwen3-filetrans: language; qwen3 sync: asr_options.language`,"zh-CN":`语言提示(例如 zh、en、ja)。传统异步/input-audio:language_hints;qwen3-filetrans:language;qwen3 同步:asr_options.language`}},diarization:{type:`switch`,description:{"en-US":`Enable automatic speaker diarization`,"zh-CN":`启用自动说话人分离`}},speakerCount:{type:`number`,valueHint:`<n>`,description:{"en-US":`Expected number of speakers (requires --diarization)`,"zh-CN":`预期的说话人数量(需启用 --diarization)`}},vocabularyId:{type:`string`,valueHint:`<id>`,description:{"en-US":"Pre-built hot-word vocabulary ID (create it via `speech vocabulary create`). Its target_model must exactly match --model, otherwise it is silently ignored. Wider model support than --vocabulary, including Fun-ASR and Paraformer","zh-CN":"预编译热词列表 ID(可用 `speech vocabulary create` 创建)。其 target_model 必须与 --model 完全一致,否则静默失效且无报错。支持模型比 --vocabulary 更广,含 Fun-ASR 与 Paraformer 系列"}},vocabulary:{type:`string`,valueHint:`<json>`,description:{"en-US":`Instant hot words as JSON object of word→weight, e.g. '{"Fendouzhe":4}'. Weight 1-5 (4 recommended; higher values can hurt other words), 50 for super hot word. No pre-built vocabulary needed. Takes effect only on Qwen-Audio-3.0-ASR-Flash models`,"zh-CN":`即时热词,JSON 对象「热词→权重」,例如 '{"奋斗者":4}'。权重 1-5(推荐 4,过高会拖累其他词),50 表示超级热词。无需预先创建热词表。仅 Qwen-Audio-3.0-ASR-Flash 系列模型生效`}},context:{type:`string`,valueHint:`<text>`,description:{"en-US":`Context enhancement word list to improve accuracy on proper nouns; must contain the target words themselves (a topic description alone has little effect); max 400 chars. Takes effect only on Qwen-Audio-3.0-ASR-Flash and Fun-ASR-Flash models`,"zh-CN":`上下文增强词表,提升专有名词准确率;须包含待识别的原词本身(只写主题描述效果有限),最长 400 字符。仅 Qwen-Audio-3.0-ASR-Flash 系列与 Fun-ASR-Flash 模型生效`}},channelId:{type:`number`,valueHint:`<n>`,description:{"en-US":`Audio channel ID (default: 0)`,"zh-CN":`音频声道 ID(默认:0)`}},out:{type:`string`,valueHint:`<path>`,description:{"en-US":`Save full transcription result to JSON file`,"zh-CN":`将完整转写结果保存到 JSON 文件`}},...t,pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Polling interval in seconds (default: 2)`,"zh-CN":`轮询间隔,单位为秒(默认:2)`}}};function Rp(e,t,r){let i=[];if(e.diarization===!0&&i.push(`--diarization`),e.speakerCount!==void 0&&i.push(`--speaker-count`),r===`qwen3`&&(e.vocabularyId!==void 0&&i.push(`--vocabulary-id`),e.vocabulary!==void 0&&i.push(`--vocabulary`),e.context!==void 0&&i.push(`--context`)),e.channelId!==void 0&&i.push(`--channel-id`),e.async===!0&&i.push(`--async`),e.pollInterval!==void 0&&i.push(`--poll-interval`),i.length>0)throw new n(`Model "${t}" uses sync Flash ASR and does not support: ${i.join(`, `)}.\n`+zp(i),l.USAGE)}function zp(e){let t=/* @__PURE__ */ new Set([`--vocabulary`,`--vocabulary-id`,`--context`]),n=e.some(e=>t.has(e)),r=e.some(e=>!t.has(e));return n&&!r?`Hint: Use qwen-audio-3.0-asr-flash (or an async filetrans model such as qwen-audio-3.0-asr-flash-filetrans) for vocabulary/context flags.`:n&&r?`Hint: For vocabulary/context flags use qwen-audio-3.0-asr-flash or qwen-audio-3.0-asr-flash-filetrans; for the other flags use an async filetrans model (e.g. fun-asr).`:`Hint: Use an async filetrans model (e.g. fun-asr, qwen3-asr-flash-filetrans) for those flags.`}var Bp=S({description:{"en-US":`Recognize speech from audio files (FunAudio-ASR / Qwen-ASR Flash)`,"zh-CN":`识别音频文件中的语音(FunAudio-ASR / Qwen-ASR Flash)`},auth:`apiKey`,usageArgs:`--url <audio-url> [flags]`,flags:Lp,exampleArgs:[`--url https://example.com/audio.mp3`,`--url https://example.com/a.mp3 --url https://example.com/b.mp3`,`--url https://example.com/meeting.wav --diarization --speaker-count 3`,`--url https://example.com/audio.mp3 --language zh`,`--url https://example.com/audio.mp3 --vocabulary-id vocab-abc123`,`--url https://example.com/audio.mp3 --model qwen-audio-3.0-asr-flash-filetrans --vocabulary '{"奋斗者":4,"鲸落":4}'`,`--url https://example.com/audio.mp3 --model qwen-audio-3.0-asr-flash-filetrans --context "奋斗者号 鲸落 深海勇士"`,`--url https://example.com/audio.mp3 --out result.json`,`--url https://example.com/audio.mp3 --async --quiet`,`--url https://example.com/audio.mp3 --model qwen-audio-3.0-asr-flash --language en`],async run(e){let{settings:t,flags:r}=e,i=[];Array.isArray(r.url)?i=r.url:typeof r.url==`string`&&(i=[r.url]);let a=r.speakerCount,o=r.diarization===!0;if(a!==void 0&&!o)throw new n(`--speaker-count requires --diarization to be enabled.
|
|
2743
|
+
Hint: Add --diarization flag to enable speaker separation.`,l.USAGE);let s=r.model||t.defaultSpeechRecognitionModel||`fun-asr`,c=vn(s);if(c.kind===`unsupported`)throw new n(c.unsupportedReason??`Unsupported ASR model: ${s}`,l.USAGE);if(c.kind===`sync-flash`&&(Rp(r,s,c.flashFamily),i.length!==1))throw new n(`Model "${s}" is a sync Flash ASR model and accepts exactly one --url (got ${i.length}).\nHint: Pass a single audio URL, or use an async filetrans model for batch files.`,l.USAGE);if(c.kind===`async-filetrans`&&c.asyncInputStyle===`file_url`&&i.length!==1)throw new n(`Model "${s}" accepts exactly one --url (got ${i.length}).\nHint: qwen3-asr-flash-filetrans* requires a single file_url.`,l.USAGE);let u=C(t.output),d=r.vocabulary===void 0?void 0:Qt(r.vocabulary),f=await Promise.all(i.map(t=>e.client.uploadFile(t,s)));if(c.kind===`sync-flash`){await Vp(e.client,t,r,u,s,c,f[0],d);return}let p=r.channelId,m=r.vocabularyId,h=de(c.asyncLanguageStyle??`language_hints`,r.language),g={model:s,input:{...c.asyncInputStyle===`file_url`?{file_url:f[0]}:{file_urls:f},...r.context===void 0?{}:{context:le(r.context)}},parameters:{channel_id:p===void 0?[0]:[p],...h,diarization_enabled:o?!0:void 0,speaker_count:a,vocabulary_id:m,vocabulary:d}};if(Hn(g.parameters),t.dryRun){O({request:g,mode:`async`,path:Ln()},u);return}t.quiet||process.stderr.write(`[Model: ${s}] [Mode: async] [Files: ${f.length}]\n`),await Hp(e.client,t,g,r,u,f.length)}});async function Vp(e,t,n,r,i,a,o,s){let c=a.flashFamily,l=ue({model:i,audioUrl:o,language:n.language,vocabularyId:n.vocabularyId,vocabulary:s,context:n.context,flashFamily:c});if(t.dryRun){O({request:l,mode:`sync`,path:a.path},r);return}t.quiet||process.stderr.write(`[Model: ${i}] [Mode: sync] [Files: 1]\n`);let u=await e.requestJson({path:a.path,method:`POST`,headers:{"X-DashScope-SSE":`disable`},body:l}),d=ze(u,c);d?process.stdout.write(d.endsWith(`
|
|
2744
|
+
`)?d:`${d}\n`):D(JSON.stringify(u)),n.out&&(Zr(n.out,JSON.stringify(u,null,2)+`
|
|
2745
|
+
`),t.quiet||process.stderr.write(`Full result saved to: ${n.out}\n`))}async function Hp(e,t,r,i,a,o){let s=(await e.requestJson({path:Ln(),method:`POST`,body:r,async:!0})).output.task_id;if(i.async){O({task_id:s},a);return}let c=i.pollInterval??2,u=e.url(Un(s)),d=await kr(e,t,{url:u,intervalSec:c,timeoutSec:t.timeout,isComplete:e=>e.output.task_status===`SUCCEEDED`,isFailed:e=>e.output.task_status===`FAILED`,getStatus:e=>e.output.task_status,getErrorMessage:e=>e.output.message}),f=ye(d.output);if(f.length===0){O({task_id:s,status:d.output.task_status},a);return}let p=[];for(let e=0;e<f.length;e++){let t=f[e],r=o>1;if(r&&process.stdout.write(`=== [${e+1}/${f.length}] ${t.file_url??``} ===\n`),t.subtask_status===`FAILED`){let e=t.message??t.code??`unknown error`;process.stdout.write(`[FAILED] ${t.file_url??``} — ${e}\n`),r&&process.stdout.write(`
|
|
2746
2746
|
`);continue}if(!t.transcription_url){r&&process.stdout.write(`
|
|
2747
2747
|
`);continue}let i=await fetch(t.transcription_url);if(!i.ok)throw new n(`Failed to download transcription: HTTP ${i.status}`,l.GENERAL);let a=await i.json();p.push(a);let s=a.transcripts;if(s&&s.length>0)for(let e of s)if(e.sentences&&e.sentences.length>0)for(let t of e.sentences){let e=t.speaker_id===void 0?``:` [Speaker ${t.speaker_id}]`;process.stdout.write(`${t.text}${e}\n`)}else e.text&&process.stdout.write(e.text+`
|
|
2748
2748
|
`);else D(JSON.stringify(a));r&&process.stdout.write(`
|
|
2749
|
-
`)}if(i.out){let e=i.out,n=p.length===1?p[0]:p;
|
|
2750
|
-
`),t.quiet||process.stderr.write(`Full result saved to: ${e}\n`)}}const Tp={id:{type:`string`,valueHint:`<id>`,description:{"en-US":`Hot-word vocabulary ID (required)`,"zh-CN":`热词表 ID(必填)`},required:!0}},Ep={words:{type:`string`,valueHint:`<json>`,description:{"en-US":`Hot words as JSON object of word→weight, e.g. '{"Fendouzhe":4}'; or the API entry array for per-entry lang. Weight 1-5 (4 recommended); when the vocabulary target_model is a Qwen-Audio-3.0-ASR-Flash series model, 50 is also allowed as super hot word. Or use --words-file`,"zh-CN":`热词,JSON 对象「热词→权重」,例如 '{"奋斗者":4}';需要逐条指定语言时可传 API 的条目数组。权重 1-5(推荐 4);当热词表的 target_model 为 Qwen-Audio-3.0-ASR-Flash 系列时还可使用 50(超级热词)。也可使用 --words-file`}},wordsFile:{type:`string`,valueHint:`<path>`,description:{"en-US":`JSON file with the hot words (use - for stdin)`,"zh-CN":`包含热词的 JSON 文件(使用 - 从 stdin 读取)`}},lang:{type:`string`,valueHint:`<code>`,description:{"en-US":`Language code applied to every hot word when using object form (optional; ignored for array form). Paraformer: zh/en/ja/yue/ko/de/fr/ru; Fun-ASR: zh/en/ja`,"zh-CN":`对象形态时应用到所有热词的语言代码(选填;数组形态忽略)。Paraformer 支持 zh/en/ja/yue/ko/de/fr/ru;Fun-ASR 支持 zh/en/ja`}}};function Dp(e){if(!e.words&&!e.wordsFile)return`Provide --words or --words-file.`;if(e.words&&e.wordsFile)return`Use either --words or --words-file, not both.`;if(e.words)try{qt(e.words,e.lang)}catch(e){if(e instanceof x)return e.message;throw e}}function Op(e){let t=e.wordsFile?nn(e.wordsFile):e.words;return qt(t,e.lang)}const kp=[{"en-US":`Each account may have at most 10 vocabularies; updates must be at least 5 minutes apart. See improve-asr-accuracy for full limits.`,"zh-CN":`每个账号最多 10 个热词表;两次更新间隔至少 5 分钟。完整限制见 improve-asr-accuracy。`},{"en-US":`Hot-word vocabularies are not supported in Singapore sub-workspaces; the server error is passed through as-is.`,"zh-CN":`新加坡子业务空间不支持热词表;服务端错误会原样透传。`},{"en-US":`Weight 1-5 (4 recommended); when the vocabulary target_model is a Qwen-Audio-3.0-ASR-Flash series model, 50 is also allowed as super hot word.`,"zh-CN":`权重 1-5(推荐 4);当热词表的 target_model 为 Qwen-Audio-3.0-ASR-Flash 系列时还可使用 50(超级热词)。`}],Ap={model:{type:`string`,valueHint:`<model>`,description:{"en-US":"ASR model this vocabulary is built for (required). Must exactly match the --model passed to `speech recognize` later, otherwise the vocabulary is silently ignored","zh-CN":"该热词表服务的 ASR 模型(必填)。必须与后续 `speech recognize` 的 --model 完全一致,否则热词表静默失效"},required:!0},prefix:{type:`string`,valueHint:`<prefix>`,description:{"en-US":`Custom vocabulary prefix (required). Digits and lowercase letters only, max 10 chars`,"zh-CN":`热词表自定义前缀(必填)。仅允许数字和小写字母,最长 10 个字符`},required:!0},...Ep};var jp=S({description:{"en-US":`Create a precompiled hot-word vocabulary for ASR`,"zh-CN":`创建用于语音识别的预编译热词表`},auth:`apiKey`,usageArgs:`--model <model> --prefix <prefix> (--words <json> | --words-file <path>) [flags]`,flags:Ap,notes:[{"en-US":"The --model must exactly match the --model used later with `speech recognize --vocabulary-id`; a mismatch causes silent failure with no error.","zh-CN":"--model 必须与后续 `speech recognize --vocabulary-id` 使用的 --model 完全一致;不一致时热词表会静默失效且无报错。"},...kp],exampleArgs:[{"en-US":`--model fun-asr --prefix demo --words '{"Fendouzhe":4,"Jingluo":4}'`,"zh-CN":`--model fun-asr --prefix demo --words '{"奋斗者":4,"鲸落":4}'`},{"en-US":`--model paraformer-v2 --prefix demo --words '[{"text":"Fendouzhe","weight":4,"lang":"zh"}]'`,"zh-CN":`--model paraformer-v2 --prefix demo --words '[{"text":"奋斗者","weight":4,"lang":"zh"}]'`},{"en-US":`--model fun-asr --prefix demo --words '{"Fendouzhe":4}' --lang zh`,"zh-CN":`--model fun-asr --prefix demo --words '{"奋斗者":4}' --lang zh`},`--model fun-asr --prefix demo --words-file ./hotwords.json`,{"en-US":`--model fun-asr --prefix demo --words '{"Fendouzhe":4}' --quiet`,"zh-CN":`--model fun-asr --prefix demo --words '{"奋斗者":4}' --quiet`}],validate:e=>Dp(e),async run(e){let{settings:t,flags:n}=e,r=Op(n),i=C(t.output),a=pe(`create_vocabulary`,{target_model:n.model,prefix:n.prefix,vocabulary:r});if(t.dryRun){O({endpoint:e.client.url(kn()),request:a},i);return}let o=await Ce(e.client,{targetModel:n.model,prefix:n.prefix,vocabulary:r});t.quiet||i===`text`?D(o.output?.vocabulary_id??``):O(o,i)}}),Mp=S({description:{"en-US":`List precompiled hot-word vocabularies`,"zh-CN":`列出预编译热词表`},auth:`apiKey`,usageArgs:`[--prefix <prefix>] [--page <n>] [--page-size <n>]`,flags:{prefix:{type:`string`,valueHint:`<prefix>`,description:{"en-US":`Filter by vocabulary prefix`,"zh-CN":`按热词表前缀过滤`}},page:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number, 1-based (default: 1). Mapped to API page_index (0-based) as page - 1`,"zh-CN":`页码,从 1 开始(默认:1)。映射为 API 的 page_index(从 0 开始):page - 1`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Results per page (default: 10)`,"zh-CN":`每页结果数(默认:10)`}}},notes:[{"en-US":"List responses do not include target_model; use `speech vocabulary get` to inspect the model a vocabulary was built for.","zh-CN":"list 响应不含 target_model;要对齐模型请使用 `speech vocabulary get`。"},{"en-US":`Vocabularies with status UNDEPLOYED are silently ignored by ASR.`,"zh-CN":`status 为 UNDEPLOYED 的热词表会被 ASR 静默忽略。`}],exampleArgs:[``,`--prefix demo`,`--page 2 --page-size 20`],validate:e=>{if(e.page!==void 0&&e.page<1)return`--page must be >= 1.`},async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=n.page===void 0?void 0:n.page-1,a={};if(n.prefix!==void 0&&(a.prefix=n.prefix),i!==void 0&&(a.page_index=i),n.pageSize!==void 0&&(a.page_size=n.pageSize),t.dryRun){O({endpoint:e.client.url(kn()),request:pe(`list_vocabulary`,a)},r);return}let o=await Ot(e.client,{prefix:n.prefix,pageIndex:i,pageSize:n.pageSize});if(t.quiet||r===`text`){let e=o.output?.vocabulary_list??[];if(e.length===0)D(`No vocabularies found.`);else{let t=!1;for(let n of e){let e=n.vocabulary_id??``,r=n.status??``,i=n.gmt_modified??``;r===`UNDEPLOYED`&&(t=!0),D(`[${e}] ${r} ${i}`.trimEnd())}t&&D("Note: UNDEPLOYED vocabularies are silently ignored by ASR. Use `speech vocabulary get` to inspect them.")}}else O(o,r)}});const Np={...Tp};var Pp=S({description:{"en-US":`Get details of a precompiled hot-word vocabulary`,"zh-CN":`查看预编译热词表详情`},auth:`apiKey`,usageArgs:`--id <id>`,flags:Np,notes:[{"en-US":"Use this command to confirm target_model before calling `speech recognize --vocabulary-id`; a model mismatch causes silent failure.","zh-CN":"调用 `speech recognize --vocabulary-id` 前请用本命令确认 target_model;模型不一致会导致静默失效。"}],exampleArgs:[`--id vocab-demo-xxx`,`--id vocab-demo-xxx --quiet`],async run(e){let{settings:t,flags:n}=e,r=n.id,i=C(t.output);if(t.dryRun){O({endpoint:e.client.url(kn()),request:pe(`query_vocabulary`,{vocabulary_id:r})},i);return}let a=await Qt(e.client,r),o=a.output;if(t.quiet){D(o?.target_model??``);return}if(i===`text`){D(`vocabulary_id: ${r}`),D(`status: ${o?.status??``}`),D(`target_model: ${o?.target_model??``}`),D(`gmt_create: ${o?.gmt_create??``}`),D(`gmt_modified: ${o?.gmt_modified??``}`);let e=o?.vocabulary??[];if(e.length>0){D(`vocabulary:`);for(let t of e){let e=t.lang?` lang=${t.lang}`:``;D(` ${t.text} weight=${t.weight}${e}`)}}}else O(a,i)}});const Fp={...Tp,...Ep};var Ip=S({description:{"en-US":`Replace the contents of a precompiled hot-word vocabulary`,"zh-CN":`完全替换预编译热词表的内容`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This fully replaces all hot words in the vocabulary. Entries not listed will be discarded and cannot be undone.`,"zh-CN":`该操作会完全替换热词表中的全部词条。未列出的词将被丢弃,且无法撤销。`}},usageArgs:`--id <id> (--words <json> | --words-file <path>) [flags]`,flags:Fp,notes:[{"en-US":`update is a full replace, not an append. Prefer --dry-run first to preview the complete vocabulary that will be written.`,"zh-CN":`update 是完全替换,不是增量追加。建议先用 --dry-run 预览将要写入的完整词表。`},...kp],exampleArgs:[{"en-US":`--id vocab-demo-xxx --words '{"Fendouzhe":4}' --dry-run`,"zh-CN":`--id vocab-demo-xxx --words '{"奋斗者":4}' --dry-run`},{"en-US":`--id vocab-demo-xxx --words '{"Fendouzhe":4,"Jingluo":4}' --yes`,"zh-CN":`--id vocab-demo-xxx --words '{"奋斗者":4,"鲸落":4}' --yes`}],validate:e=>Dp(e),async run(e){let{settings:t,flags:n}=e,r=n.id,i=Op(n),a=C(t.output),o=pe(`update_vocabulary`,{vocabulary_id:r,vocabulary:i});if(t.dryRun){O({endpoint:e.client.url(kn()),request:o},a);return}let s=await zn(e.client,r,i);t.quiet||a===`text`?D(r):O(s,a)}});const Lp={...Tp};var Rp=S({description:{"en-US":`Delete a precompiled hot-word vocabulary`,"zh-CN":`删除预编译热词表`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the specified hot-word vocabulary and cannot be undone.`,"zh-CN":`该操作会永久删除指定的热词表,且无法撤销。`}},usageArgs:`--id <id>`,flags:Lp,exampleArgs:[`--id vocab-demo-xxx --dry-run`,`--id vocab-demo-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=n.id,i=C(t.output);if(t.dryRun){O({endpoint:e.client.url(kn()),request:pe(`delete_vocabulary`,{vocabulary_id:r})},i);return}let a=await ke(e.client,r);t.quiet||i===`text`?D(r):O(a,i)}}),zp=S({description:{"en-US":`Upload a local file to DashScope temporary storage (48h)`,"zh-CN":`将本地文件上传到 DashScope 临时存储(保留 48 小时)`},auth:`apiKey`,usageArgs:`--file <path> --model <model>`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Local file to upload (image, video, audio)`,"zh-CN":`要上传的本地文件(图片、视频或音频)`},required:!0},model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Target model name (file is bound to this model)`,"zh-CN":`目标模型名称(文件将与该模型绑定)`},required:!0}},exampleArgs:[`--file photo.jpg --model qwen3-vl-plus`,`--file video.mp4 --model wan2.1-t2v-plus`,`--file audio.wav --model qwen3-asr-flash`,`--file cat.png --model qwen-image-3.0`],async run(e){let{settings:t,flags:n}=e,r=n.file,i=n.model,a=C(t.output);if(t.dryRun){O({action:`upload`,file:r,model:i},a);return}let o=await e.client.uploadFile(r,i);t.quiet?D(o):O({url:o,model:i,expires_in:`48 hours`,note:`When using this URL in API calls, add header: X-DashScope-OssResourceResolve: enable`},a)}}),Bp=S({description:{"en-US":`Call a Bailian console API via the CLI gateway`,"zh-CN":`通过 CLI Gateway 调用百炼控制台 API`},auth:`console`,usageArgs:`--api <api> --data <json> [flags]`,flags:{api:{type:`string`,valueHint:`<api>`,description:{"en-US":`API name (e.g. zeldaEasy.broadscope-bailian.memory-library.getLibraries)`,"zh-CN":`API 名称(例如 zeldaEasy.broadscope-bailian.memory-library.getLibraries)`},required:!0},data:{type:`string`,valueHint:`<json>`,description:{"en-US":`Request data as JSON string`,"zh-CN":`JSON 字符串格式的请求数据`},required:!0}},exampleArgs:[`--api zeldaEasy.bailian-commerce.freeTrial.queryFreeTierQuota --data '{"queryFreeTierQuotaRequest":{"models":["qwen3-max"]}}'`,`--api some.api.name --data '{"key":"value"}' --console-region cn-beijing`],async run(e){let{settings:t,flags:n}=e,r=n.api,i=n.data,a;try{a=JSON.parse(i)}catch{throw new x(`--data must be valid JSON`)}let o=C(t.output);if(t.dryRun){O({api:r,data:a,...w(t)},o);return}let s=await e.client.console(r,a);O(s,o)}});function Vp(e){let t=e.client.baseUrl.replace(/\/+$/,``);return t&&!ft(t)?t:ne(R(e))}const Hp={agent_identity:{"en-US":`Agent identity issuance`,"zh-CN":`Agent 身份签发`},content_safety:{"en-US":`Content safety`,"zh-CN":`内容安全`},supply_chain_scan:{"en-US":`Supply-chain static scan`,"zh-CN":`供应链静态扫描`},credential_isolation:{"en-US":`Credential isolation`,"zh-CN":`凭证隔离`},session_lifecycle:{"en-US":`Session lifecycle governance`,"zh-CN":`session 生命周期治理`}},Up={flow_agent:{"en-US":`Flow Agent`,"zh-CN":`Flow Agent`},managed_agent:{"en-US":`Managed Agents`,"zh-CN":`Managed Agents`},knowledge_base:{"en-US":`RAG`,"zh-CN":`RAG`},memory:{"en-US":`Memory`,"zh-CN":`Memory`},mcp:{"en-US":`Store`,"zh-CN":`Store`},external_agent:{"en-US":`BYOA hosting`,"zh-CN":`BYOA 托管`}},Wp=[{label:{"en-US":`Content safety`,"zh-CN":`内容安全`},keys:[`content_safety`,`contentSafety`]},{label:{"en-US":`File scan`,"zh-CN":`文件扫描`},keys:[`file_scan`,`fileScan`]},{label:{"en-US":`Skill scan`,"zh-CN":`技能扫描`},keys:[`skill_scan`,`skillScan`]}],B={unavailable:{"en-US":`(unavailable)`,"zh-CN":`(不可用)`},on:{"en-US":`on`,"zh-CN":`开启`},off:{"en-US":`off`,"zh-CN":`关闭`},scannedLabel:{"en-US":`Scanned`,"zh-CN":`扫描`},risksLabel:{"en-US":`Risks`,"zh-CN":`风险`},capabilities:{"en-US":`Capabilities`,"zh-CN":`能力项`},protection:{"en-US":`Protection`,"zh-CN":`防护项`},detections:{"en-US":`Detections`,"zh-CN":`检测项`},overviewUnavailable:{"en-US":`Overview unavailable.`,"zh-CN":`总览不可用。`},hit:{"en-US":`hit`,"zh-CN":`命中`},scanned:{"en-US":`scanned`,"zh-CN":`扫描`},total:{"en-US":`Total`,"zh-CN":`总计`},high:{"en-US":`high`,"zh-CN":`高`},medium:{"en-US":`medium`,"zh-CN":`中`},low:{"en-US":`low`,"zh-CN":`低`},noAlerts:{"en-US":`No alerts found.`,"zh-CN":`未找到告警。`},nextPageCursor:{"en-US":`Next page cursor`,"zh-CN":`下一页游标`},app:{"en-US":`app`,"zh-CN":`应用`},asset:{"en-US":`asset`,"zh-CN":`资产`},status:{"en-US":`status`,"zh-CN":`状态`},source:{"en-US":`source`,"zh-CN":`来源`},checked:{"en-US":`checked`,"zh-CN":`检测时间`}};function Gp(e,t,n){if(n!=null&&n!==``){if(Array.isArray(n)){for(let r of n)e.append(t,r);return}e.set(t,String(n))}}function Kp(e,t,n,r){if(D(`\n${e(t)}`),!n||n.length===0){D(` ${e(B.unavailable)}`);return}for(let t of n){let n=typeof t.count==`number`?` (${t.count})`:``,i=e(t.enabled?B.on:B.off),a=r[t.key]?e(r[t.key]):t.key;D(` ${i} ${a}${n}`)}}function qp(e){if(!e)return`-`;let t=/^\d+$/.test(e)?Number(e):Date.parse(e);return Number.isNaN(t)?e:new Date(t).toISOString().replace(`T`,` `).slice(0,19)}function Jp(e,t){let n=(t.risk_level??`unknown`).toUpperCase();D(`[${n}] ${t.risk_name??`-`} (${t.alert_id})`),D(` ${e(B.app)}: ${t.app_name??`-`} ${e(B.asset)}: ${t.asset_name??`-`} (${t.asset_type??`-`})`),D(` ${e(B.status)}: ${t.status??`-`} ${e(B.source)}: ${t.source??`-`} ${e(B.checked)}: ${qp(t.check_time)}`),t.risk_desc&&D(` ${t.risk_desc}`),D(``)}const Yp={...L};var Xp=S({description:{"en-US":`Show the Agent security protection overview (last 24 hours)`,"zh-CN":`查看 Agent 安全防护总览(最近 24 小时)`},auth:`apiKey`,usageArgs:`[flags]`,flags:Yp,notes:[{"en-US":`Auth: uses DashScope API Key (Bearer token).`,"zh-CN":`鉴权:使用 DashScope API Key(Bearer Token)。`},{"en-US":"`--workspace-id` can be set via BAILIAN_WORKSPACE_ID env or config workspace_id.","zh-CN":"`--workspace-id` 可通过 BAILIAN_WORKSPACE_ID 环境变量或配置项 workspace_id 设置。"},{"en-US":`Fixed to the last 24 hours; the AgentStudio region is always cn-beijing and is not configurable.`,"zh-CN":`固定统计最近 24 小时;AgentStudio 地域固定为 cn-beijing,不可配置。`},{"en-US":"AgentStudio host: derived from --workspace-id by default; point --base-url / DASHSCOPE_BASE_URL (or `auth login --base-url`) at a workspace or pre-release origin such as https://<workspace-id>.cn-beijing.maas.aliyuncs.com/api/v1/agentstudio to override it, and --workspace-id is then not required.","zh-CN":"AgentStudio 域名:默认由 --workspace-id 推导;将 --base-url / DASHSCOPE_BASE_URL(或 `auth login --base-url`)指向某个 workspace 或预发源(例如 https://<workspace-id>.cn-beijing.maas.aliyuncs.com/api/v1/agentstudio)即可覆盖,此时无需 --workspace-id。"}],exampleArgs:[{"en-US":`--workspace-id ws-xxx`,"zh-CN":`--workspace-id ws-xxx`},{"en-US":`--workspace-id ws-xxx --output json`,"zh-CN":`--workspace-id ws-xxx --output json`}],async run(e){let{settings:t,localize:n}=e,r=C(t.output),i=En(Vp(e));if(t.dryRun){O({endpoint:i,method:`GET`},r);return}let a=await Tn(e.client,i);if(!a){r===`json`?O({},r):D(n(B.overviewUnavailable));return}if(r===`json`){O(a,r);return}let o=Wp.map(({label:e,keys:t})=>{let r=t.map(e=>a[e]).find(e=>e!==void 0);return{label:n(e),stat:r??null}}),s=e=>o.reduce((t,n)=>t+(n.stat?e(n.stat)??0:0),0);D(`${n(B.scannedLabel)}: ${s(e=>e.scanned)} ${n(B.risksLabel)}: ${s(e=>e.hit)}`),Kp(n,B.capabilities,a.capabilities,Hp),Kp(n,B.protection,a.protection,Up),D(`\n${n(B.detections)}`);for(let{label:e,stat:t}of o)D(t?` ${e} ${n(B.hit)} ${t.hit??`-`} / ${n(B.scanned)} ${t.scanned??`-`}`:` ${e} ${n(B.unavailable)}`)}});const Zp=[`agent`,`tool`,`skill`,`knowledge_base`,`memory`,`channel`],Qp={...L,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: 20)`,"zh-CN":`每页结果数(默认:20)`}},riskLevel:{type:`string`,valueHint:`<level>`,choices:[`high`,`medium`,`low`],description:{"en-US":`Filter by risk level: high, medium, low`,"zh-CN":`按风险等级筛选:high、medium、low`}},riskName:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by risk name`,"zh-CN":`按风险名称筛选`}},status:{type:`string`,valueHint:`<status>`,description:{"en-US":`Filter by handling status`,"zh-CN":`按处理状态筛选`}},statusList:{type:`array`,valueHint:`<status>`,description:{"en-US":`Filter by multiple statuses (repeatable)`,"zh-CN":`按多个状态筛选(可重复传入)`}},appName:{type:`string`,valueHint:`<name>`,description:{"en-US":`Filter by application name`,"zh-CN":`按应用名称筛选`}},assetType:{type:`string`,valueHint:`<type>`,choices:Zp,description:{"en-US":`Filter by asset type: ${Zp.join(`, `)}`,"zh-CN":`按资产类型筛选:${Zp.join(`、`)}`}},vendor:{type:`string`,valueHint:`<vendor>`,description:{"en-US":`Filter by vendor`,"zh-CN":`按厂商筛选`}},orderBy:{type:`string`,valueHint:`<field>`,description:{"en-US":`Sort field (default: check_time)`,"zh-CN":`排序字段(默认:check_time)`}},order:{type:`string`,valueHint:`<dir>`,choices:[`asc`,`desc`],description:{"en-US":`Sort direction: asc, desc (default: desc)`,"zh-CN":`排序方向:asc、desc(默认:desc)`}},lang:{type:`string`,valueHint:`<lang>`,choices:[`zh`,`en`],description:{"en-US":`Response language: zh, en`,"zh-CN":`响应语言:zh、en`}}};var $p=S({description:{"en-US":`List Agent security alerts`,"zh-CN":`列出 Agent 安全告警`},auth:`apiKey`,usageArgs:`[flags]`,flags:Qp,notes:[{"en-US":`Auth: uses DashScope API Key (Bearer token).`,"zh-CN":`鉴权:使用 DashScope API Key(Bearer Token)。`},{"en-US":"`--workspace-id` can be set via BAILIAN_WORKSPACE_ID env or config workspace_id.","zh-CN":"`--workspace-id` 可通过 BAILIAN_WORKSPACE_ID 环境变量或配置项 workspace_id 设置。"},{"en-US":`Filters, pagination and sorting go in the query string; enum flags are validated before any request is sent.`,"zh-CN":`筛选、分页与排序参数走 query string;枚举类 flag 在发起请求前校验。`},{"en-US":"AgentStudio host: derived from --workspace-id by default; point --base-url / DASHSCOPE_BASE_URL (or `auth login --base-url`) at a workspace or pre-release origin such as https://<workspace-id>.cn-beijing.maas.aliyuncs.com/api/v1/agentstudio to override it, and --workspace-id is then not required.","zh-CN":"AgentStudio 域名:默认由 --workspace-id 推导;将 --base-url / DASHSCOPE_BASE_URL(或 `auth login --base-url`)指向某个 workspace 或预发源(例如 https://<workspace-id>.cn-beijing.maas.aliyuncs.com/api/v1/agentstudio)即可覆盖,此时无需 --workspace-id。"}],exampleArgs:[{"en-US":`--workspace-id ws-xxx`,"zh-CN":`--workspace-id ws-xxx`},{"en-US":`--risk-level high --page-size 50`,"zh-CN":`--risk-level high --page-size 50`},{"en-US":`--asset-type agent --app-name "demo app" --output json`,"zh-CN":`--asset-type agent --app-name "测试应用0" --output json`},{"en-US":`--status-list unhandled --status-list handling`,"zh-CN":`--status-list unhandled --status-list handling`}],async run(e){let{settings:t,flags:n,localize:r}=e,i=C(t.output),a=Vp(e),o=new URLSearchParams;Gp(o,`current_page`,n.page),Gp(o,`page_size`,n.pageSize),Gp(o,`risk_level`,n.riskLevel),Gp(o,`risk_name`,n.riskName),Gp(o,`status`,n.status),Gp(o,`status_list`,n.statusList),Gp(o,`app_name`,n.appName),Gp(o,`asset_type`,n.assetType),Gp(o,`vendor`,n.vendor),Gp(o,`order_by`,n.orderBy),Gp(o,`order`,n.order),Gp(o,`lang`,n.lang);let s=o.toString(),c=wn(a),l=s?`${c}?${s}`:c;if(t.dryRun){O({endpoint:l,method:`GET`},i);return}let u=await Tn(e.client,l),d=u?.data??[];if(t.quiet){for(let e of d)D(e.alert_id);return}if(i===`json`){O(u??{stats:null,data:[],next_page:null},i);return}let f=u?.stats;if(f&&D(`${r(B.total)}: ${f.total??`-`} ${r(B.high)}: ${f.high??`-`} ${r(B.medium)}: ${f.medium??`-`} ${r(B.low)}: ${f.low??`-`}\n`),d.length===0){D(r(B.noAlerts));return}for(let e of d)Jp(r,e);u?.next_page&&D(`${r(B.nextPageCursor)}: ${u.next_page}`)}});function V(e){return e.toLocaleString(`en-US`)}function em(e){let t=new Date(e),n=String(t.getMonth()+1).padStart(2,`0`),r=String(t.getDate()).padStart(2,`0`);return`${t.getFullYear()}-${n}-${r}`}function H(e){let t=e=>String(e).padStart(2,`0`),n=new Date(e);return`${em(e)} ${t(n.getHours())}:${t(n.getMinutes())}:${t(n.getSeconds())}`}function U(e){return[...new Set(e.split(`,`).map(e=>e.trim()).filter(Boolean))]}function tm(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))r!==void 0&&r!==``&&t.set(n,String(r));let n=t.toString();return n?`?${n}`:``}async function nm(e,t,n,r=30){let i;for(let a=0;a<r;a++){let r=await e.console(t,n(i)),a=Ln(r);if(a.taskId&&Object.keys(a).length===1){i=a.taskId,await new Promise(e=>setTimeout(e,500));continue}return r}return null}async function rm(e,t,n){return nm(e,t,e=>e?{reqDTO:{...n,asyncTaskId:e}}:{reqDTO:n})}async function im(e,t,r){let i=await rm(e,t,r);if(!i)throw new n(`Request timed out.`,l.TIMEOUT);return Ln(i)}const am=[`cn-beijing`,`ap-southeast-1`];function W(e){let t=w(e).consoleRegion;if(!am.includes(t))throw new x(`Model monitor/log/alert commands are not available in console region "${t}". Supported regions: ${am.join(`, `)} (set --console-region).`)}const om={days:{type:`number`,valueHint:`<days>`,description:{"en-US":`Number of days to look back (default: 7)`,"zh-CN":`向前查询的天数(默认:7)`}},startTime:{type:`string`,valueHint:`<time>`,description:{"en-US":`Range start (ISO date or ms epoch); overrides --days`,"zh-CN":`开始时间(ISO 日期或毫秒时间戳),设置后覆盖 --days`}},endTime:{type:`string`,valueHint:`<time>`,description:{"en-US":`Range end (ISO date or ms epoch); default: now`,"zh-CN":`结束时间(ISO 日期或毫秒时间戳),默认当前时间`}}};function sm(e,t){let n=e.trim();if(/^\d+$/.test(n))return Number(n);let r=Date.parse(n);if(Number.isNaN(r))throw new x(`${t} must be an ISO date or a millisecond timestamp.`);return r}function cm(e,t=7){let n=e.endTime?sm(e.endTime,`--end-time`):Date.now(),r=e.startTime?sm(e.startTime,`--start-time`):e.hours==null?n-(e.days||t)*864e5:n-e.hours*36e5;if(r>=n)throw new x(`--start-time must be earlier than --end-time.`);return{startTime:r,endTime:n}}const lm={hours:{type:`number`,valueHint:`<hours>`,description:{"en-US":`Hours to look back (default: 1)`,"zh-CN":`向前查询的小时数(默认:1)`}},startTime:om.startTime,endTime:om.endTime};function um(e){let t=Ln(e);return typeof t==`object`&&t&&`result`in t?t.result:t}const dm=[60,3600,86400];function fm(e,t){let n=(t-e)/36e5;return n<=12?60:n<=168?3600:86400}async function pm(e){let{originData:t,dataDownloadUrl:r}=e;if(t!=null)return t;if(r){let e=await fetch(r.replace(/^http:\/\//,`https://`));if(!e.ok)throw new n(`Failed to download telemetry data (HTTP ${e.status}).`,l.NETWORK);return await e.json()}}const mm=`zeldaEasy.bailian-telemetry.activate.getTelemetryServiceStatus`;async function hm(e,t,n){return await im(e,mm,{...n?{workspaceId:n}:{},serviceType:t})}async function gm(e,t){let r=await hm(e,t.serviceType,t.workspaceId);if(!(t.requireInstance===!1?r.openStatus:r.openStatus&&r.instanceStatus===`Ready`))throw new n(`The monitoring service is not activated yet.`,l.AUTH,`Run \`${t.enableCommand}\` to activate it, or enable it in the Bailian console.`)}async function _m(e,t,n){return um(await e.console(`zeldaEasy.bailian-telemetry.activate.getTelemetrySlrStatus`,{reqDTO:{...n?{workspaceId:n}:{},slrType:t}}))===!0}async function vm(e,t,n,r={}){if(await _m(e,t,n))return!0;r.onProgress?.(`Authorizing the service-linked role...`),await e.console(`zeldaEasy.bailian-telemetry.activate.createTelemetrySlr`,{reqDTO:{...n?{workspaceId:n}:{},slrType:t}});let i=r.pollRetries??10,a=r.pollIntervalMs??2e3;for(let r=0;r<i;r+=1){if(await _m(e,t,n))return!0;await new Promise(e=>setTimeout(e,a))}return!1}const ym=`zeldaEasy.bailian-telemetry.telemetryGroup.enableTelemetryGroup`,bm=`zeldaEasy.bailian-telemetry.telemetryGroup.disableTelemetryGroup`;function xm(e){for(let t of[`result`,`list`,`data`]){let n=e[t];if(Array.isArray(n))return n}return[]}async function Sm(e,t,n){let r=await e.console(`zeldaEasy.bailian-telemetry.telemetryGroup.getTelemetryGroupStatus`,{reqDTO:{...n?{workspaceId:n}:{},resourceType:`model`,resourceIds:[`all`],telemetryType:t}}),i=Ln(r),a=(Array.isArray(i)?i:xm(i)).filter(e=>!n||String(e.workspaceId)===String(n));return a.length===0?null:a[0].telemetryStatus===`enable`}function Cm(e,t){return{...e.workspaceId?{workspaceId:e.workspaceId,filterWorkspaceId:e.workspaceId}:{},resourceId:`all`,resourceType:`model`,telemetryType:t}}const wm={model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name(s), comma-separated`,"zh-CN":`模型名称,多个名称以逗号分隔`}},apiKeyId:{type:`string`,valueHint:`<id>`,description:{"en-US":`API key ID(s), comma-separated`,"zh-CN":`API Key ID,多个以逗号分隔`}},channel:{type:`string`,valueHint:`<channel>`,description:{"en-US":`Call channel(s), comma-separated`,"zh-CN":`调用渠道,多个以逗号分隔`}},source:{type:`string`,valueHint:`<source>`,description:{"en-US":`Call source(s), comma-separated`,"zh-CN":`调用来源,多个以逗号分隔`}},callSource:{type:`string`,valueHint:`<type>`,choices:[`Online`,`Offline`],description:{"en-US":`Inference type: Online, Offline`,"zh-CN":`推理类型:Online、Offline`}}},Tm={model:wm.model,apiKeyId:wm.apiKeyId,channel:wm.channel,source:wm.source};function Em(e){if(!e)return;let t=U(e);return t.length?t:void 0}function Dm(e,t){return{...t?{workspaceId:t}:{},models:Em(e.model),apikeyIds:Em(e.apiKeyId),channels:Em(e.channel),sources:Em(e.source),modelCallSource:e.callSource}}function Om(e){let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`}function km(e){let t=new Date(e),n=String(t.getHours()).padStart(2,`0`),r=String(t.getMinutes()).padStart(2,`0`),i=String(t.getSeconds()).padStart(2,`0`);return`${Om(e)} ${n}:${r}:${i}`}function Am(e,t){if(e.workspaceId)return e.workspaceId;throw new n(`workspace-id is required. Set via --workspace-id, BAILIAN_WORKSPACE_ID, or \`${t} config set workspace_id <id>\`.`,l.GENERAL,`Run \`${t} workspace list\` to view available workspaces.`)}function jm(e){return Ln(e)}const Mm={Reasoning:`Text`,TG:`Text`,VU:`Text`,IG:`Vision`,VG:`Vision`,"Realtime-Omni":`Multimodal`,"Multimodal-Omni":`Multimodal`,ASR:`Audio`,TTS:`Audio`,"Voice-Replication":`Audio`,"Realtime-Text-to-Speech":`Audio`,"Realtime-Voice-Replication":`Audio`,"Realtime-ASR":`Audio`,"Realtime-Audio-Translate":`Audio`,ME:`Embedding`,TR:`Embedding`};function Nm(e){for(let t of e){let e=Mm[t];if(e)return e}return`-`}async function Pm(e){return(await Ve((t,n)=>e.console(t,n))).filter(e=>typeof e.model==`string`&&e.model).map(e=>({name:e.model,type:Nm(e.capabilities||[])}))}const Fm=`zeldaEasy.bailian-commerce.freeTrial.queryFreeTierQuota`,Im=`zeldaEasy.bailian-commerce.freeTrial.queryFreeTierOnlyStatus`;function Lm(e,t){let n=e.data;if(!n)return[];let r=n.DataV2;return r?r.data?.data?.[t]||[]:n.data?.[t]||[]}function Rm(e){return Lm(e,`freeTierQuotas`)}function zm(e){return Lm(e,`freeTierOnlyStatuses`)}function Bm(e){return Vm(e)||e.quotaInitTotal==null||e.quotaInitTotal<=0?null:Math.round(e.quotaTotal/e.quotaInitTotal*1e3)/10}function Vm(e){return e.quotaValidityPeriod>0&&e.quotaValidityPeriod<Date.now()}function Hm(e){let{quotas:t,stopMap:n,typeMap:r}=e,i=E(process.stdout);e.title&&process.stdout.write(i.purple(e.title)+`
|
|
2751
|
-
`);let a=[`Model`,`Type`,`Remaining`,`Total`,`Quota Left`,`Auto-Stop`],o=[],s=[],c=a.length-1,l=t.map(e=>{let t=e.quotaInitTotal!=null&&e.quotaTotal!=null,i=
|
|
2749
|
+
`)}if(i.out){let e=i.out,n=p.length===1?p[0]:p;Zr(e,JSON.stringify(n,null,2)+`
|
|
2750
|
+
`),t.quiet||process.stderr.write(`Full result saved to: ${e}\n`)}}const Up={id:{type:`string`,valueHint:`<id>`,description:{"en-US":`Hot-word vocabulary ID (required)`,"zh-CN":`热词表 ID(必填)`},required:!0}},Wp={words:{type:`string`,valueHint:`<json>`,description:{"en-US":`Hot words as JSON object of word→weight, e.g. '{"Fendouzhe":4}'; or the API entry array for per-entry lang. Weight 1-5 (4 recommended); when the vocabulary target_model is a Qwen-Audio-3.0-ASR-Flash series model, 50 is also allowed as super hot word. Or use --words-file`,"zh-CN":`热词,JSON 对象「热词→权重」,例如 '{"奋斗者":4}';需要逐条指定语言时可传 API 的条目数组。权重 1-5(推荐 4);当热词表的 target_model 为 Qwen-Audio-3.0-ASR-Flash 系列时还可使用 50(超级热词)。也可使用 --words-file`}},wordsFile:{type:`string`,valueHint:`<path>`,description:{"en-US":`JSON file with the hot words (use - for stdin)`,"zh-CN":`包含热词的 JSON 文件(使用 - 从 stdin 读取)`}},lang:{type:`string`,valueHint:`<code>`,description:{"en-US":`Language code applied to every hot word when using object form (optional; ignored for array form). Paraformer: zh/en/ja/yue/ko/de/fr/ru; Fun-ASR: zh/en/ja`,"zh-CN":`对象形态时应用到所有热词的语言代码(选填;数组形态忽略)。Paraformer 支持 zh/en/ja/yue/ko/de/fr/ru;Fun-ASR 支持 zh/en/ja`}}};function Gp(e){if(!e.words&&!e.wordsFile)return`Provide --words or --words-file.`;if(e.words&&e.wordsFile)return`Use either --words or --words-file, not both.`;if(e.words)try{tn(e.words,e.lang)}catch(e){if(e instanceof x)return e.message;throw e}}function Kp(e){let t=e.wordsFile?dn(e.wordsFile):e.words;return tn(t,e.lang)}const qp=[{"en-US":`Each account may have at most 10 vocabularies; updates must be at least 5 minutes apart. See improve-asr-accuracy for full limits.`,"zh-CN":`每个账号最多 10 个热词表;两次更新间隔至少 5 分钟。完整限制见 improve-asr-accuracy。`},{"en-US":`Hot-word vocabularies are not supported in Singapore sub-workspaces; the server error is passed through as-is.`,"zh-CN":`新加坡子业务空间不支持热词表;服务端错误会原样透传。`},{"en-US":`Weight 1-5 (4 recommended); when the vocabulary target_model is a Qwen-Audio-3.0-ASR-Flash series model, 50 is also allowed as super hot word.`,"zh-CN":`权重 1-5(推荐 4);当热词表的 target_model 为 Qwen-Audio-3.0-ASR-Flash 系列时还可使用 50(超级热词)。`}],Jp={model:{type:`string`,valueHint:`<model>`,description:{"en-US":"ASR model this vocabulary is built for (required). Must exactly match the --model passed to `speech recognize` later, otherwise the vocabulary is silently ignored","zh-CN":"该热词表服务的 ASR 模型(必填)。必须与后续 `speech recognize` 的 --model 完全一致,否则热词表静默失效"},required:!0},prefix:{type:`string`,valueHint:`<prefix>`,description:{"en-US":`Custom vocabulary prefix (required). Digits and lowercase letters only, max 10 chars`,"zh-CN":`热词表自定义前缀(必填)。仅允许数字和小写字母,最长 10 个字符`},required:!0},...Wp};var Yp=S({description:{"en-US":`Create a precompiled hot-word vocabulary for ASR`,"zh-CN":`创建用于语音识别的预编译热词表`},auth:`apiKey`,usageArgs:`--model <model> --prefix <prefix> (--words <json> | --words-file <path>) [flags]`,flags:Jp,notes:[{"en-US":"The --model must exactly match the --model used later with `speech recognize --vocabulary-id`; a mismatch causes silent failure with no error.","zh-CN":"--model 必须与后续 `speech recognize --vocabulary-id` 使用的 --model 完全一致;不一致时热词表会静默失效且无报错。"},...qp],exampleArgs:[{"en-US":`--model fun-asr --prefix demo --words '{"Fendouzhe":4,"Jingluo":4}'`,"zh-CN":`--model fun-asr --prefix demo --words '{"奋斗者":4,"鲸落":4}'`},{"en-US":`--model paraformer-v2 --prefix demo --words '[{"text":"Fendouzhe","weight":4,"lang":"zh"}]'`,"zh-CN":`--model paraformer-v2 --prefix demo --words '[{"text":"奋斗者","weight":4,"lang":"zh"}]'`},{"en-US":`--model fun-asr --prefix demo --words '{"Fendouzhe":4}' --lang zh`,"zh-CN":`--model fun-asr --prefix demo --words '{"奋斗者":4}' --lang zh`},`--model fun-asr --prefix demo --words-file ./hotwords.json`,{"en-US":`--model fun-asr --prefix demo --words '{"Fendouzhe":4}' --quiet`,"zh-CN":`--model fun-asr --prefix demo --words '{"奋斗者":4}' --quiet`}],validate:e=>Gp(e),async run(e){let{settings:t,flags:n}=e,r=Kp(n),i=C(t.output),a=he(`create_vocabulary`,{target_model:n.model,prefix:n.prefix,vocabulary:r});if(t.dryRun){O({endpoint:e.client.url(zn()),request:a},i);return}let o=await Ee(e.client,{targetModel:n.model,prefix:n.prefix,vocabulary:r});t.quiet||i===`text`?D(o.output?.vocabulary_id??``):O(o,i)}}),Xp=S({description:{"en-US":`List precompiled hot-word vocabularies`,"zh-CN":`列出预编译热词表`},auth:`apiKey`,usageArgs:`[--prefix <prefix>] [--page <n>] [--page-size <n>]`,flags:{prefix:{type:`string`,valueHint:`<prefix>`,description:{"en-US":`Filter by vocabulary prefix`,"zh-CN":`按热词表前缀过滤`}},page:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number, 1-based (default: 1). Mapped to API page_index (0-based) as page - 1`,"zh-CN":`页码,从 1 开始(默认:1)。映射为 API 的 page_index(从 0 开始):page - 1`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Results per page (default: 10)`,"zh-CN":`每页结果数(默认:10)`}}},notes:[{"en-US":"List responses do not include target_model; use `speech vocabulary get` to inspect the model a vocabulary was built for.","zh-CN":"list 响应不含 target_model;要对齐模型请使用 `speech vocabulary get`。"},{"en-US":`Vocabularies with status UNDEPLOYED are silently ignored by ASR.`,"zh-CN":`status 为 UNDEPLOYED 的热词表会被 ASR 静默忽略。`}],exampleArgs:[``,`--prefix demo`,`--page 2 --page-size 20`],validate:e=>{if(e.page!==void 0&&e.page<1)return`--page must be >= 1.`},async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=n.page===void 0?void 0:n.page-1,a={};if(n.prefix!==void 0&&(a.prefix=n.prefix),i!==void 0&&(a.page_index=i),n.pageSize!==void 0&&(a.page_size=n.pageSize),t.dryRun){O({endpoint:e.client.url(zn()),request:he(`list_vocabulary`,a)},r);return}let o=await It(e.client,{prefix:n.prefix,pageIndex:i,pageSize:n.pageSize});if(t.quiet||r===`text`){let e=o.output?.vocabulary_list??[];if(e.length===0)D(`No vocabularies found.`);else{let t=!1;for(let n of e){let e=n.vocabulary_id??``,r=n.status??``,i=n.gmt_modified??``;r===`UNDEPLOYED`&&(t=!0),D(`[${e}] ${r} ${i}`.trimEnd())}t&&D("Note: UNDEPLOYED vocabularies are silently ignored by ASR. Use `speech vocabulary get` to inspect them.")}}else O(o,r)}});const Zp={...Up};var Qp=S({description:{"en-US":`Get details of a precompiled hot-word vocabulary`,"zh-CN":`查看预编译热词表详情`},auth:`apiKey`,usageArgs:`--id <id>`,flags:Zp,notes:[{"en-US":"Use this command to confirm target_model before calling `speech recognize --vocabulary-id`; a model mismatch causes silent failure.","zh-CN":"调用 `speech recognize --vocabulary-id` 前请用本命令确认 target_model;模型不一致会导致静默失效。"}],exampleArgs:[`--id vocab-demo-xxx`,`--id vocab-demo-xxx --quiet`],async run(e){let{settings:t,flags:n}=e,r=n.id,i=C(t.output);if(t.dryRun){O({endpoint:e.client.url(zn()),request:he(`query_vocabulary`,{vocabulary_id:r})},i);return}let a=await sn(e.client,r),o=a.output;if(t.quiet){D(o?.target_model??``);return}if(i===`text`){D(`vocabulary_id: ${r}`),D(`status: ${o?.status??``}`),D(`target_model: ${o?.target_model??``}`),D(`gmt_create: ${o?.gmt_create??``}`),D(`gmt_modified: ${o?.gmt_modified??``}`);let e=o?.vocabulary??[];if(e.length>0){D(`vocabulary:`);for(let t of e){let e=t.lang?` lang=${t.lang}`:``;D(` ${t.text} weight=${t.weight}${e}`)}}}else O(a,i)}});const $p={...Up,...Wp};var em=S({description:{"en-US":`Replace the contents of a precompiled hot-word vocabulary`,"zh-CN":`完全替换预编译热词表的内容`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This fully replaces all hot words in the vocabulary. Entries not listed will be discarded and cannot be undone.`,"zh-CN":`该操作会完全替换热词表中的全部词条。未列出的词将被丢弃,且无法撤销。`}},usageArgs:`--id <id> (--words <json> | --words-file <path>) [flags]`,flags:$p,notes:[{"en-US":`update is a full replace, not an append. Prefer --dry-run first to preview the complete vocabulary that will be written.`,"zh-CN":`update 是完全替换,不是增量追加。建议先用 --dry-run 预览将要写入的完整词表。`},...qp],exampleArgs:[{"en-US":`--id vocab-demo-xxx --words '{"Fendouzhe":4}' --dry-run`,"zh-CN":`--id vocab-demo-xxx --words '{"奋斗者":4}' --dry-run`},{"en-US":`--id vocab-demo-xxx --words '{"Fendouzhe":4,"Jingluo":4}' --yes`,"zh-CN":`--id vocab-demo-xxx --words '{"奋斗者":4,"鲸落":4}' --yes`}],validate:e=>Gp(e),async run(e){let{settings:t,flags:n}=e,r=n.id,i=Kp(n),a=C(t.output),o=he(`update_vocabulary`,{vocabulary_id:r,vocabulary:i});if(t.dryRun){O({endpoint:e.client.url(zn()),request:o},a);return}let s=await Xn(e.client,r,i);t.quiet||a===`text`?D(r):O(s,a)}});const tm={...Up};var nm=S({description:{"en-US":`Delete a precompiled hot-word vocabulary`,"zh-CN":`删除预编译热词表`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the specified hot-word vocabulary and cannot be undone.`,"zh-CN":`该操作会永久删除指定的热词表,且无法撤销。`}},usageArgs:`--id <id>`,flags:tm,exampleArgs:[`--id vocab-demo-xxx --dry-run`,`--id vocab-demo-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=n.id,i=C(t.output);if(t.dryRun){O({endpoint:e.client.url(zn()),request:he(`delete_vocabulary`,{vocabulary_id:r})},i);return}let a=await Ne(e.client,r);t.quiet||i===`text`?D(r):O(a,i)}}),rm=S({description:{"en-US":`Upload a local file to DashScope temporary storage (48h)`,"zh-CN":`将本地文件上传到 DashScope 临时存储(保留 48 小时)`},auth:`apiKey`,usageArgs:`--file <path> --model <model>`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Local file to upload (image, video, audio)`,"zh-CN":`要上传的本地文件(图片、视频或音频)`},required:!0},model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Target model name (file is bound to this model)`,"zh-CN":`目标模型名称(文件将与该模型绑定)`},required:!0}},exampleArgs:[`--file photo.jpg --model qwen3-vl-plus`,`--file video.mp4 --model wan2.1-t2v-plus`,`--file audio.wav --model qwen3-asr-flash`,`--file cat.png --model qwen-image-3.0`],async run(e){let{settings:t,flags:n}=e,r=n.file,i=n.model,a=C(t.output);if(t.dryRun){O({action:`upload`,file:r,model:i},a);return}let o=await e.client.uploadFile(r,i);t.quiet?D(o):O({url:o,model:i,expires_in:`48 hours`,note:`When using this URL in API calls, add header: X-DashScope-OssResourceResolve: enable`},a)}}),im=S({description:{"en-US":`Call a Bailian console API via the CLI gateway`,"zh-CN":`通过 CLI Gateway 调用百炼控制台 API`},auth:`console`,usageArgs:`--api <api> --data <json> [flags]`,flags:{api:{type:`string`,valueHint:`<api>`,description:{"en-US":`API name (e.g. zeldaEasy.broadscope-bailian.memory-library.getLibraries)`,"zh-CN":`API 名称(例如 zeldaEasy.broadscope-bailian.memory-library.getLibraries)`},required:!0},data:{type:`string`,valueHint:`<json>`,description:{"en-US":`Request data as JSON string`,"zh-CN":`JSON 字符串格式的请求数据`},required:!0}},exampleArgs:[`--api zeldaEasy.bailian-commerce.freeTrial.queryFreeTierQuota --data '{"queryFreeTierQuotaRequest":{"models":["qwen3-max"]}}'`,`--api some.api.name --data '{"key":"value"}' --console-region cn-beijing`],async run(e){let{settings:t,flags:n}=e,r=n.api,i=n.data,a;try{a=JSON.parse(i)}catch{throw new x(`--data must be valid JSON`)}let o=C(t.output);if(t.dryRun){O({api:r,data:a,...w(t)},o);return}let s=await e.client.console(r,a);O(s,o)}});function am(e){let t=e.client.baseUrl.replace(/\/+$/,``);return t&&!yt(t)?t:ne(R(e))}const om={agent_identity:{"en-US":`Agent identity issuance`,"zh-CN":`Agent 身份签发`},content_safety:{"en-US":`Content safety`,"zh-CN":`内容安全`},supply_chain_scan:{"en-US":`Supply-chain static scan`,"zh-CN":`供应链静态扫描`},credential_isolation:{"en-US":`Credential isolation`,"zh-CN":`凭证隔离`},session_lifecycle:{"en-US":`Session lifecycle governance`,"zh-CN":`session 生命周期治理`}},sm={flow_agent:{"en-US":`Flow Agent`,"zh-CN":`Flow Agent`},managed_agent:{"en-US":`Managed Agents`,"zh-CN":`Managed Agents`},knowledge_base:{"en-US":`RAG`,"zh-CN":`RAG`},memory:{"en-US":`Memory`,"zh-CN":`Memory`},mcp:{"en-US":`Store`,"zh-CN":`Store`},external_agent:{"en-US":`BYOA hosting`,"zh-CN":`BYOA 托管`}},cm=[{label:{"en-US":`Content safety`,"zh-CN":`内容安全`},keys:[`content_safety`,`contentSafety`]},{label:{"en-US":`File scan`,"zh-CN":`文件扫描`},keys:[`file_scan`,`fileScan`]},{label:{"en-US":`Skill scan`,"zh-CN":`技能扫描`},keys:[`skill_scan`,`skillScan`]}],B={unavailable:{"en-US":`(unavailable)`,"zh-CN":`(不可用)`},on:{"en-US":`on`,"zh-CN":`开启`},off:{"en-US":`off`,"zh-CN":`关闭`},scannedLabel:{"en-US":`Scanned`,"zh-CN":`扫描`},risksLabel:{"en-US":`Risks`,"zh-CN":`风险`},capabilities:{"en-US":`Capabilities`,"zh-CN":`能力项`},protection:{"en-US":`Protection`,"zh-CN":`防护项`},detections:{"en-US":`Detections`,"zh-CN":`检测项`},overviewUnavailable:{"en-US":`Overview unavailable.`,"zh-CN":`总览不可用。`},hit:{"en-US":`hit`,"zh-CN":`命中`},scanned:{"en-US":`scanned`,"zh-CN":`扫描`},total:{"en-US":`Total`,"zh-CN":`总计`},high:{"en-US":`high`,"zh-CN":`高`},medium:{"en-US":`medium`,"zh-CN":`中`},low:{"en-US":`low`,"zh-CN":`低`},noAlerts:{"en-US":`No alerts found.`,"zh-CN":`未找到告警。`},nextPageCursor:{"en-US":`Next page cursor`,"zh-CN":`下一页游标`},app:{"en-US":`app`,"zh-CN":`应用`},asset:{"en-US":`asset`,"zh-CN":`资产`},status:{"en-US":`status`,"zh-CN":`状态`},source:{"en-US":`source`,"zh-CN":`来源`},checked:{"en-US":`checked`,"zh-CN":`检测时间`}};function lm(e,t,n){if(n!=null&&n!==``){if(Array.isArray(n)){for(let r of n)e.append(t,r);return}e.set(t,String(n))}}function um(e,t,n,r){if(D(`\n${e(t)}`),!n||n.length===0){D(` ${e(B.unavailable)}`);return}for(let t of n){let n=typeof t.count==`number`?` (${t.count})`:``,i=e(t.enabled?B.on:B.off),a=r[t.key]?e(r[t.key]):t.key;D(` ${i} ${a}${n}`)}}function dm(e){if(!e)return`-`;let t=/^\d+$/.test(e)?Number(e):Date.parse(e);return Number.isNaN(t)?e:new Date(t).toISOString().replace(`T`,` `).slice(0,19)}function fm(e,t){let n=(t.risk_level??`unknown`).toUpperCase();D(`[${n}] ${t.risk_name??`-`} (${t.alert_id})`),D(` ${e(B.app)}: ${t.app_name??`-`} ${e(B.asset)}: ${t.asset_name??`-`} (${t.asset_type??`-`})`),D(` ${e(B.status)}: ${t.status??`-`} ${e(B.source)}: ${t.source??`-`} ${e(B.checked)}: ${dm(t.check_time)}`),t.risk_desc&&D(` ${t.risk_desc}`),D(``)}const pm={...L};var mm=S({description:{"en-US":`Show the Agent security protection overview (last 24 hours)`,"zh-CN":`查看 Agent 安全防护总览(最近 24 小时)`},auth:`apiKey`,usageArgs:`[flags]`,flags:pm,notes:[{"en-US":`Auth: uses DashScope API Key (Bearer token).`,"zh-CN":`鉴权:使用 DashScope API Key(Bearer Token)。`},{"en-US":"`--workspace-id` can be set via BAILIAN_WORKSPACE_ID env or config workspace_id.","zh-CN":"`--workspace-id` 可通过 BAILIAN_WORKSPACE_ID 环境变量或配置项 workspace_id 设置。"},{"en-US":`Fixed to the last 24 hours; the AgentStudio region is always cn-beijing and is not configurable.`,"zh-CN":`固定统计最近 24 小时;AgentStudio 地域固定为 cn-beijing,不可配置。`},{"en-US":"AgentStudio host: derived from --workspace-id by default; point --base-url / DASHSCOPE_BASE_URL (or `auth login --base-url`) at a workspace or pre-release origin such as https://<workspace-id>.cn-beijing.maas.aliyuncs.com/api/v1/agentstudio to override it, and --workspace-id is then not required.","zh-CN":"AgentStudio 域名:默认由 --workspace-id 推导;将 --base-url / DASHSCOPE_BASE_URL(或 `auth login --base-url`)指向某个 workspace 或预发源(例如 https://<workspace-id>.cn-beijing.maas.aliyuncs.com/api/v1/agentstudio)即可覆盖,此时无需 --workspace-id。"}],exampleArgs:[{"en-US":`--workspace-id ws-xxx`,"zh-CN":`--workspace-id ws-xxx`},{"en-US":`--workspace-id ws-xxx --output json`,"zh-CN":`--workspace-id ws-xxx --output json`}],async run(e){let{settings:t,localize:n}=e,r=C(t.output),i=In(am(e));if(t.dryRun){O({endpoint:i,method:`GET`},r);return}let a=await Fn(e.client,i);if(!a){r===`json`?O({},r):D(n(B.overviewUnavailable));return}if(r===`json`){O(a,r);return}let o=cm.map(({label:e,keys:t})=>{let r=t.map(e=>a[e]).find(e=>e!==void 0);return{label:n(e),stat:r??null}}),s=e=>o.reduce((t,n)=>t+(n.stat?e(n.stat)??0:0),0);D(`${n(B.scannedLabel)}: ${s(e=>e.scanned)} ${n(B.risksLabel)}: ${s(e=>e.hit)}`),um(n,B.capabilities,a.capabilities,om),um(n,B.protection,a.protection,sm),D(`\n${n(B.detections)}`);for(let{label:e,stat:t}of o)D(t?` ${e} ${n(B.hit)} ${t.hit??`-`} / ${n(B.scanned)} ${t.scanned??`-`}`:` ${e} ${n(B.unavailable)}`)}});const hm=[`agent`,`tool`,`skill`,`knowledge_base`,`memory`,`channel`],gm={...L,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: 20)`,"zh-CN":`每页结果数(默认:20)`}},riskLevel:{type:`string`,valueHint:`<level>`,choices:[`high`,`medium`,`low`],description:{"en-US":`Filter by risk level: high, medium, low`,"zh-CN":`按风险等级筛选:high、medium、low`}},riskName:{type:`string`,valueHint:`<text>`,description:{"en-US":`Filter by risk name`,"zh-CN":`按风险名称筛选`}},status:{type:`string`,valueHint:`<status>`,description:{"en-US":`Filter by handling status`,"zh-CN":`按处理状态筛选`}},statusList:{type:`array`,valueHint:`<status>`,description:{"en-US":`Filter by multiple statuses (repeatable)`,"zh-CN":`按多个状态筛选(可重复传入)`}},appName:{type:`string`,valueHint:`<name>`,description:{"en-US":`Filter by application name`,"zh-CN":`按应用名称筛选`}},assetType:{type:`string`,valueHint:`<type>`,choices:hm,description:{"en-US":`Filter by asset type: ${hm.join(`, `)}`,"zh-CN":`按资产类型筛选:${hm.join(`、`)}`}},vendor:{type:`string`,valueHint:`<vendor>`,description:{"en-US":`Filter by vendor`,"zh-CN":`按厂商筛选`}},orderBy:{type:`string`,valueHint:`<field>`,description:{"en-US":`Sort field (default: check_time)`,"zh-CN":`排序字段(默认:check_time)`}},order:{type:`string`,valueHint:`<dir>`,choices:[`asc`,`desc`],description:{"en-US":`Sort direction: asc, desc (default: desc)`,"zh-CN":`排序方向:asc、desc(默认:desc)`}},lang:{type:`string`,valueHint:`<lang>`,choices:[`zh`,`en`],description:{"en-US":`Response language: zh, en`,"zh-CN":`响应语言:zh、en`}}};var _m=S({description:{"en-US":`List Agent security alerts`,"zh-CN":`列出 Agent 安全告警`},auth:`apiKey`,usageArgs:`[flags]`,flags:gm,notes:[{"en-US":`Auth: uses DashScope API Key (Bearer token).`,"zh-CN":`鉴权:使用 DashScope API Key(Bearer Token)。`},{"en-US":"`--workspace-id` can be set via BAILIAN_WORKSPACE_ID env or config workspace_id.","zh-CN":"`--workspace-id` 可通过 BAILIAN_WORKSPACE_ID 环境变量或配置项 workspace_id 设置。"},{"en-US":`Filters, pagination and sorting go in the query string; enum flags are validated before any request is sent.`,"zh-CN":`筛选、分页与排序参数走 query string;枚举类 flag 在发起请求前校验。`},{"en-US":"AgentStudio host: derived from --workspace-id by default; point --base-url / DASHSCOPE_BASE_URL (or `auth login --base-url`) at a workspace or pre-release origin such as https://<workspace-id>.cn-beijing.maas.aliyuncs.com/api/v1/agentstudio to override it, and --workspace-id is then not required.","zh-CN":"AgentStudio 域名:默认由 --workspace-id 推导;将 --base-url / DASHSCOPE_BASE_URL(或 `auth login --base-url`)指向某个 workspace 或预发源(例如 https://<workspace-id>.cn-beijing.maas.aliyuncs.com/api/v1/agentstudio)即可覆盖,此时无需 --workspace-id。"}],exampleArgs:[{"en-US":`--workspace-id ws-xxx`,"zh-CN":`--workspace-id ws-xxx`},{"en-US":`--risk-level high --page-size 50`,"zh-CN":`--risk-level high --page-size 50`},{"en-US":`--asset-type agent --app-name "demo app" --output json`,"zh-CN":`--asset-type agent --app-name "测试应用0" --output json`},{"en-US":`--status-list unhandled --status-list handling`,"zh-CN":`--status-list unhandled --status-list handling`}],async run(e){let{settings:t,flags:n,localize:r}=e,i=C(t.output),a=am(e),o=new URLSearchParams;lm(o,`current_page`,n.page),lm(o,`page_size`,n.pageSize),lm(o,`risk_level`,n.riskLevel),lm(o,`risk_name`,n.riskName),lm(o,`status`,n.status),lm(o,`status_list`,n.statusList),lm(o,`app_name`,n.appName),lm(o,`asset_type`,n.assetType),lm(o,`vendor`,n.vendor),lm(o,`order_by`,n.orderBy),lm(o,`order`,n.order),lm(o,`lang`,n.lang);let s=o.toString(),c=Pn(a),l=s?`${c}?${s}`:c;if(t.dryRun){O({endpoint:l,method:`GET`},i);return}let u=await Fn(e.client,l),d=u?.data??[];if(t.quiet){for(let e of d)D(e.alert_id);return}if(i===`json`){O(u??{stats:null,data:[],next_page:null},i);return}let f=u?.stats;if(f&&D(`${r(B.total)}: ${f.total??`-`} ${r(B.high)}: ${f.high??`-`} ${r(B.medium)}: ${f.medium??`-`} ${r(B.low)}: ${f.low??`-`}\n`),d.length===0){D(r(B.noAlerts));return}for(let e of d)fm(r,e);u?.next_page&&D(`${r(B.nextPageCursor)}: ${u.next_page}`)}});function V(e){return e.toLocaleString(`en-US`)}function vm(e){let t=new Date(e),n=String(t.getMonth()+1).padStart(2,`0`),r=String(t.getDate()).padStart(2,`0`);return`${t.getFullYear()}-${n}-${r}`}function H(e){let t=e=>String(e).padStart(2,`0`),n=new Date(e);return`${vm(e)} ${t(n.getHours())}:${t(n.getMinutes())}:${t(n.getSeconds())}`}function U(e){return[...new Set(e.split(`,`).map(e=>e.trim()).filter(Boolean))]}function ym(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))r!==void 0&&r!==``&&t.set(n,String(r));let n=t.toString();return n?`?${n}`:``}async function bm(e,t,n,r=30){let i;for(let a=0;a<r;a++){let r=await e.console(t,n(i)),a=qn(r);if(a.taskId&&Object.keys(a).length===1){i=a.taskId,await new Promise(e=>setTimeout(e,500));continue}return r}return null}async function xm(e,t,n){return bm(e,t,e=>e?{reqDTO:{...n,asyncTaskId:e}}:{reqDTO:n})}async function Sm(e,t,r){let i=await xm(e,t,r);if(!i)throw new n(`Request timed out.`,l.TIMEOUT);return qn(i)}const Cm=[`cn-beijing`,`ap-southeast-1`];function W(e){let t=w(e).consoleRegion;if(!Cm.includes(t))throw new x(`Model monitor/log/alert commands are not available in console region "${t}". Supported regions: ${Cm.join(`, `)} (set --console-region).`)}const wm={days:{type:`number`,valueHint:`<days>`,description:{"en-US":`Number of days to look back (default: 7)`,"zh-CN":`向前查询的天数(默认:7)`}},startTime:{type:`string`,valueHint:`<time>`,description:{"en-US":`Range start (ISO date or ms epoch); overrides --days`,"zh-CN":`开始时间(ISO 日期或毫秒时间戳),设置后覆盖 --days`}},endTime:{type:`string`,valueHint:`<time>`,description:{"en-US":`Range end (ISO date or ms epoch); default: now`,"zh-CN":`结束时间(ISO 日期或毫秒时间戳),默认当前时间`}}};function Tm(e,t){let n=e.trim();if(/^\d+$/.test(n))return Number(n);let r=Date.parse(n);if(Number.isNaN(r))throw new x(`${t} must be an ISO date or a millisecond timestamp.`);return r}function Em(e,t=7){let n=e.endTime?Tm(e.endTime,`--end-time`):Date.now(),r=e.startTime?Tm(e.startTime,`--start-time`):e.hours==null?n-(e.days||t)*864e5:n-e.hours*36e5;if(r>=n)throw new x(`--start-time must be earlier than --end-time.`);return{startTime:r,endTime:n}}const Dm={hours:{type:`number`,valueHint:`<hours>`,description:{"en-US":`Hours to look back (default: 1)`,"zh-CN":`向前查询的小时数(默认:1)`}},startTime:wm.startTime,endTime:wm.endTime};function Om(e){let t=qn(e);return typeof t==`object`&&t&&`result`in t?t.result:t}const km=[60,3600,86400];function Am(e,t){let n=(t-e)/36e5;return n<=12?60:n<=168?3600:86400}async function jm(e){let{originData:t,dataDownloadUrl:r}=e;if(t!=null)return t;if(r){let e=await fetch(r.replace(/^http:\/\//,`https://`));if(!e.ok)throw new n(`Failed to download telemetry data (HTTP ${e.status}).`,l.NETWORK);return await e.json()}}const Mm=`zeldaEasy.bailian-telemetry.activate.getTelemetryServiceStatus`;async function Nm(e,t,n){return await Sm(e,Mm,{...n?{workspaceId:n}:{},serviceType:t})}async function Pm(e,t){let r=await Nm(e,t.serviceType,t.workspaceId);if(!(t.requireInstance===!1?r.openStatus:r.openStatus&&r.instanceStatus===`Ready`))throw new n(`The monitoring service is not activated yet.`,l.AUTH,`Run \`${t.enableCommand}\` to activate it, or enable it in the Bailian console.`)}async function Fm(e,t,n){return Om(await e.console(`zeldaEasy.bailian-telemetry.activate.getTelemetrySlrStatus`,{reqDTO:{...n?{workspaceId:n}:{},slrType:t}}))===!0}async function Im(e,t,n,r={}){if(await Fm(e,t,n))return!0;r.onProgress?.(`Authorizing the service-linked role...`),await e.console(`zeldaEasy.bailian-telemetry.activate.createTelemetrySlr`,{reqDTO:{...n?{workspaceId:n}:{},slrType:t}});let i=r.pollRetries??10,a=r.pollIntervalMs??2e3;for(let r=0;r<i;r+=1){if(await Fm(e,t,n))return!0;await new Promise(e=>setTimeout(e,a))}return!1}const Lm=`zeldaEasy.bailian-telemetry.telemetryGroup.enableTelemetryGroup`,Rm=`zeldaEasy.bailian-telemetry.telemetryGroup.disableTelemetryGroup`;function zm(e){for(let t of[`result`,`list`,`data`]){let n=e[t];if(Array.isArray(n))return n}return[]}async function Bm(e,t,n){let r=await e.console(`zeldaEasy.bailian-telemetry.telemetryGroup.getTelemetryGroupStatus`,{reqDTO:{...n?{workspaceId:n}:{},resourceType:`model`,resourceIds:[`all`],telemetryType:t}}),i=qn(r),a=(Array.isArray(i)?i:zm(i)).filter(e=>!n||String(e.workspaceId)===String(n));return a.length===0?null:a[0].telemetryStatus===`enable`}function Vm(e,t){return{...e.workspaceId?{workspaceId:e.workspaceId,filterWorkspaceId:e.workspaceId}:{},resourceId:`all`,resourceType:`model`,telemetryType:t}}const Hm={model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name(s), comma-separated`,"zh-CN":`模型名称,多个名称以逗号分隔`}},apiKeyId:{type:`string`,valueHint:`<id>`,description:{"en-US":`API key ID(s), comma-separated`,"zh-CN":`API Key ID,多个以逗号分隔`}},channel:{type:`string`,valueHint:`<channel>`,description:{"en-US":`Call channel(s), comma-separated`,"zh-CN":`调用渠道,多个以逗号分隔`}},source:{type:`string`,valueHint:`<source>`,description:{"en-US":`Call source(s), comma-separated`,"zh-CN":`调用来源,多个以逗号分隔`}},callSource:{type:`string`,valueHint:`<type>`,choices:[`Online`,`Offline`],description:{"en-US":`Inference type: Online, Offline`,"zh-CN":`推理类型:Online、Offline`}}},Um={model:Hm.model,apiKeyId:Hm.apiKeyId,channel:Hm.channel,source:Hm.source};function Wm(e){if(!e)return;let t=U(e);return t.length?t:void 0}function Gm(e,t){return{...t?{workspaceId:t}:{},models:Wm(e.model),apikeyIds:Wm(e.apiKeyId),channels:Wm(e.channel),sources:Wm(e.source),modelCallSource:e.callSource}}function Km(e){let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`}function qm(e){let t=new Date(e),n=String(t.getHours()).padStart(2,`0`),r=String(t.getMinutes()).padStart(2,`0`),i=String(t.getSeconds()).padStart(2,`0`);return`${Km(e)} ${n}:${r}:${i}`}function Jm(e,t){if(e.workspaceId)return e.workspaceId;throw new n(`workspace-id is required. Set via --workspace-id, BAILIAN_WORKSPACE_ID, or \`${t} config set workspace_id <id>\`.`,l.GENERAL,`Run \`${t} workspace list\` to view available workspaces.`)}function Ym(e){return qn(e)}const Xm={Reasoning:`Text`,TG:`Text`,VU:`Text`,IG:`Vision`,VG:`Vision`,"Realtime-Omni":`Multimodal`,"Multimodal-Omni":`Multimodal`,ASR:`Audio`,TTS:`Audio`,"Voice-Replication":`Audio`,"Realtime-Text-to-Speech":`Audio`,"Realtime-Voice-Replication":`Audio`,"Realtime-ASR":`Audio`,"Realtime-Audio-Translate":`Audio`,ME:`Embedding`,TR:`Embedding`};function Zm(e){for(let t of e){let e=Xm[t];if(e)return e}return`-`}async function Qm(e){return(await Ge((t,n)=>e.console(t,n))).filter(e=>typeof e.model==`string`&&e.model).map(e=>({name:e.model,type:Zm(e.capabilities||[])}))}const $m=`zeldaEasy.bailian-commerce.freeTrial.queryFreeTierQuota`,eh=`zeldaEasy.bailian-commerce.freeTrial.queryFreeTierOnlyStatus`;function th(e,t){let n=e.data;if(!n)return[];let r=n.DataV2;return r?r.data?.data?.[t]||[]:n.data?.[t]||[]}function nh(e){return th(e,`freeTierQuotas`)}function rh(e){return th(e,`freeTierOnlyStatuses`)}function ih(e){return ah(e)||e.quotaInitTotal==null||e.quotaInitTotal<=0?null:Math.round(e.quotaTotal/e.quotaInitTotal*1e3)/10}function ah(e){return e.quotaValidityPeriod>0&&e.quotaValidityPeriod<Date.now()}function oh(e){let{quotas:t,stopMap:n,typeMap:r}=e,i=E(process.stdout);e.title&&process.stdout.write(i.purple(e.title)+`
|
|
2751
|
+
`);let a=[`Model`,`Type`,`Remaining`,`Total`,`Quota Left`,`Auto-Stop`],o=[],s=[],c=a.length-1,l=t.map(e=>{let t=e.quotaInitTotal!=null&&e.quotaTotal!=null,i=ah(e),a=t?`${V(e.quotaTotal)}${i?` (expired)`:``}`:`-`,c=t?V(e.quotaInitTotal):`-`,l=ih(e);o.push(l),s.push(i?`expired`:l==null?`-`:null);let u=n.get(e.model),d=u===!0?`ON`:u===!1?`OFF`:e.quotaStatus===`UNKNOWN`?`Unsupported`:`-`;return[e.model,r.get(e.model)||`-`,a,c,``,d]}),u=jr({headers:a,rows:l,align:[`left`,`left`,`right`,`right`,`left`,`left`],barColumns:[{index:4,percents:o,labels:s}],cellColor:(e,t,n)=>{if(t===c){if(n===`ON`)return i.green(n);if(n===`OFF`)return i.yellow(n)}}});for(let e of u)process.stdout.write(e+`
|
|
2752
2752
|
`);e.moreHint&&process.stdout.write(i.dim(e.moreHint)+`
|
|
2753
|
-
`)}const
|
|
2754
|
-
`);return}let y=!i&&!s?p.slice(0,15):p,b=p.length-y.length,ee=m===`remaining`?` · sorted by urgency`:``;
|
|
2755
|
-
`);return}let a=/* @__PURE__ */ new Set,o=e.map(e=>{let t=
|
|
2753
|
+
`)}const sh=`zeldaEasy.bailian-telemetry.model.getModelUsageStatistic`,ch=`zeldaEasy.bailian-telemetry.model.listModelUsageStatisticData`;async function lh(e,t,n,r){return bm(e,t,e=>({[n]:e?{taskId:e}:{models:r}}),20)}function uh(e){let t=Ym(e);if(t.callSuccessCount!==void 0||t.usages!==void 0)return t}function dh(e){let t=Ym(e);return{list:t.list??[],totalCount:t.totalCount??0,maxResults:t.maxResults??0}}function fh(e){let t={};if(e.usages&&Array.isArray(e.usages))for(let n of e.usages)n.key&&n.value!=null&&(t[n.key]=n.value);if(e.usage&&typeof e.usage==`object`)for(let[n,r]of Object.entries(e.usage))r!=null&&(t[n]=r);return t}const ph={total_token:{en:`Total Tokens`,unit:`tokens`},input_token:{en:`Input Tokens`,unit:`tokens`},output_token:{en:`Output Tokens`,unit:`tokens`},input_token_cache:{en:`Cached Tokens`,unit:`tokens`},input_token_cache_read:{en:`Cache Read`,unit:`tokens`},input_token_cache_creation:{en:`Cache Creation`,unit:`tokens`},thinking_input_token:{en:`Thinking Input`,unit:`tokens`},thinking_output_token:{en:`Thinking Output`,unit:`tokens`},text_input_token:{en:`Text Input`,unit:`tokens`},purein_text_output_token:{en:`Text Output`,unit:`tokens`},embedding_token:{en:`Embedding`,unit:`tokens`},image_number:{en:`Images`,unit:`images`},video_duration:{en:`Video Duration`,unit:`sec`},content_duration:{en:`Audio Duration`,unit:`sec`},tts_text_number:{en:`TTS Chars`,unit:`chars`},total_token_avg:{en:`Avg Tokens/Req`}};function mh(e){let t=ph[e];if(!t)return e;let n=t.unit?` [${t.unit}]`:``;return`${t.en}${n}`}function hh(e,t,n,r,i=`Usage Overview`){let a=E(process.stdout);process.stdout.write(`${a.purple(i)} ${a.dim(`·`)} ${Km(t)} ~ ${Km(n)} ${a.dim(`(${r} days)`)}\n`);let o=[[`Models Called`,V(e.modelCount??0)],[`Successful Calls`,V(e.callSuccessCount??0)]];for(let t of e.usages??[])o.push([mh(t.key),V(t.value)]);let s=Math.max(...o.map(([e])=>hr(e)));for(let[e,t]of o)process.stdout.write(`${a.bold(k(e,s+2))}${t}\n`)}var gh=S({description:{"en-US":`Query free-tier quota for models (all models if --model is omitted)`,"zh-CN":`查询模型免费额度(省略 --model 时查询全部模型)`},auth:`console`,usageArgs:`[--model <model>[,model2,...]] [flags]`,flags:{model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name(s) to query, comma-separated for multiple; omit for all models`,"zh-CN":`要查询的模型名称;多个名称以逗号分隔,省略时查询全部模型`}},expiring:{type:`string`,valueHint:`<days>`,description:{"en-US":`Only show quotas expiring within N days`,"zh-CN":`仅显示将在 N 天内到期的额度`}},sort:{type:`string`,valueHint:`<field>`,description:{"en-US":`Sort by: remaining (ascending), expires (ascending)`,"zh-CN":`排序方式:remaining(剩余额度升序)、expires(到期时间升序)`},choices:[`remaining`,`expires`]},all:{type:`switch`,description:{"en-US":`Show all models instead of the top rows`,"zh-CN":`显示全部模型,而不只显示前几行`}}},exampleArgs:[``,`--model qwen3-max`,`--model qwen3-max,qwen-turbo`,`--expiring 30`,`--sort remaining`,`--all`,`--model qwen-turbo --output json`,`--model qwen3-max --console-region cn-beijing`],async run(e){let{identity:t,settings:n,flags:r}=e,i=r.model||void 0,a=Number(r.expiring)||0,o=r.sort||void 0,s=!!r.all,c=C(n.output),l,u=/* @__PURE__ */ new Map;l=i?[...new Set(i.split(`,`).map(e=>e.trim()).filter(Boolean))]:[];let d={queryFreeTierQuotaRequest:{models:l}};if(n.dryRun){O({api:$m,data:d},c);return}if(i){let t=await Promise.all(l.map(t=>Xe((t,n)=>e.client.console(t,n),t)));for(let e=0;e<l.length;e++){let n=t[e];n&&u.set(l[e],Zm(n.capabilities||[]))}}else{let t=await Qm(e.client);l=t.map(e=>e.name);for(let e of t)u.set(e.name,e.type);d.queryFreeTierQuotaRequest.models=l}let f=nh(await e.client.console($m,d)),p=i?f:f.filter(e=>e.quotaStatus===`VALID`&&e.quotaInitTotal>0);if(a>0){let e=Date.now()+a*24*60*60*1e3;p=p.filter(t=>t.quotaValidityPeriod>0&&t.quotaValidityPeriod<=e)}let m=o??(i?void 0:`remaining`);m===`remaining`?p.sort((e,t)=>(e.quotaInitTotal?e.quotaTotal/e.quotaInitTotal:0)-(t.quotaInitTotal?t.quotaTotal/t.quotaInitTotal:0)):m===`expires`&&p.sort((e,t)=>(e.quotaValidityPeriod??0)-(t.quotaValidityPeriod??0));let h=p.map(e=>e.model),g=h.length?await e.client.console(eh,{queryFreeTierOnlyStatusRequest:{models:h}}):null,_=g?rh(g):[],v=new Map(_.map(e=>[e.model,e.freeTierOnly]));if(c===`json`){let e=p.map(e=>{let t=e.quotaInitTotal!=null&&e.quotaTotal!=null,n=t?e.quotaInitTotal-e.quotaTotal:0,r=v.get(e.model),i=r===!0?!0:r===!1?!1:e.quotaStatus===`UNKNOWN`?`unsupported`:null;return{model:e.model,type:u.get(e.model)||null,remaining:t?e.quotaTotal:null,total:t?e.quotaInitTotal:null,usagePercent:t&&e.quotaInitTotal>0?Math.round(n/e.quotaInitTotal*1e3)/10:null,remainingPercent:ih(e),expires:e.quotaValidityPeriod?Km(e.quotaValidityPeriod):null,autoStop:i}});O(e,c);return}if(p.length===0){process.stdout.write(`No free-tier quota found.
|
|
2754
|
+
`);return}let y=!i&&!s?p.slice(0,15):p,b=p.length-y.length,ee=m===`remaining`?` · sorted by urgency`:``;oh({quotas:y,stopMap:v,typeMap:u,title:`Free Tier Quota · ${p.length} models${ee}`,moreHint:b>0?`+ ${b} more · ${t.binName} usage free --all to browse all`:void 0})}}),_h=S({description:{"en-US":`Enable or disable auto-stop for free-tier models. Enables by default; use --off to disable`,"zh-CN":`启用或停用免费额度模型自动停止。默认启用,使用 --off 停用`},auth:`console`,usageArgs:`<--model <model>[,model2,...] | --all> [--off] [flags]`,flags:{model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name(s), comma-separated for multiple`,"zh-CN":`模型名称,多个名称以逗号分隔`}},all:{type:`switch`,description:{"en-US":`Apply to all free-tier models`,"zh-CN":`应用于全部免费额度模型`}},on:{type:`switch`,description:{"en-US":`Enable auto-stop (default behavior)`,"zh-CN":`启用自动停止(默认行为)`}},off:{type:`switch`,description:{"en-US":`Disable auto-stop`,"zh-CN":`停用自动停止`}}},exampleArgs:[`--model qwen3-max`,`--model qwen3-max,qwen-turbo`,`--all`,`--on --model qwen3-max`,`--off --model qwen3-max`,`--off --all`],validate:e=>!e.model&&!e.all?`Provide --model <model>[,model2,...] or --all.`:void 0,async run(e){let{settings:t,flags:n}=e,r=n.model||void 0,i=!!n.off,a=C(t.output),o;o=r?[...new Set(r.split(`,`).map(e=>e.trim()).filter(Boolean))]:[];let s=i?`zeldaEasy.bailian-commerce.freeTrial.batchDeactivateFreeTierOnly`:`zeldaEasy.bailian-commerce.freeTrial.batchActivateFreeTierOnly`,c=i?`BatchDeactivateFreeTierOnlyRequest`:`BatchActivateFreeTierOnlyRequest`;if(t.dryRun){O({api:s,data:{[c]:{models:o}}},a);return}if(r||(o=(await Qm(e.client)).map(e=>e.name)),i){let t=rh(await e.client.console(eh,{queryFreeTierOnlyStatusRequest:{models:o}})),n=new Map(t.map(e=>[e.model,e.freeTierOnly]));for(let t of o){if(n.get(t)===!1){process.stderr.write(`Auto-stop is already disabled for "${t}".\n`);continue}await lh(e.client,s,c,[t]),process.stdout.write(`Disabled auto-stop for "${t}".\n`)}return}let l=[];for(let t of o){let n=await lh(e.client,s,c,[t]);if(a===`json`){l.push(n);continue}if(n){let e=qn(n).failureModels??[];e.length>0?process.stderr.write(`Failed to enable auto-stop for "${t}" (${e[0].errorCode}).\n`):process.stdout.write(`Enabled auto-stop for "${t}".\n`)}else process.stderr.write(`Warning: operation timed out for "${t}".\n`)}a===`json`&&O(l,a)}});function vh(e){let t=e.unit?` [${e.unit}]`:``;return`${e.en}${t}`}function yh(e,t,n,r){let i=E(process.stdout);process.stdout.write(`${i.dim(`Time Range Period:`)} ${Km(t)} ~ ${Km(n)} ${i.dim(`(${r} days)`)}\n\n`);let a=[[`Models Called`,V(e.modelCount??0)],[`Successful Calls`,V(e.callSuccessCount??0)]];for(let t of e.usages??[]){let e=ph[t.key],n=e?vh(e):t.key;a.push([n,V(t.value)])}let o=Math.max(...a.map(([e])=>hr(e)));for(let[e,t]of a)process.stdout.write(`${i.bold(k(e,o+2))}${t}\n`)}function bh(e,t,n,r){let i=E(process.stdout);if(process.stdout.write(`${i.dim(`Time Range Period:`)} ${Km(t)} ~ ${Km(n)} ${i.dim(`(${r} days)`)}\n\n`),e.length===0){process.stdout.write(`No usage data found.
|
|
2755
|
+
`);return}let a=/* @__PURE__ */ new Set,o=e.map(e=>{let t=fh(e);for(let e of Object.keys(t))a.add(e);return t}),s=[...a].sort((e,t)=>{let n=[`total_token`,`input_token`,`output_token`,`input_token_cache`,`image_number`,`video_duration`,`content_duration`,`tts_text_number`],r=n.indexOf(e),i=n.indexOf(t);return(r===-1?999:r)-(i===-1?999:i)}),c=[`Model`,`Calls`,...s.map(e=>ph[e]?.en??e)],l=e.map((e,t)=>[e.model,V(e.callSuccessCount??0),...s.map(e=>{let n=o[t][e];return n==null?`-`:V(n)})]),u=c.map((e,t)=>Math.max(hr(e),...l.map(e=>hr(e[t])))),d=c.map((e,t)=>i.bold(k(e,u[t]))).join(` `),f=u.map(e=>i.dim(`─`.repeat(e))).join(`──`);process.stdout.write(d+`
|
|
2756
2756
|
`),process.stdout.write(f+`
|
|
2757
2757
|
`);for(let e of l){let t=e.map((e,t)=>k(e,u[t]));process.stdout.write(t.join(` `)+`
|
|
2758
2758
|
`)}process.stdout.write(i.dim(`\nTotal: ${e.length} models`)+`
|
|
2759
|
-
`)}var
|
|
2760
|
-
`);return}
|
|
2761
|
-
`);else{let e=g.slice(0,10),n=g.length-e.length;
|
|
2762
|
-
`),s?y?
|
|
2759
|
+
`)}var xh=S({description:{"en-US":`Query model usage statistics`,"zh-CN":`查询模型用量统计`},auth:`console`,usageArgs:`[--model <model>] [--days <days>] [flags]`,flags:{model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name(s), comma-separated; omit for overview`,"zh-CN":`模型名称,多个名称以逗号分隔;省略时查看概览`}},days:{type:`string`,valueHint:`<days>`,description:{"en-US":`Number of days (default: 7)`,"zh-CN":`天数(默认:7)`}},type:{type:`string`,valueHint:`<type>`,description:{"en-US":`Model type: Text, Vision, Multimodal, Audio, Embedding`,"zh-CN":`模型类型:Text、Vision、Multimodal、Audio、Embedding`}}},exampleArgs:[``,`--days 30`,`--model qwen-turbo`,`--model qwen-turbo --days 7`,`--model qwen3.6-plus,deepseek-v4-pro`,`--type Text --days 14`,`--output json`],async run(e){let{identity:t,settings:r,flags:i}=e,a=i.model||void 0,o=Number(i.days)||7,s=i.type||void 0,c=C(r.output),u=Jm(r,t.binName),d=Date.now(),f=d-o*24*60*60*1e3;if(a){let t=[...new Set(a.split(`,`).map(e=>e.trim()).filter(Boolean))],n={startTime:f,endTime:d,modelCallSource:`Online`,filterWorkspaceId:u,maxResults:50,skip:0,sortField:`success_count`,sortOrder:`DESC`};if(s&&(n.obsModelType=s),r.dryRun){O({api:ch,data:{reqDTO:{...n,model:t.join(`,`)}}},c);return}let i=await Promise.all(t.map(t=>xm(e.client,ch,{...n,model:t}))),l=[];for(let e of i){if(!e)continue;let t=dh(e);l.push(...t.list)}if(c===`json`){let e=l.map(e=>{let t=fh(e),n={model:e.model,successfulCalls:e.callSuccessCount??0};for(let[e,r]of Object.entries(t))n[e]=r;return n});O({period:{start:Km(f),end:Km(d),days:o},items:e},c);return}bh(l,f,d,o)}else{let t={startTime:f,endTime:d,modelCallSource:`Online`,filterWorkspaceId:u};if(s&&(t.obsModelType=s),r.dryRun){O({api:sh,data:{reqDTO:t}},c);return}let i=await xm(e.client,sh,t);if(!i)throw new n(`Request timed out.`,l.TIMEOUT);let a=uh(i);if(c===`json`){if(!a){O({period:{start:Km(f),end:Km(d),days:o},modelsCalled:0,successfulCalls:0},c);return}O({period:{start:Km(f),end:Km(d),days:o},modelsCalled:a.modelCount??0,successfulCalls:a.callSuccessCount??0,usages:(a.usages??[]).map(e=>({key:e.key,value:e.value,unit:e.unit,label:ph[e.key]?.en??e.key}))},c);return}if(!a){process.stdout.write(`No usage data found.
|
|
2760
|
+
`);return}yh(a,f,d,o)}}}),Sh=S({description:{"en-US":`Show a unified usage summary: free-tier quota and recent usage overview`,"zh-CN":`显示统一用量摘要:免费额度和近期用量概览`},auth:`console`,usageArgs:`[--days <days>] [flags]`,flags:{days:{type:`string`,valueHint:`<days>`,description:{"en-US":`Number of days for the usage overview (default: 7)`,"zh-CN":`用量概览的天数(默认:7)`}}},exampleArgs:[``,`--days 30`,`--output json`],async run(e){let{identity:t,settings:r,flags:i}=e,a=Number(i.days)||7,o=C(r.output),s=r.workspaceId,c=Date.now(),u=c-a*24*60*60*1e3;if(r.dryRun){O({freeTier:{api:$m},usage:s?{api:sh,data:{reqDTO:{startTime:u,endTime:c,modelCallSource:`Online`,filterWorkspaceId:s}}}:null},o);return}let d=await Qm(e.client),f=d.map(e=>e.name),p=new Map(d.map(e=>[e.name,e.type])),[m,h]=await Promise.all([e.client.console($m,{queryFreeTierQuotaRequest:{models:f}}),e.client.console(eh,{queryFreeTierOnlyStatusRequest:{models:f}})]),g=nh(m).filter(e=>e.quotaStatus===`VALID`&&e.quotaInitTotal>0).sort((e,t)=>(e.quotaInitTotal?e.quotaTotal/e.quotaInitTotal:0)-(t.quotaInitTotal?t.quotaTotal/t.quotaInitTotal:0)),_=rh(h),v=new Map(_.map(e=>[e.model,e.freeTierOnly])),y;if(s){let t=await xm(e.client,sh,{startTime:u,endTime:c,modelCallSource:`Online`,filterWorkspaceId:s});if(!t)throw new n(`Request timed out.`,l.TIMEOUT);y=uh(t)}if(o===`json`){let e=g.map(e=>({model:e.model,type:p.get(e.model)||null,remaining:e.quotaTotal,total:e.quotaInitTotal,remainingPercent:ih(e),expires:e.quotaValidityPeriod?Km(e.quotaValidityPeriod):null}));O({period:{start:Km(u),end:Km(c),days:a},freeTier:e,usage:y?{modelsCalled:y.modelCount??0,successfulCalls:y.callSuccessCount??0,usages:(y.usages??[]).map(e=>({key:e.key,value:e.value,unit:e.unit,label:ph[e.key]?.en??e.key}))}:null},o);return}let b=E(process.stdout);if(process.stdout.write(`${b.bold(`Usage Summary`)} ${b.dim(`·`)} ${Km(c)}\n\n`),g.length===0)process.stdout.write(b.dim(`No active free-tier quota.`)+`
|
|
2761
|
+
`);else{let e=g.slice(0,10),n=g.length-e.length;oh({quotas:e,stopMap:v,typeMap:p,title:`Free Tier Quota · ${g.length} models · sorted by urgency`,moreHint:n>0?`+ ${n} more · ${t.binName} usage free to browse all`:void 0})}process.stdout.write(`
|
|
2762
|
+
`),s?y?hh(y,u,c,a):process.stdout.write(b.dim(`No usage data in this period.`)+`
|
|
2763
2763
|
`):process.stdout.write(b.dim(`Usage overview skipped · set --workspace-id or \`${t.binName} config set workspace_id <id>\` to include it.`)+`
|
|
2764
|
-
`)}});function
|
|
2765
|
-
`);return}
|
|
2766
|
-
`);return}let l=await
|
|
2764
|
+
`)}});function Ch(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function wh(e){let t=Math.round(e*1e3)/10;return`${Number.isInteger(t)?t:t.toFixed(1)}%`}function Th(e,t){let n=Math.max(0,e-t),r=Math.floor(n/6e4);if(r===0)return`now`;let i=Math.floor(r/1440),a=Math.floor(r%1440/60),o=r%60,s=[];return i>0&&s.push(`${i}d`),a>0&&s.push(`${a}h`),(o>0||s.length===0)&&s.push(`${o}m`),s.join(` `)}function Eh(e,t,n){let r=E(process.stdout),i=(e=``,t)=>{let n=Math.max(0,76-hr(` ${e}`));process.stdout.write(`│ ${t?t(e):e}${` `.repeat(n)}│\n`)},a=e=>{let t=Math.max(0,76-hr(` ${e.plain}`));process.stdout.write(`│ ${e.colored}${` `.repeat(t)}│\n`)},o=e=>{if(i(e.label,r.bold),e.percentage===void 0){i(e.emptyMessage,r.dim);return}let t=`${wh(e.percentage)} used`;if(a(Mr(e.percentage*100,t)),e.detail&&i(e.detail,r.dim),e.resetTime===void 0){i(`Resets: not applicable (no usage yet)`,r.dim);return}let o=`Resets: ${qm(e.resetTime)} (in ${Th(e.resetTime,n)})`;i(o,r.dim)};process.stdout.write(`┌${`─`.repeat(76)}┐\n`),i(e,r.cyan),i(`Generated at: ${qm(n)} (local time)`,r.dim);for(let e of t)process.stdout.write(`├${`─`.repeat(76)}┤\n`),o(e);process.stdout.write(`└${`─`.repeat(76)}┘\n`)}const Dh=`zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage`;function Oh(e){let t=qn(e),n={},r=Ch(t.per5HourPercentage);r!==void 0&&(n.per5HourPercentage=r);let i=Ch(t.per5HourResetTime);i!==void 0&&(n.per5HourResetTime=i);let a=Ch(t.per1WeekPercentage);a!==void 0&&(n.per1WeekPercentage=a);let o=Ch(t.per1WeekResetTime);return o!==void 0&&(n.per1WeekResetTime=o),n}function kh(e,t){Eh(`Token Plan Usage`,[{label:`5-hour quota`,emptyMessage:`The 5-hour limit may be unlimited; verify in the Bailian Token Plan console.`,percentage:e.per5HourPercentage,resetTime:e.per5HourResetTime},{label:`1-week quota`,emptyMessage:`The 1-week limit may be unlimited; verify in the Bailian Token Plan console.`,percentage:e.per1WeekPercentage,resetTime:e.per1WeekResetTime}],t)}var Ah=S({description:{"en-US":`Show Token Plan quota usage`,"zh-CN":`查看 Token Plan 配额使用情况`},auth:`console`,usageArgs:`[flags]`,exampleArgs:[``,`--output json`],async run(e){let{settings:t}=e,n=C(t.output);if(t.dryRun){O({api:Dh,data:{}},n);return}let r=Oh(await e.client.console(Dh,{}));if(n===`json`){O(r,n);return}kh(r,Date.now())}});const jh=`zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2`,Mh={domestic:`sfm_codingplan_public_cn`,international:`sfm_codingplan_public_intl`};function Nh(e,t){let n={};if(!e)return n;let r=Ch(e[`${t}UsedQuota`]);r!==void 0&&(n.usedQuota=r);let i=Ch(e[`${t}TotalQuota`]);i!==void 0&&(n.totalQuota=i);let a=Ch(e[`${t}QuotaNextRefreshTime`]);return a!==void 0&&(n.resetTime=a),r!==void 0&&i!==void 0&&i>0&&(n.percentage=r/i),n}function Ph(e){let t=qn(e),n=(Array.isArray(t.codingPlanInstanceInfos)?t.codingPlanInstanceInfos:[]).find(e=>e.status===`VALID`);if(!n)return;let r=n.codingPlanQuotaInfo,i={per5Hour:Nh(r,`per5Hour`),perWeek:Nh(r,`perWeek`),perBillMonth:Nh(r,`perBillMonth`)};return typeof n.instanceType==`string`&&n.instanceType&&(i.instanceType=n.instanceType),i}function Fh(e,t){let n={label:e,emptyMessage:`No quota data for this window; verify in the Bailian Coding Plan console.`,percentage:t.percentage,resetTime:t.resetTime};return t.usedQuota!==void 0&&t.totalQuota!==void 0&&(n.detail=`Used: ${V(t.usedQuota)} / ${V(t.totalQuota)}`),n}function Ih(e,t){Eh(`Coding Plan Usage${e.instanceType?` (${e.instanceType})`:``}`,[Fh(`5-hour quota`,e.per5Hour),Fh(`1-week quota`,e.perWeek),Fh(`Monthly quota`,e.perBillMonth)],t)}var Lh=S({description:{"en-US":`Show Coding Plan quota usage`,"zh-CN":`查看 Coding Plan 配额使用情况`},auth:`console`,usageArgs:`[flags]`,exampleArgs:[``,`--output json`],async run(e){let{settings:t}=e,n=C(t.output),r={queryCodingPlanInstanceInfoRequest:{commodityCode:Mh[t.consoleSite??`domestic`],onlyLatestOne:!0}};if(t.dryRun){O({api:jh,data:r},n);return}let i=Ph(await e.client.console(jh,r));if(n===`json`){O(i??{},n);return}if(!i){process.stdout.write(`No active Coding Plan subscription found.
|
|
2765
|
+
`);return}Ih(i,Date.now())}});async function Rh(e){let t=await Ei(e,`utf-8`).catch(e=>{throw new x(`cannot read pipeline file: ${e.message}`)}),n=fi(e).toLowerCase(),r;if(n===`.yaml`||n===`.yml`){let{parse:e}=await import(`yaml`);r=e(t)}else try{r=JSON.parse(t)}catch{let{parse:e}=await import(`yaml`);r=e(t)}return r}var zh=S({description:{"en-US":`Run a pipeline workflow definition`,"zh-CN":`运行 Pipeline 工作流定义`},auth:`none`,usageArgs:`--file <path> [flags]`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Pipeline definition file (YAML/JSON)`,"zh-CN":`Pipeline 定义文件(YAML/JSON)`},required:!0},input:{type:`string`,valueHint:`<json>`,description:{"en-US":`Runtime input as inline JSON`,"zh-CN":`内联 JSON 格式的运行时输入`}},inputFile:{type:`string`,valueHint:`<path>`,description:{"en-US":`Runtime input from a JSON file`,"zh-CN":`来自 JSON 文件的运行时输入`}},concurrency:{type:`number`,valueHint:`<n>`,description:{"en-US":`Max parallel steps (default: 1)`,"zh-CN":`最大并行步骤数(默认:1)`}},events:{type:`string`,valueHint:`<format>`,description:{"en-US":`Emit lifecycle events: jsonl`,"zh-CN":`输出生命周期事件:jsonl`},choices:[`jsonl`]},stepTimeout:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Default step timeout in seconds`,"zh-CN":`默认步骤超时时间,单位为秒`}}},exampleArgs:[{"en-US":`--file workflow.yaml --input '{"brief":"hello"}'`,"zh-CN":`--file workflow.yaml --input '{"brief":"你好"}'`},`--file workflow.json --input-file inputs.json --concurrency 3`,`--file workflow.yaml --dry-run`,`--file workflow.json --events jsonl`,`--file workflow.yaml --output json`],validate:e=>e.input&&e.inputFile?`use --input or --input-file, not both`:void 0,async run(e){let{settings:t,flags:n}=e,r=n.file;wr();let i=n.events,a=M(r),o=await Rh(a),s=await Bh(n),c=di(a);if(i===`jsonl`){for await(let e of Fr(o,s,{concurrency:n.concurrency,basePath:c,dryRun:t.dryRun,timeoutSeconds:n.stepTimeout}))process.stdout.write(JSON.stringify(e)+`
|
|
2766
|
+
`);return}let l=await vr(o,s,{concurrency:n.concurrency,basePath:c,dryRun:t.dryRun,timeoutSeconds:n.stepTimeout,onEvent:t.verbose?Vh:void 0});t.output===`json`?O(l,`json`):Uh(l),l.status===`failed`&&(process.exitCode=1)}});async function Bh(e){let t=e.input,n=e.inputFile;if(t)return JSON.parse(t);if(n){let e=await Ei(M(n),`utf-8`);return JSON.parse(e)}return{}}function Vh(e){let t=`[${e.type}]`;if(`stepCount`in e){process.stderr.write(`${t} ${e.stepCount} step${e.stepCount===1?``:`s`}\n`);return}`step`in e&&e.step?process.stderr.write(`${t} ${Hh(e.step)}\n`):process.stderr.write(`${t}\n`)}function Hh(e){return`${e.index!==void 0&&e.total!==void 0?`${e.index}/${e.total} `:``}${e.id} (${e.type})`}function Uh(e){let t=e.status===`succeeded`?`+`:e.status===`failed`?`x`:`~`;process.stdout.write(`\nPipeline ${e.status} [${t}]\n\n`);for(let t of e.steps){let e=` [${t.status===`succeeded`?`+`:t.status===`failed`?`x`:t.status===`skipped`?`-`:`~`}] ${t.id} (${t.type}) — ${t.status}`;t.skipReason&&(e+=` (${t.skipReason})`),t.error&&(e+=`: ${t.error.message}`),process.stdout.write(e+`
|
|
2767
2767
|
`)}process.stdout.write(`
|
|
2768
|
-
`)}var
|
|
2768
|
+
`)}var Wh=S({description:{"en-US":`Validate a pipeline definition without executing`,"zh-CN":`验证 Pipeline 定义但不执行`},auth:`none`,usageArgs:`--file <path>`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Pipeline definition file (YAML/JSON)`,"zh-CN":`Pipeline 定义文件(YAML/JSON)`},required:!0}},exampleArgs:[`--file workflow.yaml`,`--file workflow.json --output json`],async run(e){let{settings:t,flags:n}=e,r=n.file;wr();let i=await Rh(M(r)),a=pr(i),o=a.length===0?fr(i):[];if(t.output===`json`)O({valid:a.length===0,issues:a,...o.length>0?{hints:o}:{}},`json`),a.length>0&&(process.exitCode=1);else if(a.length===0){process.stdout.write(`Pipeline definition is valid.
|
|
2769
2769
|
`);for(let e of o)process.stderr.write(` hint: ${e}\n`)}else{process.stderr.write(`Pipeline validation failed:
|
|
2770
|
-
`);for(let e of a)process.stderr.write(` - ${e}\n`);process.exitCode=1}}});function
|
|
2771
|
-
`),{padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:1,right:0},borderColor:n?`cyan`:void 0,borderStyle:`round`,dimBorder:n})}const
|
|
2772
|
-
`),{padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:1,right:0},borderColor:r?`gray`:void 0,borderStyle:`round`,dimBorder:r})}function
|
|
2773
|
-
`)}function
|
|
2770
|
+
`);for(let e of a)process.stderr.write(` - ${e}\n`);process.exitCode=1}}});function Gh(e){return e>=1e6?`${(e/1e6).toFixed(e%1e6==0?0:1)}M`:e>=1e3?`${(e/1e3).toFixed(e%1e3==0?0:1)}K`:String(e)}const Kh={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},qh={TG:`Text Gen`,VU:`Vision`,IG:`Image Gen`,VG:`Video Gen`,TTS:`Text-to-Speech`,ASR:`Speech-to-Text`,Reasoning:`Reasoning`},Jh={low:`Cost-Effective`,medium:`Balanced`,high:`High Investment`},Yh={flagship:`Flagship`,balanced:`Balanced`,"cost-optimized":`Value`},Xh={scoped:`Scoped`,comparison:`Comparison`,alternative:`Alternative`};function Zh(e){return Ir(e)?Mi:new Ni({level:0})}function Qh(e){let t=Zh(process.stdout),n=Ir(process.stdout),r=[];r.push(t.cyan.bold(`Intent Analysis`)),e.taskSummary&&(r.push(``),r.push(e.taskSummary)),e.scenarioHints.length&&(r.push(``),r.push(`${t.dim(`Scenario`)} ${e.scenarioHints.join(` · `)}`));let i=e.inputModality.map(e=>Kh[e]??e),a=e.outputModality.map(e=>Kh[e]??e);if(i.length||a.length){r.push(``);let e=[];i.length&&e.push(`${t.dim(`Input`)} ${i.join(`, `)}`),a.length&&e.push(`${t.dim(`Output`)} ${a.join(`, `)}`),r.push(e.join(` `))}let o=e.requiredCapabilities.map(e=>qh[e]??e);o.length&&r.push(`${t.dim(`Capabilities`)} ${o.join(`, `)}`);let s=Jh[e.budget]??e.budget,c=Yh[e.qualityPreference]??e.qualityPreference;r.push(``),r.push(`${t.dim(`Budget`)} ${s} ${t.dim(`Quality`)} ${c}`);let l=e.modelPreference;if(l&&l.mode!==`unconstrained`){r.push(``);let e=Xh[l.mode]??l.mode,n=[t.dim(`Mode`)+` ${t.yellow(e)}`];l.targets?.length&&n.push(t.dim(`Targets`)+` ${l.targets.join(`, `)}`),l.excludes?.length&&n.push(t.dim(`Excludes`)+` ${l.excludes.join(`, `)}`),r.push(n.join(` `))}if(e.segments?.length){r.push(``),r.push(t.dim(`Pipeline`));for(let[n,i]of e.segments.entries()){let e=i.outputModality.map(e=>Kh[e]??e).join(`, `);r.push(` ${t.dim(`${n+1}.`)} ${i.step}${e?t.dim(` → ${e}`):``}`)}}return ji(r.join(`
|
|
2771
|
+
`),{padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:1,right:0},borderColor:n?`cyan`:void 0,borderStyle:`round`,dimBorder:n})}const $h=[`Best Pick`,`Runner-Up`,`Alternative`];function eg(e,t,n,r){let i=[n.green.bold,n.blue.bold,n.magenta.bold][t]??n.white.bold,a=$h[t]??`#${t+1}`,o=[];o.push(i(`⬢ #${t+1} — ${a}`)),o.push(``),o.push(`${n.bold(e.name)} ${n.dim(`(${e.model})`)}`),o.push(``),o.push(`${n.cyan(`Why`)} ${e.reason}`),e.highlights.length&&(o.push(``),o.push(e.highlights.map(e=>n.bgGray.white(` ${e} `)).join(` `)));let s=[];e.contextWindow&&s.push(`Context ${Gh(e.contextWindow)}`),e.maxOutputTokens&&s.push(`Max Output ${Gh(e.maxOutputTokens)}`),s.length&&(o.push(``),o.push(n.dim(s.join(` · `))));let c=fe(e.docUrl);return c&&(o.push(``),o.push(n.dim(`Docs ${c}`))),ji(o.join(`
|
|
2772
|
+
`),{padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:1,right:0},borderColor:r?`gray`:void 0,borderStyle:`round`,dimBorder:r})}function tg(e){let t=Zh(process.stdout),n=Ir(process.stdout);return e.map((e,r)=>eg(e,r,t,n)).join(`
|
|
2773
|
+
`)}function ng(e,t){let n=Zh(process.stdout),r=Ir(process.stdout),i=[];i.push(` ${n.yellow.bold(`⚡ Pipeline`)} ${e}`);for(let[e,{step:a,recommendations:o,warnings:s}]of t.entries()){if(i.push(``),i.push(n.bold(` ━━━ Step ${e+1}: ${a} ━━━`)),s?.length)for(let e of s)i.push(` ${n.yellow(`⚠`)} ${n.yellow(e)}`);i.push(``),i.push(o.map((e,t)=>eg(e,t,n,r)).join(`
|
|
2774
2774
|
`))}return i.join(`
|
|
2775
|
-
`)}function
|
|
2776
|
-
`),a.update(`Agent: Recalling candidates...`),a.start();let p=await rn(e.client,d,r,v,f);if(a.stop(),t.dryRun){O({userInput:r,intent:{taskSummary:f.taskSummary,scenarioHints:f.scenarioHints,complexity:f.complexity,inputModality:f.inputModality,outputModality:f.outputModality,requiredCapabilities:f.requiredCapabilities,budget:f.budget,qualityPreference:f.qualityPreference,modelPreference:f.modelPreference?.mode===`unconstrained`?void 0:f.modelPreference,segments:f.segments,semanticQuery:f.semanticQuery},candidateCount:p.length,candidates:p.map(({model:e,score:t,hardScore:n,softScore:r})=>({model:e.model,score:t,hardScore:n,softScore:r})),top:3},i);return}a.update(`Agent: Ranking models...`),a.start();let m=await $t(e.client,p,f,r,3);if(a.stop(),Bh(m)){D(`No suitable models found for this request.`);return}if(i!==`text`){O({intent:{taskSummary:f.taskSummary,scenarioHints:f.scenarioHints,complexity:f.complexity,inputModality:f.inputModality,outputModality:f.outputModality,requiredCapabilities:f.requiredCapabilities,budget:f.budget,qualityPreference:f.qualityPreference,modelPreference:f.modelPreference?.mode===`unconstrained`?void 0:f.modelPreference,segments:f.segments,semanticQuery:f.semanticQuery},result:m,candidates:p.length},i);return}D(Ph(f)),D(``),D(zh(m))}});const Hh=Object.values(m),Uh={provider:{type:`array`,valueHint:`<p>`,description:{"en-US":`Filter by provider (repeatable, e.g. --provider alibaba --provider deepseek)`,"zh-CN":`按提供商筛选(可重复,例如 --provider alibaba --provider deepseek)`}},capability:{type:`array`,valueHint:`<c>`,description:{"en-US":`Filter by capability code (TG, Reasoning, VU, IG, VG, TTS, ASR, …)`,"zh-CN":`按能力代码筛选(TG、Reasoning、VU、IG、VG、TTS、ASR 等)`}},feature:{type:`array`,valueHint:`<f>`,description:{"en-US":`Filter by feature (function-calling, web-search, structured-outputs, …)`,"zh-CN":`按特性筛选(function-calling、web-search、structured-outputs 等)`}},contextWindow:{type:`array`,valueHint:`<w>`,description:{"en-US":`Filter by context window range bucket`,"zh-CN":`按上下文窗口范围筛选`}},inputModality:{type:`array`,valueHint:`<m>`,choices:Hh,description:{"en-US":`Require an input modality (repeatable: Text, Image, Video, Audio)`,"zh-CN":`限定输入模态(可重复:Text、Image、Video、Audio)`}},outputModality:{type:`array`,valueHint:`<m>`,choices:Hh,description:{"en-US":`Require an output modality (repeatable: Text, Image, Video, Audio)`,"zh-CN":`限定输出模态(可重复:Text、Image、Video、Audio)`}},includeDeprecated:{type:`switch`,description:{"en-US":`Include models that are already offline (hidden by default)`,"zh-CN":`包含已下线的模型(默认隐藏)`}}};function Wh(e){return{providers:e.provider?.length?e.provider:void 0,capabilities:e.capability?.length?e.capability:void 0,features:e.feature?.length?e.feature:void 0,contextWindows:e.contextWindow?.length?e.contextWindow:void 0}}function Gh(e){if(!e?.length)return`-`;let t=e.find(e=>typeof e.type==`string`&&e.type.includes(`input`))??e[0];return`${t.type??``}:${String(t.price??`?`)}/${t.priceUnit??``}`}const Kh=/-\d{4}-\d{2}-\d{2}$/;function qh(e){return Kh.test(e??``)}function Jh(e){return e.toLowerCase().replace(Kh,``).replace(/[\s_-]+/g,``)}function Yh(e){if(e.length===0)return[];let t=e.filter(e=>!qh(e.model));return t.length>0?t:[...e].sort((e,t)=>String(t.model).localeCompare(String(e.model))).slice(0,1)}function Xh(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&Hh.includes(e)):[]}function Zh(e){let t=e.inferenceMetadata??{};return{input:Xh(t.request_modality),output:Xh(t.response_modality)}}function Qh(e,t,n){let r=Zh(e);return!(t.length>0&&!t.some(e=>r.input.includes(e))||n.length>0&&!n.some(e=>r.output.includes(e)))}function $h(e,t=Date.now()){if(e.offlineAt&&Date.parse(e.offlineAt)<=t)return{offline:!0};let n=e.offlineInfo?.inference,r=n?.offlineTime;if(r){let e=Date.parse(r.replace(` `,`T`));if(!Number.isNaN(e))return{offline:!1,upcomingOfflineAt:r,announceUrl:n?.announceUrl||void 0}}return{offline:!1}}function eg(e){return e.offline?`OFFLINE`:e.upcomingOfflineAt?`OFFLINE ${e.upcomingOfflineAt.slice(0,10)}`:``}function tg(e,t,n=Date.now()){let r=t.inputModality??[],i=t.outputModality??[];return e.filter(e=>!(!Qh(e,r,i)||!t.includeDeprecated&&$h(e,n).offline))}const ng={model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Show full details of a specific model family (switches to detail mode)`,"zh-CN":`显示指定模型系列的完整详情(切换到详情模式)`}},page:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Results per page (default: 10)`,"zh-CN":`每页结果数(默认:10)`}},...Uh,enrich:{type:`switch`,description:{"en-US":`Also fetch input parameter schema (predictConfig) for trunk models (detail mode only)`,"zh-CN":`同时获取主干模型的输入参数 Schema(predictConfig,仅详情模式)`}}};function rg(e){return(e.model??``).replace(/^group-/,``)||e.name||`unknown`}function ig(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=0,i=0,a,o=[];for(let s of e.items??[]){s.provider&&t.add(s.provider);for(let e of s.capabilities??[])n.add(e);r++,typeof s.contextWindow==`number`&&s.contextWindow>i&&(i=s.contextWindow),s.prices?.length&&(o.push(...s.prices),a||=s.prices.find(e=>typeof e.type==`string`&&e.type.includes(`input`))??s.prices[0])}return{providers:[...t].join(`,`),capabilities:[...n].join(`,`),modelCount:r,maxContext:i>0?i:void 0,price:a?Gh([a]):void 0,prices:o}}function ag(e,t){if(e.length===0){D(`No model families found.`);return}let n=[`NAME`,`PROVIDER`,`CAPABILITIES`,`MODELS`,`MAX_CONTEXT`,`PRICE`],r=e.map(e=>{let t=ig(e);return[e.name||rg(e),t.providers||`-`,t.capabilities||`-`,String(t.modelCount),t.maxContext?String(t.maxContext):`-`,t.price??`-`]});for(let e of cr(n,r))D(e);D(`\nTotal: ${t.total}`),t.hiddenModality>0&&D(`${t.hiddenModality} models on this page excluded by the modality filter (not reflected in Total).`),t.hiddenOffline>0&&D(`${t.hiddenOffline} offline models hidden — use --include-deprecated to include them.`)}function og(e,t){return{items:e.map(e=>{let t=ig(e),n=e.items?.[0];return{model:rg(e),name:e.name,description:e.description,provider:t.providers,capabilities:[...new Set((e.items??[]).flatMap(e=>e.capabilities??[]))],modelCount:t.modelCount,maxContextWindow:t.maxContext,prices:t.prices.length>0?t.prices:void 0,qpmInfo:n?.qpmInfo}}),total:t}}function sg(e,t){let n=e.items??[],r=Yh(n),i=n.length-r.length;D(e.name??e.model),e.description&&D(` ${e.description}`),e.updateAt&&D(` Updated: ${e.updateAt}`),D(``);let a=n.some(e=>eg($h(e))!==``),o=[`MODEL`,`PROVIDER`,`CAPABILITIES`,`CONTEXT`,`OUTPUT`,`CATEGORY`,`PRICE`];a&&o.push(`STATUS`);let s=n.map(e=>{let t=[e.model??`-`,e.provider??`-`,(e.capabilities??[]).join(`,`)||`-`,e.contextWindow?String(e.contextWindow):`-`,e.maxOutputTokens?String(e.maxOutputTokens):`-`,e.category??`-`,Gh(e.prices)];return a&&t.push(eg($h(e))),t});for(let e of cr(o,s))D(e);D(`\nTotal: ${n.length} models (${r.length} trunk, ${i} snapshots)`);for(let e of r){if(!e.prices?.length)continue;D(`\n── Pricing: ${e.model} ──`);let t=[`TYPE`,`PRICE`,`UNIT`],n=e.prices.map(e=>[e.type??`-`,String(e.price??`-`),e.priceUnit??`-`]);for(let e of cr(t,n))D(e)}for(let e of r){if(!e.qpmInfo||Object.keys(e.qpmInfo).length===0)continue;D(`\n── Rate Limits: ${e.model} ──`);let t=[`TIER`,`RPM`,`TPM`,`TPM_FIELD`],n=Object.entries(e.qpmInfo).map(([e,t])=>{let n=t.count_limit_period||60,r=n?Math.floor((t.count_limit||0)*60/n):0,i=t.usage_limit_period||60,a=i?Math.floor((t.usage_limit||0)*60/i):0;return[e,r>0?String(r):`-`,a>0?String(a):`-`,t.usage_limit_field??`-`]});for(let e of cr(t,n))D(e)}if(t)for(let e of r)e.predictConfig&&e.predictConfig.length!==0&&(D(`\n── predictConfig: ${e.model} ──`),lg(e.predictConfig))}function cg(e,t){let n=e.items??[];return{model:e.model,name:e.name,description:e.description,updateAt:e.updateAt,items:n.map(e=>{let n=$h(e),r={model:e.model,name:e.name,provider:e.provider,capabilities:e.capabilities,features:e.features,contextWindow:e.contextWindow,maxOutputTokens:e.maxOutputTokens,maxInputTokens:e.maxInputTokens,category:e.category,openSource:e.openSource,docUrl:e.docUrl,versionTag:e.versionTag,modalities:Zh(e)};return e.prices&&(r.prices=e.prices),e.qpmInfo&&(r.qpmInfo=e.qpmInfo),n.offline&&(r.offline=!0),n.upcomingOfflineAt&&(r.upcomingOfflineAt=n.upcomingOfflineAt),n.announceUrl&&(r.announceUrl=n.announceUrl),t&&e.predictConfig&&(r.predictConfig=e.predictConfig),r})}}function lg(e){let t=[`PARAM`,`KEY`,`DEFAULT`,`RANGE`],n=e.map(e=>[e.name??`-`,e.key??`-`,e.default===void 0?`-`:JSON.stringify(e.default),e.range===void 0?`-`:JSON.stringify(e.range)]);for(let e of cr(t,n))D(e)}var ug=S({description:{"en-US":`Browse model families or show detailed model info in the Bailian model marketplace`,"zh-CN":`浏览百炼模型市场中的模型系列,或查看模型详细信息`},auth:`none`,usageArgs:`[--model <model>] [--page <n>] [--page-size <n>] [--provider <p>] [--capability <c>] [--feature <f>] [--input-modality <m>] [--output-modality <m>] [--include-deprecated] [--enrich]`,flags:ng,exampleArgs:[``,`--provider alibaba`,`--capability TG --capability Reasoning`,`--input-modality Image --output-modality Text`,`--include-deprecated`,`--model qwen-max`,`--model qwen-max --enrich --output json`,`--feature function-calling --output json`],notes:[{"en-US":`Both the catalog and --enrich parameter-schema endpoints are public — no console login needed.`,"zh-CN":`模型目录和 --enrich 使用的参数 Schema Endpoint 均为公开接口,无需登录控制台。`},{"en-US":`Browse mode hides models that are already offline; use --include-deprecated to include them. Detail mode (--model) always lists every version and flags its status instead.`,"zh-CN":`浏览模式会隐藏已下线的模型,可用 --include-deprecated 包含它们;详情模式(--model)始终列出全部版本并标注状态。`}],async run(e){let{settings:t,flags:n}=e,r=t.outputExplicit?C(t.output):`json`,i=n.model,a=ie(t);if(i){let e=!!n.enrich;if(t.dryRun){O({action:`model.detail`,model:i,enrich:e},r);return}let o=await Re(a,i);if(!o){D(`Model "${i}" not found.`);return}if(e){let e=Yh(o.items??[]);await Promise.all(e.map(async e=>{if(!e.model)return;let t=await He(a,e.model);t&&(e.predictConfig=t)}))}if(r===`json`){O(cg(o,e),r);return}sg(o,e);return}let o={pageNo:n.page,pageSize:n.pageSize??10,...Wh(n)};if(t.dryRun){O({action:`model.list`,includeDeprecated:!!n.includeDeprecated,...o},r);return}let{total:s,groups:c}=await ze(a,o),l=c.map(e=>({...e,items:tg(e.items??[],n)})).filter(e=>e.items.length>0),u=c.flatMap(e=>e.items??[]),d=n.includeDeprecated?0:u.filter(e=>$h(e).offline).length,f=u.filter(e=>!Qh(e,n.inputModality??[],n.outputModality??[])).length;if(r===`json`){O(og(l,s),r);return}ag(l,{total:s,hiddenOffline:d,hiddenModality:f})}});const dg={modelExact:100,modelPrefix:60,modelContains:40,nameContains:30,capability:20,feature:15,provider:12,description:8},fg={recommended:10,flagship:6,trunk:5},pg={announcedRetirement:25,offline:60};function mg(e,t){return t.length>0?e.length/t.length:0}function hg(e,t){let n=Jh(t),r=t.trim().toLowerCase();if(!n&&!r)return 0;let i=Jh(e.model??``),a=Jh(e.name??``),o=0;if(n&&(i===n?o+=dg.modelExact:i.startsWith(n)?o+=dg.modelPrefix+mg(n,i)*30:i.includes(n)?o+=dg.modelContains+mg(n,i)*30:a.includes(n)&&(o+=dg.nameContains+mg(n,a)*30),(e.capabilities??[]).some(e=>Jh(e).includes(n))&&(o+=dg.capability),(e.features??[]).some(e=>Jh(e).includes(n))&&(o+=dg.feature),Jh(e.provider??``).includes(n)&&(o+=dg.provider)),r&&`${e.description??``} ${e.shortDescription??``}`.toLowerCase().includes(r)&&(o+=dg.description),o===0)return 0;e.aliyunRecommend===!0&&(o+=fg.recommended),e.category===`Flagship`&&(o+=fg.flagship),qh(e.model)||(o+=fg.trunk);let s=$h(e);return s.offline?o-=pg.offline:s.upcomingOfflineAt&&(o-=pg.announcedRetirement),Math.round(o*10)/10}function gg(e,t,n){if(e.length===0){D(`No models matched "${t}".`);return}let r=e.some(({item:e})=>eg($h(e))!==``),i=[`MODEL`,`PROVIDER`,`CAPABILITIES`,`CONTEXT`,`PRICE`];r&&i.push(`STATUS`);let a=e.map(({item:e})=>{let t=[e.model??`-`,e.provider??`-`,(e.capabilities??[]).join(`,`)||`-`,e.contextWindow?String(e.contextWindow):`-`,Gh(e.prices)];return r&&t.push(eg($h(e))||`-`),t});for(let e of cr(i,a))D(e);D(`\nMatches: ${e.length}`),n>0&&D(`${n} offline models hidden — use --include-deprecated to include them.`)}function _g(e,t,n){return{keyword:t,total:e.length,hiddenOffline:n>0?n:void 0,items:e.map(({item:e,score:t})=>{let n=$h(e);return{model:e.model,name:e.name,provider:e.provider,capabilities:e.capabilities,features:e.features,category:e.category,contextWindow:e.contextWindow,maxOutputTokens:e.maxOutputTokens,docUrl:e.docUrl,modalities:Zh(e),prices:e.prices,score:t,offline:n.offline||void 0,upcomingOfflineAt:n.upcomingOfflineAt,announceUrl:n.announceUrl}})}}var vg=S({description:{"en-US":`Search the model catalog by keyword, ranked by relevance`,"zh-CN":`按关键词搜索模型目录,并按相关度排序`},auth:`none`,usageArgs:`--keyword <kw> [--limit <n>] [--input-modality <m>] [--output-modality <m>] [flags]`,flags:{keyword:{type:`string`,valueHint:`<kw>`,required:!0,description:{"en-US":`Keyword matched against model id, name, capabilities, features and description`,"zh-CN":`关键词,匹配模型 ID、名称、能力、特性与描述`}},limit:{type:`number`,valueHint:`<n>`,description:{"en-US":`Maximum results to return (default: 20)`,"zh-CN":`最多返回的结果数(默认:20)`}},...Uh},exampleArgs:[`--keyword qwen`,`--keyword vision --output-modality Text`,`--keyword function-calling --provider alibaba`,`--keyword 长上下文 --limit 5`,`--keyword qwen --include-deprecated --output json`],notes:[{"en-US":`Search scans the whole catalog so that ranking sees every candidate; models already offline are hidden unless --include-deprecated is set.`,"zh-CN":`搜索会扫描完整目录以保证排序看到全部候选;已下线的模型默认隐藏,除非指定 --include-deprecated。`},{"en-US":`The model catalog endpoint is public — no console login needed.`,"zh-CN":`模型目录为公开接口,无需登录控制台。`}],validate:e=>{if(e.limit!=null&&e.limit<1)return`--limit must be a positive number.`},async run(e){let{settings:t,flags:n}=e,r=t.outputExplicit?C(t.output):`json`,i=n.limit??20,a=Wh(n),o=ie(t);if(t.dryRun){O({action:`model.search`,keyword:n.keyword,limit:i,includeDeprecated:!!n.includeDeprecated,...a},r);return}let s=await Be(o,a),c=tg(s,n),l=n.includeDeprecated?0:s.filter(e=>$h(e).offline).length,u=c.map(e=>({item:e,score:hg(e,n.keyword)})).filter(e=>e.score>0).sort((e,t)=>t.score-e.score||String(e.item.model).localeCompare(String(t.item.model))).slice(0,i);if(r===`json`){O(_g(u,n.keyword,l),r);return}gg(u,n.keyword,l)}});const yg={completions:`completionsAPI`,responses:`responsesAPI`},bg={node:`nodejs`,nodejs:`node`};function xg(e){return Object.entries(e).map(([e,t])=>`${e} (${Object.entries(t??{}).map(([e,t])=>`${e}: ${Object.keys(t??{}).join(`,`)}`).join(` | `)})`).join(`; `)}function Sg(e,t){return e.includes(t)?t:e[0]}function Cg(e,t){if(e[t])return t;let n=bg[t];return n&&e[n]?n:t}function wg(e,t){let r=xg(e),i=Object.keys(e);if(i.length===0)throw new n(`This model publishes no SDK sample code.`,l.GENERAL);let a=t.sdk??Sg(i,`openai`)??i[0];if(!e[a])throw new n(`Unknown --sdk "${t.sdk}". Available: ${r}`,l.USAGE);let o=e[a],s=Object.keys(o),c;if(t.api){if(c=yg[t.api]??t.api,!o[c])throw new n(`Unknown --api "${t.api}" for sdk "${a}". Available: ${r}`,l.USAGE)}else c=Sg(s,`completionsAPI`)??s[0];let u=o[c],d=Object.keys(u),f=t.lang?Cg(u,t.lang):Sg(d,`python`)??d[0];if(!u[f])throw new n(`Unknown --lang "${t.lang}" for ${a}/${c}. Available: ${r}`,l.USAGE);let p=u[f]?.code;if(!p)throw new n(`No snippet published for ${a}/${c}/${f}. Available: ${r}`,l.GENERAL);return{sdk:a,apiStyle:c,lang:f,code:p}}function Tg(e,t){let n=e.find(e=>e.model===t);return n?.sampleCodeV2?n:Yh(e).find(e=>e.sampleCodeV2)??e.find(e=>e.sampleCodeV2)}var Eg=S({description:{"en-US":`Print a ready-to-run SDK sample for calling a model`,"zh-CN":`打印调用指定模型的 SDK 示例代码`},auth:`none`,usageArgs:`--model <model> [--sdk <sdk>] [--api <style>] [--lang <lang>]`,flags:{model:{type:`string`,valueHint:`<model>`,required:!0,description:{"en-US":`Model to generate a sample for`,"zh-CN":`要生成示例代码的模型`}},sdk:{type:`string`,valueHint:`<sdk>`,description:{"en-US":`SDK flavour: openai (default) or dashscope`,"zh-CN":`SDK 类型:openai(默认)或 dashscope`}},api:{type:`string`,valueHint:`<style>`,description:{"en-US":`API style: completions (default) or responses; ignored when the SDK has one style`,"zh-CN":`API 形态:completions(默认)或 responses;SDK 只有一种形态时忽略`}},lang:{type:`string`,valueHint:`<lang>`,description:{"en-US":`Language of the snippet (default: python). Published per model — pass an unsupported value to list them`,"zh-CN":`示例代码语言(默认:python)。可选值按模型发布,传入不支持的值即可列出`}}},exampleArgs:[`--model qwen-max`,`--model qwen-max --lang curl`,`--model qwen-max --sdk dashscope --lang java`,`--model qwen-max --api responses --lang node`,`--model qwen-max --output json`],notes:[{"en-US":`Text output is the snippet alone, so it can be redirected straight into a file. Use --output json for the snippet plus its metadata.`,"zh-CN":`text 模式只输出代码本身,可直接重定向到文件;需要元信息请用 --output json。`},{"en-US":"Samples use a `[workspace-id]` placeholder in the base URL — replace it, or set BAILIAN_WORKSPACE_ID and use the DashScope endpoint.","zh-CN":"示例中的 base URL 含 `[workspace-id]` 占位符,请替换为实际 Workspace ID,或设置 BAILIAN_WORKSPACE_ID 后使用 DashScope 域名。"},{"en-US":`Available combinations are published per model; pass an unknown value to see the list for that model.`,"zh-CN":`可用组合按模型发布;传入不支持的取值即可看到该模型的可用列表。`}],async run(e){let{settings:t,flags:r}=e,i=t.outputExplicit?C(t.output):`text`,a=ie(t);if(t.dryRun){O({action:`model.code`,model:r.model,sdk:r.sdk,api:r.api,lang:r.lang},i);return}let o=await Re(a,r.model);if(!o)throw new n(`Model "${r.model}" not found.`,l.GENERAL,`Run "model list" to browse the catalog.`);let s=Tg(o.items??[],r.model);if(!s?.sampleCodeV2)throw new n(`Model "${r.model}" publishes no SDK sample code.`,l.GENERAL,`Speech, image and video models are called through their own command groups.`);let c=wg(s.sampleCodeV2,{sdk:r.sdk,api:r.api,lang:r.lang});if(i===`json`){O({model:s.model,requestedModel:r.model,sdk:c.sdk,apiStyle:c.apiStyle,lang:c.lang,available:xg(s.sampleCodeV2),code:c.code},i);return}D(c.code)}});const Dg=`zeldaEasy.bailian-dash-workspace.space.listWorkspaces`;function Og(e,t){let n=e[t];if(n&&typeof n==`object`&&!Array.isArray(n))return n}function kg(e){let t=Og(e,`data`);if(!t)return e;let n=Og(t,`DataV2`);if(n){let e=Og(n,`data`);return(e?Og(e,`data`):void 0)??e??n}return Og(t,`data`)??t}function Ag(e){let t=E(process.stdout),n=[`Name`,`Workspace ID`,`Default`],r=e.map(e=>[e.agentName,e.workspaceId,e.defaultAgent?`Yes`:`-`]),i=n.map((e,t)=>Math.max(tr(e),...r.map(e=>tr(e[t])))),a=n.map((e,n)=>t.bold(k(e,i[n]))).join(` `),o=i.map(e=>t.dim(`─`.repeat(e))).join(`──`);process.stdout.write(a+`
|
|
2775
|
+
`)}function rg(e){return e.type===`pipeline`?ng(e.summary,e.steps):tg(e.recommendations)}function ig(e){return e.type===`pipeline`?e.steps.length===0:e.recommendations.length===0}var ag=S({description:{"en-US":`Recommend the best models for your use case (intent analysis → candidate recall → LLM ranking)`,"zh-CN":`为你的使用场景推荐最佳模型(意图分析 → 候选召回 → LLM 排序)`},auth:`apiKey`,usageArgs:`--message <text> [flags]`,flags:{message:{type:`string`,valueHint:`<text>`,description:{"en-US":`Describe your requirements`,"zh-CN":`描述你的需求`},required:!0}},exampleArgs:[{"en-US":`--message "I need a visual-understanding chatbot"`,"zh-CN":`--message "我需要一个能够理解图片的聊天机器人"`},{"en-US":`--message "Build an Agent that auto-generates animations"`,"zh-CN":`--message "构建一个可以自动生成动画的智能体"`},{"en-US":`--message "Legal contract review, high precision required"`,"zh-CN":`--message "审查法律合同,要求高准确率"`},{"en-US":`--message "Low-cost high-concurrency online customer service" --output text`,"zh-CN":`--message "低成本、高并发的在线客服" --output text`},{"en-US":`--message "Long document summarization" --dry-run`,"zh-CN":`--message "长文档摘要" --dry-run`}],async run(e){let{settings:t,flags:n}=e,r=n.message;await zt();let i=t.outputExplicit?C(t.output):`json`,a=mr(`Agent: Loading model data & analyzing intent...`);a.start();let o={onPrepareStart:()=>{}},s=!1,c=!1,l=lt(t,o).then(e=>(s=!0,c||a.update(`Agent: Model data loaded, analyzing intent...`),e)),u=re(e.client,r).then(e=>(c=!0,s||a.update(`Agent: Intent analyzed, loading model data...`),e)),[d,f]=await Promise.all([l,u]);a.stop(),f.confidence===0&&process.stderr.write(`Intent analysis timed out, using defaults...
|
|
2776
|
+
`),a.update(`Agent: Recalling candidates...`),a.start();let p=await fn(e.client,d,r,v,f);if(a.stop(),t.dryRun){O({userInput:r,intent:{taskSummary:f.taskSummary,scenarioHints:f.scenarioHints,complexity:f.complexity,inputModality:f.inputModality,outputModality:f.outputModality,requiredCapabilities:f.requiredCapabilities,budget:f.budget,qualityPreference:f.qualityPreference,modelPreference:f.modelPreference?.mode===`unconstrained`?void 0:f.modelPreference,segments:f.segments,semanticQuery:f.semanticQuery},candidateCount:p.length,candidates:p.map(({model:e,score:t,hardScore:n,softScore:r})=>({model:e.model,score:t,hardScore:n,softScore:r})),top:3},i);return}a.update(`Agent: Ranking models...`),a.start();let m=await cn(e.client,p,f,r,3);if(a.stop(),ig(m)){D(`No suitable models found for this request.`);return}if(i!==`text`){O({intent:{taskSummary:f.taskSummary,scenarioHints:f.scenarioHints,complexity:f.complexity,inputModality:f.inputModality,outputModality:f.outputModality,requiredCapabilities:f.requiredCapabilities,budget:f.budget,qualityPreference:f.qualityPreference,modelPreference:f.modelPreference?.mode===`unconstrained`?void 0:f.modelPreference,segments:f.segments,semanticQuery:f.semanticQuery},result:m,candidates:p.length},i);return}D(Qh(f)),D(``),D(rg(m))}});const og=Object.values(m),sg={provider:{type:`array`,valueHint:`<p>`,description:{"en-US":`Filter by provider (repeatable, e.g. --provider alibaba --provider deepseek)`,"zh-CN":`按提供商筛选(可重复,例如 --provider alibaba --provider deepseek)`}},capability:{type:`array`,valueHint:`<c>`,description:{"en-US":`Filter by capability code (TG, Reasoning, VU, IG, VG, TTS, ASR, …)`,"zh-CN":`按能力代码筛选(TG、Reasoning、VU、IG、VG、TTS、ASR 等)`}},feature:{type:`array`,valueHint:`<f>`,description:{"en-US":`Filter by feature (function-calling, web-search, structured-outputs, …)`,"zh-CN":`按特性筛选(function-calling、web-search、structured-outputs 等)`}},contextWindow:{type:`array`,valueHint:`<w>`,description:{"en-US":`Filter by context window range bucket`,"zh-CN":`按上下文窗口范围筛选`}},inputModality:{type:`array`,valueHint:`<m>`,choices:og,description:{"en-US":`Require an input modality (repeatable: Text, Image, Video, Audio)`,"zh-CN":`限定输入模态(可重复:Text、Image、Video、Audio)`}},outputModality:{type:`array`,valueHint:`<m>`,choices:og,description:{"en-US":`Require an output modality (repeatable: Text, Image, Video, Audio)`,"zh-CN":`限定输出模态(可重复:Text、Image、Video、Audio)`}},includeDeprecated:{type:`switch`,description:{"en-US":`Include models that are already offline (hidden by default)`,"zh-CN":`包含已下线的模型(默认隐藏)`}}};function cg(e){return{providers:e.provider?.length?e.provider:void 0,capabilities:e.capability?.length?e.capability:void 0,features:e.feature?.length?e.feature:void 0,contextWindows:e.contextWindow?.length?e.contextWindow:void 0}}function lg(e){if(!e?.length)return`-`;let t=e.find(e=>typeof e.type==`string`&&e.type.includes(`input`))??e[0];return`${t.type??``}:${String(t.price??`?`)}/${t.priceUnit??``}`}const ug=/-\d{4}-\d{2}-\d{2}$/;function dg(e){return ug.test(e??``)}function fg(e){return e.toLowerCase().replace(ug,``).replace(/[\s_-]+/g,``)}function pg(e){if(e.length===0)return[];let t=e.filter(e=>!dg(e.model));return t.length>0?t:[...e].sort((e,t)=>String(t.model).localeCompare(String(e.model))).slice(0,1)}function mg(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&og.includes(e)):[]}function hg(e){let t=e.inferenceMetadata??{};return{input:mg(t.request_modality),output:mg(t.response_modality)}}function gg(e,t,n){let r=hg(e);return!(t.length>0&&!t.some(e=>r.input.includes(e))||n.length>0&&!n.some(e=>r.output.includes(e)))}function _g(e,t=Date.now()){if(e.offlineAt&&Date.parse(e.offlineAt)<=t)return{offline:!0};let n=e.offlineInfo?.inference,r=n?.offlineTime;if(r){let e=Date.parse(r.replace(` `,`T`));if(!Number.isNaN(e))return{offline:!1,upcomingOfflineAt:r,announceUrl:n?.announceUrl||void 0}}return{offline:!1}}function vg(e){return e.offline?`OFFLINE`:e.upcomingOfflineAt?`OFFLINE ${e.upcomingOfflineAt.slice(0,10)}`:``}function yg(e,t,n=Date.now()){let r=t.inputModality??[],i=t.outputModality??[];return e.filter(e=>!(!gg(e,r,i)||!t.includeDeprecated&&_g(e,n).offline))}const bg={model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Show full details of a specific model family (switches to detail mode)`,"zh-CN":`显示指定模型系列的完整详情(切换到详情模式)`}},page:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Results per page (default: 10)`,"zh-CN":`每页结果数(默认:10)`}},...sg,enrich:{type:`switch`,description:{"en-US":`Also fetch input parameter schema (predictConfig) for trunk models (detail mode only)`,"zh-CN":`同时获取主干模型的输入参数 Schema(predictConfig,仅详情模式)`}}};function xg(e){return(e.model??``).replace(/^group-/,``)||e.name||`unknown`}function Sg(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=0,i=0,a,o=[];for(let s of e.items??[]){s.provider&&t.add(s.provider);for(let e of s.capabilities??[])n.add(e);r++,typeof s.contextWindow==`number`&&s.contextWindow>i&&(i=s.contextWindow),s.prices?.length&&(o.push(...s.prices),a||=s.prices.find(e=>typeof e.type==`string`&&e.type.includes(`input`))??s.prices[0])}return{providers:[...t].join(`,`),capabilities:[...n].join(`,`),modelCount:r,maxContext:i>0?i:void 0,price:a?lg([a]):void 0,prices:o}}function Cg(e,t){if(e.length===0){D(`No model families found.`);return}let n=[`NAME`,`PROVIDER`,`CAPABILITIES`,`MODELS`,`MAX_CONTEXT`,`PRICE`],r=e.map(e=>{let t=Sg(e);return[e.name||xg(e),t.providers||`-`,t.capabilities||`-`,String(t.modelCount),t.maxContext?String(t.maxContext):`-`,t.price??`-`]});for(let e of Sr(n,r))D(e);D(`\nTotal: ${t.total}`),t.hiddenModality>0&&D(`${t.hiddenModality} models on this page excluded by the modality filter (not reflected in Total).`),t.hiddenOffline>0&&D(`${t.hiddenOffline} offline models hidden — use --include-deprecated to include them.`)}function wg(e,t){return{items:e.map(e=>{let t=Sg(e),n=e.items?.[0];return{model:xg(e),name:e.name,description:e.description,provider:t.providers,capabilities:[...new Set((e.items??[]).flatMap(e=>e.capabilities??[]))],modelCount:t.modelCount,maxContextWindow:t.maxContext,prices:t.prices.length>0?t.prices:void 0,qpmInfo:n?.qpmInfo}}),total:t}}function Tg(e,t){let n=e.items??[],r=pg(n),i=n.length-r.length;D(e.name??e.model),e.description&&D(` ${e.description}`),e.updateAt&&D(` Updated: ${e.updateAt}`),D(``);let a=n.some(e=>vg(_g(e))!==``),o=[`MODEL`,`PROVIDER`,`CAPABILITIES`,`CONTEXT`,`OUTPUT`,`CATEGORY`,`PRICE`];a&&o.push(`STATUS`);let s=n.map(e=>{let t=[e.model??`-`,e.provider??`-`,(e.capabilities??[]).join(`,`)||`-`,e.contextWindow?String(e.contextWindow):`-`,e.maxOutputTokens?String(e.maxOutputTokens):`-`,e.category??`-`,lg(e.prices)];return a&&t.push(vg(_g(e))),t});for(let e of Sr(o,s))D(e);D(`\nTotal: ${n.length} models (${r.length} trunk, ${i} snapshots)`);for(let e of r){if(!e.prices?.length)continue;D(`\n── Pricing: ${e.model} ──`);let t=[`TYPE`,`PRICE`,`UNIT`],n=e.prices.map(e=>[e.type??`-`,String(e.price??`-`),e.priceUnit??`-`]);for(let e of Sr(t,n))D(e)}for(let e of r){if(!e.qpmInfo||Object.keys(e.qpmInfo).length===0)continue;D(`\n── Rate Limits: ${e.model} ──`);let t=[`TIER`,`RPM`,`TPM`,`TPM_FIELD`],n=Object.entries(e.qpmInfo).map(([e,t])=>{let n=t.count_limit_period||60,r=n?Math.floor((t.count_limit||0)*60/n):0,i=t.usage_limit_period||60,a=i?Math.floor((t.usage_limit||0)*60/i):0;return[e,r>0?String(r):`-`,a>0?String(a):`-`,t.usage_limit_field??`-`]});for(let e of Sr(t,n))D(e)}if(t)for(let e of r)e.predictConfig&&e.predictConfig.length!==0&&(D(`\n── predictConfig: ${e.model} ──`),Dg(e.predictConfig))}function Eg(e,t){let n=e.items??[];return{model:e.model,name:e.name,description:e.description,updateAt:e.updateAt,items:n.map(e=>{let n=_g(e),r={model:e.model,name:e.name,provider:e.provider,capabilities:e.capabilities,features:e.features,contextWindow:e.contextWindow,maxOutputTokens:e.maxOutputTokens,maxInputTokens:e.maxInputTokens,category:e.category,openSource:e.openSource,docUrl:e.docUrl,versionTag:e.versionTag,modalities:hg(e)};return e.prices&&(r.prices=e.prices),e.qpmInfo&&(r.qpmInfo=e.qpmInfo),n.offline&&(r.offline=!0),n.upcomingOfflineAt&&(r.upcomingOfflineAt=n.upcomingOfflineAt),n.announceUrl&&(r.announceUrl=n.announceUrl),t&&e.predictConfig&&(r.predictConfig=e.predictConfig),r})}}function Dg(e){let t=[`PARAM`,`KEY`,`DEFAULT`,`RANGE`],n=e.map(e=>[e.name??`-`,e.key??`-`,e.default===void 0?`-`:JSON.stringify(e.default),e.range===void 0?`-`:JSON.stringify(e.range)]);for(let e of Sr(t,n))D(e)}var Og=S({description:{"en-US":`Browse model families or show detailed model info in the Bailian model marketplace`,"zh-CN":`浏览百炼模型市场中的模型系列,或查看模型详细信息`},auth:`none`,usageArgs:`[--model <model>] [--page <n>] [--page-size <n>] [--provider <p>] [--capability <c>] [--feature <f>] [--input-modality <m>] [--output-modality <m>] [--include-deprecated] [--enrich]`,flags:bg,exampleArgs:[``,`--provider alibaba`,`--capability TG --capability Reasoning`,`--input-modality Image --output-modality Text`,`--include-deprecated`,`--model qwen-max`,`--model qwen-max --enrich --output json`,`--feature function-calling --output json`],notes:[{"en-US":`Both the catalog and --enrich parameter-schema endpoints are public — no console login needed.`,"zh-CN":`模型目录和 --enrich 使用的参数 Schema Endpoint 均为公开接口,无需登录控制台。`},{"en-US":`Browse mode hides models that are already offline; use --include-deprecated to include them. Detail mode (--model) always lists every version and flags its status instead.`,"zh-CN":`浏览模式会隐藏已下线的模型,可用 --include-deprecated 包含它们;详情模式(--model)始终列出全部版本并标注状态。`}],async run(e){let{settings:t,flags:n}=e,r=t.outputExplicit?C(t.output):`json`,i=n.model,a=ie(t);if(i){let e=!!n.enrich;if(t.dryRun){O({action:`model.detail`,model:i,enrich:e},r);return}let o=await He(a,i);if(!o){D(`Model "${i}" not found.`);return}if(e){let e=pg(o.items??[]);await Promise.all(e.map(async e=>{if(!e.model)return;let t=await Ke(a,e.model);t&&(e.predictConfig=t)}))}if(r===`json`){O(Eg(o,e),r);return}Tg(o,e);return}let o={pageNo:n.page,pageSize:n.pageSize??10,...cg(n)};if(t.dryRun){O({action:`model.list`,includeDeprecated:!!n.includeDeprecated,...o},r);return}let{total:s,groups:c}=await Ue(a,o),l=c.map(e=>({...e,items:yg(e.items??[],n)})).filter(e=>e.items.length>0),u=c.flatMap(e=>e.items??[]),d=n.includeDeprecated?0:u.filter(e=>_g(e).offline).length,f=u.filter(e=>!gg(e,n.inputModality??[],n.outputModality??[])).length;if(r===`json`){O(wg(l,s),r);return}Cg(l,{total:s,hiddenOffline:d,hiddenModality:f})}});const kg={modelExact:100,modelPrefix:60,modelContains:40,nameContains:30,capability:20,feature:15,provider:12,description:8},Ag={recommended:10,flagship:6,trunk:5},jg={announcedRetirement:25,offline:60};function Mg(e,t){return t.length>0?e.length/t.length:0}function Ng(e,t){let n=fg(t),r=t.trim().toLowerCase();if(!n&&!r)return 0;let i=fg(e.model??``),a=fg(e.name??``),o=0;if(n&&(i===n?o+=kg.modelExact:i.startsWith(n)?o+=kg.modelPrefix+Mg(n,i)*30:i.includes(n)?o+=kg.modelContains+Mg(n,i)*30:a.includes(n)&&(o+=kg.nameContains+Mg(n,a)*30),(e.capabilities??[]).some(e=>fg(e).includes(n))&&(o+=kg.capability),(e.features??[]).some(e=>fg(e).includes(n))&&(o+=kg.feature),fg(e.provider??``).includes(n)&&(o+=kg.provider)),r&&`${e.description??``} ${e.shortDescription??``}`.toLowerCase().includes(r)&&(o+=kg.description),o===0)return 0;e.aliyunRecommend===!0&&(o+=Ag.recommended),e.category===`Flagship`&&(o+=Ag.flagship),dg(e.model)||(o+=Ag.trunk);let s=_g(e);return s.offline?o-=jg.offline:s.upcomingOfflineAt&&(o-=jg.announcedRetirement),Math.round(o*10)/10}function Pg(e,t,n){if(e.length===0){D(`No models matched "${t}".`);return}let r=e.some(({item:e})=>vg(_g(e))!==``),i=[`MODEL`,`PROVIDER`,`CAPABILITIES`,`CONTEXT`,`PRICE`];r&&i.push(`STATUS`);let a=e.map(({item:e})=>{let t=[e.model??`-`,e.provider??`-`,(e.capabilities??[]).join(`,`)||`-`,e.contextWindow?String(e.contextWindow):`-`,lg(e.prices)];return r&&t.push(vg(_g(e))||`-`),t});for(let e of Sr(i,a))D(e);D(`\nMatches: ${e.length}`),n>0&&D(`${n} offline models hidden — use --include-deprecated to include them.`)}function Fg(e,t,n){return{keyword:t,total:e.length,hiddenOffline:n>0?n:void 0,items:e.map(({item:e,score:t})=>{let n=_g(e);return{model:e.model,name:e.name,provider:e.provider,capabilities:e.capabilities,features:e.features,category:e.category,contextWindow:e.contextWindow,maxOutputTokens:e.maxOutputTokens,docUrl:e.docUrl,modalities:hg(e),prices:e.prices,score:t,offline:n.offline||void 0,upcomingOfflineAt:n.upcomingOfflineAt,announceUrl:n.announceUrl}})}}var Ig=S({description:{"en-US":`Search the model catalog by keyword, ranked by relevance`,"zh-CN":`按关键词搜索模型目录,并按相关度排序`},auth:`none`,usageArgs:`--keyword <kw> [--limit <n>] [--input-modality <m>] [--output-modality <m>] [flags]`,flags:{keyword:{type:`string`,valueHint:`<kw>`,required:!0,description:{"en-US":`Keyword matched against model id, name, capabilities, features and description`,"zh-CN":`关键词,匹配模型 ID、名称、能力、特性与描述`}},limit:{type:`number`,valueHint:`<n>`,description:{"en-US":`Maximum results to return (default: 20)`,"zh-CN":`最多返回的结果数(默认:20)`}},...sg},exampleArgs:[`--keyword qwen`,`--keyword vision --output-modality Text`,`--keyword function-calling --provider alibaba`,`--keyword 长上下文 --limit 5`,`--keyword qwen --include-deprecated --output json`],notes:[{"en-US":`Search scans the whole catalog so that ranking sees every candidate; models already offline are hidden unless --include-deprecated is set.`,"zh-CN":`搜索会扫描完整目录以保证排序看到全部候选;已下线的模型默认隐藏,除非指定 --include-deprecated。`},{"en-US":`The model catalog endpoint is public — no console login needed.`,"zh-CN":`模型目录为公开接口,无需登录控制台。`}],validate:e=>{if(e.limit!=null&&e.limit<1)return`--limit must be a positive number.`},async run(e){let{settings:t,flags:n}=e,r=t.outputExplicit?C(t.output):`json`,i=n.limit??20,a=cg(n),o=ie(t);if(t.dryRun){O({action:`model.search`,keyword:n.keyword,limit:i,includeDeprecated:!!n.includeDeprecated,...a},r);return}let s=await We(o,a),c=yg(s,n),l=n.includeDeprecated?0:s.filter(e=>_g(e).offline).length,u=c.map(e=>({item:e,score:Ng(e,n.keyword)})).filter(e=>e.score>0).sort((e,t)=>t.score-e.score||String(e.item.model).localeCompare(String(t.item.model))).slice(0,i);if(r===`json`){O(Fg(u,n.keyword,l),r);return}Pg(u,n.keyword,l)}});const Lg={completions:`completionsAPI`,responses:`responsesAPI`},Rg={node:`nodejs`,nodejs:`node`};function zg(e){return Object.entries(e).map(([e,t])=>`${e} (${Object.entries(t??{}).map(([e,t])=>`${e}: ${Object.keys(t??{}).join(`,`)}`).join(` | `)})`).join(`; `)}function Bg(e,t){return e.includes(t)?t:e[0]}function Vg(e,t){if(e[t])return t;let n=Rg[t];return n&&e[n]?n:t}function Hg(e,t){let r=zg(e),i=Object.keys(e);if(i.length===0)throw new n(`This model publishes no SDK sample code.`,l.GENERAL);let a=t.sdk??Bg(i,`openai`)??i[0];if(!e[a])throw new n(`Unknown --sdk "${t.sdk}". Available: ${r}`,l.USAGE);let o=e[a],s=Object.keys(o),c;if(t.api){if(c=Lg[t.api]??t.api,!o[c])throw new n(`Unknown --api "${t.api}" for sdk "${a}". Available: ${r}`,l.USAGE)}else c=Bg(s,`completionsAPI`)??s[0];let u=o[c],d=Object.keys(u),f=t.lang?Vg(u,t.lang):Bg(d,`python`)??d[0];if(!u[f])throw new n(`Unknown --lang "${t.lang}" for ${a}/${c}. Available: ${r}`,l.USAGE);let p=u[f]?.code;if(!p)throw new n(`No snippet published for ${a}/${c}/${f}. Available: ${r}`,l.GENERAL);return{sdk:a,apiStyle:c,lang:f,code:p}}function Ug(e,t){let n=e.find(e=>e.model===t);return n?.sampleCodeV2?n:pg(e).find(e=>e.sampleCodeV2)??e.find(e=>e.sampleCodeV2)}var Wg=S({description:{"en-US":`Print a ready-to-run SDK sample for calling a model`,"zh-CN":`打印调用指定模型的 SDK 示例代码`},auth:`none`,usageArgs:`--model <model> [--sdk <sdk>] [--api <style>] [--lang <lang>]`,flags:{model:{type:`string`,valueHint:`<model>`,required:!0,description:{"en-US":`Model to generate a sample for`,"zh-CN":`要生成示例代码的模型`}},sdk:{type:`string`,valueHint:`<sdk>`,description:{"en-US":`SDK flavour: openai (default) or dashscope`,"zh-CN":`SDK 类型:openai(默认)或 dashscope`}},api:{type:`string`,valueHint:`<style>`,description:{"en-US":`API style: completions (default) or responses; ignored when the SDK has one style`,"zh-CN":`API 形态:completions(默认)或 responses;SDK 只有一种形态时忽略`}},lang:{type:`string`,valueHint:`<lang>`,description:{"en-US":`Language of the snippet (default: python). Published per model — pass an unsupported value to list them`,"zh-CN":`示例代码语言(默认:python)。可选值按模型发布,传入不支持的值即可列出`}}},exampleArgs:[`--model qwen-max`,`--model qwen-max --lang curl`,`--model qwen-max --sdk dashscope --lang java`,`--model qwen-max --api responses --lang node`,`--model qwen-max --output json`],notes:[{"en-US":`Text output is the snippet alone, so it can be redirected straight into a file. Use --output json for the snippet plus its metadata.`,"zh-CN":`text 模式只输出代码本身,可直接重定向到文件;需要元信息请用 --output json。`},{"en-US":"Samples use a `[workspace-id]` placeholder in the base URL — replace it, or set BAILIAN_WORKSPACE_ID and use the DashScope endpoint.","zh-CN":"示例中的 base URL 含 `[workspace-id]` 占位符,请替换为实际 Workspace ID,或设置 BAILIAN_WORKSPACE_ID 后使用 DashScope 域名。"},{"en-US":`Available combinations are published per model; pass an unknown value to see the list for that model.`,"zh-CN":`可用组合按模型发布;传入不支持的取值即可看到该模型的可用列表。`}],async run(e){let{settings:t,flags:r}=e,i=t.outputExplicit?C(t.output):`text`,a=ie(t);if(t.dryRun){O({action:`model.code`,model:r.model,sdk:r.sdk,api:r.api,lang:r.lang},i);return}let o=await He(a,r.model);if(!o)throw new n(`Model "${r.model}" not found.`,l.GENERAL,`Run "model list" to browse the catalog.`);let s=Ug(o.items??[],r.model);if(!s?.sampleCodeV2)throw new n(`Model "${r.model}" publishes no SDK sample code.`,l.GENERAL,`Speech, image and video models are called through their own command groups.`);let c=Hg(s.sampleCodeV2,{sdk:r.sdk,api:r.api,lang:r.lang});if(i===`json`){O({model:s.model,requestedModel:r.model,sdk:c.sdk,apiStyle:c.apiStyle,lang:c.lang,available:zg(s.sampleCodeV2),code:c.code},i);return}D(c.code)}});const Gg=`zeldaEasy.bailian-dash-workspace.space.listWorkspaces`;function Kg(e,t){let n=e[t];if(n&&typeof n==`object`&&!Array.isArray(n))return n}function qg(e){let t=Kg(e,`data`);if(!t)return e;let n=Kg(t,`DataV2`);if(n){let e=Kg(n,`data`);return(e?Kg(e,`data`):void 0)??e??n}return Kg(t,`data`)??t}function Jg(e){let t=E(process.stdout),n=[`Name`,`Workspace ID`,`Default`],r=e.map(e=>[e.agentName,e.workspaceId,e.defaultAgent?`Yes`:`-`]),i=n.map((e,t)=>Math.max(hr(e),...r.map(e=>hr(e[t])))),a=n.map((e,n)=>t.bold(k(e,i[n]))).join(` `),o=i.map(e=>t.dim(`─`.repeat(e))).join(`──`);process.stdout.write(a+`
|
|
2777
2777
|
`),process.stdout.write(o+`
|
|
2778
2778
|
`);for(let e of r){let n=e.map((e,n)=>n===2&&e===`Yes`?t.green(k(e,i[n])):k(e,i[n]));process.stdout.write(n.join(` `)+`
|
|
2779
2779
|
`)}process.stdout.write(t.dim(`\nTotal: ${e.length}`)+`
|
|
2780
|
-
`)}var
|
|
2781
|
-
`);return}let o=a;if(r>0&&(o=o.slice(0,r)),i===`json`){let e=o.map(e=>({workspaceId:e.workspaceId,name:e.agentName,default:e.defaultAgent}));O(e,i);return}
|
|
2782
|
-
`);return}let n=[`Model`,`Req Limit`,`Usage Limit`,`WS Req`,`WS Usage`,`Async Q/C`],r=e.map(e=>[e.model,
|
|
2783
|
-
`);process.stdout.write(`\nTotal: ${t}\n`)}var
|
|
2780
|
+
`)}var Yg=S({description:{"en-US":`List all workspaces`,"zh-CN":`列出全部 Workspace`},auth:`console`,usageArgs:`[flags]`,flags:{list:{type:`string`,valueHint:`<n>`,description:{"en-US":`Limit number of results`,"zh-CN":`限制结果数量`}}},exampleArgs:[``,`--list 5`,`--output json`],async run(e){let{settings:t,flags:n}=e,r=Number(n.list)||0,i=C(t.output);if(t.dryRun){O({api:Gg,data:{}},i);return}let a=qg(await e.client.console(Gg,{})).data;if(!Array.isArray(a)||a.length===0){i===`json`?O([],i):process.stdout.write(`No workspace found.
|
|
2781
|
+
`);return}let o=a;if(r>0&&(o=o.slice(0,r)),i===`json`){let e=o.map(e=>({workspaceId:e.workspaceId,name:e.agentName,default:e.defaultAgent}));O(e,i);return}Jg(o)}});function Xg(e,t){if(e==null)return`-`;let n=t??60;return n===1?`${V(e)}/s`:n===60?`${V(e)}/min`:`${V(e)}/${n}s`}function Zg(e){return e?Xg(e.request_limit,e.request_limit_period):`-`}function Qg(e){return e?Xg(e.usage_limit,e.usage_limit_period):`-`}function $g(e){return!e||e.async_user_queue_limit==null&&e.async_user_concurrency_limit==null?`-`:`${e.async_user_queue_limit==null?`-`:V(e.async_user_queue_limit)}/${e.async_user_concurrency_limit==null?`-`:V(e.async_user_concurrency_limit)}`}function e_(e,t){if(e.length===0){process.stdout.write(`No rate limits found.
|
|
2782
|
+
`);return}let n=[`Model`,`Req Limit`,`Usage Limit`,`WS Req`,`WS Usage`,`Async Q/C`],r=e.map(e=>[e.model,Zg(e.model_limit),Qg(e.model_limit),Zg(e.workspace_limit),Qg(e.workspace_limit),$g(e.model_limit)]),i=jr({headers:n,rows:r,align:[`left`,`right`,`right`,`right`,`right`,`right`]});for(let e of i)process.stdout.write(e+`
|
|
2783
|
+
`);process.stdout.write(`\nTotal: ${t}\n`)}var t_=S({description:{"en-US":`View model rate limits (QPM/TPM, account and workspace level)`,"zh-CN":`查看模型限流配置(QPM/TPM,账号级和 Workspace 级)`},auth:`apiKey`,usageArgs:`[--model <model>] [--name <name>] [--page <n>] [--page-size <n>]`,flags:{model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name(s), comma-separated (exact match)`,"zh-CN":`模型名称,多个以逗号分隔(精确匹配)`}},name:{type:`string`,valueHint:`<name>`,description:{"en-US":`Fuzzy search by model name`,"zh-CN":`按模型名称模糊搜索`}},page:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Results per page (default: 20)`,"zh-CN":`每页结果数(默认:20)`}}},exampleArgs:[``,`--model qwen3-max`,`--model qwen3-max,qwen-plus`,`--name qwen --page-size 50`,`--output json`],notes:[{"en-US":"Usage-vs-limit pressure checks live in `quota check` (console auth).","zh-CN":"用量与限流压力检查位于 `quota check`(Console 鉴权)。"}],async run(e){let{settings:t,flags:n}=e,r=n.model||void 0,i=n.name||void 0,a=C(t.output),o=e.client.url(Kt());if(t.dryRun){if(r){let e=U(r).map(e=>({endpoint:o,method:`GET`,query:{model:e,page_size:100}}));O({requests:e},a)}else O({endpoint:o,method:`GET`,query:{name:i,page_no:n.page||1,page_size:n.pageSize||20}},a);return}let s,c;if(r)s=(await Promise.all(U(r).map(t=>e.client.requestJson({path:Kt()+ym({model:t,page_size:100})})))).flatMap(e=>e.output?.quotas??[]),c=s.length;else{let t=await e.client.requestJson({path:Kt()+ym({name:i,page_no:n.page||1,page_size:n.pageSize||20})});s=t.output?.quotas??[],c=t.output?.total??s.length}if(a===`json`){O({items:s,total:c},a);return}e_(s,c)}}),n_=S({description:{"en-US":`Update model rate limits (QPM/TPM)`,"zh-CN":`更新模型限流配置(QPM/TPM)`},auth:`apiKey`,usageArgs:`--model <model> [--rpm <n>] [--tpm <n>]`,flags:{model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name (required)`,"zh-CN":`模型名称(必填)`},required:!0},rpm:{type:`number`,valueHint:`<n>`,description:{"en-US":`Max requests per minute (QPM)`,"zh-CN":`每分钟最大请求数(QPM)`}},tpm:{type:`number`,valueHint:`<n>`,description:{"en-US":`Max tokens per minute (TPM)`,"zh-CN":`每分钟最大 Token 数(TPM)`}}},exampleArgs:[`--model qwen-plus --rpm 60 --tpm 100000`,`--model qwen3-max --tpm 500000`,`--model qwen-plus --rpm 60 --output json`],notes:[{"en-US":`Fields you omit keep their current values (server-side OVERLAY merge). Clear all custom limits with the "quota delete" command instead.`,"zh-CN":`未指定的字段将保留当前值(服务端 OVERLAY 合并)。清除全部自定义限流配置请改用 “quota delete” 命令。`},{"en-US":`Setting TPM without an existing QPM limit is rejected server-side — pass --rpm first or together.`,"zh-CN":`若当前没有 QPM 限制,单独设置 TPM 会被服务端拒绝——请先设置 --rpm,或同时传入。`}],validate:e=>{if(e.rpm===void 0&&e.tpm===void 0)return`one of --rpm / --tpm is required.`;if(e.rpm!==void 0&&e.rpm<0)return`--rpm must be a non-negative number.`;if(e.tpm!==void 0&&e.tpm<0)return`--tpm must be a non-negative number.`},async run(e){let{settings:t,flags:n}=e,r=n.model,i=C(t.output),a={model:r};n.rpm!==void 0&&(a.request_limit=n.rpm,a.request_limit_period=60),n.tpm!==void 0&&(a.usage_limit=n.tpm,a.usage_limit_period=60);let o={models:[a]};if(t.dryRun){O({endpoint:e.client.url(Kt()),method:`POST`,request:o},i);return}let s=await e.client.requestJson({path:Kt(),method:`POST`,body:o});if(i===`json`){O({model:r,...s},i);return}let c=[];n.rpm!==void 0&&c.push(`QPM ${V(n.rpm)}`),n.tpm!==void 0&&c.push(`TPM ${V(n.tpm)}`),process.stdout.write(`Rate limits updated for "${r}": ${c.join(`, `)}\n`)}}),r_=S({description:{"en-US":`Clear all custom rate limits (QPM/TPM) for a model`,"zh-CN":`清除模型的所有自定义限流配置(QPM/TPM)`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently clears all custom QPM/TPM rate limits for the specified model and cannot be undone.`,"zh-CN":`该操作会永久清除指定模型的所有自定义 QPM/TPM 限流配置,且无法撤销。`}},usageArgs:`--model <model>`,flags:{model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name (required)`,"zh-CN":`模型名称(必填)`},required:!0}},exampleArgs:[`--model qwen-plus`,`--model qwen-plus --dry-run --output json`,`--model qwen-plus --yes`],async run(e){let{settings:t,flags:n}=e,r=n.model,i=C(t.output),a={models:[{model:r,operation_type:`DELETE`}]};if(t.dryRun){O({endpoint:e.client.url(Kt()),method:`POST`,request:a},i);return}let o=await e.client.requestJson({path:Kt(),method:`POST`,body:a});if(i===`json`){O({model:r,...o},i);return}process.stdout.write(`Rate limits cleared for "${r}".\n`)}});const i_=`zeldaEasy.broadscope-platform.modelInstance.listModelLimitApplications`;function a_(e,t){let n=e[t];if(n&&typeof n==`object`&&!Array.isArray(n))return n}function o_(e){let t=a_(e,`data`);if(!t)return e;let n=a_(t,`DataV2`);if(n){let e=a_(n,`data`);return(e?a_(e,`data`):void 0)??e??n}return a_(t,`data`)??t}function s_(e){if(!e)return`-`;try{let t=new Date(e);return isNaN(t.getTime())?e:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)} ${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}catch{return e}}function c_(e,t){let n=E(process.stdout),r=[`Model`,`Token Limit`,`Applied At`],i=e.map(e=>[e.deployedModel,V(e.usageLimit),s_(e.gmtCreate)]),a=r.map((e,t)=>Math.max(hr(e),...i.map(e=>hr(e[t])))),o=r.map((e,t)=>n.bold(k(e,a[t]))).join(` `),s=a.map(e=>n.dim(`─`.repeat(e))).join(`──`);process.stdout.write(o+`
|
|
2784
2784
|
`),process.stdout.write(s+`
|
|
2785
2785
|
`);for(let e of i)process.stdout.write(e.map((e,t)=>k(e,a[t])).join(` `)+`
|
|
2786
2786
|
`);process.stdout.write(n.dim(`\nTotal: ${t} records`)+`
|
|
2787
|
-
`)}var
|
|
2788
|
-
`);return}
|
|
2789
|
-
`)}var
|
|
2790
|
-
`);return}let s=await Promise.all(o.map(t=>
|
|
2791
|
-
`);return}let i=[`Model`,`API Key`,`Calls`,`Failed`,`Fail%`,`Avg Duration`,`Avg First Token`],a=e.map(e=>[e.model??`-`,e.apikeyId??`-`,V(e.callCount??0),V(e.callFailedCount??0),e.callFailedPercent==null?`-`:`${(e.callFailedPercent*100).toFixed(2)}%`,e.avgCallDuration==null?`-`:`${V(Math.round(e.avgCallDuration))} ms`,e.avgFirstTokenDuration==null?`-`:`${V(Math.round(e.avgFirstTokenDuration))} ms`]),o=
|
|
2787
|
+
`)}var l_=S({description:{"en-US":`View quota change history`,"zh-CN":`查看额度变更历史`},auth:`console`,usageArgs:`[flags]`,flags:{page:{type:`string`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},pageSize:{type:`string`,valueHint:`<n>`,description:{"en-US":`Page size (default: 10)`,"zh-CN":`每页数量(默认:10)`}},model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Filter by model name`,"zh-CN":`按模型名称筛选`}}},exampleArgs:[``,`--page 2`,`--page-size 20`,`--model qwen-turbo`,`--output json`],async run(e){let{identity:t,settings:r,flags:i}=e,a=Number(i.page)||1,o=Number(i.pageSize)||10,s=i.model||void 0,c=C(r.output),u={input:{pageNo:a,pageSize:o}};if(r.dryRun){O({api:i_,data:u},c);return}let d;try{d=await e.client.console(i_,u)}catch(e){throw e instanceof n&&e.message.includes(`NotLogined`)?new n(`session expired.`,l.AUTH,`Run \`${t.binName} auth login --console\` to re-authenticate.`):e}let f=o_(d),p=f.records??[],m=f.items??p.length;if(s&&(p=p.filter(e=>e.deployedModel===s)),c===`json`){let e=p.map(e=>({model:e.deployedModel,tokenLimit:e.usageLimit,appliedAt:s_(e.gmtCreate)}));O({records:e,total:s?p.length:m},c);return}if(p.length===0){process.stdout.write(`No quota change history found.
|
|
2788
|
+
`);return}c_(p,s?p.length:m)}});const u_=`zeldaEasy.bailian-telemetry.monitor.getMonitorData`;function d_(e,t){if(!e)return 0;let n=e.count_limit_period||t;return n?Math.floor(e.count_limit*60/n):0}function f_(e,t){if(!e)return 0;let n=e.usage_limit_period||t;return n?Math.floor(e.usage_limit*60/n):0}async function p_(e){let t=[],n=1;for(;;){let r=await e.console(p,{input:{pageNo:n,pageSize:50,group:!1,queryQpmInfo:!0,ignoreWorkspaceServiceSite:!0,supports:{selfServiceLimitIncrease:!0}}}),i=qn(r),a=i.list??[],o=i.total??0;if(t.push(...a),t.length>=o||a.length===0)break;n++}return t}async function m_(e,t,r){let i=Date.now(),a=i-r*60*1e3;try{let n=await e.console(u_,{reqDTO:{monitorType:`Advanced`,metricFilters:[{aggMethod:`sum_pm`,metricName:`model_total_amount`},{aggMethod:`sum_pm`,metricName:`model_call_count`}],labelFilters:{resourceId:t,resourceType:`model`},startTime:a,endTime:i}}),r=qn(n),o=r.data??r;if(!Array.isArray(o))return{rpm:0,tpm:0};let s=0,c=0;for(let e of o){if(e.aggMethod!==`sum_pm`||!e.points?.length)continue;let t=e.points[e.points.length-1].value??0;e.metricName===`model_call_count`&&(s=Math.round(t)),e.metricName===`model_total_amount`&&(c=Math.round(t))}return{rpm:s,tpm:c}}catch(e){if(e instanceof n&&e.exitCode===l.AUTH)throw e;return{rpm:-1,tpm:-1}}}function h_(e){let t=E(process.stdout),n=[`Model`,`RPM Used/Limit`,`TPM Used/Limit`,`Status`,`RPM Left`,`TPM Left`],r=e.map(e=>e.rpmQuotaLeft),i=e.map(e=>e.rpmQuotaLabel),a=e.map(e=>e.tpmQuotaLeft),o=e.map(e=>e.tpmQuotaLabel),s=e.map(e=>{let t=e.rpmUsage<0?`-`:`${e.rpmUsage}/${e.rpmLimit}`,n=e.tpmUsage<0?`-`:`${e.tpmUsage}/${e.tpmLimit}`,r=Math.max(e.rpmLimit>0?e.rpmUsage/e.rpmLimit*100:0,e.tpmLimit>0?e.tpmUsage/e.tpmLimit*100:0),i=e.rpmUsage<0?`-`:r>=100?`Rate Limited`:r>=80?`Near limit`:`Normal`;return[e.model,t,n,i,``,``]}),c=jr({headers:n,rows:s,align:[`left`,`right`,`right`,`left`,`left`,`left`],barColumns:[{index:4,percents:r,labels:i,width:15},{index:5,percents:a,labels:o,width:15}],cellColor:(e,n,r)=>{if(n===3){if(r===`Rate Limited`)return t.red(r);if(r===`Near limit`)return t.yellow(r);if(r===`Normal`)return t.green(r)}}});for(let e of c)process.stdout.write(e+`
|
|
2789
|
+
`)}var g_=S({description:{"en-US":`Check current usage against rate limits`,"zh-CN":`根据限流额度检查当前用量`},auth:`console`,usageArgs:`[--model <model>] [flags]`,flags:{model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name(s), comma-separated`,"zh-CN":`模型名称,多个名称以逗号分隔`}},period:{type:`string`,valueHint:`<minutes>`,description:{"en-US":`Query usage for the last N minutes (default: 2)`,"zh-CN":`查询最近 N 分钟的用量(默认:2)`}}},exampleArgs:[``,`--model qwen3.6-plus`,`--period 5`,`--model qwen3.6-plus,qwen-turbo`,`--output json`],validate:e=>(Number(e.period)||2)<1?`--period must be at least 1 minute.`:void 0,async run(e){let{settings:t,flags:n}=e,r=n.model||void 0,i=Number(n.period)||2,a=C(t.output);if(t.dryRun){O({apis:[p,u_],...w(t)},a);return}let o=await p_(e.client);if(r){let e=new Set(r.split(`,`).map(e=>e.trim()).filter(Boolean));o=o.filter(t=>e.has(t.model))}if(o=o.filter(e=>e.qpmInfo),o.length===0){process.stdout.write(`No models found.
|
|
2790
|
+
`);return}let s=await Promise.all(o.map(t=>m_(e.client,t.model,i))),c=o.map((e,t)=>{let n=e.qpmInfo,r=n[`model-default`],i=n[`user-spec`],a=d_(i,r?.count_limit_period)||d_(r),o=f_(i,r?.usage_limit_period)||f_(r),c=s[t].rpm,l=s[t].tpm,u=null,d=null;c>=0&&a>0&&(u=Math.max(0,100-c/a*100),d=u.toFixed(1)+`%`);let f=null,p=null;return l>=0&&o>0&&(f=Math.max(0,100-l/o*100),p=f.toFixed(1)+`%`),{model:e.model,rpmUsage:c,rpmLimit:a,tpmUsage:l,tpmLimit:o,rpmQuotaLeft:u,tpmQuotaLeft:f,rpmQuotaLabel:d,tpmQuotaLabel:p}});if(a===`json`){O(c,a);return}h_(c)}});const __=`zeldaEasy.bailian-telemetry.platform-model.getModelStatistic`;function v_(e,t,n){let r=E(process.stdout);process.stdout.write(`${r.dim(`Time Range:`)} ${H(t)} ~ ${H(n)}\n\n`);let i=e.callCount&&e.callFailedCount!=null?`${(e.callFailedCount/e.callCount*100).toFixed(2)}%`:`-`,a=[[`Models Called`,V(e.resourceCount??0)],[`Total Calls`,V(e.callCount??0)],[`Successful Calls`,V(e.callSuccessCount??0)],[`Failed Calls`,V(e.callFailedCount??0)],[`Failure Rate`,i],[`4xx Errors`,V(e.call4xxErrorCount??0)],[`5xx Errors`,V(e.call5xxErrorCount??0)],[`Avg Call Duration`,e.avgCallDuration==null?`-`:`${V(e.avgCallDuration)} ms`],[`Avg First Token Duration`,e.avgFirstTokenDuration==null?`-`:`${V(e.avgFirstTokenDuration)} ms`]];for(let t of e.usages??[])a.push([`${t.key}${t.unit?` [${t.unit}]`:``}`,V(t.value)]);let o=Math.max(...a.map(([e])=>hr(e)));for(let[e,t]of a)process.stdout.write(`${r.bold(k(e,o+2))}${t}\n`)}var y_=S({description:{"en-US":`Show aggregated model call statistics (calls, failures, latency, token usage)`,"zh-CN":`查看模型调用汇总统计(调用量、失败率、耗时、Token 用量)`},auth:`console`,usageArgs:`[--model <model>] [--days <days>] [flags]`,flags:{...wm,...Um},exampleArgs:[``,`--days 30`,`--model qwen3.6-plus`,`--model qwen3.6-plus --api-key-id 12345 --days 7`,`--output json`],notes:[{"en-US":`Only real-time (online) inference calls are counted in the overview.`,"zh-CN":`汇总统计仅覆盖实时(在线)推理调用。`}],async run(e){let{settings:t,flags:n}=e,r=C(t.output),{startTime:i,endTime:a}=Em(n),o={...Gm(n,t.workspaceId),startTime:i,endTime:a};if(t.dryRun){O({api:__,data:{reqDTO:o},...w(t)},r);return}W(t);let s=await Sm(e.client,__,o);if(r===`json`){O({period:{start:H(i),end:H(a)},...s},r);return}v_(s,i,a)}});const b_=`zeldaEasy.bailian-telemetry.platform-model.listModelStatisticData`,x_=[`modelAndWorkspaceId`,`callCount`,`callSuccessCount`,`callFailedCount`,`callFailedPercent`,`avgCallDuration`,`avgFirstTokenDuration`];function S_(e,t,n){let r=E(process.stdout);if(process.stdout.write(`${r.dim(`Time Range:`)} ${H(t)} ~ ${H(n)}\n\n`),e.length===0){process.stdout.write(`No monitor data found.
|
|
2791
|
+
`);return}let i=[`Model`,`API Key`,`Calls`,`Failed`,`Fail%`,`Avg Duration`,`Avg First Token`],a=e.map(e=>[e.model??`-`,e.apikeyId??`-`,V(e.callCount??0),V(e.callFailedCount??0),e.callFailedPercent==null?`-`:`${(e.callFailedPercent*100).toFixed(2)}%`,e.avgCallDuration==null?`-`:`${V(Math.round(e.avgCallDuration))} ms`,e.avgFirstTokenDuration==null?`-`:`${V(Math.round(e.avgFirstTokenDuration))} ms`]),o=jr({headers:i,rows:a,align:[`left`,`left`,`right`,`right`,`right`,`right`,`right`],cellColor:(e,t,n)=>{if(t!==4||n===`-`)return;let i=Number.parseFloat(n);return i>=5?r.red(n):i>0?r.yellow(n):r.green(n)}});for(let e of o)process.stdout.write(e+`
|
|
2792
2792
|
`);process.stdout.write(r.dim(`\nTotal: ${e.length} rows`)+`
|
|
2793
|
-
`)}var
|
|
2794
|
-
`);return}for(let n of e){process.stdout.write(t.bold(
|
|
2793
|
+
`)}var C_=S({description:{"en-US":`List per-model / per-API-key call statistics with server-side sort and paging`,"zh-CN":`按模型 / API Key 维度查看调用明细统计(服务端排序与分页)`},auth:`console`,usageArgs:`[--model <model>] [--sort-by <field>] [flags]`,flags:{...wm,...Um,sortBy:{type:`string`,valueHint:`<field>`,choices:x_,description:{"en-US":`Sort field (default: callCount)`,"zh-CN":`排序字段(默认:callCount)`}},order:{type:`string`,valueHint:`<order>`,choices:[`ASC`,`DESC`],description:{"en-US":`Sort order (default: DESC)`,"zh-CN":`排序方向(默认:DESC)`}},maxResults:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows per page, 1-50 (default: 10)`,"zh-CN":`每页数量,范围 1-50(默认:10)`}},skip:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows to skip (default: 0)`,"zh-CN":`跳过的记录数(默认:0)`}},nextToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Pagination token from a previous response`,"zh-CN":`上一次响应返回的分页标记`}}},notes:[{"en-US":`Only real-time (online) inference calls are counted in monitor statistics.`,"zh-CN":`监控统计仅覆盖实时(在线)推理调用。`}],exampleArgs:[``,`--model qwen3.6-plus --days 1`,`--sort-by callFailedPercent --order DESC`,`--max-results 50 --output json`],validate:e=>{if(e.maxResults!=null&&(e.maxResults<1||e.maxResults>50))return`--max-results must be between 1 and 50.`},async run(e){let{settings:t,flags:n}=e,r=C(t.output),{startTime:i,endTime:a}=Em(n),o={...Gm(n,t.workspaceId),startTime:i,endTime:a,sortField:n.sortBy??`callCount`,sortOrder:n.order??`DESC`,maxResults:n.maxResults??10,skip:n.skip??0,nextToken:n.nextToken};if(t.dryRun){O({api:b_,data:{reqDTO:o},...w(t)},r);return}W(t);let s=await Sm(e.client,b_,o),c=(s.list??[]).filter(Boolean),l=s.nextToken;if(r===`json`){O({period:{start:H(i),end:H(a)},totalCount:s.totalCount??0,nextToken:l,list:c},r);return}S_(c,i,a),l&&process.stdout.write(`Next page: --next-token ${l}\n`)}});const w_=`zeldaEasy.bailian-telemetry.platform-model.getModelMonitorDataWithOss`,T_=[`model_call_count`,`model_call_duration`,`model_first_token_duration`,`model_generation_duration_per_token`,`model_call_failed_count`,`model_call_4xx_count`,`model_call_5xx_count`,`model_call_429_count`,`model_call_data_inspection_failed_count`,`model_total_amount`,`model_input_amount`,`model_output_amount`,`model_usage`,`model_tps_per_request`,`model_cache_hit_percent`,`model_ptu_token_quota`,`model_ptu_usage_quota`,`model_ptu_total_tokens`,`model_ptu_quota`,`model_ptu_utilization`],E_=[`sum`,`avg`,`max`,`min`,`p50`,`p95`,`p99`,`cumsum`,`cumavg`,`sum_pm`],D_=/* @__PURE__ */ new Set([`model_call_failed_count`,`model_call_4xx_count`,`model_call_5xx_count`,`model_call_429_count`,`model_call_data_inspection_failed_count`]);function O_(e){let t=e.labels?Object.entries(e.labels).map(([e,t])=>`${e}=${t}`).join(`,`):``,n=`${e.metricName} (${e.aggMethod})`;return t?`${n} {${t}}`:n}function k_(e){let t=E(process.stdout);if(e.length===0){process.stdout.write(`No monitor data found.
|
|
2794
|
+
`);return}for(let n of e){process.stdout.write(t.bold(O_(n))+`
|
|
2795
2795
|
`);let e=n.points??[];if(e.length===0){process.stdout.write(t.dim(` (no data points)`)+`
|
|
2796
2796
|
|
|
2797
2797
|
`);continue}for(let n of e)process.stdout.write(` ${t.dim(H(n.timestamp))} ${V(n.value)}\n`);process.stdout.write(`
|
|
2798
|
-
`)}}var
|
|
2799
|
-
`);return}let i=
|
|
2800
|
-
`)}var
|
|
2801
|
-
`);return}if(await
|
|
2798
|
+
`)}}var A_=S({description:{"en-US":`Query time-series monitor metrics (RPM/TPM, latency percentiles, token usage)`,"zh-CN":`查询时序监控指标(RPM/TPM、耗时分位数、Token 用量等)`},auth:`console`,usageArgs:`--metric <name>[,<name>...] [flags]`,flags:{...wm,...Um,metric:{type:`string`,valueHint:`<name>[,<name>...]`,required:!0,description:{"en-US":`Metric name(s), comma-separated; see notes for the full list`,"zh-CN":`指标名称,多个以逗号分隔;完整列表见下方说明`}},agg:{type:`string`,valueHint:`<method>`,choices:E_,description:{"en-US":`Aggregation method applied to every metric (default: sum)`,"zh-CN":`应用于所有指标的聚合方式(默认:sum)`}},step:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Data point interval in seconds: 60, 3600 or 86400 (default: auto by time range)`,"zh-CN":`数据点间隔(秒):60、3600 或 86400,默认按时间范围自动选择`}}},notes:[{"en-US":`Metrics: ${T_.join(`, `)}`,"zh-CN":`可用指标:${T_.join(`、`)}`},{"en-US":`Only real-time (online) inference calls are counted in monitor statistics.`,"zh-CN":`监控统计仅覆盖实时(在线)推理调用。`}],exampleArgs:[`--metric model_call_count --days 1`,`--metric model_call_duration --agg p99 --model qwen3.6-plus --days 1`,`--metric model_call_count,model_call_failed_count --step 300 --start-time 2026-08-01`,`--metric model_total_amount --output json`],validate:e=>{let t=U(e.metric).filter(e=>!T_.includes(e));if(t.length>0)return`Unknown metric: ${t.join(`, `)}. See notes for the full list.`;if(e.step!=null&&!km.includes(e.step))return`--step must be one of ${km.join(`, `)} seconds.`},async run(e){let{settings:t,flags:n}=e,r=C(t.output),{startTime:i,endTime:a}=Em(n),o=U(n.metric).map(e=>({metricName:e,aggMethod:n.agg??`sum`})),s={...Gm(n,t.workspaceId),metricFilters:o,startTime:i,endTime:a,step:n.step??Am(i,a)};if(t.dryRun){O({api:w_,data:{reqDTO:s},...w(t)},r);return}W(t);let c=await jm(await Sm(e.client,w_,s))??[];if(r===`json`){O({period:{start:H(i),end:H(a)},step:s.step,series:c},r);return}k_(c),U(n.metric).some(e=>D_.has(e))&&process.stdout.write(E(process.stdout).dim(`\nFor the error-code breakdown, run \`${e.identity.binName} monitor errors\`.\n`))}});const j_=`zeldaEasy.bailian-telemetry.platform-model.getModelErrorCodeStatisticData`;function M_(e){let t=e.result??e.list??e.data;return Array.isArray(t)?t:Array.isArray(e)?e:[]}function N_(e,t,n){let r=E(process.stdout);if(process.stdout.write(`${r.dim(`Time Range:`)} ${H(t)} ~ ${H(n)}\n\n`),e.length===0){process.stdout.write(`No failures found in this range.
|
|
2799
|
+
`);return}let i=jr({headers:[`HTTP Status`,`Error Code`,`Calls`,`Percent`],rows:e.map(e=>[e.httpStatusCode??`-`,e.errorCode??`-`,V(e.callCount??0),e.callPercent==null?`-`:`${(e.callPercent*100).toFixed(2)}%`]),align:[`left`,`left`,`right`,`right`]});for(let e of i)process.stdout.write(e+`
|
|
2800
|
+
`)}var P_=S({description:{"en-US":`Show failure breakdown by HTTP status code and error code`,"zh-CN":`查看失败明细(按 HTTP 状态码与错误码统计分布)`},auth:`console`,usageArgs:`[--model <model>] [--days <days>] [flags]`,flags:{...wm,...Um},exampleArgs:[``,`--model qwen3.6-plus --days 1`,`--model qwen3.6-plus --api-key-id 12345`,`--output json`],notes:[{"en-US":`Only real-time (online) inference calls are counted in monitor statistics.`,"zh-CN":`监控统计仅覆盖实时(在线)推理调用。`}],async run(e){let{settings:t,flags:n}=e,r=C(t.output),{startTime:i,endTime:a}=Em(n),o={...Gm(n,t.workspaceId),startTime:i,endTime:a};if(t.dryRun){O({api:j_,data:{reqDTO:o},...w(t)},r);return}W(t);let s=M_(await Sm(e.client,j_,o));if(r===`json`){O({period:{start:H(i),end:H(a)},list:s},r);return}N_(s,i,a)}});function F_(e,t,n,r){let i=E(process.stdout),a=[[`CMS SLR Authorization`,e?`Authorized`:`Not authorized`],[`Service Open`,t.openStatus?`Yes`:`No`],[`Instance Status`,t.instanceStatus??`-`],[`Delivery Switch`,n===null?`Never configured`:n?`On`:`Off`]],o=t.instanceInfo;o&&(a.push([`Instance ID`,o.instanceId]),o.instanceName&&a.push([`Instance Name`,o.instanceName]),o.regionName&&a.push([`Region`,o.regionName]),a.push([`Instance URL`,o.instanceUrl]),o.gmtCreate&&a.push([`Created At`,H(o.gmtCreate)]));let s=Math.max(...a.map(([e])=>hr(e)));for(let[e,t]of a)process.stdout.write(`${i.bold(k(e,s+2))}${t}\n`);(!t.openStatus||n!==!0)&&process.stdout.write(i.dim(`\nRun \`${r} monitor delivery enable\` to activate monitoring delivery.\n`))}var I_=S({description:{"en-US":`Show monitoring delivery (Prometheus instance) status`,"zh-CN":`查看监控数据投递(Prometheus 实例)状态`},auth:`console`,usageArgs:`[flags]`,exampleArgs:[``,`--output json`],async run(e){let{settings:t,identity:n}=e,r=C(t.output);W(t);let[i,a,o]=await Promise.all([Fm(e.client,`Cms`,t.workspaceId),Nm(e.client,`ModelMonitor`,t.workspaceId),Bm(e.client,`Monitor`,t.workspaceId)]);if(r===`json`){O({cmsSlrAuthorized:i,deliverySwitch:o,...a},r);return}F_(i,a,o,n.binName)}});const L_=`zeldaEasy.bailian-telemetry.activate.initCmsService`,R_=`zeldaEasy.bailian-telemetry.activate.initTelemetryStoreInstance`,z_=`ModelMonitor`,B_=`Monitor`;async function V_(e,t,n){let r=Date.now()+12e4,i=await Nm(e,z_,t);for(;Date.now()<r;){if(n(i))return i;await new Promise(e=>setTimeout(e,3e3)),i=await Nm(e,z_,t)}return i}var H_=S({description:{"en-US":`Activate monitoring delivery: CMS SLR authorization, CMS service, and the dedicated Prometheus instance`,"zh-CN":`开通监控数据投递:CMS SLR 授权、开通 CMS 服务、创建用户独享 Prometheus 实例`},auth:`console`,usageArgs:`[--no-wait] [flags]`,flags:{noWait:{type:`switch`,description:{"en-US":`Submit the activation requests and return without waiting for Ready`,"zh-CN":`提交开通请求后直接返回,不等待实例就绪`}}},notes:[{"en-US":`Steps: 1) authorize the CMS service-linked role, 2) open the CMS service (async, polled via openStatus), 3) create the dedicated Prometheus instance (async, polled until Ready), 4) turn on the monitor delivery switch for all models. Server-side throttles duplicate submissions within 30s.`,"zh-CN":`开通链路:1)授权 CMS 服务关联角色;2)开通 CMS 服务(异步,以 openStatus 为准);3)创建用户独享 Prometheus 实例(异步,等待 Ready);4)为全部模型打开监控投递开关。服务端对 30 秒内的重复提交做节流。`}],exampleArgs:[``,`--no-wait`,`--output json`],async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=E(process.stderr);if(t.dryRun){O({apis:[`zeldaEasy.bailian-telemetry.activate.getTelemetrySlrStatus`,`zeldaEasy.bailian-telemetry.activate.createTelemetrySlr`,Mm,L_,R_,Lm],data:{reqDTO:{...t.workspaceId?{workspaceId:t.workspaceId}:{},slrType:`Cms`,serviceType:z_,telemetryType:B_}},...w(t)},r);return}W(t);let[a,o]=await Promise.all([Nm(e.client,z_,t.workspaceId),Bm(e.client,B_,t.workspaceId)]);if(a.openStatus&&a.instanceStatus===`Ready`&&o===!0){r===`json`?O({activated:!0,alreadyActive:!0,...a},r):process.stdout.write(`Monitoring delivery is already active.
|
|
2801
|
+
`);return}if(await Im(e.client,`Cms`,t.workspaceId,{onProgress:e=>process.stderr.write(i.dim(e+`
|
|
2802
2802
|
`))}),a.openStatus||(process.stderr.write(i.dim(`Opening the CMS service...
|
|
2803
|
-
`)),await e.client.console(
|
|
2804
|
-
`)),await
|
|
2805
|
-
`));let s=await
|
|
2806
|
-
`)),await e.client.console(
|
|
2807
|
-
`),s.instanceInfo&&(process.stdout.write(`Instance: ${s.instanceInfo.instanceId}\n`),process.stdout.write(`URL: ${s.instanceInfo.instanceUrl}\n`))):process.stdout.write(`Activation is still in progress. Run \`${e.identity.binName} monitor delivery status\` to check later.\n`)}});const
|
|
2808
|
-
`)}});function
|
|
2809
|
-
`);return}let n=
|
|
2810
|
-
`)}function
|
|
2811
|
-
`))});let s=await
|
|
2812
|
-
`)),await
|
|
2813
|
-
`));let e=Date.now()+18e4;for(;Date.now()<e&&s.instanceStatus!==`Ready`;)await new Promise(e=>setTimeout(e,3e3)),s=await hm(r,n,i.workspaceId)}if(await r.console(ym,{reqDTO:R_(i,t)}),a===`json`){O({enabled:!0,kind:t,instanceStatus:s.instanceStatus},a);return}process.stdout.write(`${t===`audit`?`Audit`:`Inference`} log delivery enabled.\n`),e.noWait&&process.stdout.write(`The SLS instance may still be initializing; check \`${e.binName} log status\` later.\n`)}async function B_(e,t,r){let{client:i,settings:a,format:o}=e;if(a.dryRun){O({api:bm,data:{reqDTO:R_(a,t)},...w(a)},o);return}if(W(a),r&&await I_(i,`inference`,a.workspaceId)===!0)throw new n(`The audit log cannot be disabled while the inference log is enabled.`,l.USAGE,`Run \`${e.binName} log inference disable\` first, then disable the audit log.`);if(await i.console(bm,{reqDTO:R_(a,t)}),o===`json`){O({disabled:!0,kind:t},o);return}process.stdout.write(`${t===`audit`?`Audit`:`Inference`} log delivery disabled.\n`)}const V_={noWait:{type:`switch`,description:{"en-US":`Return right after submitting, without waiting for the SLS instance`,"zh-CN":`提交后立即返回,不等待 SLS 实例就绪`}}};function H_(e){if(e!=null&&e<=0)return`--hours must be positive.`}const U_=`zeldaEasy.bailian-telemetry.model.countModelLogs`;async function W_(e,t,n,r){let{settings:i}=e,a=C(i.output),{startTime:o,endTime:s}=r(),c={...i.workspaceId?{workspaceId:i.workspaceId,filterWorkspaceId:i.workspaceId}:{},startTime:o,endTime:s,telemetryType:P_[t],models:n.model?U(n.model):void 0,apikeyIds:n.apiKeyId?U(n.apiKeyId):void 0};if(i.dryRun){O({api:U_,data:{reqDTO:c},...w(i)},a);return}W(i);let l=um(await e.client.console(U_,{reqDTO:c}));if(a===`json`){O({kind:t,period:{start:H(o),end:H(s)},count:l},a);return}process.stdout.write(`${t===`audit`?`Audit`:`Inference`} logs: ${V(l)} (${H(o)} ~ ${H(s)})\n`)}const G_={audit:`ModelAuditLog`,inference:`ModelInferenceLog`};async function K_(e,t){let[n,r,i,a,o]=await Promise.all([e.console(`zeldaEasy.bailian-telemetry.activate.getTelemetrySlrStatus`,{reqDTO:{...t?{workspaceId:t}:{},slrType:`Log`}}),hm(e,G_.audit,t),hm(e,G_.inference,t),I_(e,`audit`,t),I_(e,`inference`,t)]);return{slrAuthorized:um(n)===!0,audit:r,inference:i,auditSwitch:a,inferenceSwitch:o}}function q_(e){return e.openStatus?e.instanceStatus??`-`:`Not activated`}function J_(e){return e===null?`Never configured`:e?`On`:`Off`}var Y_=S({description:{"en-US":`Show model log delivery status (SLS authorization, audit / inference service and switches)`,"zh-CN":`查看模型日志投递状态(SLS 授权、审计 / 推理日志的服务与开关状态)`},auth:`console`,usageArgs:`[flags]`,exampleArgs:[``,`--output json`],notes:[{"en-US":`Both log kinds have independent switches; the inference log additionally requires the audit log to stay on.`,"zh-CN":`审计与推理日志各有独立开关;推理日志还要求审计日志保持开启。`}],async run(e){let{settings:t,identity:n}=e,r=C(t.output);W(t);let i=await K_(e.client,t.workspaceId);if(r===`json`){O(i,r);return}let a=E(process.stdout),o=[[`SLS Authorization (SLR)`,i.slrAuthorized?`Authorized`:`Not authorized`],[`Audit Log (service)`,q_(i.audit)],[`Audit Log (switch)`,J_(i.auditSwitch)],[`Inference Log (service)`,q_(i.inference)],[`Inference Log (switch)`,J_(i.inferenceSwitch)]],s=i.inference.instanceInfo?.instanceUrl;s&&o.push([`SLS Instance URL`,s]);let c=Math.max(...o.map(([e])=>tr(e)));for(let[e,t]of o)process.stdout.write(`${a.bold(k(e,c+2))}${t}\n`);i.auditSwitch===!0?i.inferenceSwitch!==!0&&process.stdout.write(a.dim(`\nRun \`${n.binName} log inference enable\` to enable inference log delivery.\n`)):process.stdout.write(a.dim(`\nRun \`${n.binName} log audit enable\` to enable audit log delivery.\n`))}});const X_=`zeldaEasy.bailian-telemetry.platform-model.listModelLogs`;var Z_=S({description:{"en-US":`Query model audit logs (call metadata; request/response content is not recorded)`,"zh-CN":`查询模型审计日志(调用元数据;不含请求/响应内容)`},auth:`console`,usageArgs:`[--model <model>] [--hours <n>] [flags]`,flags:{...lm,...wm,requestId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Exact model request ID`,"zh-CN":`精确匹配模型请求 ID`}},statusCode:{type:`string`,valueHint:`<type>`,description:{"en-US":`Status filter(s), comma-separated: SUCCESS, CLIENT_ERROR, SERVER_ERROR, CANCEL`,"zh-CN":`状态过滤,多个以逗号分隔:SUCCESS、CLIENT_ERROR、SERVER_ERROR、CANCEL`}},maxResults:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows per page (default: 20)`,"zh-CN":`每页数量(默认:20)`}},skip:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows to skip (default: 0)`,"zh-CN":`跳过的记录数(默认:0)`}},nextToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Pagination token from a previous response`,"zh-CN":`上一次响应返回的分页标记`}}},exampleArgs:[``,`--model qwen3.6-plus --hours 3`,`--status-code SERVER_ERROR,CLIENT_ERROR`,`--request-id 6f6b2f1e-xxxx-xxxx-xxxx-xxxxxxxxxxxx`,`--output json`],notes:[{"en-US":"Audit logs carry call metadata only. For full request/response content, enable and query the inference log (`log inference list` / `log inference get`).","zh-CN":"审计日志只记录调用元数据。需要完整请求/响应内容时,请开启并查询推理日志(`log inference list` / `log inference get`)。"}],validate:e=>k_(e.statusCode)??H_(e.hours),async run(e){let{settings:t,flags:n}=e,r=C(t.output),{startTime:i,endTime:a}=cm(n,1/24),o={...Dm(n,t.workspaceId),filterWorkspaceId:t.workspaceId,startTime:i,endTime:a,maxResults:n.maxResults??20,skip:n.skip??0,nextToken:n.nextToken,modelRequestId:n.requestId,needFullContent:!1,statusCodeTypes:n.statusCode?U(n.statusCode):void 0};if(t.dryRun){O({api:X_,data:{reqDTO:o},...w(t)},r);return}W(t);let s=await im(e.client,X_,o),c=s.list??[],l=s.nextToken;if(r===`json`){O({totalCount:s.totalCount??0,nextToken:l,list:c},r);return}M_(c),l&&process.stdout.write(`Next page: --next-token ${l}\n`)}}),Q_=S({description:{"en-US":`Show a single audit log entry with its raw origin record`,"zh-CN":`查看单条审计日志详情(含原始审计记录)`},auth:`console`,usageArgs:`--request-id <id> [flags]`,flags:{...lm,requestId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":"Model request ID (from `log audit list`)","zh-CN":`模型请求 ID(可由 log audit list 获得)`}},model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name (narrows the search)`,"zh-CN":`模型名称(缩小查询范围)`}}},exampleArgs:[`--request-id 6f6b2f1e-xxxx-xxxx-xxxx-xxxxxxxxxxxx`,`--request-id 6f6b2f1e-xxxx-xxxx-xxxx-xxxxxxxxxxxx --hours 24`,`--request-id 6f6b2f1e-xxxx-xxxx-xxxx-xxxxxxxxxxxx --output json`],notes:[{"en-US":"Audit entries carry call metadata plus the raw audit record; request/response content lives in the inference log (`log inference get`).","zh-CN":"审计详情包含调用元数据与原始审计记录;请求/响应内容在推理日志中(`log inference get`)。"}],validate:e=>j_(e.requestId)??H_(e.hours),async run(e){let{settings:t,flags:r}=e,i=C(t.output),{startTime:a,endTime:o}=cm(r,1),s={...t.workspaceId?{workspaceId:t.workspaceId,filterWorkspaceId:t.workspaceId}:{},startTime:a,endTime:o,modelRequestId:r.requestId,maxResults:1,skip:0,needFullContent:!1};if(r.model&&(s.models=[r.model]),t.dryRun){O({api:X_,data:{reqDTO:s},...w(t)},i);return}W(t);let c=((await im(e.client,`zeldaEasy.bailian-telemetry.platform-model.listModelLogs`,s)).list??[])[0];if(!c)throw new n(`No audit log found for request ${r.requestId} in the selected range.`,l.GENERAL,`Widen the window with --hours/--start-time, or check the request ID.`);if(i===`json`){O(c,i);return}N_(c),c.originLog&&process.stdout.write(`\n${E(process.stdout).bold(`Origin record:`)}\n${JSON.stringify(c.originLog,null,2)}\n`)}});const $_={model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name(s), comma-separated`,"zh-CN":`模型名称,多个名称以逗号分隔`}},apiKeyId:{type:`string`,valueHint:`<id>`,description:{"en-US":`API key ID(s), comma-separated`,"zh-CN":`API Key ID,多个以逗号分隔`}}};var ev=S({description:{"en-US":`Count model audit logs in a time range (useful before exporting)`,"zh-CN":`统计时间范围内的模型审计日志条数(导出前预估量级)`},auth:`console`,usageArgs:`[--model <model>] [--hours <n>] [flags]`,flags:{...lm,...$_},exampleArgs:[``,`--model qwen3.6-plus --hours 24`,`--output json`],validate:e=>H_(e.hours),async run(e){await W_(e,`audit`,e.flags,()=>cm(e.flags,1/24))}}),tv=S({description:{"en-US":`Enable audit log delivery to SLS (SLR authorization → SLS instance → log switch)`,"zh-CN":`开启审计日志投递到 SLS(SLR 授权 → SLS 实例初始化 → 打开日志开关)`},auth:`console`,usageArgs:`[--no-wait] [flags]`,flags:V_,notes:[{"en-US":`Steps: 1) authorize the SLS service-linked role, 2) initialize the SLS store instance (async), 3) turn on audit log delivery for all models in the workspace.`,"zh-CN":`开启链路:1)授权 SLS 服务关联角色;2)初始化 SLS 存储实例(异步);3)为当前业务空间全部模型打开审计日志开关。`},{"en-US":`The audit log records call metadata only and is required before enabling the inference log.`,"zh-CN":`审计日志只记录调用元数据,且是开启推理日志的前置条件。`}],exampleArgs:[``,`--no-wait`,`--output json`],async run(e){let t=C(e.settings.output);await z_({client:e.client,settings:e.settings,binName:e.identity.binName,format:t,noWait:e.flags.noWait},`audit`,G_.audit)}}),nv=S({description:{"en-US":`Disable audit log delivery for all models in the workspace`,"zh-CN":`关闭当前业务空间全部模型的审计日志投递`},auth:`console`,usageArgs:`[flags]`,notes:[{"en-US":`Refused while the inference log is still enabled — disable the inference log first (the console enforces the same rule).`,"zh-CN":`推理日志仍开启时不允许单独关闭审计日志——请先关闭推理日志(与控制台规则一致)。`}],exampleArgs:[``,`--dry-run`,`--output json`],async run(e){let t=C(e.settings.output);await B_({client:e.client,settings:e.settings,binName:e.identity.binName,format:t},`audit`,!0)}});const rv=`zeldaEasy.bailian-telemetry.model.listModelLogs`,iv=[`SUCCESS`,`CLIENT_ERROR`,`SERVER_ERROR`,`CANCEL`];var av=S({description:{"en-US":"Query model inference logs (requires inference log delivery; use `log inference get` for request/response content)","zh-CN":"查询模型推理日志(需已开启推理日志投递;请求/响应内容请用 `log inference get` 查看)"},auth:`console`,usageArgs:`[--model <model>] [--hours <n>] [flags]`,flags:{...lm,model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name (the inference log API accepts a single model)`,"zh-CN":`模型名称(推理日志接口仅支持单个模型)`}},apiKeyId:{type:`string`,valueHint:`<id>`,description:{"en-US":`API key ID (the inference log API accepts a single ID)`,"zh-CN":`API Key ID(推理日志接口仅支持单个 ID)`}},callSource:{type:`string`,valueHint:`<type>`,choices:[`Online`,`Offline`],description:{"en-US":`Inference type: Online, Offline`,"zh-CN":`推理类型:Online、Offline`}},requestId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Exact model request ID`,"zh-CN":`精确匹配模型请求 ID`}},statusCode:{type:`string`,valueHint:`<type>`,description:{"en-US":`Status filter(s), comma-separated: ${iv.join(`, `)}`,"zh-CN":`状态过滤,多个以逗号分隔:${iv.join(`、`)}`}},maxResults:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows per page (default: 20)`,"zh-CN":`每页数量(默认:20)`}},skip:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows to skip (default: 0)`,"zh-CN":`跳过的记录数(默认:0)`}}},exampleArgs:[``,`--model qwen3.6-plus --hours 3`,`--status-code SERVER_ERROR,CLIENT_ERROR`,`--request-id 6f6b2f1e-xxxx-xxxx-xxxx-xxxxxxxxxxxx`,`--output json`],notes:[{"en-US":"Requires inference log delivery (`log inference enable`), which itself requires the audit log. Entries here mirror the audit trail; full request/response content is fetched per request via `log inference get`.","zh-CN":"需先开启推理日志投递(`log inference enable`),且推理日志依赖审计日志。列表与审计口径同构;完整请求/响应内容按请求 ID 通过 `log inference get` 回捞。"}],validate:e=>k_(e.statusCode)??H_(e.hours),async run(e){let{settings:t,flags:n}=e,r=C(t.output),{startTime:i,endTime:a}=cm(n,1/24),o={...t.workspaceId?{workspaceId:t.workspaceId,filterWorkspaceId:t.workspaceId}:{},startTime:String(i),endTime:String(a),model:n.model,apikeyId:n.apiKeyId,modelCallSource:n.callSource,modelRequestId:n.requestId,maxResults:n.maxResults??20,skip:n.skip??0,needFullContent:!1,statusCodeTypes:n.statusCode?U(n.statusCode):void 0};if(t.dryRun){O({api:rv,data:{reqDTO:o},...w(t)},r);return}W(t);let s=await im(e.client,rv,o),c=s.list??[];if(r===`json`){O({totalCount:s.totalCount??0,list:c},r);return}M_(c)}});const ov=`zeldaEasy.bailian-telemetry.model.getModelOriginLog`;var sv=S({description:{"en-US":`Show a single inference log entry with full request/response content`,"zh-CN":`查看单条推理日志详情(含完整请求/响应内容)`},auth:`console`,usageArgs:`--request-id <id> [flags]`,flags:{...lm,requestId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":"Model request ID (from `log inference list`)","zh-CN":`模型请求 ID(可由 log inference list 获得)`}},model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name (narrows the search)`,"zh-CN":`模型名称(缩小查询范围)`}}},exampleArgs:[`--request-id 6f6b2f1e-xxxx-xxxx-xxxx-xxxxxxxxxxxx`,`--request-id 6f6b2f1e-xxxx-xxxx-xxxx-xxxxxxxxxxxx --hours 24`,`--request-id 6f6b2f1e-xxxx-xxxx-xxxx-xxxxxxxxxxxx --output json`],notes:[{"en-US":`The origin content is fetched back by request ID from the inference log store, so inference log delivery must have been enabled when the call happened.`,"zh-CN":`原始内容按请求 ID 从推理日志存储回捞,因此调用发生时须已开启推理日志投递。`}],validate:e=>j_(e.requestId)??H_(e.hours),async run(e){let{settings:t,flags:r}=e,i=C(t.output),{startTime:a,endTime:o}=cm(r,1),s={...t.workspaceId?{workspaceId:t.workspaceId,filterWorkspaceId:t.workspaceId}:{},modelRequestId:r.requestId};if(t.dryRun){O({apis:[rv,ov],data:{reqDTO:{...s,startTime:String(a),endTime:String(o)}},...w(t)},i);return}W(t);let c=((await im(e.client,`zeldaEasy.bailian-telemetry.model.listModelLogs`,{...s,startTime:String(a),endTime:String(o),model:r.model,maxResults:1,skip:0,needFullContent:!1})).list??[])[0];if(!c)throw new n(`No inference log found for request ${r.requestId} in the selected range.`,l.GENERAL,`Widen the window with --hours/--start-time, or check the request ID.`);let u=(await im(e.client,ov,{...s,startTime:String(a),endTime:String(o),...c.taskUuid?{taskUuid:c.taskUuid}:{}})).originLog;if(c.request=c.request??u?.request,c.response=c.response??u?.response,i===`json`){O(c,i);return}N_(c),!c.request&&!c.response&&process.stdout.write(E(process.stdout).dim(`
|
|
2803
|
+
`)),await e.client.console(L_,{reqDTO:{...t.workspaceId?{workspaceId:t.workspaceId}:{},slrType:`Cms`}}),n.noWait||(a=await V_(e.client,t.workspaceId,e=>e.openStatus))),a.instanceStatus===`NotExist`&&(process.stderr.write(i.dim(`Creating the dedicated Prometheus instance...
|
|
2804
|
+
`)),await Sm(e.client,R_,{...t.workspaceId?{workspaceId:t.workspaceId}:{},serviceType:z_})),n.noWait){r===`json`?O({activated:!1,submitted:!0},r):process.stdout.write(`Activation submitted. Run \`${e.identity.binName} monitor delivery status\` to check progress.\n`);return}process.stderr.write(i.dim(`Waiting for the Prometheus instance to become ready...
|
|
2805
|
+
`));let s=await V_(e.client,t.workspaceId,e=>e.openStatus&&e.instanceStatus===`Ready`);s.openStatus&&s.instanceStatus===`Ready`&&o!==!0&&(process.stderr.write(i.dim(`Turning on the monitor delivery switch...
|
|
2806
|
+
`)),await e.client.console(Lm,{reqDTO:Vm(t,B_)}));let c=s.openStatus&&s.instanceStatus===`Ready`;if(r===`json`){O({activated:c,...s},r);return}c?(process.stdout.write(`Monitoring delivery is active.
|
|
2807
|
+
`),s.instanceInfo&&(process.stdout.write(`Instance: ${s.instanceInfo.instanceId}\n`),process.stdout.write(`URL: ${s.instanceInfo.instanceUrl}\n`))):process.stdout.write(`Activation is still in progress. Run \`${e.identity.binName} monitor delivery status\` to check later.\n`)}});const U_=`Monitor`;var W_=S({description:{"en-US":`Disable monitor delivery for all models in the workspace`,"zh-CN":`关闭当前业务空间全部模型的监控数据投递`},auth:`console`,usageArgs:`[flags]`,notes:[{"en-US":"Only the delivery switch is turned off; the CMS service and the Prometheus instance (with stored data) are kept. Re-enable with `monitor delivery enable`.","zh-CN":"仅关闭投递开关;CMS 服务与 Prometheus 实例(含已存储数据)保留。可用 `monitor delivery enable` 重新开启。"}],exampleArgs:[``,`--dry-run`,`--output json`],async run(e){let{settings:t}=e,n=C(t.output);if(t.dryRun){O({api:Rm,data:{reqDTO:Vm(t,U_)},...w(t)},n);return}if(W(t),await e.client.console(Rm,{reqDTO:Vm(t,U_)}),n===`json`){O({disabled:!0},n);return}process.stdout.write(`Monitor delivery disabled.
|
|
2808
|
+
`)}});function G_(e){if(!e)return{};if(typeof e==`string`)try{return JSON.parse(e)}catch{return{}}return e}const K_=[`SUCCESS`,`CLIENT_ERROR`,`SERVER_ERROR`,`CANCEL`];function q_(e){if(!e)return;let t=U(e).filter(e=>!K_.includes(e));if(t.length>0)return`Unknown status code type: ${t.join(`, `)}. Valid: ${K_.join(`, `)}.`}const J_={min:32,max:36};function Y_(e){let t=e.length;if(t<J_.min||t>J_.max)return`--request-id must be ${J_.min}-${J_.max} characters.`}function X_(e){let t=E(process.stdout);if(e.length===0){process.stdout.write(`No logs found in this range.
|
|
2809
|
+
`);return}let n=jr({headers:[`Time`,`Request ID`,`Model`,`Status`,`Duration`,`First Token`,`Tokens`],rows:e.map(e=>{let t=G_(e.usage),n=t.input_tokens!=null||t.output_tokens!=null?`${t.input_tokens??`-`}/${t.output_tokens??`-`}`:`-`;return[H(e.startTime),e.modelRequestId??`-`,e.model??`-`,e.httpStatusCode==null?`-`:String(e.httpStatusCode),e.callDuration==null?`-`:`${V(e.callDuration)} ms`,e.firstTokenDuration==null?`-`:`${V(e.firstTokenDuration)} ms`,n]}),align:[`left`,`left`,`left`,`right`,`right`,`right`,`right`],cellColor:(e,n,r)=>{if(n===3){if(r.startsWith(`2`))return t.green(r);if(r.startsWith(`5`))return t.red(r);if(r!==`-`)return t.yellow(r)}}});for(let e of n)process.stdout.write(e+`
|
|
2810
|
+
`)}function Z_(e){let t=E(process.stdout),n=G_(e.usage),r=[[`Request ID`,e.modelRequestId],[`Model`,e.model??`-`],[`Time`,e.startTime?H(e.startTime):`-`],[`Status`,e.httpStatusCode==null?`-`:String(e.httpStatusCode)],[`Duration`,e.callDuration==null?`-`:`${e.callDuration} ms`],[`First Token`,e.firstTokenDuration==null?`-`:`${e.firstTokenDuration} ms`],[`Tokens (in/out/total)`,`${n.input_tokens??`-`}/${n.output_tokens??`-`}/${n.total_tokens??`-`}`]];e.apikeyId&&r.push([`API Key ID`,e.apikeyId]),e.errorCode&&r.push([`Error Code`,e.errorCode]),e.errorMessage&&r.push([`Error Message`,e.errorMessage]);for(let[e,n]of r)process.stdout.write(`${t.bold(e)}: ${n}\n`);e.request&&process.stdout.write(`\n${t.bold(`Request:`)}\n${e.request}\n`),e.response&&process.stdout.write(`\n${t.bold(`Response:`)}\n${e.response}\n`)}const Q_={audit:`AuditLog`,inference:`InferenceLog`},$_=`zeldaEasy.bailian-telemetry.activate.initTelemetryStoreInstance`;async function ev(e,t,n){return Bm(e,Q_[t],n)}async function tv(e,t,r){let i=await ev(e,`audit`,t);for(let n=0;n<3&&i!==!0;n+=1)await new Promise(e=>setTimeout(e,2e3)),i=await ev(e,`audit`,t);if(i!==!0)throw new n(`Model audit log is not enabled yet.`,l.USAGE,`Inference log delivery requires the audit log. Run \`${r} log audit enable\` first, then check \`${r} log status\`.`)}function nv(e,t){return Vm(e,Q_[t])}async function rv(e,t,n){let{client:r,settings:i,format:a}=e,o=E(process.stderr);if(i.dryRun){O({apis:[`zeldaEasy.bailian-telemetry.activate.createTelemetrySlr`,$_,Lm],data:{reqDTO:nv(i,t)},...w(i)},a);return}W(i),await Im(r,`Log`,i.workspaceId,{pollRetries:5,onProgress:e=>process.stderr.write(o.dim(e+`
|
|
2811
|
+
`))});let s=await Nm(r,n,i.workspaceId);if(s.instanceStatus===`NotExist`&&(process.stderr.write(o.dim(`Initializing the SLS store instance...
|
|
2812
|
+
`)),await Sm(r,$_,{...i.workspaceId?{workspaceId:i.workspaceId}:{},serviceType:n}),!e.noWait)){process.stderr.write(o.dim(`Waiting for the SLS instance to become ready...
|
|
2813
|
+
`));let e=Date.now()+18e4;for(;Date.now()<e&&s.instanceStatus!==`Ready`;)await new Promise(e=>setTimeout(e,3e3)),s=await Nm(r,n,i.workspaceId)}if(await r.console(Lm,{reqDTO:nv(i,t)}),a===`json`){O({enabled:!0,kind:t,instanceStatus:s.instanceStatus},a);return}process.stdout.write(`${t===`audit`?`Audit`:`Inference`} log delivery enabled.\n`),e.noWait&&process.stdout.write(`The SLS instance may still be initializing; check \`${e.binName} log status\` later.\n`)}async function iv(e,t,r){let{client:i,settings:a,format:o}=e;if(a.dryRun){O({api:Rm,data:{reqDTO:nv(a,t)},...w(a)},o);return}if(W(a),r&&await ev(i,`inference`,a.workspaceId)===!0)throw new n(`The audit log cannot be disabled while the inference log is enabled.`,l.USAGE,`Run \`${e.binName} log inference disable\` first, then disable the audit log.`);if(await i.console(Rm,{reqDTO:nv(a,t)}),o===`json`){O({disabled:!0,kind:t},o);return}process.stdout.write(`${t===`audit`?`Audit`:`Inference`} log delivery disabled.\n`)}const av={noWait:{type:`switch`,description:{"en-US":`Return right after submitting, without waiting for the SLS instance`,"zh-CN":`提交后立即返回,不等待 SLS 实例就绪`}}};function ov(e){if(e!=null&&e<=0)return`--hours must be positive.`}const sv=`zeldaEasy.bailian-telemetry.model.countModelLogs`;async function cv(e,t,n,r){let{settings:i}=e,a=C(i.output),{startTime:o,endTime:s}=r(),c={...i.workspaceId?{workspaceId:i.workspaceId,filterWorkspaceId:i.workspaceId}:{},startTime:o,endTime:s,telemetryType:Q_[t],models:n.model?U(n.model):void 0,apikeyIds:n.apiKeyId?U(n.apiKeyId):void 0};if(i.dryRun){O({api:sv,data:{reqDTO:c},...w(i)},a);return}W(i);let l=Om(await e.client.console(sv,{reqDTO:c}));if(a===`json`){O({kind:t,period:{start:H(o),end:H(s)},count:l},a);return}process.stdout.write(`${t===`audit`?`Audit`:`Inference`} logs: ${V(l)} (${H(o)} ~ ${H(s)})\n`)}const lv={audit:`ModelAuditLog`,inference:`ModelInferenceLog`};async function uv(e,t){let[n,r,i,a,o]=await Promise.all([e.console(`zeldaEasy.bailian-telemetry.activate.getTelemetrySlrStatus`,{reqDTO:{...t?{workspaceId:t}:{},slrType:`Log`}}),Nm(e,lv.audit,t),Nm(e,lv.inference,t),ev(e,`audit`,t),ev(e,`inference`,t)]);return{slrAuthorized:Om(n)===!0,audit:r,inference:i,auditSwitch:a,inferenceSwitch:o}}function dv(e){return e.openStatus?e.instanceStatus??`-`:`Not activated`}function fv(e){return e===null?`Never configured`:e?`On`:`Off`}var pv=S({description:{"en-US":`Show model log delivery status (SLS authorization, audit / inference service and switches)`,"zh-CN":`查看模型日志投递状态(SLS 授权、审计 / 推理日志的服务与开关状态)`},auth:`console`,usageArgs:`[flags]`,exampleArgs:[``,`--output json`],notes:[{"en-US":`Both log kinds have independent switches; the inference log additionally requires the audit log to stay on.`,"zh-CN":`审计与推理日志各有独立开关;推理日志还要求审计日志保持开启。`}],async run(e){let{settings:t,identity:n}=e,r=C(t.output);W(t);let i=await uv(e.client,t.workspaceId);if(r===`json`){O(i,r);return}let a=E(process.stdout),o=[[`SLS Authorization (SLR)`,i.slrAuthorized?`Authorized`:`Not authorized`],[`Audit Log (service)`,dv(i.audit)],[`Audit Log (switch)`,fv(i.auditSwitch)],[`Inference Log (service)`,dv(i.inference)],[`Inference Log (switch)`,fv(i.inferenceSwitch)]],s=i.inference.instanceInfo?.instanceUrl;s&&o.push([`SLS Instance URL`,s]);let c=Math.max(...o.map(([e])=>hr(e)));for(let[e,t]of o)process.stdout.write(`${a.bold(k(e,c+2))}${t}\n`);i.auditSwitch===!0?i.inferenceSwitch!==!0&&process.stdout.write(a.dim(`\nRun \`${n.binName} log inference enable\` to enable inference log delivery.\n`)):process.stdout.write(a.dim(`\nRun \`${n.binName} log audit enable\` to enable audit log delivery.\n`))}});const mv=`zeldaEasy.bailian-telemetry.platform-model.listModelLogs`;var hv=S({description:{"en-US":`Query model audit logs (call metadata; request/response content is not recorded)`,"zh-CN":`查询模型审计日志(调用元数据;不含请求/响应内容)`},auth:`console`,usageArgs:`[--model <model>] [--hours <n>] [flags]`,flags:{...Dm,...Hm,requestId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Exact model request ID`,"zh-CN":`精确匹配模型请求 ID`}},statusCode:{type:`string`,valueHint:`<type>`,description:{"en-US":`Status filter(s), comma-separated: SUCCESS, CLIENT_ERROR, SERVER_ERROR, CANCEL`,"zh-CN":`状态过滤,多个以逗号分隔:SUCCESS、CLIENT_ERROR、SERVER_ERROR、CANCEL`}},maxResults:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows per page (default: 20)`,"zh-CN":`每页数量(默认:20)`}},skip:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows to skip (default: 0)`,"zh-CN":`跳过的记录数(默认:0)`}},nextToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Pagination token from a previous response`,"zh-CN":`上一次响应返回的分页标记`}}},exampleArgs:[``,`--model qwen3.6-plus --hours 3`,`--status-code SERVER_ERROR,CLIENT_ERROR`,`--request-id 6f6b2f1e-xxxx-xxxx-xxxx-xxxxxxxxxxxx`,`--output json`],notes:[{"en-US":"Audit logs carry call metadata only. For full request/response content, enable and query the inference log (`log inference list` / `log inference get`).","zh-CN":"审计日志只记录调用元数据。需要完整请求/响应内容时,请开启并查询推理日志(`log inference list` / `log inference get`)。"}],validate:e=>q_(e.statusCode)??ov(e.hours),async run(e){let{settings:t,flags:n}=e,r=C(t.output),{startTime:i,endTime:a}=Em(n,1/24),o={...Gm(n,t.workspaceId),filterWorkspaceId:t.workspaceId,startTime:i,endTime:a,maxResults:n.maxResults??20,skip:n.skip??0,nextToken:n.nextToken,modelRequestId:n.requestId,needFullContent:!1,statusCodeTypes:n.statusCode?U(n.statusCode):void 0};if(t.dryRun){O({api:mv,data:{reqDTO:o},...w(t)},r);return}W(t);let s=await Sm(e.client,mv,o),c=s.list??[],l=s.nextToken;if(r===`json`){O({totalCount:s.totalCount??0,nextToken:l,list:c},r);return}X_(c),l&&process.stdout.write(`Next page: --next-token ${l}\n`)}}),gv=S({description:{"en-US":`Show a single audit log entry with its raw origin record`,"zh-CN":`查看单条审计日志详情(含原始审计记录)`},auth:`console`,usageArgs:`--request-id <id> [flags]`,flags:{...Dm,requestId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":"Model request ID (from `log audit list`)","zh-CN":`模型请求 ID(可由 log audit list 获得)`}},model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name (narrows the search)`,"zh-CN":`模型名称(缩小查询范围)`}}},exampleArgs:[`--request-id 6f6b2f1e-xxxx-xxxx-xxxx-xxxxxxxxxxxx`,`--request-id 6f6b2f1e-xxxx-xxxx-xxxx-xxxxxxxxxxxx --hours 24`,`--request-id 6f6b2f1e-xxxx-xxxx-xxxx-xxxxxxxxxxxx --output json`],notes:[{"en-US":"Audit entries carry call metadata plus the raw audit record; request/response content lives in the inference log (`log inference get`).","zh-CN":"审计详情包含调用元数据与原始审计记录;请求/响应内容在推理日志中(`log inference get`)。"}],validate:e=>Y_(e.requestId)??ov(e.hours),async run(e){let{settings:t,flags:r}=e,i=C(t.output),{startTime:a,endTime:o}=Em(r,1),s={...t.workspaceId?{workspaceId:t.workspaceId,filterWorkspaceId:t.workspaceId}:{},startTime:a,endTime:o,modelRequestId:r.requestId,maxResults:1,skip:0,needFullContent:!1};if(r.model&&(s.models=[r.model]),t.dryRun){O({api:mv,data:{reqDTO:s},...w(t)},i);return}W(t);let c=((await Sm(e.client,`zeldaEasy.bailian-telemetry.platform-model.listModelLogs`,s)).list??[])[0];if(!c)throw new n(`No audit log found for request ${r.requestId} in the selected range.`,l.GENERAL,`Widen the window with --hours/--start-time, or check the request ID.`);if(i===`json`){O(c,i);return}Z_(c),c.originLog&&process.stdout.write(`\n${E(process.stdout).bold(`Origin record:`)}\n${JSON.stringify(c.originLog,null,2)}\n`)}});const _v={model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name(s), comma-separated`,"zh-CN":`模型名称,多个名称以逗号分隔`}},apiKeyId:{type:`string`,valueHint:`<id>`,description:{"en-US":`API key ID(s), comma-separated`,"zh-CN":`API Key ID,多个以逗号分隔`}}};var vv=S({description:{"en-US":`Count model audit logs in a time range (useful before exporting)`,"zh-CN":`统计时间范围内的模型审计日志条数(导出前预估量级)`},auth:`console`,usageArgs:`[--model <model>] [--hours <n>] [flags]`,flags:{...Dm,..._v},exampleArgs:[``,`--model qwen3.6-plus --hours 24`,`--output json`],validate:e=>ov(e.hours),async run(e){await cv(e,`audit`,e.flags,()=>Em(e.flags,1/24))}}),yv=S({description:{"en-US":`Enable audit log delivery to SLS (SLR authorization → SLS instance → log switch)`,"zh-CN":`开启审计日志投递到 SLS(SLR 授权 → SLS 实例初始化 → 打开日志开关)`},auth:`console`,usageArgs:`[--no-wait] [flags]`,flags:av,notes:[{"en-US":`Steps: 1) authorize the SLS service-linked role, 2) initialize the SLS store instance (async), 3) turn on audit log delivery for all models in the workspace.`,"zh-CN":`开启链路:1)授权 SLS 服务关联角色;2)初始化 SLS 存储实例(异步);3)为当前业务空间全部模型打开审计日志开关。`},{"en-US":`The audit log records call metadata only and is required before enabling the inference log.`,"zh-CN":`审计日志只记录调用元数据,且是开启推理日志的前置条件。`}],exampleArgs:[``,`--no-wait`,`--output json`],async run(e){let t=C(e.settings.output);await rv({client:e.client,settings:e.settings,binName:e.identity.binName,format:t,noWait:e.flags.noWait},`audit`,lv.audit)}}),bv=S({description:{"en-US":`Disable audit log delivery for all models in the workspace`,"zh-CN":`关闭当前业务空间全部模型的审计日志投递`},auth:`console`,usageArgs:`[flags]`,notes:[{"en-US":`Refused while the inference log is still enabled — disable the inference log first (the console enforces the same rule).`,"zh-CN":`推理日志仍开启时不允许单独关闭审计日志——请先关闭推理日志(与控制台规则一致)。`}],exampleArgs:[``,`--dry-run`,`--output json`],async run(e){let t=C(e.settings.output);await iv({client:e.client,settings:e.settings,binName:e.identity.binName,format:t},`audit`,!0)}});const xv=`zeldaEasy.bailian-telemetry.model.listModelLogs`,Sv=[`SUCCESS`,`CLIENT_ERROR`,`SERVER_ERROR`,`CANCEL`];var Cv=S({description:{"en-US":"Query model inference logs (requires inference log delivery; use `log inference get` for request/response content)","zh-CN":"查询模型推理日志(需已开启推理日志投递;请求/响应内容请用 `log inference get` 查看)"},auth:`console`,usageArgs:`[--model <model>] [--hours <n>] [flags]`,flags:{...Dm,model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name (the inference log API accepts a single model)`,"zh-CN":`模型名称(推理日志接口仅支持单个模型)`}},apiKeyId:{type:`string`,valueHint:`<id>`,description:{"en-US":`API key ID (the inference log API accepts a single ID)`,"zh-CN":`API Key ID(推理日志接口仅支持单个 ID)`}},callSource:{type:`string`,valueHint:`<type>`,choices:[`Online`,`Offline`],description:{"en-US":`Inference type: Online, Offline`,"zh-CN":`推理类型:Online、Offline`}},requestId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Exact model request ID`,"zh-CN":`精确匹配模型请求 ID`}},statusCode:{type:`string`,valueHint:`<type>`,description:{"en-US":`Status filter(s), comma-separated: ${Sv.join(`, `)}`,"zh-CN":`状态过滤,多个以逗号分隔:${Sv.join(`、`)}`}},maxResults:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows per page (default: 20)`,"zh-CN":`每页数量(默认:20)`}},skip:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows to skip (default: 0)`,"zh-CN":`跳过的记录数(默认:0)`}}},exampleArgs:[``,`--model qwen3.6-plus --hours 3`,`--status-code SERVER_ERROR,CLIENT_ERROR`,`--request-id 6f6b2f1e-xxxx-xxxx-xxxx-xxxxxxxxxxxx`,`--output json`],notes:[{"en-US":"Requires inference log delivery (`log inference enable`), which itself requires the audit log. Entries here mirror the audit trail; full request/response content is fetched per request via `log inference get`.","zh-CN":"需先开启推理日志投递(`log inference enable`),且推理日志依赖审计日志。列表与审计口径同构;完整请求/响应内容按请求 ID 通过 `log inference get` 回捞。"}],validate:e=>q_(e.statusCode)??ov(e.hours),async run(e){let{settings:t,flags:n}=e,r=C(t.output),{startTime:i,endTime:a}=Em(n,1/24),o={...t.workspaceId?{workspaceId:t.workspaceId,filterWorkspaceId:t.workspaceId}:{},startTime:String(i),endTime:String(a),model:n.model,apikeyId:n.apiKeyId,modelCallSource:n.callSource,modelRequestId:n.requestId,maxResults:n.maxResults??20,skip:n.skip??0,needFullContent:!1,statusCodeTypes:n.statusCode?U(n.statusCode):void 0};if(t.dryRun){O({api:xv,data:{reqDTO:o},...w(t)},r);return}W(t);let s=await Sm(e.client,xv,o),c=s.list??[];if(r===`json`){O({totalCount:s.totalCount??0,list:c},r);return}X_(c)}});const wv=`zeldaEasy.bailian-telemetry.model.getModelOriginLog`;var Tv=S({description:{"en-US":`Show a single inference log entry with full request/response content`,"zh-CN":`查看单条推理日志详情(含完整请求/响应内容)`},auth:`console`,usageArgs:`--request-id <id> [flags]`,flags:{...Dm,requestId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":"Model request ID (from `log inference list`)","zh-CN":`模型请求 ID(可由 log inference list 获得)`}},model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name (narrows the search)`,"zh-CN":`模型名称(缩小查询范围)`}}},exampleArgs:[`--request-id 6f6b2f1e-xxxx-xxxx-xxxx-xxxxxxxxxxxx`,`--request-id 6f6b2f1e-xxxx-xxxx-xxxx-xxxxxxxxxxxx --hours 24`,`--request-id 6f6b2f1e-xxxx-xxxx-xxxx-xxxxxxxxxxxx --output json`],notes:[{"en-US":`The origin content is fetched back by request ID from the inference log store, so inference log delivery must have been enabled when the call happened.`,"zh-CN":`原始内容按请求 ID 从推理日志存储回捞,因此调用发生时须已开启推理日志投递。`}],validate:e=>Y_(e.requestId)??ov(e.hours),async run(e){let{settings:t,flags:r}=e,i=C(t.output),{startTime:a,endTime:o}=Em(r,1),s={...t.workspaceId?{workspaceId:t.workspaceId,filterWorkspaceId:t.workspaceId}:{},modelRequestId:r.requestId};if(t.dryRun){O({apis:[xv,wv],data:{reqDTO:{...s,startTime:String(a),endTime:String(o)}},...w(t)},i);return}W(t);let c=((await Sm(e.client,`zeldaEasy.bailian-telemetry.model.listModelLogs`,{...s,startTime:String(a),endTime:String(o),model:r.model,maxResults:1,skip:0,needFullContent:!1})).list??[])[0];if(!c)throw new n(`No inference log found for request ${r.requestId} in the selected range.`,l.GENERAL,`Widen the window with --hours/--start-time, or check the request ID.`);let u=(await Sm(e.client,wv,{...s,startTime:String(a),endTime:String(o),...c.taskUuid?{taskUuid:c.taskUuid}:{}})).originLog;if(c.request=c.request??u?.request,c.response=c.response??u?.response,i===`json`){O(c,i);return}Z_(c),!c.request&&!c.response&&process.stdout.write(E(process.stdout).dim(`
|
|
2814
2814
|
Request/response content is only available when inference log delivery was enabled at call time.
|
|
2815
|
-
`))}});const
|
|
2816
|
-
`);return}let n=
|
|
2817
|
-
`)}var
|
|
2818
|
-
`);return}let l=
|
|
2819
|
-
`)}});const
|
|
2820
|
-
`);return}let o=
|
|
2821
|
-
`)}});const
|
|
2822
|
-
`);return}let o=
|
|
2823
|
-
`)}});const
|
|
2824
|
-
`);return}let n=
|
|
2825
|
-
`)}var
|
|
2826
|
-
`);return}let c=E(process.stdout),l=
|
|
2827
|
-
`);s.nextToken&&process.stdout.write(`Next page: --next-token ${s.nextToken}\n`)}});function
|
|
2828
|
-
`);process.stdout.write(`\nTotal: ${t}\n`)}var
|
|
2815
|
+
`))}});const Ev={model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model name(s), comma-separated`,"zh-CN":`模型名称,多个名称以逗号分隔`}},apiKeyId:{type:`string`,valueHint:`<id>`,description:{"en-US":`API key ID(s), comma-separated`,"zh-CN":`API Key ID,多个以逗号分隔`}}};var Dv=S({description:{"en-US":`Count model inference logs in a time range (useful before exporting)`,"zh-CN":`统计时间范围内的模型推理日志条数(导出前预估量级)`},auth:`console`,usageArgs:`[--model <model>] [--hours <n>] [flags]`,flags:{...Dm,...Ev},exampleArgs:[``,`--model qwen3.6-plus --hours 24`,`--output json`],notes:[{"en-US":`Only calls made while inference log delivery was enabled are counted.`,"zh-CN":`仅统计推理日志投递开启期间产生的调用。`}],validate:e=>ov(e.hours),async run(e){await cv(e,`inference`,e.flags,()=>Em(e.flags,1/24))}}),Ov=S({description:{"en-US":`Enable inference log delivery to SLS (SLR authorization → SLS instance → log switch)`,"zh-CN":`开启推理日志投递到 SLS(SLR 授权 → SLS 实例初始化 → 打开日志开关)`},auth:`console`,usageArgs:`[--no-wait] [flags]`,flags:av,notes:[{"en-US":`Steps: 1) authorize the SLS service-linked role, 2) initialize the SLS store instance (async), 3) turn on inference log delivery for all models in the workspace.`,"zh-CN":`开启链路:1)授权 SLS 服务关联角色;2)初始化 SLS 存储实例(异步);3)为当前业务空间全部模型打开推理日志开关。`},{"en-US":"Requires the audit log to be enabled first (`log audit enable`) — the console enforces the same rule.","zh-CN":"需先开启审计日志(`log audit enable`)——与控制台规则一致。"}],exampleArgs:[``,`--no-wait`,`--output json`],async run(e){let t=C(e.settings.output),n={client:e.client,settings:e.settings,binName:e.identity.binName,format:t,noWait:e.flags.noWait};e.settings.dryRun||await tv(e.client,e.settings.workspaceId,e.identity.binName),await rv(n,`inference`,lv.inference)}}),kv=S({description:{"en-US":`Disable inference log delivery for all models in the workspace`,"zh-CN":`关闭当前业务空间全部模型的推理日志投递`},auth:`console`,usageArgs:`[flags]`,notes:[{"en-US":"Only the inference log (request/response content) is disabled; the audit log keeps its own switch (`log audit disable`).","zh-CN":"仅关闭推理日志(请求/响应内容);审计日志有独立开关(`log audit disable`)。"}],exampleArgs:[``,`--dry-run`,`--output json`],async run(e){let t=C(e.settings.output);await iv({client:e.client,settings:e.settings,binName:e.identity.binName,format:t},`inference`)}});const Av=`zeldaEasy.bailian-telemetry.trace.listTracesWithOss`,jv={0:`Unset`,1:`OK`,2:`Error`};function Mv(e){let t=E(process.stdout);if(e.length===0){process.stdout.write(`No traces found in this range.
|
|
2816
|
+
`);return}let n=jr({headers:[`Time`,`Trace ID`,`Span`,`Status`,`Duration`,`Tokens`],rows:e.map(e=>[H(e.startTime),e.traceId??`-`,e.spanName??`-`,jv[e.statusCode??`0`]??e.statusCode??`-`,e.callDuration==null?e.duration??`-`:`${V(e.callDuration)} ms`,e.totalTokens==null?`-`:V(e.totalTokens)]),align:[`left`,`left`,`left`,`left`,`right`,`right`],cellColor:(e,n,r)=>{if(n===3){if(r===`Error`)return t.red(r);if(r===`OK`)return t.green(r)}}});for(let e of n)process.stdout.write(e+`
|
|
2817
|
+
`)}var Nv=S({description:{"en-US":`List call traces for a model or app`,"zh-CN":`查询模型或应用的调用链列表`},auth:`console`,usageArgs:`--resource-id <id> [flags]`,flags:{...Dm,resourceId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Model name or app ID to query traces for`,"zh-CN":`要查询调用链的模型名称或应用 ID`}},resourceType:{type:`string`,valueHint:`<type>`,choices:[`model`,`app`],description:{"en-US":`Resource type: model, app (default: model)`,"zh-CN":`资源类型:model、app(默认:model)`}},maxResults:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows per page (default: 20)`,"zh-CN":`每页数量(默认:20)`}},skip:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows to skip (default: 0)`,"zh-CN":`跳过的记录数(默认:0)`}}},exampleArgs:[`--resource-id qwen3.6-plus`,`--resource-id qwen3.6-plus --hours 24 --max-results 50`,`--resource-id 123456 --resource-type app --output json`],async run(e){let{settings:t,flags:n}=e,r=C(t.output),{startTime:i,endTime:a}=Em(n,1/24),o={...t.workspaceId?{workspaceId:t.workspaceId}:{},resourceId:n.resourceId,resourceType:n.resourceType??`model`,startTime:i,endTime:a,maxResults:n.maxResults??20,skip:n.skip??0,nextToken:``};if(t.dryRun){O({api:Av,data:{reqDTO:o},...w(t)},r);return}W(t);let s=await jm(await Sm(e.client,Av,o)),c=Array.isArray(s)?s:s?.list??[],l=Array.isArray(s)?void 0:s?.totalCount;if(r===`json`){O({totalCount:l,list:c},r);return}Mv(c)}});const Pv=`zeldaEasy.bailian-telemetry.trace.getTraceWithOss`;function Fv(e,t){let n=E(process.stdout),r=` `.repeat(t),i=jv[e.statusCode??`0`]??`-`,a=e.callDuration==null?e.duration??`-`:`${V(e.callDuration)} ms`,o=e.totalTokens==null?``:`, ${V(e.totalTokens)} tokens`,s=i===`Error`?n.red(i):i;process.stdout.write(`${r}${e.spanName??`-`} ${n.dim(`[${s}, ${a}${o}]`)}\n`),e.statusCode===`2`&&e.statusMessage&&process.stdout.write(`${r} ${n.red(e.statusMessage)}\n`);for(let n of e.children??[])Fv(n,t+1)}var Iv=S({description:{"en-US":`Show a single call trace with its span tree`,"zh-CN":`查看单条调用链详情(含 span 树)`},auth:`console`,usageArgs:`--trace-id <id> [flags]`,flags:{...Dm,traceId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":"Trace ID (from `log trace list`)","zh-CN":`调用链 ID(可由 log trace list 获得)`}},resourceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Model name or app ID (narrows the search)`,"zh-CN":`模型名称或应用 ID(缩小查询范围)`}}},exampleArgs:[`--trace-id 0a1b2c3d4e5f --hours 24`,`--trace-id 0a1b2c3d4e5f --resource-id qwen3.6-plus`,`--trace-id 0a1b2c3d4e5f --output json`],async run(e){let{settings:t,flags:r}=e,i=C(t.output),{startTime:a,endTime:o}=Em(r,1),s={...t.workspaceId?{workspaceId:t.workspaceId}:{},traceId:r.traceId,resourceId:r.resourceId,startTime:a,endTime:o};if(t.dryRun){O({api:Pv,data:{reqDTO:s},...w(t)},i);return}W(t);let c=await jm(await Sm(e.client,Pv,s));if(!c||!c.traceId)throw new n(`No trace found for ${r.traceId} in the selected range.`,l.GENERAL,`Widen the window with --hours/--start-time, or check the trace ID.`);if(i===`json`){O(c,i);return}let u=E(process.stdout);process.stdout.write(`${u.bold(`Trace`)} ${c.traceId} ${u.dim(H(c.startTime))}\n\n`),Fv(c,0)}});const Lv=`zeldaEasy.bailian-telemetry.trace.getTraceStatistic`;var Rv=S({description:{"en-US":`Show per-resource trace statistics (calls, tokens, latency)`,"zh-CN":`查看调用链维度统计(调用量、Token、延迟)`},auth:`console`,usageArgs:`[--resource-id <id>] [flags]`,flags:{...Dm,resourceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Model name(s) or app ID(s), comma-separated; omit for all`,"zh-CN":`模型名称或应用 ID,多个以逗号分隔;省略表示全部`}},resourceType:{type:`string`,valueHint:`<type>`,choices:[`model`,`app`],description:{"en-US":`Resource type: model, app (default: model)`,"zh-CN":`资源类型:model、app(默认:model)`}}},exampleArgs:[``,`--resource-id qwen3.6-plus --hours 24`,`--resource-type app --output json`],async run(e){let{settings:t,flags:n}=e,r=C(t.output),{startTime:i,endTime:a}=Em(n,1/24),o={...t.workspaceId?{workspaceId:t.workspaceId,filterWorkspaceId:t.workspaceId}:{},resourceIdList:n.resourceId?U(n.resourceId):void 0,resourceType:n.resourceType??`model`,startTime:i,endTime:a};if(t.dryRun){O({api:Lv,data:{reqDTO:o},...w(t)},r);return}W(t);let s=await Sm(e.client,Lv,o),c=Object.values(s);if(r===`json`){O({period:{start:H(i),end:H(a)},list:c},r);return}if(c.length===0){process.stdout.write(`No trace statistics found in this range.
|
|
2818
|
+
`);return}let l=jr({headers:[`Resource`,`Calls`,`Total Tokens`,`Avg Duration`,`Avg First Token`],rows:c.map(e=>[e.resourceId??`-`,V(Number(e.callCount??0)),V(Number(e.totalTokens??0)),e.avgDuration?`${V(Math.round(Number(e.avgDuration)))} ms`:`-`,e.avgLlmFirstTokenDuration?`${V(Math.round(Number(e.avgLlmFirstTokenDuration)))} ms`:`-`]),align:[`left`,`right`,`right`,`right`,`right`]});for(let e of l)process.stdout.write(e+`
|
|
2819
|
+
`)}});const zv=[`INFO`,`WARNING`,`ERROR`],Bv={name:{type:`string`,valueHint:`<name>`,required:!0,description:{"en-US":`Alert rule name (max 64 chars)`,"zh-CN":`告警规则名称(最长 64 字符)`}},templateId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":"Alert template ID (from `alert template list`)","zh-CN":`告警模板 ID(可由 alert template list 获得)`}},model:{type:`string`,valueHint:`<model>`,required:!0,description:{"en-US":`Model name(s) to alert on, comma-separated`,"zh-CN":`告警生效的模型名称,多个以逗号分隔`}},message:{type:`string`,valueHint:`<text>`,description:{"en-US":`Alert notification content (Go template); defaults to the console template`,"zh-CN":`告警通知内容(Go 模板语法),默认与控制台一致`}},level:{type:`string`,valueHint:`<level>`,choices:zv,description:{"en-US":`Alert level (default: INFO)`,"zh-CN":`告警等级(默认:INFO)`}},interval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Check interval in seconds (default: 60)`,"zh-CN":`告警检查周期(秒,默认:60)`}},duration:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`How long the condition must hold before alerting; 0 = immediately (default: 60)`,"zh-CN":`条件持续多久后告警(秒),0 表示立即告警(默认:60)`}},contact:{type:`string`,valueHint:`<id>`,description:{"en-US":`CMS alert contact ID(s), comma-separated; create them in the CloudMonitor console`,"zh-CN":`云监控告警联系人 ID,多个以逗号分隔;需在云监控控制台创建`}},contactGroup:{type:`string`,valueHint:`<id>`,description:{"en-US":`CMS alert contact group ID(s), comma-separated`,"zh-CN":`云监控告警联系组 ID,多个以逗号分隔`}},notifyWindow:{type:`string`,valueHint:`<HH:mm-HH:mm>`,description:{"en-US":`Daily notification window (default: 00:00-23:59)`,"zh-CN":`每日通知时间窗口(默认:00:00-23:59)`}},notifyDays:{type:`string`,valueHint:`<days>`,description:{"en-US":`Days of week to notify, 1-7 comma-separated (default: every day)`,"zh-CN":`每周通知日,1-7 逗号分隔(默认:每天)`}},silence:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Silence period between repeat notifications (default: never repeat)`,"zh-CN":`重复通知的静默时间(秒,默认:不重复通知)`}},gmtOffset:{type:`string`,valueHint:`<offset>`,description:{"en-US":`Timezone offset for the notify window (default: +0800)`,"zh-CN":`通知窗口的时区偏移(默认:+0800)`}}};function Vv(e){if(e.notifyWindow&&!/^(\d{2}:\d{2})-(\d{2}:\d{2})$/.exec(e.notifyWindow))return`--notify-window must be in HH:mm-HH:mm format, e.g. 09:00-18:00.`;if(e.notifyDays&&U(e.notifyDays).filter(e=>!/^[1-7]$/.test(e)).length>0)return`--notify-days accepts values 1-7, e.g. 1,2,3,4,5.`;if(e.interval!=null&&e.interval<1)return`--interval must be positive seconds.`;if(e.duration!=null&&e.duration<0)return`--duration must be >= 0 seconds.`;if(e.silence!=null&&e.silence<0)return`--silence must be >= 0 seconds.`;if(e.gmtOffset!=null&&!/^[+-]\d{4}$/.test(e.gmtOffset))return`--gmt-offset must look like +0800.`}function Hv(e){if(e.interval===0)throw new x(`--interval must be positive seconds.`);let t=e.notifyWindow?/^(\d{2}:\d{2})-(\d{2}:\d{2})$/.exec(e.notifyWindow):null;return{name:e.name,templateId:e.templateId,resourceIds:U(e.model),message:e.message??`业务空间({{$tags.workspace_id}})下的模型({{$tags.model}})发生告警,当前值为{{ printf "%.2f" $value }}`,level:e.level??`INFO`,interval:e.interval??60,duration:e.duration??60,notification:{startTime:t?.[1]??`00:00`,endTime:t?.[2]??`23:59`,gmtOffset:e.gmtOffset??`+0800`,dayOfWeek:e.notifyDays?U(e.notifyDays).map(Number):[1,2,3,4,5,6,7],silenceTime:e.silence??2147483647,contacts:e.contact?U(e.contact):void 0,contactGroups:e.contactGroup?U(e.contactGroup):void 0}}}async function Uv(e,t,n,r){W(r),await Pm(e,{serviceType:`ModelMonitor`,workspaceId:t,enableCommand:`${n} monitor delivery enable`,requireInstance:!1})}const Wv=[`>`,`>=`,`<`,`<=`,`==`,`!=`];function Gv(e){let t=e.split(`:`);if(t.length!==5)throw new x(`Invalid --condition "${e}". Expected metricName:aggregator:compareType:value:period. If the value contains > or <, wrap the whole condition in quotes so the shell does not treat it as redirection.`);let[n,r,i,a,o]=t;if(!n||!r)throw new x(`Invalid --condition "${e}": metricName and aggregator are required.`);if(!Wv.includes(i))throw new x(`Invalid --condition "${e}": compareType must be one of ${Wv.join(` `)}.`);let s=Number(o);if(!Number.isFinite(s)||s<1)throw new x(`Invalid --condition "${e}": period must be positive seconds.`);return{metricName:n,aggregator:r,compareType:i,compareValue:a,period:s}}function Kv(e,t){if(!e||e.length===0)return t?void 0:`At least one --condition is required (or use --from to copy a template).`;if(e.length>10)return`At most 10 --condition entries are allowed.`;for(let t of e)try{Gv(t)}catch(e){return e instanceof Error?e.message:String(e)}}function qv(e){let t=qn(e);return{list:t.list??[],totalCount:t.totalCount??0,nextToken:t.nextToken}}const Jv=`zeldaEasy.bailian-telemetry.alertMetric.listMetrics`;var Yv=S({description:{"en-US":`List metrics that alert rules can be created on, with supported aggregations`,"zh-CN":`查看可创建告警的指标及其支持的聚合方式`},auth:`console`,usageArgs:`[flags]`,exampleArgs:[``,`--output json`],async run(e){let{settings:t}=e,n=t.outputExplicit?C(t.output):`json`;if(t.dryRun){O({api:Jv,data:{reqDTO:{workspaceId:t.workspaceId,resourceType:`model`}},...w(t)},n);return}await Uv(e.client,t.workspaceId,e.identity.binName,t);let r=await e.client.console(Jv,{reqDTO:{workspaceId:t.workspaceId,resourceType:`model`}}),i=qn(r),a=Array.isArray(i)?i:i.list??i.result??[];if(n===`json`){O(a,n);return}if(a.length===0){process.stdout.write(`No alertable metrics found.
|
|
2820
|
+
`);return}let o=jr({headers:[`Metric`,`Aggregations`,`Unit`,`Description`],rows:a.map(e=>[e.metricName,(e.aggregators??[]).join(`, `),e.unit??`-`,e.desc??`-`]),align:[`left`,`left`,`left`,`left`]});for(let e of o)process.stdout.write(e+`
|
|
2821
|
+
`)}});const Xv=`zeldaEasy.bailian-telemetry.alertTemplate.listAlertTemplates`;function Zv(e){let t=e.metricName??e.alertMetric??`?`;return`${e.aggregator?`${e.aggregator} `:``}${t} ${e.compareType} ${e.compareValue} (${e.period}s)`}var Qv=S({description:{"en-US":`List alert templates (official and custom); pass --template-id for details`,"zh-CN":`查看告警模板(官方与自定义);传 --template-id 查看单个模板详情`},auth:`console`,usageArgs:`[--name <name>] [--source <source>] [flags]`,flags:{templateId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Exact template ID (view a single template)`,"zh-CN":`精确模板 ID(查看单个模板)`}},name:{type:`string`,valueHint:`<name>`,description:{"en-US":`Fuzzy filter by template name`,"zh-CN":`按模板名称模糊过滤`}},source:{type:`string`,valueHint:`<source>`,choices:[`Official`,`Customize`],description:{"en-US":`Template source: Official, Customize; omit for all`,"zh-CN":`模板来源:Official、Customize;省略表示全部`}},maxResults:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows per page (default: 50)`,"zh-CN":`每页数量(默认:50)`}},skip:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows to skip (default: 0)`,"zh-CN":`跳过的记录数(默认:0)`}}},exampleArgs:[``,`--source Official`,`--name 失败率`,`--template-id 123 --output json`],async run(e){let{settings:t,flags:n}=e,r=t.outputExplicit?C(t.output):`json`,i={resourceType:`model`,templateId:n.templateId,templateName:n.name,source:n.source,maxResults:n.maxResults??50,skip:n.skip??0};if(t.dryRun){O({api:Xv,data:{reqDTO:i},...w(t)},r);return}await Uv(e.client,t.workspaceId,e.identity.binName,t);let a=qv(await e.client.console(Xv,{reqDTO:i}));if(r===`json`){O(a,r);return}if(a.list.length===0){process.stdout.write(`No alert templates found.
|
|
2822
|
+
`);return}let o=jr({headers:[`Template ID`,`Name`,`Source`,`Conditions`],rows:a.list.map(e=>[e.templateId,e.templateName,e.source===`Official`?`Official`:`Custom`,(e.conditions??[]).map(Zv).join(e.logicalOperator===`and`?` AND `:` OR `)||`-`]),align:[`left`,`left`,`left`,`left`]});for(let e of o)process.stdout.write(e+`
|
|
2823
|
+
`)}});const $v=`zeldaEasy.bailian-telemetry.alertTemplate.createAlertTemplate`;async function ey(e,t){if(t.condition?.length)return t.condition.map(Gv);if(!t.from)return[];let r=qv(await e.client.console(`zeldaEasy.bailian-telemetry.alertTemplate.listAlertTemplates`,{reqDTO:{resourceType:`model`,templateId:t.from,maxResults:1,skip:0}})).list[0];if(!r)throw new n(`Source template not found: ${t.from}`,l.GENERAL,"Check the ID with `alert template list`.");return(r.conditions??[]).map(e=>({metricName:e.metricName,aggregator:e.aggregator,compareType:e.compareType,compareValue:e.compareValue,period:e.period}))}var ty=S({description:{"en-US":`Create a custom alert template (or copy an official one with --from)`,"zh-CN":`创建自定义告警模板(或用 --from 复制官方模板)`},auth:`console`,usageArgs:`--name <name> [--condition <metric:agg:cmp:value:period>...] [--from <template-id>] [flags]`,flags:{name:{type:`string`,valueHint:`<name>`,required:!0,description:{"en-US":`Template name (max 64 chars)`,"zh-CN":`模板名称(最长 64 字符)`}},condition:{type:`array`,valueHint:`<metric:agg:cmp:value:period>`,description:{"en-US":"Alert condition, repeatable (1-10). Example: 'model_call_failed_count:sum:>:10:60' (quote it: > is a shell metacharacter). See `alert metrics` for metric names","zh-CN":"告警条件,可重复(1-10 条)。示例:'model_call_failed_count:sum:>:10:60'(含 > 等 shell 特殊字符,需加引号)。指标名见 `alert metrics`"}},from:{type:`string`,valueHint:`<template-id>`,description:{"en-US":`Copy conditions from an existing (e.g. official) template`,"zh-CN":`复制已有(如官方)模板的条件`}},logicalOperator:{type:`string`,valueHint:`<op>`,choices:[`or`,`and`],description:{"en-US":`How multiple conditions combine (default: or)`,"zh-CN":`多条件组合逻辑(默认:or)`}}},exampleArgs:[`--name 失败率告警 --condition 'model_call_failed_count:sum:>:10:60'`,`--name 高延迟 --condition 'model_call_duration:avg:>:3000:300' --condition 'model_call_5xx_count:sum:>:5:60' --logical-operator and`,`--name 我的模板 --from <template-id>`,`--name test --condition 'model_call_count:sum:>:100:60' --dry-run`],validate:e=>Kv(e.condition,!!e.from),async run(e){let{settings:t,flags:n}=e,r=t.outputExplicit?C(t.output):`json`,i=n.condition?.length?n.condition.map(Gv):void 0;if(t.dryRun){O({api:$v,data:{reqDTO:{templateName:n.name,resourceType:`model`,logicalOperator:n.logicalOperator??`or`,srcTemplateId:n.from,conditions:i??`(copied from --from template)`}},...w(t)},r);return}await Uv(e.client,t.workspaceId,e.identity.binName,t);let a={templateName:n.name,resourceType:`model`,logicalOperator:n.logicalOperator??`or`,srcTemplateId:n.from,conditions:i??await ey(e,n)},o=await e.client.console($v,{reqDTO:a}),s=qn(o),c=s.data??s.templateId??s;if(r===`json`){O({created:!0,templateId:c},r);return}process.stdout.write(`Alert template created${c?`: ${c}`:`.`}\n`)}});const ny=`zeldaEasy.bailian-telemetry.alertTemplate.updateAlertTemplate`;var ry=S({description:{"en-US":`Update a custom alert template (full replacement of conditions)`,"zh-CN":`更新自定义告警模板(整体替换条件)`},auth:`console`,usageArgs:`--template-id <id> --name <name> --condition <metric:agg:cmp:value:period>... [flags]`,flags:{templateId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":"Template ID (from `alert template list`)","zh-CN":`模板 ID(可由 alert template list 获得)`}},name:{type:`string`,valueHint:`<name>`,required:!0,description:{"en-US":`Template name (max 64 chars)`,"zh-CN":`模板名称(最长 64 字符)`}},condition:{type:`array`,valueHint:`<metric:agg:cmp:value:period>`,description:{"en-US":`Alert condition, repeatable (1-10). Example: 'model_call_failed_count:sum:>:10:60' (quote it: > is a shell metacharacter)`,"zh-CN":`告警条件,可重复(1-10 条)。示例:'model_call_failed_count:sum:>:10:60'(含 > 等 shell 特殊字符,需加引号)`}},logicalOperator:{type:`string`,valueHint:`<op>`,choices:[`or`,`and`],description:{"en-US":`How multiple conditions combine (default: or)`,"zh-CN":`多条件组合逻辑(默认:or)`}}},exampleArgs:[`--template-id 123 --name 失败率告警 --condition 'model_call_failed_count:sum:>:20:60'`,`--template-id 123 --name test --condition 'model_call_count:sum:>:100:60' --dry-run`],validate:e=>Kv(e.condition,!1),async run(e){let{settings:t,flags:n}=e,r=t.outputExplicit?C(t.output):`json`,i={templateId:n.templateId,templateName:n.name,resourceType:`model`,logicalOperator:n.logicalOperator??`or`,conditions:(n.condition??[]).map(Gv)};if(t.dryRun){O({api:ny,data:{reqDTO:i},...w(t)},r);return}if(await Uv(e.client,t.workspaceId,e.identity.binName,t),await e.client.console(ny,{reqDTO:i}),r===`json`){O({updated:!0,templateId:n.templateId},r);return}process.stdout.write(`Alert template updated: ${n.templateId}\n`)}});const iy=`zeldaEasy.bailian-telemetry.alertTemplate.deleteAlertTemplates`;var ay=S({description:{"en-US":`Delete custom alert templates (official templates cannot be deleted)`,"zh-CN":`删除自定义告警模板(官方模板不可删除)`},auth:`console`,risk:{level:`high`,message:{"en-US":`This permanently deletes the specified alert templates and cannot be undone.`,"zh-CN":`该操作会永久删除指定的告警模板,且无法撤销。`}},usageArgs:`--template-id <id>[,<id>...] [--yes]`,flags:{templateId:{type:`string`,valueHint:`<id>[,<id>...]`,required:!0,description:{"en-US":`Template ID(s) to delete, comma-separated`,"zh-CN":`要删除的模板 ID,多个以逗号分隔`}}},exampleArgs:[`--template-id 123`,`--template-id 123,124 --dry-run`,`--template-id 123 --yes`],notes:[{"en-US":`Irreversible — the alert templates are permanently removed.`,"zh-CN":`该操作不可撤销——告警模板将被永久删除。`}],async run(e){let{settings:t,flags:n}=e,r=t.outputExplicit?C(t.output):`json`,i={templateIds:U(n.templateId)};if(t.dryRun){O({api:iy,data:{reqDTO:i},...w(t)},r);return}await Uv(e.client,t.workspaceId,e.identity.binName,t);let a=await e.client.console(iy,{reqDTO:i}),o=qn(a);if(r===`json`){O({deleted:i.templateIds,result:o},r);return}process.stdout.write(`Deleted ${i.templateIds.length} alert template(s).\n`)}});const oy=`zeldaEasy.bailian-telemetry.alertRule.listAlertRules`;function sy(e){let t=E(process.stdout);if(e.length===0){process.stdout.write(`No alert rules found.
|
|
2824
|
+
`);return}let n=jr({headers:[`Rule ID`,`Name`,`Level`,`Enabled`,`Models`,`Interval`],rows:e.map(e=>[e.ruleId,e.name,e.level??`-`,e.enabled?`ON`:`OFF`,(e.resourceIds??[]).join(`, `)||`-`,e.interval==null?`-`:`${e.interval}s`]),align:[`left`,`left`,`left`,`left`,`left`,`right`],cellColor:(e,n,r)=>{if(n===3)return r===`ON`?t.green(r):t.yellow(r);if(n===2&&r===`ERROR`)return t.red(r)}});for(let e of n)process.stdout.write(e+`
|
|
2825
|
+
`)}var cy=S({description:{"en-US":`List model alert rules`,"zh-CN":`查看模型告警规则列表`},auth:`console`,usageArgs:`[--name <name>] [--enabled true|false] [flags]`,flags:{ruleId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Exact rule ID filter`,"zh-CN":`按规则 ID 精确过滤`}},name:{type:`string`,valueHint:`<name>`,description:{"en-US":`Fuzzy filter by rule name`,"zh-CN":`按规则名称模糊过滤`}},enabled:{type:`boolean`,valueHint:`<true|false>`,description:{"en-US":`Filter by enabled state`,"zh-CN":`按启用状态过滤`}},level:{type:`string`,valueHint:`<level>`,choices:zv,description:{"en-US":`Filter by alert level`,"zh-CN":`按告警等级过滤`}},maxResults:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows per page (default: 20)`,"zh-CN":`每页数量(默认:20)`}},skip:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows to skip (default: 0)`,"zh-CN":`跳过的记录数(默认:0)`}},nextToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Pagination token from a previous response`,"zh-CN":`上一次响应返回的分页标记`}}},exampleArgs:[``,`--enabled true`,`--name 失败率 --level ERROR`,`--output json`],async run(e){let{settings:t,flags:n}=e,r=t.outputExplicit?C(t.output):`json`,i={workspaceId:t.workspaceId,bizSource:`bailian`,resourceType:`model`,ruleId:n.ruleId,name:n.name,enabled:n.enabled,level:n.level,maxResults:n.maxResults??20,skip:n.skip??0,nextToken:n.nextToken};if(t.dryRun){O({api:oy,data:{reqDTO:i},...w(t)},r);return}await Uv(e.client,t.workspaceId,e.identity.binName,t);let a=qv(await e.client.console(oy,{reqDTO:i}));if(r===`json`){O(a,r);return}sy(a.list),a.nextToken&&process.stdout.write(`Next page: --next-token ${a.nextToken}\n`)}});const ly=`zeldaEasy.bailian-telemetry.alertRule.createAlertRule`;var uy=S({description:{"en-US":`Create a model alert rule from an alert template`,"zh-CN":`基于告警模板创建模型告警规则`},auth:`console`,usageArgs:`--name <name> --template-id <id> --model <model> [flags]`,flags:Bv,notes:[{"en-US":"Alert conditions come from the template; browse `alert template list` first. Notification contacts/contact groups are created in the CloudMonitor console — pass their IDs via --contact/--contact-group.","zh-CN":"告警条件来自模板,请先用 `alert template list` 挑选。通知联系人/联系组需在云监控控制台创建,本命令通过 --contact/--contact-group 接收其 ID。"}],exampleArgs:[`--name high-failure-rate --template-id 123 --model qwen3.6-plus`,`--name latency --template-id 456 --model qwen3.6-plus,qwen-turbo --level ERROR --contact-group 4004200`,`--name nightly --template-id 123 --model qwen3.6-plus --notify-window 09:00-18:00 --notify-days 1,2,3,4,5 --silence 3600`,`--name test --template-id 123 --model qwen3.6-plus --dry-run`],validate:e=>Vv(e),async run(e){let{settings:t,flags:n}=e,r=t.outputExplicit?C(t.output):`json`,i={...t.workspaceId?{workspaceId:t.workspaceId}:{},...Hv(n)};if(t.dryRun){O({api:ly,data:{reqDTO:i},...w(t)},r);return}await Uv(e.client,t.workspaceId,e.identity.binName,t);let a=await e.client.console(ly,{reqDTO:i}),o=qn(a),s=o.data??o.ruleId??o;if(r===`json`){O({created:!0,ruleId:s},r);return}process.stdout.write(`Alert rule created${s?`: ${s}`:`.`}\n`)}});const dy=`zeldaEasy.bailian-telemetry.alertRule.updateAlertRule`;var fy=S({description:{"en-US":`Update a model alert rule (full replacement; same fields as create)`,"zh-CN":`更新模型告警规则(整体替换,字段与 create 一致)`},auth:`console`,usageArgs:`--rule-id <id> --name <name> --template-id <id> --model <model> [flags]`,flags:{ruleId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":"Alert rule ID (from `alert list`)","zh-CN":`告警规则 ID(可由 alert list 获得)`}},...Bv},exampleArgs:[`--rule-id 789 --name high-failure-rate --template-id 123 --model qwen3.6-plus --level WARNING`,`--rule-id 789 --name nightly --template-id 123 --model qwen3.6-plus --silence 1800`,`--rule-id 789 --name test --template-id 123 --model qwen3.6-plus --dry-run`],validate:e=>Vv(e),async run(e){let{settings:t,flags:n}=e,r=t.outputExplicit?C(t.output):`json`,i={...t.workspaceId?{workspaceId:t.workspaceId}:{},ruleId:n.ruleId,...Hv(n)};if(t.dryRun){O({api:dy,data:{reqDTO:i},...w(t)},r);return}if(await Uv(e.client,t.workspaceId,e.identity.binName,t),await e.client.console(dy,{reqDTO:i}),r===`json`){O({updated:!0,ruleId:n.ruleId},r);return}process.stdout.write(`Alert rule updated: ${n.ruleId}\n`)}});const py=`zeldaEasy.bailian-telemetry.alertRule.deleteAlertRules`;var my=S({description:{"en-US":`Delete model alert rules`,"zh-CN":`删除模型告警规则`},auth:`console`,risk:{level:`high`,message:{"en-US":`This permanently deletes the specified alert rules and cannot be undone.`,"zh-CN":`该操作会永久删除指定的告警规则,且无法撤销。`}},usageArgs:`--rule-id <id>[,<id>...] [--yes]`,flags:{ruleId:{type:`string`,valueHint:`<id>[,<id>...]`,required:!0,description:{"en-US":`Rule ID(s) to delete, comma-separated`,"zh-CN":`要删除的规则 ID,多个以逗号分隔`}}},exampleArgs:[`--rule-id 789`,`--rule-id 789,790 --dry-run`,`--rule-id 789 --yes`],notes:[{"en-US":`Irreversible — the alert rules are permanently removed.`,"zh-CN":`该操作不可撤销——告警规则将被永久删除。`}],async run(e){let{settings:t,flags:n}=e,r=t.outputExplicit?C(t.output):`json`,i={ruleIds:U(n.ruleId)};if(t.dryRun){O({api:py,data:{reqDTO:i},...w(t)},r);return}if(await Uv(e.client,t.workspaceId,e.identity.binName,t),await e.client.console(py,{reqDTO:i}),r===`json`){O({deleted:i.ruleIds},r);return}process.stdout.write(`Deleted ${i.ruleIds.length} alert rule(s).\n`)}}),hy=S({description:{"en-US":`Enable a model alert rule`,"zh-CN":`启用模型告警规则`},auth:`console`,usageArgs:`--rule-id <id> [flags]`,flags:{ruleId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Alert rule ID`,"zh-CN":`告警规则 ID`}}},exampleArgs:[`--rule-id 789`,`--rule-id 789 --dry-run`],async run(e){let{settings:t,flags:n}=e,r=t.outputExplicit?C(t.output):`json`,i={workspaceId:t.workspaceId,bizSource:`bailian`,ruleId:n.ruleId};if(t.dryRun){O({api:`zeldaEasy.bailian-telemetry.alertRule.enableAlertRule`,data:{reqDTO:i},...w(t)},r);return}if(await Uv(e.client,t.workspaceId,e.identity.binName,t),await e.client.console(`zeldaEasy.bailian-telemetry.alertRule.enableAlertRule`,{reqDTO:i}),r===`json`){O({enabled:!0,ruleId:n.ruleId},r);return}process.stdout.write(`Alert rule enabled: ${n.ruleId}\n`)}});const gy=`zeldaEasy.bailian-telemetry.alertRule.disableAlertRule`;var _y=S({description:{"en-US":`Disable a model alert rule (keeps the rule, stops notifications)`,"zh-CN":`停用模型告警规则(保留规则,停止通知)`},auth:`console`,usageArgs:`--rule-id <id> [flags]`,flags:{ruleId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Alert rule ID`,"zh-CN":`告警规则 ID`}}},exampleArgs:[`--rule-id 789`,`--rule-id 789 --dry-run`],async run(e){let{settings:t,flags:n}=e,r=t.outputExplicit?C(t.output):`json`,i={workspaceId:t.workspaceId,bizSource:`bailian`,ruleId:n.ruleId};if(t.dryRun){O({api:gy,data:{reqDTO:i},...w(t)},r);return}if(await Uv(e.client,t.workspaceId,e.identity.binName,t),await e.client.console(gy,{reqDTO:i}),r===`json`){O({enabled:!1,ruleId:n.ruleId},r);return}process.stdout.write(`Alert rule disabled: ${n.ruleId}\n`)}});const vy=`zeldaEasy.bailian-telemetry.alertRule.listAlertHistories`;function yy(e){let t=e.instanceDetail;return t&&Object.entries(t).map(([e,t])=>`${e}:${t}`).join(`,`)||`-`}var by=S({description:{"en-US":`List model alert history (firing and recovered events)`,"zh-CN":`查看模型告警历史(告警中与已恢复事件)`},auth:`console`,usageArgs:`[--rule-id <id>] [--status <status>] [flags]`,flags:{...wm,ruleId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by alert rule ID`,"zh-CN":`按告警规则 ID 过滤`}},status:{type:`string`,valueHint:`<status>`,choices:[`ALARM`,`OK`],description:{"en-US":`Alert state: ALARM (firing), OK (recovered)`,"zh-CN":`告警状态:ALARM(告警中)、OK(已恢复)`}},level:{type:`string`,valueHint:`<level>`,choices:zv,description:{"en-US":`Filter by highest alert level`,"zh-CN":`按最高告警等级过滤`}},maxResults:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows per page, 1-50 (default: 10)`,"zh-CN":`每页数量,范围 1-50(默认:10)`}},skip:{type:`number`,valueHint:`<n>`,description:{"en-US":`Rows to skip (default: 0)`,"zh-CN":`跳过的记录数(默认:0)`}},nextToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Pagination token from a previous response`,"zh-CN":`上一次响应返回的分页标记`}}},exampleArgs:[``,`--status ALARM --days 1`,`--rule-id 789 --days 30`,`--level ERROR --output json`],validate:e=>{if(e.maxResults!=null&&(e.maxResults<1||e.maxResults>50))return`--max-results must be between 1 and 50.`},async run(e){let{settings:t,flags:n}=e,r=t.outputExplicit?C(t.output):`json`,{startTime:i,endTime:a}=Em(n),o={workspaceId:t.workspaceId,bizSource:`bailian`,resourceType:`model`,alertRuleId:n.ruleId,status:n.status,maxLevel:n.level,startTimeFrom:i,startTimeTo:a,maxResults:n.maxResults??10,skip:n.skip??0,nextToken:n.nextToken};if(t.dryRun){O({api:vy,data:{reqDTO:o},...w(t)},r);return}await Uv(e.client,t.workspaceId,e.identity.binName,t);let s=qv(await e.client.console(vy,{reqDTO:o}));if(r===`json`){O(s,r);return}if(s.list.length===0){process.stdout.write(`No alert history found in this range.
|
|
2826
|
+
`);return}let c=E(process.stdout),l=jr({headers:[`Start Time`,`Rule`,`Status`,`Max Level`,`Count`,`Instance`],rows:s.list.map(e=>[e.startTime?H(e.startTime):`-`,e.ruleDisplayName??e.alertRuleId,e.status??`-`,e.maxLevel??`-`,String(e.count??0),yy(e)]),align:[`left`,`left`,`left`,`left`,`right`,`left`],cellColor:(e,t,n)=>{if(t===2)return n===`ALARM`?c.red(n):c.green(n);if(t===3&&n===`ERROR`)return c.red(n)}});for(let e of l)process.stdout.write(e+`
|
|
2827
|
+
`);s.nextToken&&process.stdout.write(`Next page: --next-token ${s.nextToken}\n`)}});function xy(e){return e==null?`-`:e?`yes`:`no`}function Sy(e,t,n){if(e.length===0){process.stdout.write(`No model permissions found.\n${n}\n`);return}let r=[`Model`,`Name`,`Inference`,`Fine-tune`,`Deploy`],i=e.map(e=>[e.model,e.name??`-`,xy(e.permissions?.inference),xy(e.permissions?.fine_tune),xy(e.permissions?.deploy)]),a=jr({headers:r,rows:i,align:[`left`,`left`,`right`,`right`,`right`]});for(let e of a)process.stdout.write(e+`
|
|
2828
|
+
`);process.stdout.write(`\nTotal: ${t}\n`)}var Cy=S({description:{"en-US":`List model permissions (inference / fine-tune / deploy) in the workspace`,"zh-CN":`列出 Workspace 中的模型权限(推理 / 微调 / 部署)`},auth:`apiKey`,usageArgs:`[--scope <scope>] [--model <model>] [--name <name>] [--page <n>] [--page-size <n>]`,flags:{scope:{type:`string`,valueHint:`<scope>`,choices:[`authorized`,`authorizable`],description:{"en-US":`Authorization scope: authorizable (default, full catalog), authorized`,"zh-CN":`授权范围:authorizable(默认,完整目录)、authorized(已授权)`}},model:{type:`string`,valueHint:`<model>`,description:{"en-US":`Model ID (exact match)`,"zh-CN":`模型 ID(精确匹配)`}},name:{type:`string`,valueHint:`<name>`,description:{"en-US":`Fuzzy search by model name or ID`,"zh-CN":`按模型名称或 ID 模糊搜索`}},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: 20)`,"zh-CN":`每页结果数(默认:20)`}}},exampleArgs:[``,`--model qwen-plus`,`--scope authorized`,`--name qwen --page-size 50`,`--output text`],notes:[{"en-US":"Default scope is `authorizable` (the full grantable catalog); use `--scope authorized` to see only models already granted.","zh-CN":"默认范围为 `authorizable`(完整可授权目录);使用 `--scope authorized` 仅查看已授权模型。"},{"en-US":"Output defaults to JSON; pass `--output text` for a table. Permission values are tri-state: true / false / null (never set).","zh-CN":"默认输出 JSON;传入 `--output text` 可查看表格。权限值为三态:true / false / null(从未设置)。"},{"en-US":`Values mirror the server's grant records as-is for the workspace bound to your API key. A model reporting false/null can still be callable (access may come from other channels); see the Model Studio authorization docs for the exact semantics.`,"zh-CN":`这些值原样反映 API Key 所绑定 Workspace 的服务端授权记录。显示 false/null 的模型仍可能可以调用(访问权限可能来自其他渠道);准确语义请参阅百炼模型授权文档。`}],async run(e){let{settings:t,flags:n}=e,r=t.outputExplicit?C(t.output):`json`,i=n.scope??`authorizable`,a={authorization_scope:i.toUpperCase(),model:n.model||void 0,name:n.name||void 0,page_no:n.page||1,page_size:n.pageSize||20};if(t.dryRun){O({endpoint:e.client.url(qt()),method:`GET`,query:a},r);return}let o=await e.client.requestJson({path:qt()+ym(a)}),s=o.output?.permissions??[],c=o.output?.total??s.length;if(r===`json`){O({items:s,total:c},r);return}let l=e.identity.binName;Sy(s,c,i===`authorized`?`Nothing granted yet in this workspace. Browse grantable models with \`${l} permission list --scope authorizable\`, then grant with \`${l} permission grant --model <model>\`.`:`Adjust --name/--model filters, or check pagination with --page/--page-size.`)}});const wy=[`inference`,`finetune`,`deploy`];function Ty(e){if(!e)return[`inference`];let t=U(e);if(t.length===0)return{error:`--action must not be empty.`};for(let e of t)if(!wy.includes(e))return{error:`--action "${e}" is invalid; use ${wy.join(`, `)}.`};return t}function Ey(e){if(e.all&&e.model)return`--all cannot be combined with --model.`;if(!e.all&&!e.model)return`one of --model / --all is required.`;let t=Ty(e.action);if(`error`in t)return t.error;if(e.all&&(t.length!==1||t[0]!==`inference`))return`--all only supports the inference action.`;if(e.model){let t=U(e.model);if(t.length===0)return`--model must not be empty.`;if(t.length>20)return`--model accepts at most 20 models per call.`}}async function Dy(e,t,n){let r=e.settings.outputExplicit?C(e.settings.output):`json`,i=Ty(t.action),a=t.model?U(t.model):[],o=t.all?{access_all_entities:n?`OPEN`:`CLOSE`}:{models:a.map(e=>{let t={model:e};for(let e of i)t[e]=n;return t})};if(e.settings.dryRun){O({endpoint:e.client.url(qt()),method:`POST`,request:o},r);return}let s=await e.client.requestJson({path:qt(),method:`POST`,body:o}),c=n?`granted`:`revoked`;if(r===`json`){let e=t.all?{all:!0,action:`inference`}:{models:a,actions:i};O({...e,[c]:!0,request_id:s.request_id},r);return}if(t.all){process.stdout.write(n?`Inference permission granted for all models in the workspace (including future ones).
|
|
2829
2829
|
`:`One-key authorization closed; historical inference grants cleared.
|
|
2830
|
-
`);return}process.stdout.write(`Permissions ${c} (${i.join(`, `)}): ${a.join(`, `)}\n`)}var
|
|
2831
|
-
`),l.GENERAL)}if(e.warnings.length>0&&!r.quiet){process.stderr.write(`Dataset validation passed with ${e.warnings.length} warning(s):\n`);for(let t of e.warnings.slice(0,5))process.stderr.write(`${
|
|
2832
|
-
`),l.GENERAL)}if(u.warnings.length>0&&!e.quiet){process.stderr.write(`Dataset validation passed with ${u.warnings.length} warning(s) for ${r}:\n`);for(let e of u.warnings.slice(0,5))process.stderr.write(`${qe(e)}\n`);u.warnings.length>5&&process.stderr.write(` … and ${u.warnings.length-5} more.\n`)}let g=u.stats.totalRecords;typeof g==`number`&&(m=(m??0)+g),p===void 0&&(p=Fr(r).size)}return{fileIds:d,localPaths:f,firstSize:p,recordCount:h?m:void 0}}async function yy(e,t,r,i,a){let o=[];for(let[s,c]of r.fileIds.entries()){if(!_y(c))continue;let u=await Bn(e,{filePath:c,purpose:i});if(!u.file_id)throw new n(`Upload of ${c} succeeded but no file_id was returned.`,l.GENERAL);o.push(u),r.fileIds[s]=u.file_id,t.quiet||process.stderr.write(`Uploaded ${Lr(c)} → ${u.file_id} (auto from --${a})\n`)}return o}const by={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|paths>`,description:{"en-US":`Comma-separated dataset file IDs or local paths (.jsonl for text, .zip for audio/image/video). Local paths are uploaded (validated) first, then their file-ids are used.`,"zh-CN":`数据集文件 ID 或本地路径,以逗号分隔(文本使用 .jsonl,音频、图片和视频使用 .zip)。本地路径会先验证并上传,再使用对应的 file-id。`},required:!0},validations:{type:`string`,valueHint:`<ids|paths>`,description:{"en-US":`Comma-separated validation dataset file IDs or local paths (auto-uploaded like --datasets).`,"zh-CN":`验证数据集文件 ID 或本地路径,以逗号分隔(与 --datasets 一样自动上传)。`}},modelName:{type:`string`,valueHint:`<name>`,description:{"en-US":`Output model name (after training)`,"zh-CN":`训练完成后的输出模型名称`}},suffix:{type:`string`,valueHint:`<text>`,description:{"en-US":`Output suffix appended by the platform (finetuned_output_suffix)`,"zh-CN":`平台追加的输出后缀(finetuned_output_suffix)`}}},xy={...by,trainingType:{type:`string`,valueHint:`<t>`,description:{"en-US":`Training type: ${ee.join(` | `)} (default: ${s}). Mapping to the server happens at the interface boundary (e.g. sft-lora -> efficient_sft, dpo -> dpo_full).`,"zh-CN":`训练类型:${ee.join(` | `)}(默认:${s})。在接口边界转换为服务端值(例如 sft-lora -> efficient_sft、dpo -> dpo_full)。`}},nEpochs:{type:`number`,valueHint:`<n>`,description:{"en-US":`Number of epochs (default: 3)`,"zh-CN":`训练轮数(默认:3)`}},batchSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Per-device batch size (clamped to [8, 1024]). Auto-set to 8 for small datasets (<100KB)`,"zh-CN":`单设备 Batch Size(限制在 [8, 1024])。小数据集(<100KB)自动设为 8`}},learningRate:{type:`string`,valueHint:`<str>`,description:{"en-US":`Learning rate as a string to preserve precision (e.g. "1.6e-5")`,"zh-CN":`以字符串形式指定学习率以保留精度(例如 "1.6e-5")`}},maxLength:{type:`number`,valueHint:`<n>`,description:{"en-US":`Max sequence length`,"zh-CN":`最大序列长度`}}},Sy={...by},Cy={...by,generationType:{type:`string`,choices:[`t2i`,`i2i`],valueHint:`<t2i|i2i>`,description:{"en-US":`Generation type: t2i (default) | i2i. Sets generation_type/max_pixels. Required to train I2I from a file-id or with --dry-run (local data auto-detects input_img).`,"zh-CN":`生成类型:t2i(默认)| i2i。用于设置 generation_type/max_pixels。通过 file-id 训练 I2I 或使用 --dry-run 时必填(本地数据会自动识别 input_img)。`}},learningRate:{type:`string`,valueHint:`<str>`,description:{"en-US":`Learning rate as a string to preserve precision (e.g. "3e-5")`,"zh-CN":`以字符串形式指定学习率以保留精度(例如 "3e-5")`}}},wy={...by,nEpochs:{type:`number`,valueHint:`<n>`,description:{"en-US":`Training epochs (default: 50)`,"zh-CN":`训练轮数(默认:50)`}},batchSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Batch size (default: model-specific, 1 for wan2.7, 4 for wan2.5/2.2)`,"zh-CN":`Batch Size(默认值因模型而异:wan2.7 为 1,wan2.5/2.2 为 4)`}},learningRate:{type:`string`,valueHint:`<str>`,description:{"en-US":`Learning rate as a string to preserve precision (default: "2e-5")`,"zh-CN":`以字符串形式指定学习率以保留精度(默认:"2e-5")`}}},Ty=[{"en-US":`Creating a job uploads any local datasets and consumes training quota.`,"zh-CN":`创建任务会上传所有本地数据集并消耗训练额度。`},{"en-US":`Use --dry-run to preview the request body without submitting.`,"zh-CN":`使用 --dry-run 预览请求体,不实际提交。`},{"en-US":"--datasets / --validations accept either file-ids (from `dataset upload`) or local paths. Local paths are validated and uploaded first, then their file-ids are submitted — a one-step upload-and-train.","zh-CN":"--datasets / --validations 可接受 file-id(来自 `dataset upload`)或本地路径。本地路径会先验证并上传,再提交对应的 file-id,实现一步上传并训练。"}],Ey=[...Ty,{"en-US":"Training-type values use the `<method>` / `<method>-lora` convention: sft (full) | sft-lora (LoRA) | dpo (full) | dpo-lora (LoRA) | cpt. These map to the server's training_type at the interface boundary, so the rest of the CLI never sees the raw server strings.","zh-CN":"训练类型遵循 `<method>` / `<method>-lora` 命名约定:sft(全量)| sft-lora(LoRA)| dpo(全量)| dpo-lora(LoRA)| cpt。这些值会在接口边界映射为服务端 training_type,因此 CLI 的其他部分不会接触服务端原始字符串。"},{"en-US":`Before submitting (non dry-run) the job, the model's training capability is checked via listFoundationModels (no console login required); an unsupported training type fails fast with the list the model actually supports.`,"zh-CN":`提交任务前(非 dry-run),会通过 listFoundationModels 检查模型训练能力(无需登录控制台);如果训练类型不受支持,会立即失败并列出该模型实际支持的训练类型。`},{"en-US":`n_epochs defaults to 3. Other hyper-parameters are platform defaults unless set.`,"zh-CN":`n_epochs 默认为 3。其他超参数未设置时使用平台默认值。`},{"en-US":`Learning rate is forwarded as a string to avoid JSON-number precision loss.`,"zh-CN":`学习率以字符串形式传递,避免 JSON 数字精度损失。`},{"en-US":`Pre-submit gate: if the training dataset's sample count is not greater than batch_size, the job is rejected before upload or quota consumption (the platform would otherwise fail ~10 min in, after data processing).`,"zh-CN":`提交前检查:如果训练数据集的样本数不大于 batch_size,会在上传或消耗额度前拒绝任务(否则平台会在数据处理约 10 分钟后才失败)。`}],Dy=[...Ty,{"en-US":`Audio TTS training runs sft-lora (efficient_sft) with fixed CosyVoice hyper-parameter defaults; there are no training-type or hyper-parameter knobs to set.`,"zh-CN":`音频 TTS 训练使用 sft-lora(efficient_sft)和固定的 CosyVoice 超参数默认值;没有可设置的训练类型或超参数选项。`}],Oy=[...Ty,{"en-US":`Image generation training runs sft-lora (efficient_sft) with fixed defaults; only --learning-rate is overridable. T2I vs I2I is declared with --generation-type (default t2i), which sets generation_type/max_pixels. For local data the type is auto-detected (records with input_img train I2I); pass --generation-type explicitly to train I2I from a file-id or in --dry-run.`,"zh-CN":`图片生成训练使用 sft-lora(efficient_sft)和固定默认值;仅 --learning-rate 可覆盖。通过 --generation-type(默认 t2i)声明 T2I 或 I2I,并设置 generation_type/max_pixels。本地数据会自动识别类型(包含 input_img 的记录训练 I2I);通过 file-id 训练 I2I 或使用 --dry-run 时,请显式传入 --generation-type。`}];async function ky(e,t){let{identity:r,settings:i}=t,a=t.flags,o=a.baseModel,c=a.datasets;if(e===`audio`){let e=c.split(`,`).map(e=>e.trim()).filter(Boolean);if(e.length>1)throw new n(`Audio (TTS) fine-tuning accepts exactly one training file, got ${e.length}.`,l.USAGE,`Merge your recordings into a single .zip (or pass one file-id).`)}let u=a.trainingType||s;if(!ht(u))throw new n(`--training-type "${u}" is not supported.`,l.USAGE,`Supported values: ${ee.join(`, `)} (default: ${s}).`);let d=it(u),f=c.split(`,`).map(e=>e.trim()).find(e=>_y(e)),p=e;if(e===`image`){let e=a.generationType;(e===`i2i`||!e&&f&&!i.dryRun&&await je(f)===`image-i2i`)&&(p=`image-i2i`)}e===`video`&&f&&!i.dryRun&&await je(f)===`video-kf2v`&&(p=`video-kf2v`);let m=await vy(i,r.binName,c,`datasets`,d,p,o,f?{path:f,modality:p}:void 0),h=m.fileIds,g=a.validations?await vy(i,r.binName,a.validations,`validations`,d,p,o):void 0,_=g?.fileIds,v=a.modelName,y=a.suffix,b=d.resolveHyperParameters(p,a);if(a.batchSize!==void 0&&b.batch_size!==void 0&&!i.quiet&&!d.shouldSkipGate(`batch_size`,p)){let e=a.batchSize;b.batch_size!==e&&process.stderr.write(`warning: --batch-size ${e} clamped to ${b.batch_size} (server range [8, 1024] for the common training types).\n`)}if(a.batchSize!==void 0&&!i.quiet&&d.shouldSkipGate(`batch_size`,p)){let e=a.batchSize;b.batch_size!==void 0&&b.batch_size!==e&&process.stderr.write(`warning: --batch-size ${e} ignored for ${p} training (model uses a fixed batch_size of ${b.batch_size}).\n`)}if(p===`text`&&b.batch_size===void 0&&!i.dryRun){let e=m.firstSize??0;if(e===0)try{e=(await Qe(t.client,h[0])).data?.size??0}catch{}e>0&&e<102400&&(b.batch_size=8)}if(!i.dryRun&&m.recordCount!==void 0&&!d.shouldSkipGate(`batch_size`,p)){let e=b.batch_size??16,t=Xt({recordCount:m.recordCount,batchSize:e});if(!t.ok&&t.issue)throw new n(t.issue.message,l.GENERAL,t.hint)}if(!i.dryRun&&!d.shouldSkipCapabilityCheck(p)){let e;try{e=await Le(i,o)}catch(e){i.quiet||process.stderr.write(`warning: model capability lookup failed (${e.message}); proceeding without local pre-flight.
|
|
2833
|
-
`)}if(e&&!Dt(e).includes(u)){let t=Dt(e);throw new n(`Model "${o}" does not support training type "${u}".`,l.USAGE,t.length?`This model supports: ${t.join(`, `)}.`:`This model reports no supported training types.`)}}i.dryRun||(await yy(t.client,i,m,`fine-tune`,`datasets`),g&&await yy(t.client,i,g,`fine-tune`,`validations`));let x={model:o,training_file_ids:h,training_type:d.serverTrainingType,hyper_parameters:b};if(_&&_.length>0&&(x.validation_file_ids=_),v&&(x.model_name=v),y&&(x.finetuned_output_suffix=y),i.dryRun){let e=[...m.localPaths.map(e=>({field:`datasets`,path:e})),...(g?.localPaths??[]).map(e=>({field:`validations`,path:e}))];O(e.length>0?{action:`finetune.create`,body:x,pending_uploads:e}:{action:`finetune.create`,body:x},`json`);return}let te=await xe(t.client,x),ne=te.output??te.data;i.quiet?ne?.job_id&&D(ne.job_id):O(te,`json`)}const Ay=S({description:{"en-US":`Create a text model fine-tune job (sft | sft-lora | dpo | dpo-lora | cpt)`,"zh-CN":`创建文本模型微调任务(sft | sft-lora | dpo | dpo-lora | cpt)`},auth:`apiKey`,usageArgs:`--base-model <model> --datasets <id|path,...> [--validations <id|path,...>] [--model-name <name>] [--suffix <text>] [--n-epochs <n>] [--batch-size <n>] [--learning-rate <str>] [--max-length <n>] [--training-type <sft|sft-lora|dpo|dpo-lora|cpt>]`,flags:xy,exampleArgs:[`--base-model qwen3-8b --datasets file-xxx`,`--base-model qwen3-8b --datasets ./train.jsonl`,`--base-model qwen3-8b --datasets ./train.jsonl --validations ./eval.jsonl`,`--base-model qwen3-8b --datasets file-aaa,./extra.jsonl`,`--base-model qwen3-8b --datasets ./train.jsonl --training-type sft`,`--base-model qwen3-8b --datasets file-xxx --learning-rate "1.6e-5" --n-epochs 4`,`--base-model qwen3-8b --datasets file-xxx --output json`,`--base-model qwen3-8b --datasets file-xxx --dry-run`],notes:Ey,run:e=>ky(`text`,e)}),jy=S({description:{"en-US":`Create an audio TTS model fine-tune job (sft-lora)`,"zh-CN":`创建音频 TTS 模型微调任务(sft-lora)`},auth:`apiKey`,usageArgs:`--base-model <model> --datasets <id|path> [--validations <id|path>] [--model-name <name>] [--suffix <text>]`,flags:Sy,exampleArgs:[`--base-model cosyvoice-v3-flash --datasets ./audio.zip`,`--base-model cosyvoice-v3-flash --datasets file-xxx`,`--base-model cosyvoice-v3-flash --datasets ./audio.zip --model-name my-tts`,`--base-model cosyvoice-v3-flash --datasets file-xxx --output json`,`--base-model cosyvoice-v3-flash --datasets ./audio.zip --dry-run`],notes:Dy,run:e=>ky(`audio`,e)}),My=S({description:{"en-US":`Create an image generation model fine-tune job (sft-lora)`,"zh-CN":`创建图片生成模型微调任务(sft-lora)`},auth:`apiKey`,usageArgs:`--base-model <model> --datasets <id|path> [--validations <id|path>] [--model-name <name>] [--suffix <text>] [--generation-type <t2i|i2i>] [--learning-rate <str>]`,flags:Cy,exampleArgs:[`--base-model wan2.7-image-pro --datasets ./images.zip`,`--base-model wan2.7-image-pro --datasets file-xxx`,`--base-model wan2.7-image-pro --datasets file-xxx --generation-type i2i`,`--base-model wan2.7-image-pro --datasets ./images.zip --model-name my-wan`,`--base-model wan2.7-image-pro --datasets file-xxx --output json`,`--base-model wan2.7-image-pro --datasets ./images.zip --dry-run`],notes:Oy,run:e=>ky(`image`,e)}),Ny=[...Ty,{"en-US":`Video generation training (Wan i2v/kf2v) runs efficient_sft with model-specific defaults: wan2.7 (batch_size=1, max_pixels=102400), wan2.5/2.2 (batch_size=4, max_pixels per model). Override with --batch-size/--n-epochs.`,"zh-CN":`视频生成训练(Wan i2v/kf2v)使用 efficient_sft 和模型专属默认值:wan2.7(batch_size=1、max_pixels=102400),wan2.5/2.2(batch_size=4,max_pixels 因模型而异)。可通过 --batch-size/--n-epochs 覆盖。`},{"en-US":`Datasets are .zip archives with data.jsonl + frame images + videos.`,"zh-CN":`数据集为包含 data.jsonl、帧图片和视频的 .zip 归档。`},{"en-US":`Recommended: ≥10 training samples, 20-100 for stable results.`,"zh-CN":`建议至少准备 10 个训练样本;20–100 个样本可获得更稳定的效果。`}],Py=S({description:{"en-US":`Create a video generation model fine-tune job (Wan i2v/kf2v, efficient_sft)`,"zh-CN":`创建视频生成模型微调任务(Wan i2v/kf2v,efficient_sft)`},auth:`apiKey`,usageArgs:`--base-model <model> --datasets <id|path> [--validations <id|path>] [--model-name <name>] [--suffix <text>] [--n-epochs <n>] [--batch-size <n>] [--learning-rate <str>]`,flags:wy,exampleArgs:[`--base-model wan2.7-i2v --datasets file-xxx`,`--base-model wan2.7-i2v --datasets ./i2v-data.zip`,`--base-model wan2.2-kf2v-flash --datasets file-xxx --n-epochs 100`,`--base-model wan2.7-i2v --datasets file-xxx --dry-run`],notes:Ny,run:e=>ky(`video`,e)});var Fy=S({description:{"en-US":`List fine-tune jobs`,"zh-CN":`列出微调任务`},auth:`apiKey`,usageArgs:`[--page <n>] [--page-size <n>] [--status <s>] [--base-model <model>]`,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 / SUCCEEDED / FAILED / CANCELED)`,"zh-CN":`按状态筛选(PENDING / RUNNING / SUCCEEDED / FAILED / CANCELED)`}},baseModel:{type:`string`,valueHint:`<model>`,description:{"en-US":`Filter by base model ID (server-side)`,"zh-CN":`按基础模型 ID 筛选(服务端筛选)`}}},exampleArgs:[``,`--status RUNNING`,`--base-model qwen3-8b`,`--page-size 20`],async run(e){let{settings:t,flags:n}=e,r=n.page,i=n.pageSize,a=n.status||void 0,o=n.baseModel||void 0;if(t.dryRun){O({action:`finetune.list`,page:r,page_size:i,status:a,model:o},`json`);return}let s=await wt(e.client,{pageNo:r,pageSize:i,status:a,model:o}),c=s.output??s.data,l=c?.jobs??[],u=c?.total,d=l.map(e=>({job_id:e.job_id??``,base_model:e.model??``,status:e.status??``,training_type:e.training_type??``,output_model:e.finetuned_output??``,created_at:e.create_time??e.gmt_create??``}));O({items:d,total:u,request_id:s.request_id},`json`)}});async function Iy(e,t){let n=w(e),r=await me({region:n.consoleRegion,site:n.consoleSite,switchAgent:n.consoleSwitchAgent},e.timeout,{api:p,data:{input:{pageNo:1,pageSize:10,group:!0,model:t,queryPrice:!0,querySampleCode:!1,queryGroupByModel:!0,queryQuota:!1,queryQpmInfo:!1,queryApplyStatus:!1,queryPermissions:!1,queryActivationStatus:!1}}}),i=Ln(r).list??[];for(let e of i){let n=e.items??[];for(let e of n)if(e.model===t)return(e.prices??[]).find(e=>e.type===`ft`)??null;if(e.model===t)return(e.prices??[]).find(e=>e.type===`ft`)??null}return null}async function Ly(e,t,n){try{let r=await Iy(e,t),i=Number(r?.price);if(!Number.isFinite(i)||i<=0)return null;let a=r?.priceUnit??`每百万tokens`,o=n/1e6*i;return{cost:Number(o.toFixed(4)),unitPrice:i,priceUnit:a}}catch{return null}}var Ry=S({description:{"en-US":`Get details of a single fine-tune job`,"zh-CN":`获取单个微调任务的详情`},auth:`apiKey`,usageArgs:`--job-id <id>`,flags:{jobId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Fine-tune job ID (required)`,"zh-CN":`微调任务 ID(必填)`},required:!0}},exampleArgs:[`--job-id ft-xxx`,`--job-id ft-xxx --output json`],async run(e){let{settings:t,flags:n}=e,r=n.jobId;if(t.dryRun){O({action:`finetune.get`,job_id:r},`json`);return}let i=await et(e.client,r),a=i.output??i.data;if(!a){O({job_id:r,error:`No data returned`},`json`);return}let o=a.hyper_parameters,s=[];o?.n_epochs!==void 0&&s.push(`n_epochs=${o.n_epochs}`),o?.batch_size!==void 0&&s.push(`batch_size=${o.batch_size}`),o?.learning_rate!==void 0&&s.push(`learning_rate=${o.learning_rate}`),o?.max_length!==void 0&&s.push(`max_length=${o.max_length}`);let c=typeof a.usage==`number`?a.usage:void 0,l={job_id:a.job_id??r,base_model:a.model??``,status:a.status??``,training_type:a.training_type??``,training_files:a.training_file_ids??[],validation_files:a.validation_file_ids??[],hyper_params:s.length?s.join(` · `):``,output_model:a.finetuned_output??``,model_name:a.model_name??``,created_at:a.create_time??a.gmt_create??``,updated_at:a.end_time??a.gmt_modified??``,usage_tokens:c??``,charge_type:typeof a.charge_type==`string`?a.charge_type:``};if(c!==void 0&&c>0&&a.model){let e=await Ly(t,a.model,c);e&&(l.training_cost=e.cost,l.cost_basis=`${e.unitPrice} 元/${e.priceUnit}`)}O({...l,request_id:i.request_id},`json`)}}),zy=S({description:{"en-US":`Cancel a running fine-tune job`,"zh-CN":`取消正在运行的微调任务`},auth:`apiKey`,usageArgs:`--job-id <id>`,flags:{jobId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Fine-tune job ID (required)`,"zh-CN":`微调任务 ID(必填)`},required:!0}},exampleArgs:[`--job-id ft-xxx`,`--job-id ft-xxx --dry-run`],notes:[{"en-US":`Only PENDING / RUNNING jobs can be cancelled. Completed / failed / already-cancelled jobs return a server-side error (passed through verbatim).`,"zh-CN":`只有 PENDING / RUNNING 状态的任务可以取消。已完成、失败或已取消的任务会返回服务端错误(原样透传)。`}],async run(e){let{settings:t,flags:n}=e,r=n.jobId;if(t.dryRun){O({action:`finetune.cancel`,job_id:r},`json`);return}let i=await he(e.client,r);t.quiet?D(r):O(i,`json`)}}),By=S({description:{"en-US":`Delete a fine-tune job record`,"zh-CN":`删除微调任务记录`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the specified fine-tune job record and cannot be undone.`,"zh-CN":`该操作会永久删除指定的微调任务记录,且无法撤销。`}},usageArgs:`--job-id <id>`,flags:{jobId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Fine-tune job ID (required)`,"zh-CN":`微调任务 ID(必填)`},required:!0}},exampleArgs:[`--job-id ft-xxx`,`--job-id ft-xxx --dry-run`,`--job-id ft-xxx --yes`],notes:[{"en-US":`Irreversible — the job record is permanently removed.`,"zh-CN":`该操作不可撤销——任务记录将被永久删除。`},{"en-US":"Cancel a RUNNING job first via `finetune cancel` — the platform refuses to delete jobs that are still in flight.","zh-CN":"请先通过 `finetune cancel` 取消 RUNNING 任务,平台拒绝删除仍在运行的任务。"}],async run(e){let{settings:t,flags:n}=e,r=n.jobId;if(t.dryRun){O({action:`finetune.delete`,job_id:r},`json`);return}let i=await Oe(e.client,r);t.quiet?D(r):O(i,`json`)}});function Vy(e){if(typeof e==`string`)return e;let t=e,n=t.timestamp??t.time??t.create_time??``,r=t.level??``,i=t.message??t.msg??t.log??``;return i||n||r?[n,r,i].filter(Boolean).join(` `):JSON.stringify(e)}function Hy(e,t){return Vy(e).toLowerCase().includes(t)}async function Uy(e,t,n){let r=[],i=1,a=0;for(let o=0;o<200;o++){let o=await tt(e,t,{pageNo:i,pageSize:n}),s=o.output??o.data,c=s?.logs??[];if(a=s?.total??a,c.length===0||(r.push(...c),a&&r.length>=a)||c.length<n)break;i++}return{entries:r,total:a}}var Wy=S({description:{"en-US":`Fetch training logs for a fine-tune job`,"zh-CN":`获取微调任务的训练日志`},auth:`apiKey`,usageArgs:`--job-id <id> [--page <n>] [--page-size <n>] [--search <keyword>] [--tail <n>]`,flags:{jobId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Fine-tune job ID (required)`,"zh-CN":`微调任务 ID(必填)`},required:!0},page:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Lines per page (default: server-defined)`,"zh-CN":`每页行数(默认:由服务端决定)`}},search:{type:`string`,valueHint:`<keyword>`,description:{"en-US":`Case-insensitive substring filter. When set, all log pages are fetched and filtered client-side (--page is ignored).`,"zh-CN":`不区分大小写的子字符串筛选。设置后会获取全部日志页并在客户端筛选(忽略 --page)。`}},tail:{type:`number`,valueHint:`<n>`,description:{"en-US":`Keep only the last N entries. When set, all log pages are fetched and the trailing N are kept (--page is ignored).`,"zh-CN":`仅保留最后 N 条记录。设置后会获取全部日志页并保留末尾 N 条(忽略 --page)。`}}},exampleArgs:[`--job-id ft-xxx`,`--job-id ft-xxx --page-size 100 --output json`,`--job-id ft-xxx --search checkpoint`,`--job-id ft-xxx --search error --output json`,`--job-id ft-xxx --tail 20`,`--job-id ft-xxx --search checkpoint --tail 5`],async run(e){let{settings:t,flags:n}=e,r=n.jobId,i=n.page,a=n.pageSize,o=n.search||void 0,s=n.tail;if(t.dryRun){O({action:`finetune.logs`,job_id:r,page:i,page_size:a,search:o,tail:s},`json`);return}if(o||s!==void 0){let{entries:t,total:n}=await Uy(e.client,r,a??100),i=t,c;if(o){let e=o.toLowerCase();i=t.filter(t=>Hy(t,e)),c=i.length}let l=s!==void 0&&s>=0?Math.min(s,i.length):void 0,u=l===void 0?i:i.slice(i.length-l);O({...c===void 0?{}:{matched:c},scanned:t.length,total:n||t.length,...o?{search:o}:{},...l===void 0?{}:{tail:l},logs:u},`json`);return}let c=await tt(e.client,r,{pageNo:i,pageSize:a});O(c,`json`)}}),Gy=S({description:{"en-US":`List checkpoints produced by a fine-tune job`,"zh-CN":`列出微调任务生成的 Checkpoint`},auth:`apiKey`,usageArgs:`--job-id <id>`,flags:{jobId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Fine-tune job ID (required)`,"zh-CN":`微调任务 ID(必填)`},required:!0}},exampleArgs:[`--job-id ft-xxx`,`--job-id ft-xxx --output json`],notes:[{"en-US":"`model_name` (shown for SUCCEEDED checkpoints) is the direct input for `deploy create --model-name`.","zh-CN":"SUCCEEDED Checkpoint 中显示的 `model_name` 可直接作为 `deploy create --model-name` 的输入。"},{"en-US":"Checkpoints expire ~15 days after creation; `expire_time` shows the deadline. Export or deploy before expiry.","zh-CN":"Checkpoint 创建后约 15 天过期,`expire_time` 显示截止时间。请在过期前导出或部署。"}],async run(e){let{settings:t,flags:n}=e,r=n.jobId;if(t.dryRun){O({action:`finetune.checkpoints`,job_id:r},`json`);return}let i=await bt(e.client,r),a=i.output??i.data,o=Array.isArray(a)?a:a?.checkpoints??[],s=Array.isArray(a)?a.length:a?.total??o.length,c=o.map(e=>({checkpoint:e.checkpoint??e.checkpoint_id??``,step:e.step===void 0?``:String(e.step),status:e.status??``,model_name:e.model_name??``,expire_time:e.expire_time??``}));O({items:c,total:s,request_id:i.request_id},`json`);let l=Date.now(),u=c.filter(e=>{if(!e.expire_time)return!1;let t=new Date(e.expire_time).getTime();if(Number.isNaN(t))return!1;let n=t-l;return n>0&&n<2592e5});u.length>0&&process.stderr.write(`\n[warning] ${u.length} checkpoint(s) will expire within 72 hours. Export or deploy before expiry to avoid losing the model artifact.
|
|
2834
|
-
`)}}),
|
|
2830
|
+
`);return}process.stdout.write(`Permissions ${c} (${i.join(`, `)}): ${a.join(`, `)}\n`)}var Oy=S({description:{"en-US":`Grant model permissions (inference / finetune / deploy)`,"zh-CN":`授予模型权限(推理 / 微调 / 部署)`},auth:`apiKey`,usageArgs:`--model <models> [--action <actions>] | --all`,flags:{model:{type:`string`,valueHint:`<models>`,description:{"en-US":`Model ID(s), comma-separated (max 20)`,"zh-CN":`模型 ID,多个以逗号分隔(最多 20 个)`}},action:{type:`string`,valueHint:`<actions>`,description:{"en-US":`Permission action(s), comma-separated: inference, finetune, deploy (default: inference)`,"zh-CN":`权限操作,多个以逗号分隔:inference、finetune、deploy(默认:inference)`}},all:{type:`switch`,description:{"en-US":`One-key grant inference for all models in the workspace (including future ones)`,"zh-CN":`一键授予 Workspace 中所有模型的推理权限(包括未来新增模型)`}}},exampleArgs:[`--model qwen-plus`,`--model qwen-plus,qwen3-max --action inference,finetune`,`--all`,`--model qwen-plus --dry-run --output json`],notes:[{"en-US":`Grants apply to the business workspace your API key belongs to.`,"zh-CN":`授权将应用于 API Key 所属的业务 Workspace。`},{"en-US":`--all maps to the server one-key switch (access_all_entities: OPEN) and only covers inference.`,"zh-CN":`--all 对应服务端一键授权开关(access_all_entities: OPEN),仅涵盖推理权限。`},{"en-US":`Actions you omit keep their current grants (server-side tri-state patch).`,"zh-CN":`未指定的操作将保留当前授权状态(服务端三态增量更新)。`}],validate:e=>Ey(e),async run(e){await Dy(e,e.flags,!0)}}),ky=S({description:{"en-US":`Revoke model permissions (inference / finetune / deploy)`,"zh-CN":`撤销模型权限(推理 / 微调 / 部署)`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This revokes model permissions and may interrupt inference, fine-tuning, or deployment workloads. With --all, it also clears all historical inference grants.`,"zh-CN":`该操作会撤销模型权限,可能导致推理、精调或部署任务中断;使用 --all 时会清除全部历史推理授权。`}},usageArgs:`--model <models> [--action <actions>] | --all [flags]`,flags:{model:{type:`string`,valueHint:`<models>`,description:{"en-US":`Model ID(s), comma-separated (max 20)`,"zh-CN":`模型 ID,多个以逗号分隔(最多 20 个)`}},action:{type:`string`,valueHint:`<actions>`,description:{"en-US":`Permission action(s), comma-separated: inference, finetune, deploy (default: inference)`,"zh-CN":`权限操作,多个以逗号分隔:inference、finetune、deploy(默认:inference)`}},all:{type:`switch`,description:{"en-US":`Close one-key authorization and clear ALL historical inference grants`,"zh-CN":`关闭一键授权并清除所有历史推理授权`}}},exampleArgs:[`--model qwen-plus --yes`,`--model qwen-plus,qwen3-max --action inference,finetune --yes`,`--all --yes`,`--model qwen-plus --dry-run --output json`],notes:[{"en-US":`Grants apply to the business workspace your API key belongs to.`,"zh-CN":`授权将应用于 API Key 所属的业务 Workspace。`},{"en-US":`All revoke operations require --yes; use --dry-run to preview the request without confirmation.`,"zh-CN":`所有撤权操作均需使用 --yes;可通过 --dry-run 免确认预览请求。`},{"en-US":`--all maps to the server one-key switch (access_all_entities: CLOSE): it clears every historical inference grant and cannot be undone, so it requires --yes.`,"zh-CN":`--all 对应服务端一键授权开关(access_all_entities: CLOSE):它会清除所有历史推理授权且无法撤销,因此必须同时传入 --yes。`},{"en-US":`Actions you omit keep their current grants (server-side tri-state patch).`,"zh-CN":`未指定的操作将保留当前授权状态(服务端三态增量更新)。`}],validate:e=>Ey(e),async run(e){await Dy(e,e.flags,!1)}}),Ay=S({description:{"en-US":`Upload a dataset file (.jsonl or .zip) to Bailian`,"zh-CN":`将数据集文件(.jsonl 或 .zip)上传到百炼`},auth:`apiKey`,usageArgs:`--file <path> [--purpose <name>] [--schema <chatml|dpo|cpt|tts|image|video>] [--no-validate] [--full-validate]`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Local dataset file (.jsonl or .zip; ≤200MB SFT/DPO, ≤300MB CPT, ≤2GB media zip)`,"zh-CN":`本地数据集文件(.jsonl 或 .zip;SFT/DPO 不超过 200MB,CPT 不超过 300MB,媒体 ZIP 不超过 2GB)`},required:!0},purpose:{type:`string`,valueHint:`<name>`,description:{"en-US":`Dataset purpose tag (default: "fine-tune"; e.g. "evaluation")`,"zh-CN":`数据集用途标签(默认:"fine-tune";例如 "evaluation")`}},schema:{type:`string`,valueHint:`<s>`,description:{"en-US":`Record schema: "chatml" (SFT), "dpo" (chosen/rejected), "cpt" (raw text), "tts" (audio), "image" (image generation), or "video" (video generation). Default auto-detects per record.`,"zh-CN":`记录 Schema:"chatml"(SFT)、"dpo"(chosen/rejected)、"cpt"(原始文本)、"tts"(音频)、"image"(图片生成)或 "video"(视频生成)。默认逐条自动识别。`}},noValidate:{type:`switch`,description:{"en-US":`Skip the local JSONL pre-flight check (not recommended)`,"zh-CN":`跳过本地 JSONL 预检查(不推荐)`}},fullValidate:{type:`switch`,description:{"en-US":`JSON.parse every line instead of sampling (slower)`,"zh-CN":`使用 JSON.parse 检查每一行,而不是抽样检查(速度较慢)`}}},exampleArgs:[`--file train.jsonl`,`--file dpo.jsonl --schema dpo`,`--file cpt.jsonl --schema cpt`,`--file audio.zip --schema tts`,`--file eval.jsonl --purpose evaluation`,`--file train.jsonl --full-validate`,`--file train.jsonl --no-validate`],notes:[{"en-US":`Supports .jsonl (text) and .zip (audio/image/video archives with a data.jsonl manifest). Six record schemas are recognized: chatml = {messages:[...]} (SFT); dpo = {messages:[...], chosen, rejected}; cpt = {text:"..."} (continual pre-training, raw text); tts = {wav_fn:"train/xxx.wav", text:"..."} (audio fine-tuning); image = {img_path:"..."} (image generation); video = {first_frame_path:...} (video generation).`,"zh-CN":`支持 .jsonl(文本)和 .zip(包含 data.jsonl 清单的音频、图片或视频归档)。可识别六种记录 Schema:chatml = {messages:[...]}(SFT);dpo = {messages:[...], chosen, rejected};cpt = {text:"..."}(持续预训练,原始文本);tts = {wav_fn:"train/xxx.wav", text:"..."}(音频微调);image = {img_path:"..."}(图片生成);video = {first_frame_path:...}(视频生成)。`},{"en-US":`With no --schema, a record carrying wav_fn is validated as TTS, img_path as image, chosen/rejected as DPO, text (no messages) as CPT, otherwise ChatML.`,"zh-CN":`未指定 --schema 时,包含 wav_fn 的记录按 TTS 验证,包含 img_path 的按 image 验证,包含 chosen/rejected 的按 DPO 验证,仅含 text(无 messages)的按 CPT 验证,其他记录按 ChatML 验证。`},{"en-US":`Upload cap: 200MB SFT/DPO text, 300MB CPT, 2GB media zip. Upload uses the OpenAI-compatible /compatible-mode/v1/files endpoint so the purpose tag is persisted (the DashScope-native /api/v1/files drops it).`,"zh-CN":`上传上限:SFT/DPO 文本 200MB、CPT 300MB、媒体 ZIP 2GB。上传使用 OpenAI 兼容的 /compatible-mode/v1/files Endpoint,以便保留 purpose 标签;DashScope 原生 /api/v1/files 会丢弃该标签。`}],async run(e){let{identity:t,settings:r,flags:i}=e,a=i.file,o=i.purpose||`fine-tune`,s=Zt(i.schema),c=s===`image`||s===`video`?f:s===`cpt`?u:d;if(!i.noValidate){let e=await $n(a,{fullValidate:i.fullValidate,schema:s,maxBytes:c});if(!e.valid){let r=[`Dataset validation failed for ${a}`,...e.errors.slice(0,10).map(Ze)];throw e.errors.length>10&&r.push(` … and ${e.errors.length-10} more error(s).`),r.push(``,`Hint: re-run \`${t.binName} dataset validate --file <path>\` for the full report,`,` or pass --no-validate to skip this check at your own risk.`),new n(r.join(`
|
|
2831
|
+
`),l.GENERAL)}if(e.warnings.length>0&&!r.quiet){process.stderr.write(`Dataset validation passed with ${e.warnings.length} warning(s):\n`);for(let t of e.warnings.slice(0,5))process.stderr.write(`${Ze(t)}\n`);e.warnings.length>5&&process.stderr.write(` … and ${e.warnings.length-5} more.\n`)}}if(r.dryRun){O({action:`dataset.upload`,file:a,purpose:o,max_bytes:c,validate:!i.noValidate,schema:s??`auto`},`json`);return}let{request_id:p,...m}=await Zn(e.client,{filePath:a,purpose:o});r.quiet?D(m.file_id):O({...m,request_id:p},`json`)}}),jy=S({description:{"en-US":`List uploaded dataset files`,"zh-CN":`列出已上传的数据集文件`},auth:`apiKey`,usageArgs:`[--page <n>] [--page-size <n>] [--purpose <name>]`,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)`}},purpose:{type:`string`,valueHint:`<name>`,description:{"en-US":`Filter by purpose (e.g. "fine-tune", "evaluation"). Omit to list all.`,"zh-CN":`按用途筛选(例如 "fine-tune"、"evaluation")。省略时列出全部。`}}},exampleArgs:[``,`--purpose fine-tune`,`--purpose evaluation --page-size 20`,`--output json`],async run(e){let{settings:t,flags:n}=e;if(t.dryRun){O({action:`dataset.list`,page:n.page,page_size:n.pageSize,purpose:n.purpose},`json`);return}let r=await kt(e.client,{pageNo:n.page,pageSize:n.pageSize,purpose:n.purpose||void 0}),i=r.data?.files??[],a=r.data?.total,o=i.map(e=>({file_id:e.file_id??``,name:e.name??``,size:e.size===void 0?`?`:`${(e.size/1024).toFixed(1)} KB`,purpose:e.purpose??``}));if(t.quiet)for(let e of o)D(e.file_id);else O({items:o,total:a,request_id:r.request_id},`json`)}}),My=S({description:{"en-US":`Get details of a single dataset file`,"zh-CN":`获取单个数据集文件的详情`},auth:`apiKey`,usageArgs:`--file-id <id>`,flags:{fileId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Dataset file ID (required)`,"zh-CN":`数据集文件 ID(必填)`},required:!0}},exampleArgs:[`--file-id file-xxx`,`--file-id file-xxx --output json`],async run(e){let{settings:t,flags:n}=e,r=n.fileId;if(t.dryRun){O({action:`dataset.get`,file_id:r},`json`);return}let i=await it(e.client,r),a=i.data;if(!a){D(`No data returned for ${r}`);return}let o=a.size===void 0?`?`:`${(a.size/1024).toFixed(1)} KB`,s={file_id:a.file_id??r,name:a.name??``,size:o,md5:a.md5??``,purpose:a.purpose??``,created_at:a.gmt_create??``,description:a.description??``};t.quiet?D(s.file_id):O({...s,request_id:i.request_id},`json`)}}),Ny=S({description:{"en-US":`Delete a dataset file by ID`,"zh-CN":`通过 ID 删除数据集文件`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the specified dataset file and cannot be undone.`,"zh-CN":`该操作会永久删除指定的数据集文件,且无法撤销。`}},usageArgs:`--file-id <id>`,flags:{fileId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Dataset file ID (required)`,"zh-CN":`数据集文件 ID(必填)`},required:!0}},exampleArgs:[`--file-id file-id-xxx`,`--file-id file-id-xxx --dry-run`,`--file-id file-id-xxx --yes`],async run(e){let{settings:t,flags:n}=e,r=n.fileId;if(t.dryRun){O({action:`dataset.delete`,file_id:r},`json`);return}let i=await Ae(e.client,r);t.quiet?D(r):O(i,`json`)}}),Py=S({description:{"en-US":`Locally validate a dataset file (.jsonl or .zip) without uploading`,"zh-CN":`在本地验证数据集文件(.jsonl 或 .zip),不执行上传`},auth:`none`,usageArgs:`--file <path> [--full-validate] [--schema <chatml|dpo|cpt|tts|image|video>]`,flags:{file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Local dataset file (.jsonl or .zip)`,"zh-CN":`本地数据集文件(.jsonl 或 .zip)`},required:!0},fullValidate:{type:`switch`,description:{"en-US":`JSON.parse every line instead of sampling (slower)`,"zh-CN":`使用 JSON.parse 检查每一行,而不是抽样检查(速度较慢)`}},schema:{type:`string`,valueHint:`<s>`,description:{"en-US":`Record schema: "chatml" (SFT), "dpo" (chosen/rejected), "cpt" (raw text), "tts" (audio), "image" (image generation), or "video" (video generation). Default auto-detects per record.`,"zh-CN":`记录 Schema:"chatml"(SFT)、"dpo"(chosen/rejected)、"cpt"(原始文本)、"tts"(音频)、"image"(图片生成)或 "video"(视频生成)。默认逐条自动识别。`}}},exampleArgs:[`--file train.jsonl`,`--file dpo.jsonl --schema dpo`,`--file cpt.jsonl --schema cpt`,`--file audio.zip --schema tts`,`--file wan-i2v-training-dataset.zip --schema video`,`--file eval.jsonl --full-validate`,`--file train.jsonl --output json`],notes:[{"en-US":`Default scan: every line gets a structural check, then ~160 lines (front 50, evenly spaced 100, last 10) are JSON.parsed against the active schema.`,"zh-CN":`默认扫描:先对每一行进行结构检查,再抽取约 160 行(前 50 行、均匀抽取 100 行、最后 10 行),使用 JSON.parse 按当前 Schema 验证。`},{"en-US":`Schemas: chatml = {messages:[...]} (SFT); dpo = {messages:[...], chosen, rejected}; cpt = {text:"..."} (continual pre-training, raw text); tts = {wav_fn:"train/xxx.wav", text:"..."} (audio fine-tuning); image = {img_path:"..."} (image generation); video = {first_frame_path:"...", video_path:"..."} (video generation, i2v first-frame or kf2v first+last-frame with last_frame_path).`,"zh-CN":`Schema:chatml = {messages:[...]}(SFT);dpo = {messages:[...], chosen, rejected};cpt = {text:"..."}(持续预训练,原始文本);tts = {wav_fn:"train/xxx.wav", text:"..."}(音频微调);image = {img_path:"..."}(图片生成);video = {first_frame_path:"...", video_path:"..."}(视频生成,支持 i2v 首帧或通过 last_frame_path 指定 kf2v 首尾帧)。`},{"en-US":`With no --schema, a record carrying wav_fn is validated as TTS, img_path as image, first_frame_path/video_path as video, chosen/rejected as DPO, text (no messages) as CPT, otherwise ChatML. Pass --schema to require a specific shape on every record.`,"zh-CN":`未指定 --schema 时,包含 wav_fn 的记录按 TTS 验证,包含 img_path 的按 image 验证,包含 first_frame_path/video_path 的按 video 验证,包含 chosen/rejected 的按 DPO 验证,仅含 text(无 messages)的按 CPT 验证,其他记录按 ChatML 验证。使用 --schema 要求每条记录符合指定结构。`},{"en-US":`ZIP archives (.zip) are validated structurally (data.jsonl present, media references resolve) in addition to per-record content checks. Use --full-validate to JSON.parse every line.`,"zh-CN":`ZIP 归档(.zip)除逐条检查记录内容外,还会执行结构验证(存在 data.jsonl、媒体引用可解析)。使用 --full-validate 对每一行执行 JSON.parse。`}],async run(e){let{settings:t,flags:r}=e,i=r.file,a=Zt(r.schema);if(t.dryRun){O({action:`dataset.validate`,file:i,full:r.fullValidate,schema:a??`auto`},`json`);return}let o=await $n(i,{fullValidate:r.fullValidate,schema:a});if(t.quiet?D(o.valid?`ok`:`fail`):O(o,`json`),!o.valid)throw new n(`Dataset validation failed: ${o.errors.length} error(s).`,l.GENERAL)}});function Fy(e){return Kr(e)&&Xr(e).isFile()}async function Iy(e,t,r,i,a,o,s,c){let u=r.split(`,`).map(e=>e.trim()).filter(Boolean);if(u.length===0)throw new n(`--${i} must contain at least one entry.`,l.USAGE);let d=[],f=[],p,m,h=!0;for(let r of u){if(!Fy(r)){d.push(r),h=!1;continue}if(d.push(r),f.push(r),e.dryRun)continue;let i=c&&c.path===r?c.modality:o,u=await a.validate(r,i,{model:s});if(!u.valid){let e=[`Dataset validation failed for ${r}`,...u.errors.slice(0,10).map(Ze)];throw u.errors.length>10&&e.push(` … and ${u.errors.length-10} more error(s).`),e.push(``,`Hint: re-run \`${t} dataset validate --file <path>\` for the full report,`,` or upload manually with \`${t} dataset upload --no-validate\` and`,` pass the resulting file-id here.`),new n(e.join(`
|
|
2832
|
+
`),l.GENERAL)}if(u.warnings.length>0&&!e.quiet){process.stderr.write(`Dataset validation passed with ${u.warnings.length} warning(s) for ${r}:\n`);for(let e of u.warnings.slice(0,5))process.stderr.write(`${Ze(e)}\n`);u.warnings.length>5&&process.stderr.write(` … and ${u.warnings.length-5} more.\n`)}let g=u.stats.totalRecords;typeof g==`number`&&(m=(m??0)+g),p===void 0&&(p=Xr(r).size)}return{fileIds:d,localPaths:f,firstSize:p,recordCount:h?m:void 0}}async function Ly(e,t,r,i,a){let o=[];for(let[s,c]of r.fileIds.entries()){if(!Fy(c))continue;let u=await Zn(e,{filePath:c,purpose:i});if(!u.file_id)throw new n(`Upload of ${c} succeeded but no file_id was returned.`,l.GENERAL);o.push(u),r.fileIds[s]=u.file_id,t.quiet||process.stderr.write(`Uploaded ${Qr(c)} → ${u.file_id} (auto from --${a})\n`)}return o}const Ry={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|paths>`,description:{"en-US":`Comma-separated dataset file IDs or local paths (.jsonl for text, .zip for audio/image/video). Local paths are uploaded (validated) first, then their file-ids are used.`,"zh-CN":`数据集文件 ID 或本地路径,以逗号分隔(文本使用 .jsonl,音频、图片和视频使用 .zip)。本地路径会先验证并上传,再使用对应的 file-id。`},required:!0},validations:{type:`string`,valueHint:`<ids|paths>`,description:{"en-US":`Comma-separated validation dataset file IDs or local paths (auto-uploaded like --datasets).`,"zh-CN":`验证数据集文件 ID 或本地路径,以逗号分隔(与 --datasets 一样自动上传)。`}},modelName:{type:`string`,valueHint:`<name>`,description:{"en-US":`Output model name (after training)`,"zh-CN":`训练完成后的输出模型名称`}},suffix:{type:`string`,valueHint:`<text>`,description:{"en-US":`Output suffix appended by the platform (finetuned_output_suffix)`,"zh-CN":`平台追加的输出后缀(finetuned_output_suffix)`}}},zy={...Ry,jobName:{type:`string`,valueHint:`<value>`,description:{"en-US":`Training job display name (job_name)`,"zh-CN":`训练任务显示名称(job_name)`}},priority:{type:`string`,valueHint:`<value>`,description:{"en-US":`Requested scheduling priority; verify the service response`,"zh-CN":`请求的调度优先级;请核对服务端回执`},choices:[`L0`,`L1`,`L2`,`L3`]},evalSteps:{type:`number`,valueHint:`<value>`,description:{"en-US":`Validation interval in training steps`,"zh-CN":`训练验证间隔步数`}},loraAlpha:{type:`number`,valueHint:`<value>`,description:{"en-US":`LoRA scaling coefficient`,"zh-CN":`LoRA 缩放系数`}},loraDropout:{type:`number`,valueHint:`<value>`,description:{"en-US":`LoRA dropout probability`,"zh-CN":`LoRA 丢弃率`}},loraRank:{type:`number`,valueHint:`<value>`,description:{"en-US":`LoRA matrix rank`,"zh-CN":`LoRA 矩阵秩`}},lrSchedulerType:{type:`string`,valueHint:`<value>`,description:{"en-US":`Learning rate scheduler supported by the selected model`,"zh-CN":`所选模型支持的学习率调度策略`}},saveStrategy:{type:`string`,valueHint:`<value>`,description:{"en-US":`Checkpoint saving strategy`,"zh-CN":`Checkpoint 保存策略`},choices:[`epoch`,`steps`]},saveTotalLimit:{type:`number`,valueHint:`<value>`,description:{"en-US":`Maximum number of saved checkpoints`,"zh-CN":`最多保存的 Checkpoint 数量`}},saveSteps:{type:`number`,valueHint:`<value>`,description:{"en-US":`Checkpoint saving interval for strategy=steps`,"zh-CN":`按 steps 保存时的间隔`}},split:{type:`number`,valueHint:`<value>`,description:{"en-US":`Training fraction when no validation dataset is supplied`,"zh-CN":`未指定验证集时训练集所占比例`}},maxSplitValDatasetSample:{type:`number`,valueHint:`<value>`,description:{"en-US":`Maximum automatically split validation samples`,"zh-CN":`自动切分验证集的样本数量上限`}},dataAugmentation:{type:`string`,valueHint:`<value>`,description:{"en-US":`Mix platform training data (true or false)`,"zh-CN":`是否混入平台训练数据(true 或 false)`},choices:[`true`,`false`]},trainingType:{type:`string`,valueHint:`<t>`,description:{"en-US":`Training type: ${ee.join(` | `)} (default: ${s}). Mapping to the server happens at the interface boundary (e.g. sft-lora -> efficient_sft, dpo -> dpo_full).`,"zh-CN":`训练类型:${ee.join(` | `)}(默认:${s})。在接口边界转换为服务端值(例如 sft-lora -> efficient_sft、dpo -> dpo_full)。`}},nEpochs:{type:`number`,valueHint:`<n>`,description:{"en-US":`Number of epochs (default: 3)`,"zh-CN":`训练轮数(默认:3)`}},batchSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Per-device batch size (clamped to [8, 1024]). Auto-set to 8 for small datasets (<100KB)`,"zh-CN":`单设备 Batch Size(限制在 [8, 1024])。小数据集(<100KB)自动设为 8`}},learningRate:{type:`string`,valueHint:`<str>`,description:{"en-US":`Learning rate as a string to preserve precision (e.g. "1.6e-5")`,"zh-CN":`以字符串形式指定学习率以保留精度(例如 "1.6e-5")`}},maxLength:{type:`number`,valueHint:`<n>`,description:{"en-US":`Max sequence length`,"zh-CN":`最大序列长度`}}},By={...Ry},Vy={...Ry,generationType:{type:`string`,choices:[`t2i`,`i2i`],valueHint:`<t2i|i2i>`,description:{"en-US":`Generation type: t2i (default) | i2i. Sets generation_type/max_pixels. Required to train I2I from a file-id or with --dry-run (local data auto-detects input_img).`,"zh-CN":`生成类型:t2i(默认)| i2i。用于设置 generation_type/max_pixels。通过 file-id 训练 I2I 或使用 --dry-run 时必填(本地数据会自动识别 input_img)。`}},learningRate:{type:`string`,valueHint:`<str>`,description:{"en-US":`Learning rate as a string to preserve precision (e.g. "3e-5")`,"zh-CN":`以字符串形式指定学习率以保留精度(例如 "3e-5")`}}},Hy={...Ry,nEpochs:{type:`number`,valueHint:`<n>`,description:{"en-US":`Training epochs (default: 50)`,"zh-CN":`训练轮数(默认:50)`}},batchSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Batch size (default: model-specific, 1 for wan2.7, 4 for wan2.5/2.2)`,"zh-CN":`Batch Size(默认值因模型而异:wan2.7 为 1,wan2.5/2.2 为 4)`}},learningRate:{type:`string`,valueHint:`<str>`,description:{"en-US":`Learning rate as a string to preserve precision (default: "2e-5")`,"zh-CN":`以字符串形式指定学习率以保留精度(默认:"2e-5")`}}},Uy=[{"en-US":`Creating a job uploads any local datasets and consumes training quota.`,"zh-CN":`创建任务会上传所有本地数据集并消耗训练额度。`},{"en-US":`Use --dry-run to preview the request body without submitting.`,"zh-CN":`使用 --dry-run 预览请求体,不实际提交。`},{"en-US":"--datasets / --validations accept either file-ids (from `dataset upload`) or local paths. Local paths are validated and uploaded first, then their file-ids are submitted — a one-step upload-and-train.","zh-CN":"--datasets / --validations 可接受 file-id(来自 `dataset upload`)或本地路径。本地路径会先验证并上传,再提交对应的 file-id,实现一步上传并训练。"}],Wy=[...Uy,{"en-US":"Training-type values use the `<method>` / `<method>-lora` convention: sft (full) | sft-lora (LoRA) | dpo (full) | dpo-lora (LoRA) | cpt. These map to the server's training_type at the interface boundary, so the rest of the CLI never sees the raw server strings.","zh-CN":"训练类型遵循 `<method>` / `<method>-lora` 命名约定:sft(全量)| sft-lora(LoRA)| dpo(全量)| dpo-lora(LoRA)| cpt。这些值会在接口边界映射为服务端 training_type,因此 CLI 的其他部分不会接触服务端原始字符串。"},{"en-US":`Before submitting (non dry-run) the job, the model's training capability is checked via listFoundationModels (no console login required); an unsupported training type fails fast with the list the model actually supports.`,"zh-CN":`提交任务前(非 dry-run),会通过 listFoundationModels 检查模型训练能力(无需登录控制台);如果训练类型不受支持,会立即失败并列出该模型实际支持的训练类型。`},{"en-US":`n_epochs defaults to 3. Other hyper-parameters are platform defaults unless set.`,"zh-CN":`n_epochs 默认为 3。其他超参数未设置时使用平台默认值。`},{"en-US":`Learning rate is forwarded as a string to avoid JSON-number precision loss.`,"zh-CN":`学习率以字符串形式传递,避免 JSON 数字精度损失。`},{"en-US":`Pre-submit gate: if the training dataset's sample count is not greater than batch_size, the job is rejected before upload or quota consumption (the platform would otherwise fail ~10 min in, after data processing).`,"zh-CN":`提交前检查:如果训练数据集的样本数不大于 batch_size,会在上传或消耗额度前拒绝任务(否则平台会在数据处理约 10 分钟后才失败)。`}],Gy=[...Uy,{"en-US":`Audio TTS training runs sft-lora (efficient_sft) with fixed CosyVoice hyper-parameter defaults; there are no training-type or hyper-parameter knobs to set.`,"zh-CN":`音频 TTS 训练使用 sft-lora(efficient_sft)和固定的 CosyVoice 超参数默认值;没有可设置的训练类型或超参数选项。`}],Ky=[...Uy,{"en-US":`Image generation training runs sft-lora (efficient_sft) with fixed defaults; only --learning-rate is overridable. T2I vs I2I is declared with --generation-type (default t2i), which sets generation_type/max_pixels. For local data the type is auto-detected (records with input_img train I2I); pass --generation-type explicitly to train I2I from a file-id or in --dry-run.`,"zh-CN":`图片生成训练使用 sft-lora(efficient_sft)和固定默认值;仅 --learning-rate 可覆盖。通过 --generation-type(默认 t2i)声明 T2I 或 I2I,并设置 generation_type/max_pixels。本地数据会自动识别类型(包含 input_img 的记录训练 I2I);通过 file-id 训练 I2I 或使用 --dry-run 时,请显式传入 --generation-type。`}];async function qy(e,t){let{identity:r,settings:i}=t,a=t.flags,o=a.baseModel,c=a.datasets;if(e===`audio`){let e=c.split(`,`).map(e=>e.trim()).filter(Boolean);if(e.length>1)throw new n(`Audio (TTS) fine-tuning accepts exactly one training file, got ${e.length}.`,l.USAGE,`Merge your recordings into a single .zip (or pass one file-id).`)}let u=a.trainingType||s;if(!St(u))throw new n(`--training-type "${u}" is not supported.`,l.USAGE,`Supported values: ${ee.join(`, `)} (default: ${s}).`);let d=ut(u),f=c.split(`,`).map(e=>e.trim()).find(e=>Fy(e)),p=e;if(e===`image`){let e=a.generationType;(e===`i2i`||!e&&f&&!i.dryRun&&await Fe(f)===`image-i2i`)&&(p=`image-i2i`)}e===`video`&&f&&!i.dryRun&&await Fe(f)===`video-kf2v`&&(p=`video-kf2v`);let m=await Iy(i,r.binName,c,`datasets`,d,p,o,f?{path:f,modality:p}:void 0),h=m.fileIds,g=a.validations?await Iy(i,r.binName,a.validations,`validations`,d,p,o):void 0,_=g?.fileIds,v=a.modelName,y=a.suffix,b=d.resolveHyperParameters(p,a);if(e===`text`){for(let[e,t]of Object.entries({evalSteps:`eval_steps`,loraAlpha:`lora_alpha`,loraDropout:`lora_dropout`,loraRank:`lora_rank`,lrSchedulerType:`lr_scheduler_type`,saveStrategy:`save_strategy`,saveTotalLimit:`save_total_limit`,saveSteps:`save_steps`,split:`split`,maxSplitValDatasetSample:`max_split_val_dataset_sample`})){let n=a[e];n!==void 0&&(b[t]=n)}for(let e of[`eval_steps`,`lora_alpha`,`lora_rank`,`save_total_limit`,`save_steps`,`max_split_val_dataset_sample`]){let t=b[e];if(t!==void 0&&(typeof t!=`number`||!Number.isInteger(t)||t<=0))throw new n(`${e} must be a positive integer. / 必须为正整数。`,l.USAGE)}if(b.lora_dropout!==void 0&&(typeof b.lora_dropout!=`number`||!Number.isFinite(b.lora_dropout)||b.lora_dropout<0||b.lora_dropout>=1))throw new n(`lora_dropout must be in [0, 1). / LoRA 丢弃率必须在 [0, 1) 内。`,l.USAGE);if(b.split!==void 0&&(typeof b.split!=`number`||!Number.isFinite(b.split)||b.split<=0||b.split>=1||a.validations))throw new n(`split must be in (0, 1) and cannot be combined with validations. / 切分比例须在 (0, 1) 内,且不能与独立验证集同时设置。`,l.USAGE);if(a.dataAugmentation!==void 0&&(b.data_augmentation=a.dataAugmentation===`true`),b.save_strategy===`steps`&&b.save_steps===void 0)throw new n(`save_strategy=steps requires --save-steps. / 按步保存时必须指定 --save-steps。`,l.USAGE)}if(a.batchSize!==void 0&&b.batch_size!==void 0&&!i.quiet&&!d.shouldSkipGate(`batch_size`,p)){let e=a.batchSize;b.batch_size!==e&&process.stderr.write(`warning: --batch-size ${e} clamped to ${b.batch_size} (server range [8, 1024] for the common training types).\n`)}if(a.batchSize!==void 0&&!i.quiet&&d.shouldSkipGate(`batch_size`,p)){let e=a.batchSize;b.batch_size!==void 0&&b.batch_size!==e&&process.stderr.write(`warning: --batch-size ${e} ignored for ${p} training (model uses a fixed batch_size of ${b.batch_size}).\n`)}if(p===`text`&&b.batch_size===void 0&&!i.dryRun){let e=m.firstSize??0;if(e===0)try{e=(await it(t.client,h[0])).data?.size??0}catch{}e>0&&e<102400&&(b.batch_size=8)}if(!i.dryRun&&m.recordCount!==void 0&&!d.shouldSkipGate(`batch_size`,p)){let e=b.batch_size??16,t=an({recordCount:m.recordCount,batchSize:e});if(!t.ok&&t.issue)throw new n(t.issue.message,l.GENERAL,t.hint)}if(!i.dryRun&&!d.shouldSkipCapabilityCheck(p)){let e;try{e=await Ve(i,o)}catch(e){i.quiet||process.stderr.write(`warning: model capability lookup failed (${e.message}); proceeding without local pre-flight.
|
|
2833
|
+
`)}if(e&&!Ft(e).includes(u)){let t=Ft(e);throw new n(`Model "${o}" does not support training type "${u}".`,l.USAGE,t.length?`This model supports: ${t.join(`, `)}.`:`This model reports no supported training types.`)}}i.dryRun||(await Ly(t.client,i,m,`fine-tune`,`datasets`),g&&await Ly(t.client,i,g,`fine-tune`,`validations`));let x={model:o,training_file_ids:h,training_type:d.serverTrainingType,hyper_parameters:b};if(_&&_.length>0&&(x.validation_file_ids=_),typeof a.jobName==`string`&&(x.job_name=a.jobName),typeof a.priority==`string`&&(x.priority=a.priority),v&&(x.model_name=v),y&&(x.finetuned_output_suffix=y),i.dryRun){let e=[...m.localPaths.map(e=>({field:`datasets`,path:e})),...(g?.localPaths??[]).map(e=>({field:`validations`,path:e}))];O(e.length>0?{action:`finetune.create`,body:x,pending_uploads:e}:{action:`finetune.create`,body:x},`json`);return}let te=await we(t.client,x),ne=te.output??te.data;i.quiet?ne?.job_id&&D(ne.job_id):O(te,`json`)}const Jy=S({description:{"en-US":`Create a text model fine-tune job (sft | sft-lora | dpo | dpo-lora | cpt)`,"zh-CN":`创建文本模型微调任务(sft | sft-lora | dpo | dpo-lora | cpt)`},auth:`apiKey`,usageArgs:`--base-model <model> --datasets <id|path,...> [--validations <id|path,...>] [--job-name <name>] [--priority <L0|L1|L2|L3>] [--model-name <name>] [--suffix <text>] [--n-epochs <n>] [--batch-size <n>] [--learning-rate <str>] [--max-length <n>] [--training-type <sft|sft-lora|dpo|dpo-lora|cpt>]`,flags:zy,exampleArgs:[`--base-model qwen3-8b --datasets file-xxx`,`--base-model qwen3-8b --datasets ./train.jsonl`,`--base-model qwen3-8b --datasets ./train.jsonl --validations ./eval.jsonl`,`--base-model qwen3-8b --datasets file-aaa,./extra.jsonl`,`--base-model qwen3-8b --datasets ./train.jsonl --training-type sft`,`--base-model qwen3-8b --datasets ./jev-train.jsonl --job-name jev-train-v1 --priority L0 --lora-rank 8 --lora-alpha 16 --lora-dropout 0.1 --lr-scheduler-type linear --eval-steps 50 --save-strategy epoch --save-total-limit 3 --split 0.9 --max-split-val-dataset-sample 1000 --data-augmentation false --dry-run`,`--base-model qwen3-8b --datasets file-xxx --learning-rate "1.6e-5" --n-epochs 4`,`--base-model qwen3-8b --datasets file-xxx --output json`,`--base-model qwen3-8b --datasets file-xxx --dry-run`],notes:Wy,run:e=>qy(`text`,e)}),Yy=S({description:{"en-US":`Create an audio TTS model fine-tune job (sft-lora)`,"zh-CN":`创建音频 TTS 模型微调任务(sft-lora)`},auth:`apiKey`,usageArgs:`--base-model <model> --datasets <id|path> [--validations <id|path>] [--model-name <name>] [--suffix <text>]`,flags:By,exampleArgs:[`--base-model cosyvoice-v3-flash --datasets ./audio.zip`,`--base-model cosyvoice-v3-flash --datasets file-xxx`,`--base-model cosyvoice-v3-flash --datasets ./audio.zip --model-name my-tts`,`--base-model cosyvoice-v3-flash --datasets file-xxx --output json`,`--base-model cosyvoice-v3-flash --datasets ./audio.zip --dry-run`],notes:Gy,run:e=>qy(`audio`,e)}),Xy=S({description:{"en-US":`Create an image generation model fine-tune job (sft-lora)`,"zh-CN":`创建图片生成模型微调任务(sft-lora)`},auth:`apiKey`,usageArgs:`--base-model <model> --datasets <id|path> [--validations <id|path>] [--model-name <name>] [--suffix <text>] [--generation-type <t2i|i2i>] [--learning-rate <str>]`,flags:Vy,exampleArgs:[`--base-model wan2.7-image-pro --datasets ./images.zip`,`--base-model wan2.7-image-pro --datasets file-xxx`,`--base-model wan2.7-image-pro --datasets file-xxx --generation-type i2i`,`--base-model wan2.7-image-pro --datasets ./images.zip --model-name my-wan`,`--base-model wan2.7-image-pro --datasets file-xxx --output json`,`--base-model wan2.7-image-pro --datasets ./images.zip --dry-run`],notes:Ky,run:e=>qy(`image`,e)}),Zy=[...Uy,{"en-US":`Video generation training (Wan i2v/kf2v) runs efficient_sft with model-specific defaults: wan2.7 (batch_size=1, max_pixels=102400), wan2.5/2.2 (batch_size=4, max_pixels per model). Override with --batch-size/--n-epochs.`,"zh-CN":`视频生成训练(Wan i2v/kf2v)使用 efficient_sft 和模型专属默认值:wan2.7(batch_size=1、max_pixels=102400),wan2.5/2.2(batch_size=4,max_pixels 因模型而异)。可通过 --batch-size/--n-epochs 覆盖。`},{"en-US":`Datasets are .zip archives with data.jsonl + frame images + videos.`,"zh-CN":`数据集为包含 data.jsonl、帧图片和视频的 .zip 归档。`},{"en-US":`Recommended: ≥10 training samples, 20-100 for stable results.`,"zh-CN":`建议至少准备 10 个训练样本;20–100 个样本可获得更稳定的效果。`}],Qy=S({description:{"en-US":`Create a video generation model fine-tune job (Wan i2v/kf2v, efficient_sft)`,"zh-CN":`创建视频生成模型微调任务(Wan i2v/kf2v,efficient_sft)`},auth:`apiKey`,usageArgs:`--base-model <model> --datasets <id|path> [--validations <id|path>] [--model-name <name>] [--suffix <text>] [--n-epochs <n>] [--batch-size <n>] [--learning-rate <str>]`,flags:Hy,exampleArgs:[`--base-model wan2.7-i2v --datasets file-xxx`,`--base-model wan2.7-i2v --datasets ./i2v-data.zip`,`--base-model wan2.2-kf2v-flash --datasets file-xxx --n-epochs 100`,`--base-model wan2.7-i2v --datasets file-xxx --dry-run`],notes:Zy,run:e=>qy(`video`,e)});var $y=S({description:{"en-US":`List fine-tune jobs`,"zh-CN":`列出微调任务`},auth:`apiKey`,usageArgs:`[--page <n>] [--page-size <n>] [--status <s>] [--base-model <model>]`,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 / SUCCEEDED / FAILED / CANCELED)`,"zh-CN":`按状态筛选(PENDING / RUNNING / SUCCEEDED / FAILED / CANCELED)`}},baseModel:{type:`string`,valueHint:`<model>`,description:{"en-US":`Filter by base model ID (server-side)`,"zh-CN":`按基础模型 ID 筛选(服务端筛选)`}}},exampleArgs:[``,`--status RUNNING`,`--base-model qwen3-8b`,`--page-size 20`],async run(e){let{settings:t,flags:n}=e,r=n.page,i=n.pageSize,a=n.status||void 0,o=n.baseModel||void 0;if(t.dryRun){O({action:`finetune.list`,page:r,page_size:i,status:a,model:o},`json`);return}let s=await Mt(e.client,{pageNo:r,pageSize:i,status:a,model:o}),c=s.output??s.data,l=c?.jobs??[],u=c?.total,d=l.map(e=>({job_id:e.job_id??``,base_model:e.model??``,status:e.status??``,training_type:e.training_type??``,output_model:e.finetuned_output??``,created_at:e.create_time??e.gmt_create??``}));O({items:d,total:u,request_id:s.request_id},`json`)}});async function eb(e,t){let n=w(e),r=await ge({region:n.consoleRegion,site:n.consoleSite,switchAgent:n.consoleSwitchAgent},e.timeout,{api:p,data:{input:{pageNo:1,pageSize:10,group:!0,model:t,queryPrice:!0,querySampleCode:!1,queryGroupByModel:!0,queryQuota:!1,queryQpmInfo:!1,queryApplyStatus:!1,queryPermissions:!1,queryActivationStatus:!1}}}),i=qn(r).list??[];for(let e of i){let n=e.items??[];for(let e of n)if(e.model===t)return(e.prices??[]).find(e=>e.type===`ft`)??null;if(e.model===t)return(e.prices??[]).find(e=>e.type===`ft`)??null}return null}async function tb(e,t,n){try{let r=await eb(e,t),i=Number(r?.price);if(!Number.isFinite(i)||i<=0)return null;let a=r?.priceUnit??`每百万tokens`,o=n/1e6*i;return{cost:Number(o.toFixed(4)),unitPrice:i,priceUnit:a}}catch{return null}}var nb=S({description:{"en-US":`Get details of a single fine-tune job`,"zh-CN":`获取单个微调任务的详情`},auth:`apiKey`,usageArgs:`--job-id <id>`,flags:{jobId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Fine-tune job ID (required)`,"zh-CN":`微调任务 ID(必填)`},required:!0}},exampleArgs:[`--job-id ft-xxx`,`--job-id ft-xxx --output json`],async run(e){let{settings:t,flags:n}=e,r=n.jobId;if(t.dryRun){O({action:`finetune.get`,job_id:r},`json`);return}let i=await ot(e.client,r),a=i.output??i.data;if(!a){O({job_id:r,error:`No data returned`},`json`);return}let o=a.hyper_parameters,s=Object.entries(o??{}).map(([e,t])=>`${e}=${typeof t==`string`?t:JSON.stringify(t)}`),c=typeof a.usage==`number`?a.usage:void 0,l={job_id:a.job_id??r,job_name:a.job_name??``,priority:a.priority??``,hyper_parameters:o??{},max_output_cnt:a.max_output_cnt??null,base_model:a.model??``,status:a.status??``,training_type:a.training_type??``,training_files:a.training_file_ids??[],validation_files:a.validation_file_ids??[],hyper_params:s.length?s.join(` · `):``,output_model:a.finetuned_output??``,model_name:a.model_name??``,created_at:a.create_time??a.gmt_create??``,updated_at:a.end_time??a.gmt_modified??``,usage_tokens:c??``,charge_type:typeof a.charge_type==`string`?a.charge_type:``};if(c!==void 0&&c>0&&a.model){let e=await tb(t,a.model,c);e&&(l.training_cost=e.cost,l.cost_basis=`${e.unitPrice} 元/${e.priceUnit}`)}O({...l,request_id:i.request_id},`json`)}}),rb=S({description:{"en-US":`Cancel a running fine-tune job`,"zh-CN":`取消正在运行的微调任务`},auth:`apiKey`,usageArgs:`--job-id <id>`,flags:{jobId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Fine-tune job ID (required)`,"zh-CN":`微调任务 ID(必填)`},required:!0}},exampleArgs:[`--job-id ft-xxx`,`--job-id ft-xxx --dry-run`],notes:[{"en-US":`Only PENDING / RUNNING jobs can be cancelled. Completed / failed / already-cancelled jobs return a server-side error (passed through verbatim).`,"zh-CN":`只有 PENDING / RUNNING 状态的任务可以取消。已完成、失败或已取消的任务会返回服务端错误(原样透传)。`}],async run(e){let{settings:t,flags:n}=e,r=n.jobId;if(t.dryRun){O({action:`finetune.cancel`,job_id:r},`json`);return}let i=await _e(e.client,r);t.quiet?D(r):O(i,`json`)}}),ib=S({description:{"en-US":`Delete a fine-tune job record`,"zh-CN":`删除微调任务记录`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`This permanently deletes the specified fine-tune job record and cannot be undone.`,"zh-CN":`该操作会永久删除指定的微调任务记录,且无法撤销。`}},usageArgs:`--job-id <id>`,flags:{jobId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Fine-tune job ID (required)`,"zh-CN":`微调任务 ID(必填)`},required:!0}},exampleArgs:[`--job-id ft-xxx`,`--job-id ft-xxx --dry-run`,`--job-id ft-xxx --yes`],notes:[{"en-US":`Irreversible — the job record is permanently removed.`,"zh-CN":`该操作不可撤销——任务记录将被永久删除。`},{"en-US":"Cancel a RUNNING job first via `finetune cancel` — the platform refuses to delete jobs that are still in flight.","zh-CN":"请先通过 `finetune cancel` 取消 RUNNING 任务,平台拒绝删除仍在运行的任务。"}],async run(e){let{settings:t,flags:n}=e,r=n.jobId;if(t.dryRun){O({action:`finetune.delete`,job_id:r},`json`);return}let i=await Me(e.client,r);t.quiet?D(r):O(i,`json`)}});function ab(e){if(typeof e==`string`)return e;let t=e,n=t.timestamp??t.time??t.create_time??``,r=t.level??``,i=t.message??t.msg??t.log??``;return i||n||r?[n,r,i].filter(Boolean).join(` `):JSON.stringify(e)}function ob(e,t){return ab(e).toLowerCase().includes(t)}async function sb(e,t,n){let r=[],i=1,a=0;for(let o=0;o<200;o++){let o=await st(e,t,{pageNo:i,pageSize:n}),s=o.output??o.data,c=s?.logs??[];if(a=s?.total??a,c.length===0||(r.push(...c),a&&r.length>=a)||c.length<n)break;i++}return{entries:r,total:a}}var cb=S({description:{"en-US":`Fetch training logs for a fine-tune job`,"zh-CN":`获取微调任务的训练日志`},auth:`apiKey`,usageArgs:`--job-id <id> [--page <n>] [--page-size <n>] [--search <keyword>] [--tail <n>]`,flags:{jobId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Fine-tune job ID (required)`,"zh-CN":`微调任务 ID(必填)`},required:!0},page:{type:`number`,valueHint:`<n>`,description:{"en-US":`Page number (default: 1)`,"zh-CN":`页码(默认:1)`}},pageSize:{type:`number`,valueHint:`<n>`,description:{"en-US":`Lines per page (default: server-defined)`,"zh-CN":`每页行数(默认:由服务端决定)`}},search:{type:`string`,valueHint:`<keyword>`,description:{"en-US":`Case-insensitive substring filter. When set, all log pages are fetched and filtered client-side (--page is ignored).`,"zh-CN":`不区分大小写的子字符串筛选。设置后会获取全部日志页并在客户端筛选(忽略 --page)。`}},tail:{type:`number`,valueHint:`<n>`,description:{"en-US":`Keep only the last N entries. When set, all log pages are fetched and the trailing N are kept (--page is ignored).`,"zh-CN":`仅保留最后 N 条记录。设置后会获取全部日志页并保留末尾 N 条(忽略 --page)。`}}},exampleArgs:[`--job-id ft-xxx`,`--job-id ft-xxx --page-size 100 --output json`,`--job-id ft-xxx --search checkpoint`,`--job-id ft-xxx --search error --output json`,`--job-id ft-xxx --tail 20`,`--job-id ft-xxx --search checkpoint --tail 5`],async run(e){let{settings:t,flags:n}=e,r=n.jobId,i=n.page,a=n.pageSize,o=n.search||void 0,s=n.tail;if(t.dryRun){O({action:`finetune.logs`,job_id:r,page:i,page_size:a,search:o,tail:s},`json`);return}if(o||s!==void 0){let{entries:t,total:n}=await sb(e.client,r,a??100),i=t,c;if(o){let e=o.toLowerCase();i=t.filter(t=>ob(t,e)),c=i.length}let l=s!==void 0&&s>=0?Math.min(s,i.length):void 0,u=l===void 0?i:i.slice(i.length-l);O({...c===void 0?{}:{matched:c},scanned:t.length,total:n||t.length,...o?{search:o}:{},...l===void 0?{}:{tail:l},logs:u},`json`);return}let c=await st(e.client,r,{pageNo:i,pageSize:a});O(c,`json`)}}),lb=S({description:{"en-US":`List checkpoints produced by a fine-tune job`,"zh-CN":`列出微调任务生成的 Checkpoint`},auth:`apiKey`,usageArgs:`--job-id <id>`,flags:{jobId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Fine-tune job ID (required)`,"zh-CN":`微调任务 ID(必填)`},required:!0}},exampleArgs:[`--job-id ft-xxx`,`--job-id ft-xxx --output json`],notes:[{"en-US":"`model_name` (shown for SUCCEEDED checkpoints) is the direct input for `deploy create --model-name`.","zh-CN":"SUCCEEDED Checkpoint 中显示的 `model_name` 可直接作为 `deploy create --model-name` 的输入。"},{"en-US":"Checkpoints expire ~15 days after creation; `expire_time` shows the deadline. Export or deploy before expiry.","zh-CN":"Checkpoint 创建后约 15 天过期,`expire_time` 显示截止时间。请在过期前导出或部署。"}],async run(e){let{settings:t,flags:n}=e,r=n.jobId;if(t.dryRun){O({action:`finetune.checkpoints`,job_id:r},`json`);return}let i=await Ot(e.client,r),a=i.output??i.data,o=Array.isArray(a)?a:a?.checkpoints??[],s=Array.isArray(a)?a.length:a?.total??o.length,c=o.map(e=>({checkpoint:e.checkpoint??e.checkpoint_id??``,step:e.step===void 0?``:String(e.step),status:e.status??``,model_name:e.model_name??``,expire_time:e.expire_time??``}));O({items:c,total:s,request_id:i.request_id},`json`);let l=Date.now(),u=c.filter(e=>{if(!e.expire_time)return!1;let t=new Date(e.expire_time).getTime();if(Number.isNaN(t))return!1;let n=t-l;return n>0&&n<2592e5});u.length>0&&process.stderr.write(`\n[warning] ${u.length} checkpoint(s) will expire within 72 hours. Export or deploy before expiry to avoid losing the model artifact.
|
|
2834
|
+
`)}}),ub=S({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){O({action:`finetune.export`,job_id:r,checkpoint:i,model_name:a},`json`);return}let o=await Re(e.client,r,i,a),s=(o.output??o.data)?.model_name??a;t.quiet?D(s):O(o,`json`)}});const db=/* @__PURE__ */ new Set([`SUCCEEDED`,`FAILED`,`CANCELED`]);function fb(){let e=/* @__PURE__ */ new Date,t=e=>String(e).padStart(2,`0`);return`${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}`}function pb(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 mb(e,t){return new Promise((n,r)=>{if(t.aborted){r(/* @__PURE__ */ Error(`aborted`));return}let i=()=>{clearTimeout(a),r(/* @__PURE__ */ Error(`aborted`))},a=setTimeout(()=>{t.removeEventListener(`abort`,i),n()},e);t.addEventListener(`abort`,i,{once:!0})})}var hb=S({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){O({action:`finetune.watch`,job_id:i,follow:a,interval:o,timeout:s},`json`);return}if(!a){let r=await ot(e.client,i),a=r.output??r.data,o=String(a?.status??``).toUpperCase(),s=db.has(o);if(t.quiet)D(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 tb(t,a.model,n);r&&(e.training_cost=r.cost,e.cost_basis=`${r.unitPrice} 元/${r.priceUnit}`)}O(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 ot(e.client,i,c.signal),d=u.output??u.data,f=String(d?.status??``).toUpperCase();if(!t.quiet&&f!==r&&(process.stderr.write(`${fb()} ${i} ${f||`UNKNOWN`}\n`),r=f),db.has(f)){let e=Date.now()-a;if(t.quiet)D(f||`UNKNOWN`);else{let e=typeof d?.usage==`number`?d.usage:void 0,n={...u};if(e&&e>0&&d?.model){let r=await tb(t,d.model,e);r&&(n.training_cost=r.cost,n.usage_tokens=e,n.cost_basis=`${r.unitPrice} 元/${r.priceUnit}`)}O(n,`json`)}if(f!==`SUCCEEDED`)throw new n(`Fine-tune job ${i} ended in status ${f} (elapsed ${pb(e)}).`,l.GENERAL);return}if(s!==void 0&&(Date.now()-a)/1e3>=s)throw new n(`Watching fine-tune job ${i} timed out after ${pb(Date.now()-a)} (last status: ${f||`UNKNOWN`}).`,l.TIMEOUT);await mb(o*1e3,c.signal)}}catch(e){if(c.signal.aborted){process.stderr.write(`
|
|
2835
2835
|
Interrupted.
|
|
2836
|
-
`);return}throw e}finally{process.off(`SIGINT`,u)}}});async function Qy(e){return await Ve(ie(e))}const $y={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: ${ee.join(` | `)}.`,"zh-CN":`列出支持该训练类型的模型:${ee.join(` | `)}。`}}};var eb=S({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:$y,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){O({action:`finetune.capability`,model:r,training_type:i},`json`);return}if(r){let e=await Le(t,r);if(!e){O({model:r,error:`No foundation model found matching "${r}".`},`json`);return}let n=Dt(e);if(t.quiet){for(let e of n)D(e);return}O({model:e.model??r,supported:n,supports:e.supports,trainingTypes:e.trainingTypes},`json`);return}if(!i||!ht(i))throw new x(`--training-type "${i}" is not supported. Valid: ${ee.join(`, `)}.`);let{method:a,variant:o}=Fn(i),s=(await Qy(t)).filter(e=>Lt(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)D(e.model);return}O({training_type:i,method:a,variant:o,count:s.length,models:s},`json`)}});const tb={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)`}}},nb=[`sft`,`dpo`,`cpt`];var rb=S({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:tb,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(!nb.includes(o))throw new n(`Unsupported training type "${o}". Supported: ${nb.join(`, `)}.`,l.USAGE);if(a.length===0)throw new n(`--datasets must contain at least one file ID.`,l.USAGE);if(t.dryRun){O({action:`finetune.price`,model:i,datasets:a,trainingType:o,nEpochs:s},`json`);return}let c=await We(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 Me(e.client,i,a.join(`,`),s):await Ne(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;O({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 ib={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 数(部分模型可选)`}}},ab=`--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>]`,ob=[{"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 sb(e,t){let n=t.plan||we(e),r=y[n];return r?r.validateFlags(t):`Unsupported plan "${n}". Supported plans: ${Object.keys(y).join(`, `)}.`}async function cb(e,t){let{identity:n,settings:r,flags:i}=t,a=i.modelName,o=i.displayName,s=i.plan||we(e),c={model_name:a,name:o,plan:s,...(await Jt(s).resolve({client:t.client,dryRun:r.dryRun,binName:n.binName,flags:i,model:a,name:o})).body};if(r.dryRun){O({action:`deploy.create`,body:c},`json`);return}let l=await be(t.client,c),u=l.output??l.data;r.quiet?D(u?.deployed_model??``):O(l,`json`)}const lb=S({description:{"en-US":`Create a text model deployment`,"zh-CN":`创建文本模型部署`},auth:`apiKey`,usageArgs:ab,flags:ib,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:ob,validate:e=>sb(`text`,e),run:e=>cb(`text`,e)}),ub=S({description:{"en-US":`Create an audio (TTS) model deployment`,"zh-CN":`创建音频(TTS)模型部署`},auth:`apiKey`,usageArgs:ab,flags:ib,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:ob,validate:e=>sb(`audio`,e),run:e=>cb(`audio`,e)}),db=S({description:{"en-US":`Create an image generation model deployment`,"zh-CN":`创建图片生成模型部署`},auth:`apiKey`,usageArgs:ab,flags:ib,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:ob,validate:e=>sb(`image`,e),run:e=>cb(`image`,e)});var fb=S({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){O({action:`deploy.list`,page:n.page,page_size:n.pageSize,status:r},`json`);return}let i=await Ct(e.client,{pageNo:n.page,pageSize:n.pageSize,status:r}),a=i.output??i.data,o=a?.deployments??[],s=a?.total,c=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??``}));O({items:c,total:s,request_id:i.request_id},`json`)}}),pb=S({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){O({action:`deploy.get`,deployed_model:r},`json`);return}let i=await $e(e.client,r),a=i.output??i.data;if(!a){O({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),O({...o,request_id:i.request_id},`json`)}}),mb=S({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){O({action:`deploy.models`,page:n.page,page_size:n.pageSize,version:r,model_source:i},`json`);return}let a=await St(e.client,{pageNo:n.page,pageSize:n.pageSize,version:r,modelSource:i}),o=a.output??a.data,s=o?.models??[],c=o?.total,l=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});O({items:l,total:c,request_id:a.request_id},`json`)}}),hb=S({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){O({action:`deploy.scale`,deployed_model:r,body:i},`json`);return}let a=await Cn(e.client,r,i);t.quiet?D(r):O(a,`json`)}}),gb=S({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){O({action:`deploy.update`,deployed_model:r,body:i},`json`);return}let a=await Rn(e.client,r,i);t.quiet?D(r):O(a,`json`)}}),_b=S({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){O({action:`deploy.delete`,deployed_model:i},`json`);return}if(!r.skipPrecheck)try{let t=await $e(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 De(e.client,i);t.quiet?D(i):O(a,`json`)}}),vb=S({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){O({action:`deploy.pause`,deployed_model:i},`json`);return}if(!r.skipPrecheck)try{let t=await Tt(e.client),r=Ge(t,i);if(r){let e=(r.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 jn(e.client,i);t.quiet?D(i):O({deployed_model:i,action:`pause`,...a},`json`)}}),yb=S({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){O({action:`deploy.resume`,deployed_model:i},`json`);return}if(!r.skipPrecheck)try{let t=await Tt(e.client),r=Ge(t,i);if(r){let e=(r.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 An(e.client,i);t.quiet?D(i):O({deployed_model:i,action:`resume`,...a},`json`)}});const bb={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)`}}},xb={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)`}}},Sb={cn:`modelstudio.cn-beijing.aliyuncs.com`,intl:`modelstudio.ap-southeast-1.aliyuncs.com`};function Cb(e){for(let[t,n]of Object.entries(g))if(e===n||e.startsWith(`${n}/`))return t;return`cn`}function wb(e){let t=Cb(e);return Sb[t]??Sb.cn}function Tb(e,t,r){let i=t.workspaceId||e.workspaceId;if(!i)throw new n(`Missing workspace ID.
|
|
2837
|
-
Set via: --workspace-id flag, env: BAILIAN_WORKSPACE_ID, or config: ${r} config set workspace_id <id>`,l.USAGE);return i}function Eb(e,t){t.callerUacAccountId&&(e.CallerUacAccountId=t.callerUacAccountId),t.namespaceId&&(e.NamespaceId=t.namespaceId)}function Db(e,t,n){let r=ce(n),i=wb(e);return{host:i,endpoint:`https://${i}${t}${r?`?${r}`:``}`,queryString:r,queryParams:n}}async function Ob(e){let{client:t,baseUrl:n,action:r,path:i,method:a,queryParams:o}=e,{host:s}=Db(n,i,o);return t.openApiQueryJson({host:s,path:i,action:r,version:`2026-02-10`,method:a,queryParams:o})}const kb=`/tokenplan/subscription/seat-detail`,Ab={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)`}},...bb,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=未分配`}}};var jb=S({description:{"en-US":`List Token Plan subscription seat details`,"zh-CN":`列出 Token Plan 订阅席位详情`},auth:`openapi`,usageArgs:`[flags]`,flags:Ab,exampleArgs:[``,`--page-size 20 --status NORMAL`,`--query-assigned true --seat-type standard`],async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=Mb(n);if(t.dryRun){let{endpoint:t,queryParams:n}=Db(e.client.baseUrl,kb,i);O({endpoint:t,query:n},r);return}let a=await Ob({client:e.client,baseUrl:e.client.baseUrl,action:`GetSubscriptionSeatDetails`,path:kb,method:`GET`,queryParams:i}),o=a.Data?.Items??[];t.quiet||r===`text`?Nb(o,a.Data?.Total,a.Data?.PageNo,a.Data?.PageSize):O(a,r)}});function Mb(e){let t={};if(e.pageNo!==void 0&&(t.PageNo=String(e.pageNo)),e.pageSize!==void 0&&(t.PageSize=String(e.pageSize)),Eb(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 Nb(e,t,n,r){if(e.length===0){D(`No seats found.`);return}let i=[k(`SeatId`,18),k(`Type`,10),k(`Status`,10),k(`Assigned`,12),k(`Account`,20)].join(` `);D(i),D(`-`.repeat(i.length));for(let t of e){let e=[k(t.SeatId??`-`,18),k(t.SpecType??`-`,10),k(t.Status??`-`,10),k(t.AssignedStatus??`-`,12),k(t.AccountName??t.AccountId??`-`,20)].join(` `);D(e)}t!==void 0&&(D(``),D(`Total: ${t}${n===void 0?``:` | Page: ${n}`}${r===void 0?``:` | PageSize: ${r}`}`))}const Pb=`/tokenplan/api-keys`,Fb={accountId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Target member account ID`,"zh-CN":`目标成员账号 ID`},required:!0},...xb,description:{type:`string`,valueHint:`<text>`,description:{"en-US":`API key description`,"zh-CN":`API Key 描述`}},...bb};var Ib=S({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:Fb,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=C(n.output),a=Tb(n,r,t.binName),o=Lb(r,{accountId:r.accountId,workspaceId:a});if(n.dryRun){let{endpoint:t,queryParams:n}=Db(e.client.baseUrl,Pb,o);O({endpoint:t,query:n},i);return}let s=await Ob({client:e.client,baseUrl:e.client.baseUrl,action:`CreateTokenPlanKey`,path:Pb,method:`POST`,queryParams:o});n.quiet||i===`text`?Rb(s):O(s,i)}});function Lb(e,t){let n={};return n.AccountId=t.accountId,n.WorkspaceId=t.workspaceId,e.description&&(n.Description=e.description),Eb(n,e),n}function Rb(e){let t=e.Data;if(!t){D(`API key created.`);return}D(`${k(`ApiKeyId`,14)} ${t.ApiKeyId??`-`}`),D(`${k(`MaskedApiKey`,14)} ${t.MaskedApiKey??`-`}`),t.Description&&D(`${k(`Description`,14)} ${t.Description}`),t.PlainApiKey&&(D(``),D(`PlainApiKey (shown once): ${t.PlainApiKey}`))}const zb=`/tokenplan/subscription/seat-assignments`,Bb={...xb,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(可重复)`}},...bb,locale:{type:`string`,valueHint:`<locale>`,description:{"en-US":`Language: zh-CN or en-US`,"zh-CN":`语言:zh-CN 或 en-US`}}};var Vb=S({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:Bb,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=C(n.output),a=Hb(r,Tb(n,r,t.binName));if(n.dryRun){let{endpoint:t,queryParams:n}=Db(e.client.baseUrl,zb,a);O({endpoint:t,query:n},i);return}let o=await Ob({client:e.client,baseUrl:e.client.baseUrl,action:`BatchAssignSeats`,path:zb,method:`POST`,queryParams:a});n.quiet||i===`text`?D(`Seats assigned successfully.`):O(o,i)}});function Hb(e,t){let n={};return n.WorkspaceId=t,e.seatType&&(n.SeatType=e.seatType),Eb(n,e),e.locale&&(n.Locale=e.locale),e.accountId&&e.accountId.length>0&&(n.AccountIds=e.accountId),n}const Ub=`/tokenplan/organization/member-additions`,Wb={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`}},...bb};var Gb=S({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:Wb,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=C(t.output),i=Kb(n);if(t.dryRun){let{endpoint:t,queryParams:n}=Db(e.client.baseUrl,Ub,i);O({endpoint:t,query:n},r);return}let a=await Ob({client:e.client,baseUrl:e.client.baseUrl,action:`AddOrganizationMember`,path:Ub,method:`POST`,queryParams:i});t.quiet||r===`text`?qb(a):O(a,r)}});function Kb(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),Eb(t,e),t}function qb(e){let t=e.Data;if(!t){D(`Member added.`);return}D(`${k(`AccountId`,14)} ${t.AccountId??`-`}`),D(`${k(`SeatAssigned`,14)} ${String(t.SeatAssigned??`-`)}`)}const Jb=`zeldaEasy.broadscope-bailian.token-plan.detail`,Yb=`zeldaEasy.bailian-commerce.tokenPlan.queryTokenPlanEquityInfo`;function Xb(e,t){let n=Ln(e)[t];return Array.isArray(n)?n:[]}function Zb(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=ah(i.totalQuota);s!==void 0&&(o.totalQuota=s);let c=ah(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=ah(i.instanceStartTime);l!==void 0&&(o.instanceStartTime=l);let u=ah(i.instanceEndTime);u!==void 0&&(o.instanceEndTime=u),n.push(o)}return n}function Qb(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 $b=S({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=C(t.output),i=n.type?{type:n.type}:{},a={queryTokenPlanEquityInfoRequest:{requestId:wr()}};if(t.dryRun){O({requests:[{api:Jb,data:i},{api:Yb,data:a}]},r);return}let[o,s]=await Promise.all([e.client.console(Jb,i),e.client.console(Yb,a)]),c=Zb(Xb(o,`items`),Xb(s,`tokenPlanEquityInfos`));if(r===`json`){O({generatedAt:Date.now(),items:c},r);return}if(c.length===0){process.stdout.write(`No harness with entitlement quota found.
|
|
2838
|
-
`);return}ch(`Token Plan Harness Quota`,c.map(Qb),Date.now())}});function ex(e){return`version: "1"
|
|
2836
|
+
`);return}throw e}finally{process.off(`SIGINT`,u)}}});async function gb(e){return await Ge(ie(e))}const _b={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: ${ee.join(` | `)}.`,"zh-CN":`列出支持该训练类型的模型:${ee.join(` | `)}。`}}};var vb=S({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:_b,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){O({action:`finetune.capability`,model:r,training_type:i},`json`);return}if(r){let e=await Ve(t,r);if(!e){O({model:r,error:`No foundation model found matching "${r}".`},`json`);return}let n=Ft(e);if(t.quiet){for(let e of n)D(e);return}O({model:e.model??r,supported:n,supports:e.supports,trainingTypes:e.trainingTypes},`json`);return}if(!i||!St(i))throw new x(`--training-type "${i}" is not supported. Valid: ${ee.join(`, `)}.`);let{method:a,variant:o}=Gn(i),s=(await gb(t)).filter(e=>Gt(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)D(e.model);return}O({training_type:i,method:a,variant:o,count:s.length,models:s},`json`)}});const yb={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)`}}},bb=[`sft`,`dpo`,`cpt`];var xb=S({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:yb,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(!bb.includes(o))throw new n(`Unsupported training type "${o}". Supported: ${bb.join(`, `)}.`,l.USAGE);if(a.length===0)throw new n(`--datasets must contain at least one file ID.`,l.USAGE);if(t.dryRun){O({action:`finetune.price`,model:i,datasets:a,trainingType:o,nEpochs:s},`json`);return}let c=await Je(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 Ie(e.client,i,a.join(`,`),s):await Le(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;O({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 Sb={deployedModel:{type:`string`,valueHint:`<code>`,required:!0,description:{"en-US":`Deployed model identifier (ModelCode)`,"zh-CN":`部署调用标识(ModelCode)`}}},Cb={instanceId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Capacity instance ID returned by the API`,"zh-CN":`接口返回的容量实例 ID`}}},wb={...Sb,operationId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Capacity operation ID returned by a write request`,"zh-CN":`写请求返回的容量操作 ID`}}};function Tb(e){for(let[t,n]of Object.entries(e))if([`deployedModel`,`instanceId`,`operationId`].includes(t)&&typeof n==`string`&&!n.trim())return`Identifiers must not be empty. / 标识不能为空。`}function Eb(e){if(e.page!==void 0&&(!Number.isSafeInteger(e.page)||e.page<1))return`--page must be a positive integer. / --page 必须是正整数。`;if(e.pageSize!==void 0&&(!Number.isSafeInteger(e.pageSize)||e.pageSize<1||e.pageSize>100))return`--page-size must be an integer from 1 to 100. / --page-size 必须是 1–100 的整数。`}function Db(e){return e===void 0?void 0:e.split(`,`).map(e=>e.trim())}const Ob=2147483;function kb(e,t){return new Promise((n,r)=>{t.throwIfAborted();let i=()=>{clearTimeout(a),r(t.reason)},a=setTimeout(()=>{t.removeEventListener(`abort`,i),n()},e);t.addEventListener(`abort`,i,{once:!0})})}async function Ab(e,t,r,i){let a=new AbortController,o,s=i.initialResponse,c=()=>new n(`Capacity operation wait timed out; query the same operation ID before retrying any write. / 等待容量操作超时;重试写操作前请查询同一操作 ID。`,l.TIMEOUT,void 0,{cause:{deployed_model:t,operation_id:r,last_response:o}}),u=()=>a.abort(i.signal?.reason);i.signal?.addEventListener(`abort`,u,{once:!0}),i.signal?.aborted&&u();let d=Date.now()+i.pollTimeout*1e3,f=setTimeout(()=>a.abort(c()),i.pollTimeout*1e3),p=()=>{Date.now()>=d&&!a.signal.aborted&&a.abort(c()),a.signal.throwIfAborted()},m=i.interval*1e3,h=Math.max(m,3e4);try{for(;;){p();let c=s??await nt(e,t,r,a.signal);s=void 0,o=c,p();let u=c.output??c.data;if(u?.operation_status===`FAILED`)throw new n(u.error_message??u.error_code??`Capacity operation failed. / 容量操作失败。`,l.GENERAL,void 0,{api:{httpStatus:200,apiCode:u.error_code,requestId:c.request_id},cause:u,rawResponse:JSON.stringify(c)});if(u?.operation_status===`SUCCEEDED`){let n=u.instance_id??i.fallbackInstanceId,r=n?await tt(e,t,n,a.signal):void 0;p();let o=await at(e,t,a.signal);return p(),{...c,instance:r,deployment:o}}if(u?.operation_status!==`PROCESSING`)throw new n(`Missing or unsupported operation_status; cannot determine completion. / 缺少或不支持的 operation_status,无法判断完成状态。`,l.GENERAL,void 0,{cause:c,rawResponse:JSON.stringify(c)});await kb(Math.min(m,Math.max(0,d-Date.now())),a.signal),m=Math.min(m*2,h)}}catch(e){throw a.signal.aborted?a.signal.reason:e}finally{clearTimeout(f),i.signal?.removeEventListener(`abort`,u)}}const jb={...wb,interval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Initial poll interval (1–3600 seconds, default: 2); doubles up to max(initial, 30)`,"zh-CN":`初始轮询间隔(1–3600 秒,默认:2);逐次翻倍至 max(初始值, 30)`}},pollTimeout:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Total wait budget including requests and refresh (default: 600 seconds)`,"zh-CN":`总等待时限,包含请求及刷新(默认:600 秒)`}}};var Mb=S({description:{"en-US":`Wait for a capacity operation and refresh confirmed capacity`,"zh-CN":`等待容量操作完成并刷新已确认容量`},auth:`apiKey`,flags:jb,usageArgs:`--deployed-model <code> --operation-id <id> [--interval <seconds>] [--poll-timeout <seconds>]`,exampleArgs:[`--deployed-model example-model-code --operation-id 100001`,`--deployed-model example-model-code --operation-id 100001 --interval 2 --poll-timeout 600`],notes:[{"en-US":`Read-only GET polling: PROCESSING continues, FAILED exits 1 with the server error, SUCCEEDED refreshes the instance (when an ID is returned) and deployment. Output preserves the operation envelope and adds instance/deployment response envelopes. Missing or unknown status fails rather than assuming success.`,"zh-CN":`只读 GET 轮询:PROCESSING 继续等待,FAILED 透传服务端错误并退出 1,SUCCEEDED 刷新实例(返回 ID 时)及部署。输出保留操作响应结构,追加 instance/deployment 响应结构。缺失或未知状态报错,不推定成功。`},{"en-US":`--timeout limits each HTTP request; --poll-timeout bounds the entire wait (exit 5 on expiry). Ctrl-C stops local waiting, not the remote operation. No write is retried; use the original operation ID after a timeout or interruption.`,"zh-CN":`--timeout 限制单次 HTTP 请求,--poll-timeout 限制整个等待过程(超时退出 5)。Ctrl-C 只停止本地等待,不取消远端操作。不重试任何写请求;超时或中断后仍使用原操作 ID 查询。`}],validate(e){let t=Tb(e);if(t)return t;if(e.interval!==void 0&&(!Number.isFinite(e.interval)||e.interval<1||e.interval>3600))return`--interval must be 1–3600 seconds. / --interval 必须为 1–3600 秒。`;if(e.pollTimeout!==void 0&&(!Number.isFinite(e.pollTimeout)||e.pollTimeout<=0||e.pollTimeout>Ob))return`--poll-timeout must be > 0 and <= ${Ob} seconds. / --poll-timeout 必须大于 0 且不超过 ${Ob} 秒。`},async run(e){let{flags:t,settings:n}=e,r=t.interval??2,i=t.pollTimeout??600;if(n.dryRun){O({action:`deploy.operation.wait`,deployed_model:t.deployedModel,operation_id:t.operationId,interval:r,poll_timeout:i},`json`);return}let a=new AbortController,o=()=>a.abort(/* @__PURE__ */ Error(`Interrupted. / 已中断。`));process.once(`SIGINT`,o);try{let n=await Ab(e.client,t.deployedModel,t.operationId,{interval:r,pollTimeout:i,signal:a.signal});O(n,`json`)}catch(e){if(!a.signal.aborted)throw e}finally{process.removeListener(`SIGINT`,o)}}});const Nb={inputTpm:{type:`number`,valueHint:`<kTPM>`,description:{"en-US":`Absolute input capacity in kTPM (1 kTPM = 1000 tokens/minute)`,"zh-CN":`输入绝对容量,单位 kTPM(1 kTPM = 1000 Tokens/分钟)`}},outputTpm:{type:`number`,valueHint:`<kTPM>`,description:{"en-US":`Absolute output capacity in kTPM`,"zh-CN":`输出绝对容量,单位 kTPM`}}},Pb={duration:{type:`number`,valueHint:`<days>`,description:{"en-US":`Prepaid purchase/renewal duration, positive integer days`,"zh-CN":`预付费购买或续订天数,正整数`}},autoRenewal:{type:`boolean`,valueHint:`<true|false>`,description:{"en-US":`Explicitly enable or disable automatic renewal for prepaid purchases`,"zh-CN":`显式开启或关闭预付费自动续费`}},autoRenewalDuration:{type:`number`,valueHint:`<days>`,description:{"en-US":`Automatic renewal duration; required when enabled`,"zh-CN":`自动续费天数,开启自动续费时必填`}},autoRenewalCycle:{type:`string`,valueHint:`<cycle>`,description:{"en-US":`Optional supported renewal cycle, e.g. Day`,"zh-CN":`可选续费周期单位,按服务支持的值传入,如 Day`}}},Fb={wait:{type:`switch`,description:{"en-US":`Wait for the returned capacity operation and refresh capacity`,"zh-CN":`等待返回的容量操作完成并刷新容量`}},interval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Initial wait poll interval (1–3600, default: 2 seconds)`,"zh-CN":`等待初始轮询间隔(1–3600,默认:2 秒)`}},pollTimeout:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Wait budget after submission (default: 600 seconds)`,"zh-CN":`提交后的等待总时限(默认:600 秒)`}}},Ib={requestId:{type:`string`,valueHint:`<uuid>`,description:{"en-US":`Request identifier; generated if omitted. Reuse with identical parameters only for the same capacity operation`,"zh-CN":`请求标识,省略时生成;仅重试同一容量操作时保持标识和参数一致`}},...Fb},Lb={orderType:{type:`string`,valueHint:`<UPGRADE|DOWNGRADE>`,choices:[`UPGRADE`,`DOWNGRADE`],description:{"en-US":`Optional order direction; otherwise the server decides`,"zh-CN":`可选变配方向,省略时由服务端判定`}}},Rb=[{"en-US":`Use --dry-run before confirming with --yes. A write is submitted once, never automatically retried. HTTP 200 is not operation success: inspect operation_status or pass --wait. After interruption or timeout, query the saved ModelCode/operation ID before considering another write.`,"zh-CN":`先用 --dry-run 预览,确认后再用 --yes。写请求只提交一次,不自动重试。HTTP 200 不等于操作成功:检查 operation_status 或使用 --wait。中断或超时后,先查询已保存的 ModelCode/操作 ID,再考虑是否重试写请求。`},{"en-US":`Capacities are absolute kTPM for one instance, not increments or ModelCode totals. Zero capacity is not release. Model-specific steps, limits and purchase periods are validated by the server. Automatic renewal configuration is part of purchase/scale/renew, not a standalone free setting change.`,"zh-CN":`容量是单个实例的绝对 kTPM,不是增量或 ModelCode 总量;容量归零不等于释放。模型步长、上下限及购买时长限制由服务端校验。自动续费配置属于购买、变配或续订流程,不是独立免费设置操作。`}];function zb(e){if(e.requestId!==void 0&&(!e.requestId.trim()||/[\r\n]/.test(e.requestId)))return`--request-id must be non-empty and contain no line breaks. / --request-id 不能为空或包含换行。`;if(!e.wait&&(e.interval!==void 0||e.pollTimeout!==void 0))return`--interval/--poll-timeout require --wait. / --interval/--poll-timeout 需要同时指定 --wait。`;if(e.interval!==void 0&&(!Number.isFinite(e.interval)||e.interval<1||e.interval>3600))return`--interval must be 1–3600 seconds. / --interval 必须为 1–3600 秒。`;if(e.pollTimeout!==void 0&&(!Number.isFinite(e.pollTimeout)||e.pollTimeout<=0||e.pollTimeout>2147483))return`--poll-timeout must be > 0 and <= 2147483 seconds. / --poll-timeout 必须大于 0 且不超过 2147483 秒。`}async function Bb(e,t,r,i){let a=await tt(e,t,r),o=a.output??a.data;if(!o||o.deleted===!0||o[`can_${i}`]!==!0)throw new n(`Capacity instance does not currently allow ${i}; refresh its details. / 容量实例当前不允许 ${i},请刷新详情。`,l.USAGE,void 0,{cause:a});return o}async function Vb(e,t){try{return await t()}catch(t){let r={client_request_id:e,error:t instanceof Error?t.message:t},i=`Request ID: ${e}. No automatic retry; first check whether the operation was accepted. / 请求标识:${e}。未自动重试,请先核查操作是否已受理。`;if(t instanceof n)throw new n(t.message,t.exitCode,[t.hint,i].filter(Boolean).join(`
|
|
2837
|
+
`),{api:t.api,rawResponse:t.rawResponse,cause:{...r,original_cause:t.cause}});if(t instanceof Error)try{t.message+=`\n${i}`}catch{}throw t}}async function Hb(e,t,r,i,a,o=!1,s){let c=r.output??r.data,u={...r,...a?{client_request_id:a}:{}};if(c?.operation_status===`FAILED`){let e=typeof c.error_message==`string`?c.error_message:typeof c.error_code==`string`?c.error_code:`Capacity operation failed. / 容量操作失败。`;throw new n(e,l.GENERAL,void 0,{api:{httpStatus:200,apiCode:typeof c.error_code==`string`?c.error_code:void 0,requestId:r.request_id},cause:u,rawResponse:JSON.stringify(u)})}if(o&&![`PROCESSING`,`SUCCEEDED`].includes(String(c?.operation_status)))throw new n(`Missing or unsupported operation_status after submission; do not repeat the write. / 提交后缺少或不支持的 operation_status,请勿重复写入。`,l.GENERAL,void 0,{cause:u});if(!i.wait){O(u,`json`);return}let d=t??(typeof c?.deployed_model==`string`?c.deployed_model:void 0),f=c?.operation_id;if(!d||typeof f!=`string`||!f.trim())throw new n(`Write submitted but no ModelCode/operation ID was returned for waiting; query the deployment before retrying. / 写请求已提交,但未返回等待所需的 ModelCode/操作 ID;重试前请查询部署。`,l.GENERAL,void 0,{cause:u,rawResponse:JSON.stringify(u)});process.stderr.write(`${JSON.stringify({submitted:!0,deployed_model:d,operation_id:f,client_request_id:a})}\n`);let p=new AbortController,m=()=>p.abort(/* @__PURE__ */ Error(`Interrupted. / 已中断。`));process.once(`SIGINT`,m);try{let t=await Ab(e,d,f,{interval:i.interval??2,pollTimeout:i.pollTimeout??600,signal:p.signal,initialResponse:c?.operation_status===`SUCCEEDED`?r:void 0,fallbackInstanceId:s}),o=t.output??t.data,u=t.output?`output`:`data`,m={...t,...o?{[u]:{...o,operation_id:o.operation_id??f}}:{},...a?{client_request_id:a}:{}};if(s&&(t.instance?.output??t.instance?.data)?.deleted!==!0)throw new n(`Release operation completed but deleted=true is not confirmed; refresh the instance before deleting the ModelCode. / 释放操作已结束,但未确认 deleted=true;删除 ModelCode 前请刷新实例。`,l.GENERAL,void 0,{cause:m});O(m,`json`)}catch(e){if(!p.signal.aborted)throw e}finally{process.removeListener(`SIGINT`,m)}}const Ub={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 (optional for PTU; required for other plans)`,"zh-CN":`控制台显示名称(PTU 可选;其他方案必填)`}},plan:{type:`string`,valueHint:`<plan>`,description:{"en-US":`Billing plan: lora (default, Token-billed) | ptu (throughput reservation) | mu`,"zh-CN":`计费方案:lora(默认,按 Token 计费)| ptu(吞吐预留)| 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")`}},...Nb,thinkingOutputTpm:{type:`number`,valueHint:`<n>`,description:{"en-US":`Legacy thinking-output capacity flag; not supported for PTU`,"zh-CN":`旧版思考输出容量参数;PTU 不支持此参数`}},chargeType:{type:`string`,valueHint:`<type>`,choices:[`pre_paid`,`post_paid`],description:{"en-US":`PTU payment type (required for plan=ptu): pre_paid or post_paid`,"zh-CN":`PTU 付费方式(plan=ptu 必填):pre_paid 或 post_paid`}},serviceTier:{type:`string`,valueHint:`<tier>`,choices:[`ptu_fast`,`ptu_default`],description:{"en-US":`PTU service tier: ptu_fast (default) or ptu_default (prepaid only)`,"zh-CN":`PTU 性能档位:ptu_fast(默认高速)或 ptu_default(标速,仅预付费)`}},suffix:{type:`string`,valueHint:`<suffix>`,description:{"en-US":`Optional PTU ModelCode suffix; generated by the service when omitted`,"zh-CN":`可选 PTU ModelCode 后缀;省略时由服务端生成`}},...Pb,...Fb},Wb=`--model-name <model_name> [--display-name <display_name>] [--plan <plan>] [--charge-type <type>] [--service-tier <tier>] [--suffix <suffix>] [--input-tpm <n> --output-tpm <n>] [flags]`,Gb={level:`high`,message:{"en-US":`Creating a deployment purchases or provisions resources and may incur charges.`,"zh-CN":`创建部署会购买或开通资源,可能产生费用。`}},Kb=[{"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, --charge-type, --input-tpm and --output-tpm are required. Capacity is in kTPM (1 kTPM = 1000 tokens/minute). Separate thinking-output capacity is unsupported. Prepaid requires --duration and explicit --auto-renewal true|false.`,"zh-CN":`plan=ptu 时,--charge-type、--input-tpm 和 --output-tpm 必填。容量单位为 kTPM(1 kTPM = 1000 Token/分钟),不支持单独的思考输出容量。预付费须提供 --duration 和显式 --auto-renewal true|false。`},{"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 `deploy models --source base` to inspect available templates.","zh-CN":"使用 `deploy models --source base` 查看可用模板。"},{"en-US":`PTU creation preserves the original JSON and operation_id even with --quiet. --wait only queries the returned operation; pending capacity is not effective capacity. Check the actual status before invoking the model.`,"zh-CN":`PTU 创建即使指定 --quiet 也保留原始 JSON 和 operation_id。--wait 仅查询返回的操作;待生效容量不等于已生效容量。调用模型前请确认实际状态。`},{"en-US":"--model-name identifies the source model; the returned deployed_model is the invocation identifier (ModelCode). Use it for inference (`text chat --model <deployed_model>`) and deployment lifecycle commands.","zh-CN":"--model-name 标识源模型;返回的 deployed_model 为调用标识(ModelCode),用于推理(`text chat --model <deployed_model>`)和部署生命周期命令。"},{"en-US":`Initial ModelCode creation does not support --request-id or promise idempotency. A timeout is not proof of failure: check whether the deployment was created before trying again. This command never automatically resubmits creation.`,"zh-CN":`首次创建 ModelCode 不支持 --request-id,也不承诺幂等。超时不代表失败:再次尝试前先确认部署是否已创建。本命令不会自动重新提交创建请求。`},{"en-US":`Use --dry-run to preview without requests. Pass --yes only after confirming the costs.`,"zh-CN":`使用 --dry-run 离线预览;仅在确认费用后传入 --yes 执行。`}];function qb(e,t){let n=t.plan||De(e),r=y[n];if(!r)return`Unsupported plan "${n}". Supported plans: ${Object.keys(y).join(`, `)}. / 不支持方案 "${n}";支持的方案:${Object.keys(y).join(`, `)}。`;if(n!==`ptu`){if(t.chargeType!==void 0||t.serviceTier!==void 0||t.suffix!==void 0||mt(t)||t.wait||t.interval!==void 0||t.pollTimeout!==void 0)return`Payment, service tier, suffix, prepaid and wait options are PTU-only. / 付费方式、性能档位、后缀、预付费和等待参数仅适用于 PTU。`;if(!t.displayName?.trim())return`--display-name is required for non-PTU plans. / 非 PTU 方案必须提供 --display-name。`}else if(t.thinkingOutputTpm!==void 0)return`--thinking-output-tpm is not supported for PTU. / PTU 不支持 --thinking-output-tpm。`;return zb(t)??r.validateFlags(t)}async function Jb(e,t){let{identity:n,settings:r,flags:i}=t,a=i.plan||De(e),o=nn(a),s=async e=>{let r=await o.resolve({client:t.client,dryRun:e,binName:n.binName,flags:i,model:i.modelName,name:i.displayName});return{model_name:i.modelName,...i.displayName===void 0?{}:{name:i.displayName},plan:a,...r.body}};if(r.dryRun){O({action:`deploy.create`,body:await s(!0)},`json`);return}let c=await Ce(t.client,await s(!1)),l=c.output??c.data;a===`ptu`?await Hb(t.client,l?.deployed_model,c,i):r.quiet?D(l?.deployed_model??``):O(c,`json`)}const Yb=S({description:{"en-US":`Create a text model deployment`,"zh-CN":`创建文本模型部署`},auth:`apiKey`,risk:Gb,usageArgs:Wb,flags:Ub,exampleArgs:[`--model-name my-qwen-sft --display-name my-sft-test`,`--model-name qwen3.6-flash-2026-04-16 --plan ptu --charge-type post_paid --input-tpm 10000 --output-tpm 1000 --dry-run`,`--model-name qwen3.6-flash-2026-04-16 --plan ptu --charge-type pre_paid --service-tier ptu_default --input-tpm 10000 --output-tpm 1000 --duration 30 --auto-renewal false --dry-run`,`--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:Kb,validate:e=>qb(`text`,e),run:e=>Jb(`text`,e)}),Xb=S({description:{"en-US":`Create an audio (TTS) model deployment`,"zh-CN":`创建音频(TTS)模型部署`},auth:`apiKey`,risk:Gb,usageArgs:Wb,flags:Ub,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:Kb,validate:e=>qb(`audio`,e),run:e=>Jb(`audio`,e)}),Zb=S({description:{"en-US":`Create an image generation model deployment`,"zh-CN":`创建图片生成模型部署`},auth:`apiKey`,risk:Gb,usageArgs:Wb,flags:Ub,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:Kb,validate:e=>qb(`image`,e),run:e=>Jb(`image`,e)});var Qb=S({description:{"en-US":`List model deployments and throughput reservations`,"zh-CN":`列出模型部署及吞吐预留`},auth:`apiKey`,usageArgs:`[--page <n>] [--page-size <n>] [--plan <plan>] [--status <status>]`,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)`}},plan:{type:`string`,valueHint:`<plan>`,description:{"en-US":`Server-side plan filter; use ptu for throughput reservations`,"zh-CN":`服务端方案筛选;吞吐预留使用 ptu`}},status:{type:`string`,valueHint:`<status>`,description:{"en-US":`Filter only the fetched page locally by ModelCode status; total remains unfiltered`,"zh-CN":`仅在已获取的当前页本地筛选 ModelCode 状态;total 仍为筛选前总数`}}},exampleArgs:[``,`--plan ptu`,`--plan ptu --status RUNNING --page-size 100`,`--page-size 20 --output json`],notes:[{"en-US":`The deployment list API supports page_no/page_size/plan, not status. --status filters only the requested page, not the entire account; an empty filtered page does not mean there are no matches on later pages. total is the server total before local filtering; local_filter reports the current-page match count. PTU capacities are kTPM.`,"zh-CN":`部署列表 API 支持 page_no/page_size/plan,不支持 status。--status 仅筛选所请求的当前页,不代表全账号筛选;当前页为空不代表后续页没有匹配项。total 是本地筛选前的服务端总数,local_filter 给出当前页匹配数量。PTU 容量单位为 kTPM。`}],validate(e){return Eb(e)??([e.plan,e.status].some(e=>e!==void 0&&!e.trim())?`Filters must not be empty. / 筛选条件不能为空。`:void 0)},async run(e){let{settings:t,flags:n}=e,r=n.page??1,i=n.pageSize??10,a=n.status?.trim(),o=n.plan?.trim();if(t.dryRun){O({action:`deploy.list`,page:r,page_size:i,plan:o,status:a,...a?{filter_scope:`page`}:{}},`json`);return}let s=await jt(e.client,{pageNo:r,pageSize:i,plan:o}),c=s.output??s.data,l=c?.deployments??[],u=(a?l.filter(e=>e.status===a):l).map(e=>({...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??``}));O({items:u,total:c?.total,page_no:c?.page_no??r,page_size:c?.page_size??i,...a?{local_filter:{status:a,scope:`page`,matched_count:u.length,unfiltered_page_count:l.length}}:{},request_id:s.request_id},`json`)}}),$b=S({description:{"en-US":`Get details of a single model deployment`,"zh-CN":`获取单个模型部署的详情`},auth:`apiKey`,usageArgs:`--deployed-model <id>`,flags:Sb,exampleArgs:[`--deployed-model qwen-plus-2025-12-01-b6d61c71`,`--deployed-model qwen-plus-2025-12-01-b6d61c71 --output json`],notes:[{"en-US":`Preserves deployment fields including ptu_capacity (aggregate effective kTPM), ptu_service_tier, overflow_strategy and pre_paid_info. For mixed billing or multiple instances, query capacity list/get for each instance's status, expiry and capacity; ModelCode status is not instance status.`,"zh-CN":`保留部署字段,包括 ptu_capacity(汇总生效容量,kTPM)、ptu_service_tier、overflow_strategy 及 pre_paid_info。混合付费或多实例时,通过 capacity list/get 查询各实例状态、到期时间和容量;ModelCode 状态不等于实例状态。`}],validate:Tb,async run(e){let{settings:t,flags:n}=e,r=n.deployedModel;if(t.dryRun){O({action:`deploy.get`,deployed_model:r},`json`);return}let i=await at(e.client,r),a=i.output??i.data;if(!a){O({deployed_model:r,request_id:i.request_id},`json`);return}let o={...a,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),O({...o,request_id:i.request_id},`json`)}});const ex={...Sb,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 (1–100, default: 20)`,"zh-CN":`每页条数(1–100,默认:20)`}},includeDeleted:{type:`boolean`,valueHint:`<true|false>`,description:{"en-US":`Include released instances (default: true)`,"zh-CN":`包含已释放实例(默认:true)`}},statuses:{type:`string`,valueHint:`<status,...>`,description:{"en-US":`Instance statuses, comma-separated (not ModelCode statuses)`,"zh-CN":`实例状态,逗号分隔(非 ModelCode 状态)`}},chargeTypes:{type:`string`,valueHint:`<pre_paid,post_paid>`,description:{"en-US":`Charge types: pre_paid, post_paid; comma-separated`,"zh-CN":`付费类型:pre_paid、post_paid,逗号分隔`}}};var tx=S({description:{"en-US":`List throughput reservation capacity instances`,"zh-CN":`查询吞吐预留容量实例列表`},auth:`apiKey`,flags:ex,usageArgs:`--deployed-model <code> [--page <n>] [--page-size <n>] [--include-deleted <true|false>] [--statuses <status,...>] [--charge-types <pre_paid,post_paid>]`,exampleArgs:[`--deployed-model example-model-code`,`--deployed-model example-model-code --include-deleted false --statuses RUNNING,STOPPED`],notes:[{"en-US":`Preserves the API envelope and records/items/page/itemsPerPage/pageCount pagination. Capacities are kTPM; effective, configured and target capacities are distinct. STOPPED alone does not mean released: inspect deleted.`,"zh-CN":`保留 API 响应结构及 records/items/page/itemsPerPage/pageCount 分页字段。容量单位为 kTPM,区分生效、配置和目标容量。仅 STOPPED 不代表已释放,需检查 deleted。`}],validate(e){let t=Tb(e)??Eb(e);if(t)return t;if([e.statuses,e.chargeTypes].some(e=>Db(e)?.some(e=>!e)))return`Filter lists must not contain empty values. / 筛选列表不能包含空值。`;if(Db(e.chargeTypes)?.some(e=>![`pre_paid`,`post_paid`].includes(e)))return`--charge-types accepts pre_paid,post_paid. / --charge-types 仅支持 pre_paid、post_paid。`},async run(e){let{flags:t,settings:n}=e,r={pageNo:t.page??1,pageSize:t.pageSize??20,includeDeleted:t.includeDeleted??!0,statuses:Db(t.statuses),chargeTypes:Db(t.chargeTypes)};if(n.dryRun){O({action:`deploy.capacity.list`,deployed_model:t.deployedModel,query:{page_no:r.pageNo,page_size:r.pageSize,include_deleted:r.includeDeleted,statuses:r.statuses?.join(`,`),charge_types:r.chargeTypes?.join(`,`)}},`json`);return}O(await Dt(e.client,t.deployedModel,r),`json`)}}),nx=S({description:{"en-US":`Get a throughput reservation capacity instance`,"zh-CN":`查询吞吐预留容量实例详情`},auth:`apiKey`,flags:{...Sb,...Cb},usageArgs:`--deployed-model <code> --instance-id <id>`,exampleArgs:[`--deployed-model example-model-code --instance-id example-capacity-instance`],notes:[{"en-US":`Read-only; released instances can also be queried. Preserves the API envelope, capacity fields, can_scale/can_renew/can_delete and deleted. Capacities are kTPM; the instance must belong to this ModelCode.`,"zh-CN":`只读查询,已释放实例也可查询。保留 API 响应结构、容量字段、can_scale/can_renew/can_delete 和 deleted。容量单位为 kTPM,实例必须属于指定 ModelCode。`}],validate:Tb,async run(e){let{settings:t,flags:n}=e;if(t.dryRun){O({action:`deploy.capacity.get`,deployed_model:n.deployedModel,instance_id:n.instanceId},`json`);return}O(await tt(e.client,n.deployedModel,n.instanceId),`json`)}});const rx={...Sb,...Nb,...Pb,...Ib,billingMethod:{type:`string`,valueHint:`<PRE_PAY|POST_PAY>`,required:!0,choices:[`PRE_PAY`,`POST_PAY`],description:{"en-US":`Capacity instance billing method (case-sensitive)`,"zh-CN":`容量实例付费方式(区分大小写)`}}},ix=S({description:{"en-US":`Purchase an additional capacity instance for a ModelCode`,"zh-CN":`为已有 ModelCode 叠加购买容量实例`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`Purchases additional throughput capacity and may enable recurring charges.`,"zh-CN":`该操作将购买额外吞吐容量,可能开启持续续费。`}},flags:rx,usageArgs:`--deployed-model <code> --billing-method <PRE_PAY|POST_PAY> --input-tpm <kTPM> --output-tpm <kTPM> [--duration <days>] [--auto-renewal <true|false>] [--wait]`,exampleArgs:[`--deployed-model example-code --billing-method POST_PAY --input-tpm 10000 --output-tpm 1000 --dry-run`,`--deployed-model example-code --billing-method PRE_PAY --input-tpm 10000 --output-tpm 1000 --duration 30 --auto-renewal false --dry-run`],notes:[...Rb,{"en-US":`Keeps the ModelCode, model and performance tier. Only one unreleased postpaid instance is allowed per ModelCode; the server validates purchase eligibility and slot limits.`,"zh-CN":`沿用原 ModelCode、模型和性能档位。同一 ModelCode 只允许一个未释放的后付费实例;购买资格和实例数量限制由服务端校验。`}],validate(e){return(Tb(e)??zb(e)??tr(e,!0))||(e.billingMethod===`POST_PAY`&&mt(e)?`POST_PAY cannot include prepaid settings. / 后付费不能携带预付费配置。`:er(e,e.billingMethod===`PRE_PAY`))},async run(e){let{flags:t,settings:n}=e,r=pe(t),i={billing_method:t.billingMethod,ptu_capacity:me(t),...r?{pre_paid_info:r}:{}};if(n.dryRun){O({action:`deploy.capacity.create`,deployed_model:t.deployedModel,body:i,client_request_id:t.requestId??`<generated UUID>`,wait:t.wait},`json`);return}let a=t.requestId??zr(),o=await Vb(a,()=>Se(e.client,t.deployedModel,i,{requestId:a}));await Hb(e.client,t.deployedModel,o,t,a,!0)}}),ax={...Sb,...Cb,...Nb,...Pb,...Lb,...Ib},ox=S({description:{"en-US":`Scale the absolute capacity of one reservation instance`,"zh-CN":`调整单个预留实例的绝对容量`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`Changes purchased capacity, may incur charges and can reduce serving capacity to zero.`,"zh-CN":`该操作会变更购买容量、可能产生费用,也可能将服务容量降至零。`}},flags:ax,usageArgs:`--deployed-model <code> --instance-id <id> --input-tpm <kTPM> --output-tpm <kTPM> [--order-type <UPGRADE|DOWNGRADE>] [--wait]`,exampleArgs:[`--deployed-model example-code --instance-id example-instance --input-tpm 20000 --output-tpm 2000 --dry-run`,`--deployed-model example-code --instance-id example-instance --input-tpm 0 --output-tpm 0 --dry-run`],notes:[...Rb,{"en-US":`Refreshes can_scale before writing. Omitted prepaid settings remain omitted, so the server can reuse saved information. Postpaid instances cannot receive prepaid settings.`,"zh-CN":`写入前刷新 can_scale。未指定预付费参数时不发送该对象,由服务端复用已保存的信息。后付费实例不能携带预付费配置。`}],validate:e=>Tb(e)??zb(e)??tr(e,!0)??er(e,!1),async run(e){let{flags:t,settings:r}=e,i=pe(t),a={ptu_capacity:me(t),...t.orderType?{order_type:t.orderType}:{},...i?{pre_paid_info:i}:{}};if(r.dryRun){O({action:`deploy.capacity.scale`,deployed_model:t.deployedModel,instance_id:t.instanceId,body:a,client_request_id:t.requestId??`<generated UUID>`,precheck:`can_scale`,wait:t.wait},`json`);return}let o=await Bb(e.client,t.deployedModel,t.instanceId,`scale`);if(![`pre_paid`,`post_paid`].includes(o.charge_type??``))throw new n(`Unknown instance billing type; cannot safely scale. / 实例付费类型不明确,无法安全变配。`,l.USAGE);if(i&&o.charge_type!==`pre_paid`)throw new n(`Prepaid settings require a prepaid instance. / 预付费配置只能用于预付费实例。`,l.USAGE);let s=t.requestId??zr(),c=await Vb(s,()=>Mn(e.client,t.deployedModel,t.instanceId,a,{requestId:s}));await Hb(e.client,t.deployedModel,c,t,s,!0)}}),sx={...Sb,...Cb,...Nb,...Pb,...Ib,isChange:{type:`boolean`,valueHint:`<true|false>`,description:{"en-US":`Change capacity during renewal (default: false)`,"zh-CN":`续订时同时变更容量(默认:false)`}}},cx=S({description:{"en-US":`Renew a prepaid capacity instance, optionally changing capacity`,"zh-CN":`续订预付费容量实例,可同时变更容量`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`Renews a paid capacity instance and may enable automatic recurring renewal.`,"zh-CN":`该操作将付费续订容量实例,可能开启自动持续续费。`}},flags:sx,usageArgs:`--deployed-model <code> --instance-id <id> --duration <days> --auto-renewal <true|false> [--is-change <true|false>] [--input-tpm <kTPM>] [--output-tpm <kTPM>] [--wait]`,exampleArgs:[`--deployed-model example-code --instance-id example-instance --duration 30 --auto-renewal false --dry-run`,`--deployed-model example-code --instance-id example-instance --duration 30 --auto-renewal true --auto-renewal-duration 30 --dry-run`],notes:[...Rb,{"en-US":`Prepaid only; refreshes can_renew. Different capacity requires --is-change true; an unchanged capacity may be sent with false. No order_type is accepted by this endpoint.`,"zh-CN":`仅支持预付费,写入前刷新 can_renew。变更容量必须指定 --is-change true;相同配置容量可随 false 发送。本接口不接受 order_type。`}],validate:e=>Tb(e)??zb(e)??tr(e,!1)??er(e,!0),async run(e){let{flags:t,settings:r}=e,i=t.inputTpm===void 0?void 0:me(t),a={pre_paid_info:pe(t),is_change:t.isChange??!1,...i?{ptu_capacity:i}:{}};if(r.dryRun){O({action:`deploy.capacity.renew`,deployed_model:t.deployedModel,instance_id:t.instanceId,body:a,client_request_id:t.requestId??`<generated UUID>`,precheck:`can_renew/pre_paid/configured_capacity`,wait:t.wait},`json`);return}let o=await Bb(e.client,t.deployedModel,t.instanceId,`renew`);if(o.charge_type!==`pre_paid`)throw new n(`Only prepaid instances can be renewed. / 仅预付费实例可以续订。`,l.USAGE);if(i&&!t.isChange&&(i.input_tpm!==o.configured_capacity?.input_tpm||i.output_tpm!==o.configured_capacity?.output_tpm))throw new n(`Different capacity requires --is-change true. / 变更容量必须指定 --is-change true。`,l.USAGE);let s=t.requestId??zr(),c=await Vb(s,()=>hn(e.client,t.deployedModel,t.instanceId,a,{requestId:s}));await Hb(e.client,t.deployedModel,c,t,s,!0)}}),lx={...Sb,...Cb,...Ib,reason:{type:`string`,valueHint:`<text>`,description:{"en-US":`Optional release reason, sent as a query parameter`,"zh-CN":`可选释放原因,以查询参数发送`}}},ux=S({description:{"en-US":`Release a capacity instance without deleting its ModelCode`,"zh-CN":`释放容量实例,保留所属 ModelCode`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`Releases serving capacity and may interrupt requests; this cannot be undone by this command. This is not a prepaid unsubscribe/refund action.`,"zh-CN":`该操作将释放服务容量,可能中断请求,不能通过本命令撤销。这不是预付费退订或退款操作。`}},flags:lx,usageArgs:`--deployed-model <code> --instance-id <id> [--reason <text>] [--wait]`,exampleArgs:[`--deployed-model example-code --instance-id example-instance --dry-run`],notes:[...Rb,{"en-US":"Active prepaid instances must be unsubscribed via `deploy capacity unsubscribe` (billing console link), even when can_delete=true. Failed prepaid instances may have no associated order; only the server can decide whether direct release is supported. Release is asynchronous; verify deleted=true, not merely STOPPED or zero capacity.","zh-CN":"已生效预付费实例须通过 `deploy capacity unsubscribe` 获取费用中心退订链接完成退订,即使 can_delete=true 也不能直接删除。失败的预付费实例可能尚未关联订单,能否直接释放由服务端裁决。释放是异步操作,须确认 deleted=true,不能只看 STOPPED 或零容量。"}],validate:e=>Tb(e)??zb(e),async run(e){let{flags:t,settings:r}=e;if(r.dryRun){O({action:`deploy.capacity.delete`,deployed_model:t.deployedModel,instance_id:t.instanceId,query:t.reason===void 0?{}:{reason:t.reason},client_request_id:t.requestId??`<generated UUID>`,precheck:`can_delete/prepaid_unsubscribe`,wait:t.wait},`json`);return}let i=await Bb(e.client,t.deployedModel,t.instanceId,`delete`);if(i.charge_type===`pre_paid`&&i.status!==`FAILED`)throw new n("Prepaid instances must be unsubscribed in the billing console; DELETE is not a refund. Run `deploy capacity unsubscribe --instance-id <id>` to get the refund page link. / 预付费实例请在费用中心退订,DELETE 不能替代退订退款。运行 `deploy capacity unsubscribe --instance-id <id>` 获取退订页面链接。",l.USAGE);if(![`pre_paid`,`post_paid`].includes(i.charge_type??``))throw new n(`Unknown instance billing type; cannot safely release. / 实例付费类型不明确,无法安全释放。`,l.USAGE);let a=t.requestId??zr(),o=await Vb(a,()=>Oe(e.client,t.deployedModel,t.instanceId,{requestId:a,reason:t.reason}));await Hb(e.client,t.deployedModel,o,t,a,!0,t.instanceId)}});var dx=S({description:{"en-US":`Build the Aliyun billing console unsubscribe link for a prepaid capacity instance`,"zh-CN":`生成预付费容量实例在阿里云费用中心的退订链接`},auth:`none`,flags:Cb,usageArgs:`--instance-id <id>`,exampleArgs:[`--instance-id example-instance`],notes:[{"en-US":`No API is called and nothing is unsubscribed by this command; it only builds the refund page link. Open the link and finish the unsubscribe flow in the billing console with the account that placed the order.`,"zh-CN":`本命令不调用任何接口,也不会执行退订,只生成费用中心退订页面链接。请用下单账号打开链接,在费用中心完成退订流程。`},{"en-US":"Only prepaid instances are unsubscribed this way; postpaid instances are released with `deploy capacity delete`. The ID is the capacity instance ID (see `deploy capacity list` / `get`), not the ModelCode. Unsubscription may interrupt serving and is irreversible; refund rules are decided by the billing console.","zh-CN":"仅预付费实例通过此方式退订;后付费实例请使用 `deploy capacity delete` 释放。此处为容量实例 ID(见 `deploy capacity list` / `get`),不是 ModelCode。退订可能中断服务且不可撤销,退款规则以费用中心为准。"}],validate:Tb,async run(e){let{settings:t,flags:n}=e,r=Ar(n.instanceId);if(t.quiet){D(r);return}O({action:`deploy.capacity.unsubscribe`,instance_id:n.instanceId,refund_url:r},`json`)}}),fx=S({description:{"en-US":`Set the overflow strategy for a throughput reservation ModelCode`,"zh-CN":`设置吞吐预留 ModelCode 的溢出策略`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`Enabling overflow incurs pay-as-you-go charges beyond reserved capacity; disabling it rate-limits excess requests.`,"zh-CN":`开启溢出后,预留容量外的流量将产生按量费用;关闭后,超额请求会被限流。`}},flags:{...Sb,strategy:{type:`string`,valueHint:`<enable|disable>`,required:!0,choices:[`enable`,`disable`],description:{"en-US":`Allow pay-as-you-go overflow or restrict requests to reserved capacity`,"zh-CN":`允许按量溢出或将请求限制在预留容量内`}}},usageArgs:`--deployed-model <code> --strategy <enable|disable>`,exampleArgs:[`--deployed-model example-code --strategy enable --dry-run`,`--deployed-model example-code --strategy disable --dry-run`],notes:[{"en-US":`Applies to the whole ModelCode, not one capacity instance. Sends one update then one GET to confirm the strategy. Never retries the update automatically; a read-back failure does not mean the change was not applied.`,"zh-CN":`配置作用于整个 ModelCode,而非单个容量实例。提交一次更新后 GET 回读确认策略。不自动重试更新;回读失败不代表配置未生效。`}],validate:Tb,async run(e){let{settings:t,flags:r}=e;if(t.dryRun){O({action:`deploy.overflow`,deployed_model:r.deployedModel,body:{overflow_strategy:r.strategy}},`json`);return}let i=await Yn(e.client,r.deployedModel,r.strategy),a=await at(e.client,r.deployedModel);if((a.output??a.data)?.overflow_strategy!==r.strategy)throw new n(`Overflow update submitted but not confirmed by read-back; query the deployment before retrying. / 溢出配置已提交,但回读未确认,请先查询部署再决定是否重试。`,l.GENERAL,void 0,{cause:{response:i,deployment:a}});O({...i,deployment:a},`json`)}}),px=S({description:{"en-US":`Query a throughput reservation capacity operation once`,"zh-CN":`单次查询吞吐预留容量操作`},auth:`apiKey`,flags:wb,usageArgs:`--deployed-model <code> --operation-id <id>`,exampleArgs:[`--deployed-model example-model-code --operation-id 100001`],notes:[{"en-US":`Preserves the API envelope, including FAILED and its error fields; a successful GET returns exit code 0 regardless of operation status. Use operation wait to wait for success or fail with a non-zero exit. Use the actual returned operation ID; do not construct one.`,"zh-CN":`保留 API 响应结构,包括 FAILED 状态及错误字段;GET 请求成功即返回退出码 0,不以操作状态判断。需要等待成功或失败时非零退出,请使用 operation wait。操作 ID 必须使用实际返回值,不要自行构造。`}],validate:Tb,async run(e){let{settings:t,flags:n}=e;if(t.dryRun){O({action:`deploy.operation.get`,deployed_model:n.deployedModel,operation_id:n.operationId},`json`);return}O(await nt(e.client,n.deployedModel,n.operationId),`json`)}}),mx=S({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){O({action:`deploy.models`,page:n.page,page_size:n.pageSize,version:r,model_source:i},`json`);return}let a=await At(e.client,{pageNo:n.page,pageSize:n.pageSize,version:r,modelSource:i}),o=a.output??a.data,s=o?.models??[],c=o?.total,l=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});O({items:l,total:c,request_id:a.request_id},`json`)}});const hx={deployedModel:{type:`string`,valueHint:`<id>`,description:{"en-US":`Deployed model identifier (required)`,"zh-CN":`已部署模型标识(必填)`},required:!0},capacity:{type:`number`,valueHint:`<n>`,description:{"en-US":`MU target capacity: non-negative integer in plan units; must satisfy base_capacity`,"zh-CN":`MU 目标容量:非负整数,单位为方案单元;须满足 base_capacity 约束`}},...Nb,instanceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`PTU capacity instance ID; required when multiple unreleased instances exist`,"zh-CN":`PTU 容量实例 ID;存在多个未释放实例时必填`}},...Pb,...Ib,...Lb};async function gx(e,t){let r=await Dt(e,t,{includeDeleted:!1,pageNo:1,pageSize:2}),i=r.output??r.data,a=i?.records;if(!Array.isArray(a)||a.length!==1||i?.items!==1||i.page!==void 0&&i.page!==1||i.pageCount!==void 0&&i.pageCount!==1||a[0]?.deleted===!0||typeof a[0]?.instance_id!=`string`||!a[0].instance_id.trim())throw new n(`Cannot confirm exactly one unreleased capacity instance. Specify --instance-id; multiple instances must never be selected implicitly. / 无法确认恰好一个未释放容量实例,请指定 --instance-id;多个实例不能自动选择。`,l.USAGE);return a[0].instance_id}var _x=S({description:{"en-US":`Scale a deployment's capacity`,"zh-CN":`调整部署容量`},auth:`apiKey`,risk:{level:`high`,message:{"en-US":`Scaling changes purchased capacity and may incur charges or reduce serving capacity.`,"zh-CN":`扩缩容会变更购买的容量,可能产生费用或降低服务容量。`}},usageArgs:`--deployed-model <id> (--capacity <n> | --input-tpm <n> --output-tpm <n>) [--instance-id <id>] [flags]`,flags:hx,exampleArgs:[`--deployed-model dep-... --capacity 8 --dry-run`,`--deployed-model dep-... --instance-id instance-... --input-tpm 20000 --output-tpm 2000 --order-type UPGRADE --dry-run`],notes:[...Rb,{"en-US":`PTU input/output values are the selected instance's absolute target capacity in kTPM (1 kTPM = 1000 tokens/minute), not deltas or deployment totals. Both zero is valid and does not release the instance. PTU options cannot be combined with --capacity.`,"zh-CN":`PTU 输入/输出值为选中实例的绝对目标容量,单位 kTPM(1 kTPM = 1000 Token/分钟),不是增量或部署总容量。允许同时为零,但不等于释放实例。PTU 参数不能与 --capacity 混用。`},{"en-US":`Without --instance-id, execution must confirm exactly one unreleased instance and recheck can_scale. Dry-run does not resolve an instance or validate its billing type. Pass --yes only after confirming the costs and target.`,"zh-CN":`省略 --instance-id 时,执行前必须确认恰好一个未释放实例并复查 can_scale。dry-run 不解析实例或验证其付费方式;仅在确认费用及目标后传入 --yes 执行。`}],validate(e){return(Tb(e)??zb(e))||(e.capacity===void 0?tr(e,!0)??er(e,!1):!Number.isSafeInteger(e.capacity)||e.capacity<0?`--capacity must be a non-negative safe integer. / --capacity 必须是非负安全整数。`:e.inputTpm!==void 0||e.outputTpm!==void 0||e.instanceId!==void 0||e.orderType!==void 0||mt(e)||e.wait||e.requestId!==void 0||e.interval!==void 0||e.pollTimeout!==void 0?`PTU options cannot be used with --capacity. / PTU 参数不能与 --capacity 混用。`:void 0)},async run(e){let{settings:t,flags:r}=e,i=r.deployedModel,a=r.capacity===void 0,o=a?{ptu_capacity:me(r),...r.instanceId===void 0?{}:{instance_id:r.instanceId},...r.orderType===void 0?{}:{order_type:r.orderType},...mt(r)?{pre_paid_info:pe(r)}:{}}:{capacity:r.capacity};if(t.dryRun){O({action:`deploy.scale`,deployed_model:i,body:o,...a&&r.instanceId===void 0?{instance_resolution:`Execution must resolve exactly one unreleased instance or require --instance-id. / 执行时须确认唯一未释放实例,否则必须指定 --instance-id。`}:{}},`json`);return}if(a){let t=r.instanceId??await gx(e.client,i),a=await Bb(e.client,i,t,`scale`);if(![`pre_paid`,`post_paid`].includes(a.charge_type??``))throw new n(`Unknown instance billing type; cannot safely scale. / 实例付费类型不明确,无法安全变配。`,l.USAGE);if(a.charge_type===`post_paid`&&mt(r))throw new n(`Postpaid instances do not accept prepaid options. / 后付费实例不接受预付费参数。`,l.USAGE);o.instance_id=t;let s=r.requestId??zr(),c=await Vb(s,()=>Nn(e.client,i,o,void 0,s));await Hb(e.client,i,c,r,s);return}let s=await Nn(e.client,i,o);t.quiet?D(i):O(s,`json`)}}),vx=S({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){O({action:`deploy.update`,deployed_model:r,body:i},`json`);return}let a=await Jn(e.client,r,i);t.quiet?D(r):O(a,`json`)}}),yx=S({description:{"en-US":`Delete a model deployment (PTU must be STOPPED with all capacity released)`,"zh-CN":`删除模型部署(PTU 须为 STOPPED 且已释放全部容量)`},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 local checks only; the service still validates deletion prerequisites`,"zh-CN":`仅跳过本地检查;服务端仍验证删除前提条件`}}},exampleArgs:[`--deployed-model dep-... --dry-run`,{"en-US":`--deployed-model dep-... --yes # Execute only after confirming deletion`,"zh-CN":`--deployed-model dep-... --yes # 仅在确认删除后执行`}],notes:[{"en-US":`PTU deletion requires STOPPED, all capacity instances released, and no processing or queued capacity operations. Pausing or scaling to zero does not release an instance; prepaid capacity may require unsubscription.`,"zh-CN":`PTU 删除要求状态为 STOPPED、全部容量实例已释放,且不存在执行中或排队的容量操作。暂停或缩容到零不等于释放实例;预付费容量可能需要先退订。`},{"en-US":`Local checks inspect the deployment, unreleased instances and any returned operation_id. There is no public queued-operation list API, so these checks cannot confirm all operations are finished; the service makes the final decision. --skip-precheck only omits local checks, never service validation or resource release requirements.`,"zh-CN":`本地检查部署、未释放实例及返回的 operation_id。没有公开的排队操作列表接口,因此无法在本地确认所有操作均已完成,最终以服务端裁决为准。--skip-precheck 仅省略本地检查,不绕过服务端验证或资源释放要求。`}],async run(e){let{settings:t,flags:r}=e,i=r.deployedModel;if(t.dryRun){O({action:`deploy.delete`,deployed_model:i},`json`);return}if(!r.skipPrecheck){let t=await at(e.client,i),r=t.output??t.data,a=(r?.status??``).toUpperCase();if(r?.plan===`ptu`||r?.plan===`ptu_v2`||r?.ptu_capacity!==void 0||r?.ptu_service_tier!==void 0){if(a!==`STOPPED`)throw new n(`PTU deployment ${i} must be STOPPED before deletion (current: ${a||`unknown`}). Release all capacity instances first; pausing is not release. / PTU 部署 ${i} 删除前必须为 STOPPED(当前:${a||`未知`});请先释放全部容量实例,暂停不等于释放。`,l.USAGE);let t=await Dt(e.client,i,{includeDeleted:!1,pageNo:1,pageSize:1}),o=t.output??t.data;if(Array.isArray(o?.records)&&o.records.length>0||typeof o?.items==`number`&&o.items>0||typeof o?.total==`number`&&o.total>0)throw new n(`Release all capacity instances before deleting the PTU deployment; STOPPED or zero capacity does not mean released. / 删除 PTU 部署前请先释放全部容量实例;STOPPED 或零容量不等于已释放。`,l.USAGE);if(!Array.isArray(o?.records)||o.records.length!==0||o.items!==0||o.total!==void 0&&o.total!==0||o.page!==void 0&&o.page!==1||o.pageCount!==void 0&&o.pageCount!==0&&o.pageCount!==1)throw new n(`Cannot confirm all capacity instances are released from the list response; deletion was not submitted. / 无法从列表响应确认全部容量实例已释放;未提交删除请求。`,l.USAGE);if(r?.operation_id){let t=await nt(e.client,i,r.operation_id),a=t.output??t.data;if(a?.operation_status===`PROCESSING`)throw new n(`A capacity operation is processing or queued. Wait for it to finish before deleting the deployment. / 存在执行中或排队的容量操作,请等待其结束后再删除部署。`,l.USAGE);if(a?.operation_status!==`SUCCEEDED`&&a?.operation_status!==`FAILED`)throw new n(`Cannot confirm the returned capacity operation has finished; deletion was not submitted. / 无法确认返回的容量操作已结束;未提交删除请求。`,l.USAGE)}}else if(a!==`STOPPED`&&a!==`FAILED`)throw new n(`Deployment ${i} must be STOPPED or FAILED before deletion (current: ${a||`unknown`}). / 部署 ${i} 删除前必须为 STOPPED 或 FAILED(当前:${a||`未知`})。`,l.USAGE,"Check the deployment status with `deploy get` before deletion. / 删除前请使用 `deploy get` 检查部署状态。")}let a=await je(e.client,i);t.quiet?D(i):O(a,`json`)}}),bx=S({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){O({action:`deploy.pause`,deployed_model:i},`json`);return}if(!r.skipPrecheck)try{let t=await Nt(e.client),r=Ye(t,i);if(r){let e=(r.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 Vn(e.client,i);t.quiet?D(i):O({deployed_model:i,action:`pause`,...a},`json`)}}),xx=S({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){O({action:`deploy.resume`,deployed_model:i},`json`);return}if(!r.skipPrecheck)try{let t=await Nt(e.client),r=Ye(t,i);if(r){let e=(r.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 Bn(e.client,i);t.quiet?D(i):O({deployed_model:i,action:`resume`,...a},`json`)}});const Sx={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)`}}},Cx={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)`}}},wx={cn:`modelstudio.cn-beijing.aliyuncs.com`,intl:`modelstudio.ap-southeast-1.aliyuncs.com`};function Tx(e){for(let[t,n]of Object.entries(g))if(e===n||e.startsWith(`${n}/`))return t;return`cn`}function Ex(e){let t=Tx(e);return wx[t]??wx.cn}function Dx(e,t,r){let i=t.workspaceId||e.workspaceId;if(!i)throw new n(`Missing workspace ID.
|
|
2838
|
+
Set via: --workspace-id flag, env: BAILIAN_WORKSPACE_ID, or config: ${r} config set workspace_id <id>`,l.USAGE);return i}function Ox(e,t){t.callerUacAccountId&&(e.CallerUacAccountId=t.callerUacAccountId),t.namespaceId&&(e.NamespaceId=t.namespaceId)}function kx(e,t,n){let r=ce(n),i=Ex(e);return{host:i,endpoint:`https://${i}${t}${r?`?${r}`:``}`,queryString:r,queryParams:n}}async function Ax(e){let{client:t,baseUrl:n,action:r,path:i,method:a,queryParams:o}=e,{host:s}=kx(n,i,o);return t.openApiQueryJson({host:s,path:i,action:r,version:`2026-02-10`,method:a,queryParams:o})}const jx=`/tokenplan/subscription/seat-detail`,Mx={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)`}},...Sx,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=未分配`}}};var Nx=S({description:{"en-US":`List Token Plan subscription seat details`,"zh-CN":`列出 Token Plan 订阅席位详情`},auth:`openapi`,usageArgs:`[flags]`,flags:Mx,exampleArgs:[``,`--page-size 20 --status NORMAL`,`--query-assigned true --seat-type standard`],async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=Px(n);if(t.dryRun){let{endpoint:t,queryParams:n}=kx(e.client.baseUrl,jx,i);O({endpoint:t,query:n},r);return}let a=await Ax({client:e.client,baseUrl:e.client.baseUrl,action:`GetSubscriptionSeatDetails`,path:jx,method:`GET`,queryParams:i}),o=a.Data?.Items??[];t.quiet||r===`text`?Fx(o,a.Data?.Total,a.Data?.PageNo,a.Data?.PageSize):O(a,r)}});function Px(e){let t={};if(e.pageNo!==void 0&&(t.PageNo=String(e.pageNo)),e.pageSize!==void 0&&(t.PageSize=String(e.pageSize)),Ox(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 Fx(e,t,n,r){if(e.length===0){D(`No seats found.`);return}let i=[k(`SeatId`,18),k(`Type`,10),k(`Status`,10),k(`Assigned`,12),k(`Account`,20)].join(` `);D(i),D(`-`.repeat(i.length));for(let t of e){let e=[k(t.SeatId??`-`,18),k(t.SpecType??`-`,10),k(t.Status??`-`,10),k(t.AssignedStatus??`-`,12),k(t.AccountName??t.AccountId??`-`,20)].join(` `);D(e)}t!==void 0&&(D(``),D(`Total: ${t}${n===void 0?``:` | Page: ${n}`}${r===void 0?``:` | PageSize: ${r}`}`))}const Ix=`/tokenplan/api-keys`,Lx={accountId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Target member account ID`,"zh-CN":`目标成员账号 ID`},required:!0},...Cx,description:{type:`string`,valueHint:`<text>`,description:{"en-US":`API key description`,"zh-CN":`API Key 描述`}},...Sx};var Rx=S({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:Lx,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=C(n.output),a=Dx(n,r,t.binName),o=zx(r,{accountId:r.accountId,workspaceId:a});if(n.dryRun){let{endpoint:t,queryParams:n}=kx(e.client.baseUrl,Ix,o);O({endpoint:t,query:n},i);return}let s=await Ax({client:e.client,baseUrl:e.client.baseUrl,action:`CreateTokenPlanKey`,path:Ix,method:`POST`,queryParams:o});n.quiet||i===`text`?Bx(s):O(s,i)}});function zx(e,t){let n={};return n.AccountId=t.accountId,n.WorkspaceId=t.workspaceId,e.description&&(n.Description=e.description),Ox(n,e),n}function Bx(e){let t=e.Data;if(!t){D(`API key created.`);return}D(`${k(`ApiKeyId`,14)} ${t.ApiKeyId??`-`}`),D(`${k(`MaskedApiKey`,14)} ${t.MaskedApiKey??`-`}`),t.Description&&D(`${k(`Description`,14)} ${t.Description}`),t.PlainApiKey&&(D(``),D(`PlainApiKey (shown once): ${t.PlainApiKey}`))}const Vx=`/tokenplan/subscription/seat-assignments`,Hx={...Cx,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(可重复)`}},...Sx,locale:{type:`string`,valueHint:`<locale>`,description:{"en-US":`Language: zh-CN or en-US`,"zh-CN":`语言:zh-CN 或 en-US`}}};var Ux=S({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:Hx,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=C(n.output),a=Wx(r,Dx(n,r,t.binName));if(n.dryRun){let{endpoint:t,queryParams:n}=kx(e.client.baseUrl,Vx,a);O({endpoint:t,query:n},i);return}let o=await Ax({client:e.client,baseUrl:e.client.baseUrl,action:`BatchAssignSeats`,path:Vx,method:`POST`,queryParams:a});n.quiet||i===`text`?D(`Seats assigned successfully.`):O(o,i)}});function Wx(e,t){let n={};return n.WorkspaceId=t,e.seatType&&(n.SeatType=e.seatType),Ox(n,e),e.locale&&(n.Locale=e.locale),e.accountId&&e.accountId.length>0&&(n.AccountIds=e.accountId),n}const Gx=`/tokenplan/organization/member-additions`,Kx={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`}},...Sx};var qx=S({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:Kx,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=C(t.output),i=Jx(n);if(t.dryRun){let{endpoint:t,queryParams:n}=kx(e.client.baseUrl,Gx,i);O({endpoint:t,query:n},r);return}let a=await Ax({client:e.client,baseUrl:e.client.baseUrl,action:`AddOrganizationMember`,path:Gx,method:`POST`,queryParams:i});t.quiet||r===`text`?Yx(a):O(a,r)}});function Jx(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),Ox(t,e),t}function Yx(e){let t=e.Data;if(!t){D(`Member added.`);return}D(`${k(`AccountId`,14)} ${t.AccountId??`-`}`),D(`${k(`SeatAssigned`,14)} ${String(t.SeatAssigned??`-`)}`)}const Xx=`zeldaEasy.broadscope-bailian.token-plan.detail`,Zx=`zeldaEasy.bailian-commerce.tokenPlan.queryTokenPlanEquityInfo`;function Qx(e,t){let n=qn(e)[t];return Array.isArray(n)?n:[]}function $x(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=Ch(i.totalQuota);s!==void 0&&(o.totalQuota=s);let c=Ch(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=Ch(i.instanceStartTime);l!==void 0&&(o.instanceStartTime=l);let u=Ch(i.instanceEndTime);u!==void 0&&(o.instanceEndTime=u),n.push(o)}return n}function eS(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 tS=S({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=C(t.output),i=n.type?{type:n.type}:{},a={queryTokenPlanEquityInfoRequest:{requestId:zr()}};if(t.dryRun){O({requests:[{api:Xx,data:i},{api:Zx,data:a}]},r);return}let[o,s]=await Promise.all([e.client.console(Xx,i),e.client.console(Zx,a)]),c=$x(Qx(o,`items`),Qx(s,`tokenPlanEquityInfos`));if(r===`json`){O({generatedAt:Date.now(),items:c},r);return}if(c.length===0){process.stdout.write(`No harness with entitlement quota found.
|
|
2839
|
+
`);return}Eh(`Token Plan Harness Quota`,c.map(eS),Date.now())}});function nS(e){return`version: "1"
|
|
2839
2840
|
|
|
2840
2841
|
providers:
|
|
2841
2842
|
bailian:
|
|
@@ -2862,18 +2863,18 @@ agents:
|
|
|
2862
2863
|
environment: dev
|
|
2863
2864
|
tools:
|
|
2864
2865
|
builtin: [bash, read, glob, grep]
|
|
2865
|
-
`}var
|
|
2866
|
+
`}var rS=S({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=C(t.output),a=r.agentName??`assistant`,o=r.file??`agents.yaml`;if(A(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;A(s)&&(e=!(await Ei(s,`utf8`)).includes(`agents.state.json`)),O({would_create:o,provider:`bailian`,agent:a,would_update_gitignore:e},i);return}let c=nS({agentName:a});if(await Ai(o,c,`utf8`),A(s)){let e=await Ei(s,`utf8`);e.includes(`agents.state.json`)||await Ai(s,e+`
|
|
2866
2867
|
# agents
|
|
2867
2868
|
agents.state.json
|
|
2868
2869
|
.openagentpack/versions/
|
|
2869
2870
|
.env
|
|
2870
|
-
`,`utf8`)}else await
|
|
2871
|
+
`,`utf8`)}else await Ai(s,`# agents
|
|
2871
2872
|
agents.state.json
|
|
2872
2873
|
.openagentpack/versions/
|
|
2873
2874
|
.env
|
|
2874
|
-
`,`utf8`);i===`json`?O({created:o,provider:`bailian`,agent:a},i):(D(`Created ${M(o)}`),D("Credentials: run `bl auth login --api-key <key> --base-url <url>`, or set DASHSCOPE_API_KEY / BAILIAN_BASE_URL."),D("Next: edit agents.yaml, then run `bl managed-agent plan`."))}});const
|
|
2875
|
+
`,`utf8`);i===`json`?O({created:o,provider:`bailian`,agent:a},i):(D(`Created ${M(o)}`),D("Credentials: run `bl auth login --api-key <key> --base-url <url>`, or set DASHSCOPE_API_KEY / BAILIAN_BASE_URL."),D("Next: edit agents.yaml, then run `bl managed-agent plan`."))}});const iS=`/api/v1/agentstudio`,aS=[.../* @__PURE__ */ new Set([...Object.values(Fi).flatMap(e=>e.map(e=>e.key)),`BAILIAN_API_KEY`,`BAILIAN_BASE_URL`,`CLAUDE_API_KEY`,`QODER_API_KEY`])],oS={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.`},sS={"en-US":`bl managed-agent supports the Bailian provider only; configurations containing other providers are rejected.`,"zh-CN":`bl managed-agent 仅支持百炼 Provider;包含其他 Provider 的配置会被拒绝。`},G=[sS,{"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,并从环境中清除;不会持久保留在进程环境变量中。`}],cS=[sS,{"en-US":`Runs fully offline against local files: no login or provider credentials required.`,"zh-CN":`完全离线处理本地文件:无需登录或提供 Provider 凭证。`}];function lS(){Vi();for(let e of aS)process.env[e]===void 0&&(process.env[e]=``)}function uS(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(iS)?e:`${e}${iS}`}`workspace_id`in i&&!i.workspace_id&&t.settings.workspaceId&&(i.workspace_id=t.settings.workspaceId)}function dS(){for(let e of aS)delete process.env[e]}function fS(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 pS(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,oS[r]??`Provide credentials for provider '${r}'.`)}}function mS(e,t){let n=M(e);return{projectId:t??ui(di(n))}}async function hS(e,t,n){let r=M(e),i=new Ii({configPath:r,statePath:t}).getStatePath(mS(r,n));return Ri.load(i)}let gS=!1;function _S(e){if(gS)return;let t=Pi.setDefaultFetch;typeof t==`function`&&(t(Te(e)),gS=!0)}const vS=`bailian`;async function yS(e,t,n={}){lS();let r=await Ea(t,n);return fS(r.config.providers),uS(r.config.providers,e,{overrideBaseUrl:n.overrideBailianBaseUrl}),dS(),bS(r.config.providers),(n.credentials??`all`)!==`none`&&pS(r.config.providers),r}async function K(e,t,n={}){_S(e);let{config:r,configPath:i,projectName:a}=await yS(e,t,n),o=await hS(i,n.statePath,a);return{...Ui({projectName:a,config:r,state:o,configPath:i,providers:r.providers}),configPath:i}}function bS(e){let t=Object.keys(e).filter(e=>e!==vS);if(t.length>0){let e=t.join(`, `);throw new n(`bl managed-agent only supports provider '${vS}'; remove unsupported providers: ${e}. / bl managed-agent 仅支持 Provider '${vS}';请移除不支持的 Provider:${e}。`,l.USAGE)}if(!(`bailian`in e))throw new n(`bl managed-agent requires a '${vS}' provider configuration. / bl managed-agent 需要配置 Provider '${vS}'。`,l.USAGE)}function xS(e){let t=e;return typeof t.statusCode==`number`&&typeof t.responseBody==`string`}function SS(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`)return t}catch{}return{message:e.trim()||void 0}}function CS(e){return/did not complete within the timeout/i.test(e.message)}function wS(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 TS(e,t,r){if(e instanceof n)return new n(e.message,e.exitCode,t,{api:e.api,rawResponse:e.rawResponse,cause:e.cause});if(e instanceof Error)return new n(e.message,l.GENERAL,t,{cause:e});let i=typeof e==`string`&&e.trim()?e:r;return new n(i,l.GENERAL,t)}async function q(e){try{return await e()}catch(e){throw e instanceof n?e:e instanceof zi?CS(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&&xS(e)?Lt(e.statusCode,SS(e.responseBody)):e instanceof TypeError&&e.message===`fetch failed`?e:e instanceof Error?new n(e.message,l.GENERAL):e}}var ES=S({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:cS,async run(e){let{settings:t,flags:r}=e,i=C(t.output),a=r.file??`agents.yaml`,o=await q(async()=>{let{config:t}=await yS(e,a,{credentials:`none`});return za(t)}),s=o.filter(e=>e.severity===`error`).length;if(i===`json`)O({valid:s===0,diagnostics:o},i);else{for(let e of o){let t=e.resource?` (${e.resource.type}.${e.resource.name})`:``;D(`[${e.severity}] ${e.message}${t}`)}s===0&&D(`Configuration is valid.`)}if(s>0)throw new n(wS(o,`Validation failed with ${s} error(s).`),l.GENERAL)}});function DS(e){return`${e.type}.${e.name} (${e.provider})`}async function J(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 OS(e){process.stderr.write(`${e.message}\n`)}var kS=S({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:[...G,{"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=C(t.output),a=r.file??`agents.yaml`,o=!!r.noRefresh||t.dryRun,s=(await q(()=>J(async()=>{let t=await K(e,a,{credentials:o?`none`:`all`});return Ca(t,{provider:`bailian`,refresh:!o,quiet:i===`json`,onFeedback:i===`json`?void 0:OS})}))).plan,c=s.diagnostics.some(e=>e.severity===`error`),u=wS(s.diagnostics,`Plan contains errors.`);if(i===`json`){if(O(s,i),c)throw new n(u,l.GENERAL);return}for(let e of s.diagnostics)D(`[${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){D(`No changes. Infrastructure is up-to-date.`),r.refreshOnly&&D(`Refresh-only mode: no remote mutations were performed.`);return}D(`
|
|
2875
2876
|
Planned actions:
|
|
2876
|
-
`);for(let e of d)D(` + ${Tx(e.address)}`);for(let e of f)D(` ~ ${Tx(e.address)}`),e.reason&&D(` ${e.reason}`);for(let e of p)D(` - ${Tx(e.address)}`);D(`\nPlan: ${d.length} to create, ${f.length} to update, ${p.length} to destroy.`),r.refreshOnly&&D(`Refresh-only mode: no remote mutations will be performed.`)}}),Ox=S({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:G,async run(e){let{settings:t,flags:r}=e,i=C(t.output),a=r.file??`agents.yaml`;if(t.dryRun){O({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 q(()=>J(async()=>{let t=await K(e,a);return ca(t,{provider:`bailian`,refresh:!r.noRefresh,quiet:!0,onFeedback:Ex})})),s=o.plan,c=e=>{i===`json`?process.stderr.write(`${e}\n`):D(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(Sx(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`?O({succeeded:0,failed:0,skipped:0,results:[]},i):D(`No changes. Infrastructure is up-to-date.`);return}for(let e of d)c(` ${e.action===`create`?`+`:e.action===`update`?`~`:`-`} ${Tx(e.address)}`);let f=await q(()=>J(()=>Ii(o,{onFeedback:Ex,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`?O({succeeded:p,failed:h,skipped:g,results:f.results},i):D(`\nApply finished: ${p} succeeded, ${h} failed, ${g} skipped.`),h>0){let e=m.find(e=>e.error);throw new n(e?.error??`Apply failed.`,l.GENERAL)}}}),kx=S({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:G,async run(e){let{settings:t,flags:r}=e,i=C(t.output),a=r.file??`agents.yaml`;if(t.dryRun){O({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 q(()=>J(async()=>{let t=await K(e,a),n=sa(t);return{...n,resources:n.resources.filter(e=>e.address.provider===`bailian`),defaultMemoryStores:(n.defaultMemoryStores??[]).filter(e=>e.provider===`bailian`)}})),s=o.resources;if(s.length===0){i===`json`?O({destroyed:0,total:0},i):D(`No resources in state. Nothing to destroy.`);return}for(let e of s){let t=` - ${Tx(e.address)} [${e.remote_id}]`;i===`json`?process.stderr.write(`${t}\n`):D(t)}let c=await q(()=>J(()=>Ni(o,{cascade:r.cascade,onCascadeRequired:async()=>!!r.cascade,onResourceResult:e=>{let t=Tx(e.resource.address);process.stderr.write(` ${e.status===`success`?`✓`:`✗`} ${t}\n`)}})));if(i===`json`)O({destroyed:c.destroyed,total:c.resources.length},i);else{let e=c.partial?`Destroy incomplete`:`Destroy complete`;D(`\n${e}. ${c.destroyed}/${c.resources.length} resources removed.`)}if(c.partial){let e=c.results.find(e=>e.status!==`success`);throw new n(e?.error||`Destroy incomplete: ${c.destroyed}/${c.resources.length} resources removed.`,l.GENERAL)}}});const Ax=`@openagentpack/playground`,jx=Ta(Dr),Mx=/running at http:\/\/localhost:(\d+)/i;async function Nx(e){Fx();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=Sr(`sha256`).update(r).digest(`hex`).slice(0,16),a=await Ix(),o=await Hx(t);if(o){if(o.projectId===i&&(a.version===void 0||o.version===a.version)){D(`Workbench already running at http://localhost:${t} (pid ${o.pid}).`),await Wx(t,e.surface,e.agent,e.open);return}if(!await Ux(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=Bx(e,t,r);a.fetched&&D(`Fetching ${Ax} (first run may take a moment)...`);let c=Or(a.command,a.args,{env:s,stdio:[`inherit`,`pipe`,`inherit`]}),u=qx(c);try{let r=await Vx(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);D(`Workbench ready at http://localhost:${r}`),await Wx(r,e.surface,e.agent,e.open);let a=await Jx(c);if(a!==0)throw new n(`Workbench exited with code ${a}.`,l.GENERAL)}finally{u()}}function Px(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 Fx(){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 Ix(){let e=process.env.BAILIAN_MANAGED_AGENT_PLAYGROUND_BIN?.trim()||process.env.AGENTS_PLAYGROUND_BIN?.trim();if(e){if(!A(e))throw new n(`Configured Workbench binary does not exist: ${e}`,l.USAGE);return{command:process.execPath,args:[e],fetched:!1}}let t=process.env.BAILIAN_MANAGED_AGENT_PLAYGROUND_VERSION?.trim()||`latest`,{stdout:r}=await jx(`npm`,[`view`,`${Ax}@${t}`,`version`,`--json`,`--prefer-online`,`--fetch-retries=0`,`--fetch-timeout=10000`],{timeout:15e3,maxBuffer:1048576}),i;try{i=JSON.parse(r)}catch{i=void 0}if(typeof i!=`string`||!/^\d+\.\d+\.\d+(?:-[\da-zA-Z.-]+)?(?:\+[\da-zA-Z.-]+)?$/.test(i))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 a=Rx();if(a?.version===i)return a;let o=zx(process.cwd());return o&&Lx(M(Xr(o),`../../package.json`))===i?{command:process.execPath,args:[o],version:i,fetched:!1}:{command:`npx`,args:[`-y`,`${Ax}@${i}`],version:i,fetched:!0}}function Lx(e){try{return JSON.parse(Wr(e,`utf8`)).version}catch{return}}function Rx(){try{let t=e(import.meta.url).resolve(`${Ax}/package.json`),n=JSON.parse(Wr(t,`utf8`)),r=typeof n.bin==`string`?n.bin:n.bin?.[`agents-playground`];if(!r)return;let i=M(Xr(t),r);return A(i)?{command:process.execPath,args:[i],version:n.version,fetched:!1}:void 0}catch{return}}function zx(e){let t=e;for(let e=0;e<10;e+=1){let e=M(t,`packages/playground/dist/bin/playground.js`);if(A(e))return e;let n=Xr(t);if(n===t)break;t=n}}function Bx(e,t,n){let r=e.client.exportApiCredential(),i={...process.env,PORT:String(t),AGENTS_PLAYGROUND_TOKEN:Cr(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 Vx(e,t,n,r){let i=t,a=``;e.stdout?.on(`data`,e=>{process.stdout.write(e),a+=e.toString();let t=a.match(Mx);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 Hx(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 Ux(e,t){D(`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 Hx(t))return!0;return!1}async function Wx(e,t,n,r){if(!r)return;let i=t===`workbench`?{url:`http://localhost:${e}`}:await Gx(e,n);i.warning&&D(`Warning: ${i.warning}`),Kx(i.url)}async function Gx(e,t){let n=`http://localhost:${e}`;try{let e=await fetch(`${n}/api/project`,{signal:AbortSignal.timeout(3e3)});return e.ok?Px(n,await e.json(),t):{url:n}}catch{return{url:n}}}function Kx(e){let t=process.platform===`darwin`?`open`:process.platform===`win32`?`start`:`xdg-open`,n=process.platform===`win32`?[``,e]:[e];try{Or(t,n,{stdio:`ignore`,detached:!0,shell:process.platform===`win32`}).unref()}catch{D(`Could not open a browser automatically. Visit ${e}`)}}function qx(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 Jx(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 Yx={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 时需要指定)`}}},Xx=[...G,{"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。`}],Zx=S({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:Yx,exampleArgs:[``,`--agent assistant`,`--file agents.yaml --no-open`],notes:Xx,async run(e){let t=e.flags.file??`agents.yaml`,n=e.flags.port??4848;if(e.settings.dryRun){O({would_launch:`playground`,config_file:t,agent:e.flags.agent,port:n,open_browser:!e.flags.noOpen},C(e.settings.output));return}await Nx({file:t,agent:e.flags.agent,port:n,open:!e.flags.noOpen,surface:`preview`,client:e.client,settings:e.settings})}}),Qx={project:{type:`string`,valueHint:`<directory>`,description:{"en-US":`Directory project root (default: current directory)`,"zh-CN":`目录项目根路径(默认:当前目录)`}}},$x=S({description:{"en-US":`Create a directory project or convert the local agents.yaml`,"zh-CN":`创建目录项目,或转换当前 agents.yaml`},auth:`none`,usageArgs:`[--project <directory>]`,flags:{project:{...Qx.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){O({would_initialize_project:t},C(e.settings.output));return}let n=await ka({projectRoot:t});O(n,C(e.settings.output))}}),eS=S({description:{"en-US":`Validate a directory Agent project`,"zh-CN":`校验目录式 Agent 项目`},auth:`none`,usageArgs:`[--project <directory>]`,flags:Qx,exampleArgs:[``,`--project ./my-agent`],async run(e){let t=await Na(e.flags.project??`.`),r=C(e.settings.output);if(r===`json`)O(fS(t),r);else{for(let e of[...t.diagnostics,...t.warnings])D(`${e.severity}: ${e.code}: ${e.message}`);t.diagnostics.some(e=>e.severity===`error`)||D(`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)}}),tS=S({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:Qx,exampleArgs:[``,`--dry-run`,`--project ./my-agent`],async validate(e){await q(async()=>{let t=await Ma(e.project??`.`);if(!(await pi(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 ja(t),i=C(e.settings.output);if(e.settings.dryRun){O(fS(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);let a=await Ea({projectRoot:t,baseRevision:r.project_revision});O({manifest:a.manifest,organization_moves:r.organization_moves},i)}}),nS=S({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:{...Qx,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:G,async run(e){hx(e);let t=e.flags.project??`.`,n=async(t,n)=>await _x(e,t,{environment:n?.environment,overrideBailianBaseUrl:!0}),r=await q(()=>J(()=>Aa(t,{provider:`bailian`,refresh:!e.flags.noRefresh,quiet:!0,onFeedback:Ex,resolveBuild:n}))),i=r.planned.plan.actions.filter(e=>e.action!==`no-op`);if(e.settings.dryRun){O({project_revision:r.project_revision,build_manifest:r.build_manifest,plan:r.planned.plan},C(e.settings.output));return}for(let e of i){let t=e.action===`create`?`+`:e.action===`update`?`~`:`-`;D(`${t} ${Tx(e.address)}`)}let a=await q(()=>J(()=>Oa({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:Ex,resolveBuild:n})));O(a,C(e.settings.output))}}),rS=S({description:{"en-US":`Launch the directory project Workbench`,"zh-CN":`启动目录项目 Workbench`},auth:`apiKey`,usageArgs:`[--project <directory>] [--port <n>] [--no-open]`,flags:{...Qx,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:G,async run(e){let t=e.flags.project??`.`;if(e.settings.dryRun){O({would_launch:`workbench`,project_root:t,port:e.flags.port??4848},C(e.settings.output));return}await Nx({project:t,port:e.flags.port??4848,open:!e.flags.noOpen,surface:`workbench`,client:e.client,settings:e.settings})}}),iS=oS(!0),aS=oS(!1);function oS(e){return S({description:e?{"en-US":`Enable directory project versions`,"zh-CN":`启用目录项目版本管理`}:{"en-US":`Disable directory project versions`,"zh-CN":`关闭目录项目版本管理`},auth:`none`,usageArgs:`[--project <directory>]`,flags:Qx,exampleArgs:[``,`--project ./my-agent`],async run(t){let n=Da(t.flags.project??`.`);if(t.settings.dryRun){O({would_set_enabled:e,status:await n.status()},C(t.settings.output));return}let r=e?await n.enable(`Enable project versions`):await n.disable();O(r,C(t.settings.output))}})}const sS=S({description:{"en-US":`Show directory project version status`,"zh-CN":`显示目录项目版本状态`},auth:`none`,usageArgs:`[--project <directory>]`,flags:Qx,exampleArgs:[``,`--project ./my-agent --output json`],async run(e){O(await Da(e.flags.project??`.`).status(),C(e.settings.output))}}),cS=S({description:{"en-US":`List directory project versions`,"zh-CN":`列出目录项目版本`},auth:`none`,usageArgs:`[--project <directory>] [--limit <n>] [--cursor <cursor>]`,flags:{...Qx,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){O(await Da(e.flags.project??`.`).listVersions({limit:e.flags.limit,cursor:e.flags.cursor}),C(e.settings.output))}}),lS={versionId:{type:`string`,valueHint:`<full-version>`,required:!0,description:{"en-US":`Full project version ID`,"zh-CN":`完整的项目版本 ID`}}},uS=S({description:{"en-US":`Preview a directory project version`,"zh-CN":`预览目录项目历史版本`},auth:`none`,usageArgs:`--version-id <full-version> [--project <directory>]`,flags:{...Qx,...lS},exampleArgs:[`--version-id <full-version>`],async run(e){O(await Da(e.flags.project??`.`).previewVersion(e.flags.versionId),C(e.settings.output))}}),dS=S({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:{...Qx,...lS},exampleArgs:[`--version-id <full-version>`,`--version-id <full-version> --yes`],async run(e){let t=Da(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){O({would_restore:e.flags.versionId,preview:r},C(e.settings.output));return}let i=await t.restoreVersion(e.flags.versionId,{headVersion:r.base_head_version,projectRevision:r.base_project_revision});O(i,C(e.settings.output))}});function fS(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 pS=S({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:ox,async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=n.file??`agents.yaml`,a=await q(()=>J(async()=>(await K(e,i,{credentials:`none`})).state.listResources()));if(r===`json`){O({resources:a},r);return}if(a.length===0){D(`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 cr(o,s))D(e);D(`\nTotal: ${a.length}`)}}),mS=S({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:ox,async run(e){let{settings:t,flags:r}=e,i=C(t.output),a=r.file??`agents.yaml`,o=await q(()=>J(async()=>{let t=await K(e,a,{credentials:`none`}),n=oa(r.address,{requireProvider:!1});return t.state.findResource(n)}));if(!o)throw new n(`Resource not found: ${r.address}`,l.GENERAL);i===`json`?O(o,i):D(JSON.stringify(o,null,2))}}),hS=S({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:ox,async run(e){let{settings:t,flags:r}=e,i=C(t.output),a=r.file??`agents.yaml`;if(t.dryRun){await q(async()=>{oa(r.address,{requireProvider:!1})}),O({would_remove:r.address,config_file:a},i);return}await q(()=>J(async()=>{let t=await K(e,a,{credentials:`none`}),i=oa(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`?O({removed:r.address},i):D(o)}});const gS={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 _S(e){let t=oa(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 vS=S({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:gS,exampleArgs:[`--address bailian.agent.assistant --remote-id agent-abc123`],notes:G,async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=n.file??`agents.yaml`;if(t.dryRun){await q(async()=>{_S(n.address)}),O({would_import:n.address,remote_id:n.remoteId,resource_version:n.resourceVersion,config_file:i},r);return}await q(()=>J(async()=>{let t=_S(n.address),r=await K(e,i);await Ki(r,t,n.remoteId,{resourceVersion:n.resourceVersion})})),r===`json`?O({imported:n.address,remote_id:n.remoteId},r):D(`Imported ${n.address} (remote_id: ${n.remoteId}) into state.`)}});function yS(e){return e.type!==`thinking`&&(e.type!==`message`||e.role!==`user`)}function bS(e,t){t||process.stderr.write(`\n[session ${e}]\n`)}function xS(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 SS(e,t){if(e===`failed`)throw new n(t??`Session failed.`,l.GENERAL)}async function CS(e,t,n={}){let r=[],i,a;for await(let n of e)if(t?r.push(n):wS(n),n.type===`error`&&n.content?.trim()&&(a=n.content),n.type===`status`&&Ji(n.status)){i=n.status,bS(n.status??``,t);break}t&&process.stdout.write(`${JSON.stringify({...n,events:Pa(r)},null,2)}\n`),SS(i,a)}function wS(e){if(yS(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(`
|
|
2877
|
+
`);for(let e of d)D(` + ${DS(e.address)}`);for(let e of f)D(` ~ ${DS(e.address)}`),e.reason&&D(` ${e.reason}`);for(let e of p)D(` - ${DS(e.address)}`);D(`\nPlan: ${d.length} to create, ${f.length} to update, ${p.length} to destroy.`),r.refreshOnly&&D(`Refresh-only mode: no remote mutations will be performed.`)}}),AS=S({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:G,async run(e){let{settings:t,flags:r}=e,i=C(t.output),a=r.file??`agents.yaml`;if(t.dryRun){O({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 q(()=>J(async()=>{let t=await K(e,a);return Ca(t,{provider:`bailian`,refresh:!r.noRefresh,quiet:!0,onFeedback:OS})})),s=o.plan,c=e=>{i===`json`?process.stderr.write(`${e}\n`):D(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(wS(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`?O({succeeded:0,failed:0,skipped:0,results:[]},i):D(`No changes. Infrastructure is up-to-date.`);return}for(let e of d)c(` ${e.action===`create`?`+`:e.action===`update`?`~`:`-`} ${DS(e.address)}`);let f=await q(()=>J(()=>Zi(o,{onFeedback:OS,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`?O({succeeded:p,failed:h,skipped:g,results:f.results},i):D(`\nApply finished: ${p} succeeded, ${h} failed, ${g} skipped.`),h>0){let e=m.find(e=>e.error);throw new n(e?.error??`Apply failed.`,l.GENERAL)}}}),jS=S({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:G,async run(e){let{settings:t,flags:r}=e,i=C(t.output),a=r.file??`agents.yaml`;if(t.dryRun){O({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 q(()=>J(async()=>{let t=await K(e,a),n=Sa(t);return{...n,resources:n.resources.filter(e=>e.address.provider===`bailian`),defaultMemoryStores:(n.defaultMemoryStores??[]).filter(e=>e.provider===`bailian`)}})),s=o.resources;if(s.length===0){i===`json`?O({destroyed:0,total:0},i):D(`No resources in state. Nothing to destroy.`);return}for(let e of s){let t=` - ${DS(e.address)} [${e.remote_id}]`;i===`json`?process.stderr.write(`${t}\n`):D(t)}let c=await q(()=>J(()=>Ji(o,{cascade:r.cascade,onCascadeRequired:async()=>!!r.cascade,onResourceResult:e=>{let t=DS(e.resource.address);process.stderr.write(` ${e.status===`success`?`✓`:`✗`} ${t}\n`)}})));if(i===`json`)O({destroyed:c.destroyed,total:c.resources.length},i);else{let e=c.partial?`Destroy incomplete`:`Destroy complete`;D(`\n${e}. ${c.destroyed}/${c.resources.length} resources removed.`)}if(c.partial){let e=c.results.find(e=>e.status!==`success`);throw new n(e?.error||`Destroy incomplete: ${c.destroyed}/${c.resources.length} resources removed.`,l.GENERAL)}}});const MS=`@openagentpack/playground`,NS=Ba(Hr),PS=/running at http:\/\/localhost:(\d+)/i;async function FS(e){LS();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=Lr(`sha256`).update(r).digest(`hex`).slice(0,16),a=await RS(),o=await WS(t);if(o){if(o.projectId===i&&(a.version===void 0||o.version===a.version)){D(`Workbench already running at http://localhost:${t} (pid ${o.pid}).`),await KS(t,e.surface,e.agent,e.open);return}if(!await GS(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=HS(e,t,r);a.fetched&&D(`Fetching ${MS} (first run may take a moment)...`);let c=Ur(a.command,a.args,{env:s,stdio:[`inherit`,`pipe`,`inherit`]}),u=YS(c);try{let r=await US(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);D(`Workbench ready at http://localhost:${r}`),await KS(r,e.surface,e.agent,e.open);let a=await XS(c);if(a!==0)throw new n(`Workbench exited with code ${a}.`,l.GENERAL)}finally{u()}}function IS(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 LS(){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 RS(){let e=process.env.BAILIAN_MANAGED_AGENT_PLAYGROUND_BIN?.trim()||process.env.AGENTS_PLAYGROUND_BIN?.trim();if(e){if(!A(e))throw new n(`Configured Workbench binary does not exist: ${e}`,l.USAGE);return{command:process.execPath,args:[e],fetched:!1}}let t=process.env.BAILIAN_MANAGED_AGENT_PLAYGROUND_VERSION?.trim()||`latest`,{stdout:r}=await NS(`npm`,[`view`,`${MS}@${t}`,`version`,`--json`,`--prefer-online`,`--fetch-retries=0`,`--fetch-timeout=10000`],{timeout:15e3,maxBuffer:1048576}),i;try{i=JSON.parse(r)}catch{i=void 0}if(typeof i!=`string`||!/^\d+\.\d+\.\d+(?:-[\da-zA-Z.-]+)?(?:\+[\da-zA-Z.-]+)?$/.test(i))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 a=BS();if(a?.version===i)return a;let o=VS(process.cwd());return o&&zS(M(di(o),`../../package.json`))===i?{command:process.execPath,args:[o],version:i,fetched:!1}:{command:`npx`,args:[`-y`,`${MS}@${i}`],version:i,fetched:!0}}function zS(e){try{return JSON.parse(ai(e,`utf8`)).version}catch{return}}function BS(){try{let t=e(import.meta.url).resolve(`${MS}/package.json`),n=JSON.parse(ai(t,`utf8`)),r=typeof n.bin==`string`?n.bin:n.bin?.[`agents-playground`];if(!r)return;let i=M(di(t),r);return A(i)?{command:process.execPath,args:[i],version:n.version,fetched:!1}:void 0}catch{return}}function VS(e){let t=e;for(let e=0;e<10;e+=1){let e=M(t,`packages/playground/dist/bin/playground.js`);if(A(e))return e;let n=di(t);if(n===t)break;t=n}}function HS(e,t,n){let r=e.client.exportApiCredential(),i={...process.env,PORT:String(t),AGENTS_PLAYGROUND_TOKEN:Rr(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 US(e,t,n,r){let i=t,a=``;e.stdout?.on(`data`,e=>{process.stdout.write(e),a+=e.toString();let t=a.match(PS);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 WS(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 GS(e,t){D(`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 WS(t))return!0;return!1}async function KS(e,t,n,r){if(!r)return;let i=t===`workbench`?{url:`http://localhost:${e}`}:await qS(e,n);i.warning&&D(`Warning: ${i.warning}`),JS(i.url)}async function qS(e,t){let n=`http://localhost:${e}`;try{let e=await fetch(`${n}/api/project`,{signal:AbortSignal.timeout(3e3)});return e.ok?IS(n,await e.json(),t):{url:n}}catch{return{url:n}}}function JS(e){let t=process.platform===`darwin`?`open`:process.platform===`win32`?`start`:`xdg-open`,n=process.platform===`win32`?[``,e]:[e];try{Ur(t,n,{stdio:`ignore`,detached:!0,shell:process.platform===`win32`}).unref()}catch{D(`Could not open a browser automatically. Visit ${e}`)}}function YS(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 XS(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 ZS={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 时需要指定)`}}},QS=[...G,{"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。`}],$S=S({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:ZS,exampleArgs:[``,`--agent assistant`,`--file agents.yaml --no-open`],notes:QS,async run(e){let t=e.flags.file??`agents.yaml`,n=e.flags.port??4848;if(e.settings.dryRun){O({would_launch:`playground`,config_file:t,agent:e.flags.agent,port:n,open_browser:!e.flags.noOpen},C(e.settings.output));return}await FS({file:t,agent:e.flags.agent,port:n,open:!e.flags.noOpen,surface:`preview`,client:e.client,settings:e.settings})}}),eC={project:{type:`string`,valueHint:`<directory>`,description:{"en-US":`Directory project root (default: current directory)`,"zh-CN":`目录项目根路径(默认:当前目录)`}}},tC=S({description:{"en-US":`Create a directory project or convert the local agents.yaml`,"zh-CN":`创建目录项目,或转换当前 agents.yaml`},auth:`none`,usageArgs:`[--project <directory>]`,flags:{project:{...eC.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){O({would_initialize_project:t},C(e.settings.output));return}let n=await Wa({projectRoot:t});O(n,C(e.settings.output))}}),nC=S({description:{"en-US":`Validate a directory Agent project`,"zh-CN":`校验目录式 Agent 项目`},auth:`none`,usageArgs:`[--project <directory>]`,flags:eC,exampleArgs:[``,`--project ./my-agent`],async run(e){let t=await Ja(e.flags.project??`.`),r=C(e.settings.output);if(r===`json`)O(mC(t),r);else{for(let e of[...t.diagnostics,...t.warnings])D(`${e.severity}: ${e.code}: ${e.message}`);t.diagnostics.some(e=>e.severity===`error`)||D(`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)}}),rC=S({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:eC,exampleArgs:[``,`--dry-run`,`--project ./my-agent`],async validate(e){await q(async()=>{let t=await qa(e.project??`.`);if(!(await Oi(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 Ka(t),i=C(e.settings.output);if(e.settings.dryRun){O(mC(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);let a=await Va({projectRoot:t,baseRevision:r.project_revision});O({manifest:a.manifest,organization_moves:r.organization_moves},i)}}),iC=S({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:{...eC,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:G,async run(e){_S(e);let t=e.flags.project??`.`,n=async(t,n)=>await yS(e,t,{environment:n?.environment,overrideBailianBaseUrl:!0}),r=await q(()=>J(()=>Ga(t,{provider:`bailian`,refresh:!e.flags.noRefresh,quiet:!0,onFeedback:OS,resolveBuild:n}))),i=r.planned.plan.actions.filter(e=>e.action!==`no-op`);if(e.settings.dryRun){O({project_revision:r.project_revision,build_manifest:r.build_manifest,plan:r.planned.plan},C(e.settings.output));return}for(let e of i){let t=e.action===`create`?`+`:e.action===`update`?`~`:`-`;D(`${t} ${DS(e.address)}`)}let a=await q(()=>J(()=>Ua({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:OS,resolveBuild:n})));O(a,C(e.settings.output))}}),aC=S({description:{"en-US":`Launch the directory project Workbench`,"zh-CN":`启动目录项目 Workbench`},auth:`apiKey`,usageArgs:`[--project <directory>] [--port <n>] [--no-open]`,flags:{...eC,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:G,async run(e){let t=e.flags.project??`.`;if(e.settings.dryRun){O({would_launch:`workbench`,project_root:t,port:e.flags.port??4848},C(e.settings.output));return}await FS({project:t,port:e.flags.port??4848,open:!e.flags.noOpen,surface:`workbench`,client:e.client,settings:e.settings})}}),oC=cC(!0),sC=cC(!1);function cC(e){return S({description:e?{"en-US":`Enable directory project versions`,"zh-CN":`启用目录项目版本管理`}:{"en-US":`Disable directory project versions`,"zh-CN":`关闭目录项目版本管理`},auth:`none`,usageArgs:`[--project <directory>]`,flags:eC,exampleArgs:[``,`--project ./my-agent`],async run(t){let n=Ha(t.flags.project??`.`);if(t.settings.dryRun){O({would_set_enabled:e,status:await n.status()},C(t.settings.output));return}let r=e?await n.enable(`Enable project versions`):await n.disable();O(r,C(t.settings.output))}})}const lC=S({description:{"en-US":`Show directory project version status`,"zh-CN":`显示目录项目版本状态`},auth:`none`,usageArgs:`[--project <directory>]`,flags:eC,exampleArgs:[``,`--project ./my-agent --output json`],async run(e){O(await Ha(e.flags.project??`.`).status(),C(e.settings.output))}}),uC=S({description:{"en-US":`List directory project versions`,"zh-CN":`列出目录项目版本`},auth:`none`,usageArgs:`[--project <directory>] [--limit <n>] [--cursor <cursor>]`,flags:{...eC,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){O(await Ha(e.flags.project??`.`).listVersions({limit:e.flags.limit,cursor:e.flags.cursor}),C(e.settings.output))}}),dC={versionId:{type:`string`,valueHint:`<full-version>`,required:!0,description:{"en-US":`Full project version ID`,"zh-CN":`完整的项目版本 ID`}}},fC=S({description:{"en-US":`Preview a directory project version`,"zh-CN":`预览目录项目历史版本`},auth:`none`,usageArgs:`--version-id <full-version> [--project <directory>]`,flags:{...eC,...dC},exampleArgs:[`--version-id <full-version>`],async run(e){O(await Ha(e.flags.project??`.`).previewVersion(e.flags.versionId),C(e.settings.output))}}),pC=S({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:{...eC,...dC},exampleArgs:[`--version-id <full-version>`,`--version-id <full-version> --yes`],async run(e){let t=Ha(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){O({would_restore:e.flags.versionId,preview:r},C(e.settings.output));return}let i=await t.restoreVersion(e.flags.versionId,{headVersion:r.base_head_version,projectRevision:r.base_project_revision});O(i,C(e.settings.output))}});function mC(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 hC=S({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:cS,async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=n.file??`agents.yaml`,a=await q(()=>J(async()=>(await K(e,i,{credentials:`none`})).state.listResources()));if(r===`json`){O({resources:a},r);return}if(a.length===0){D(`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 Sr(o,s))D(e);D(`\nTotal: ${a.length}`)}}),gC=S({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:cS,async run(e){let{settings:t,flags:r}=e,i=C(t.output),a=r.file??`agents.yaml`,o=await q(()=>J(async()=>{let t=await K(e,a,{credentials:`none`}),n=xa(r.address,{requireProvider:!1});return t.state.findResource(n)}));if(!o)throw new n(`Resource not found: ${r.address}`,l.GENERAL);i===`json`?O(o,i):D(JSON.stringify(o,null,2))}}),_C=S({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:cS,async run(e){let{settings:t,flags:r}=e,i=C(t.output),a=r.file??`agents.yaml`;if(t.dryRun){await q(async()=>{xa(r.address,{requireProvider:!1})}),O({would_remove:r.address,config_file:a},i);return}await q(()=>J(async()=>{let t=await K(e,a,{credentials:`none`}),i=xa(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`?O({removed:r.address},i):D(o)}});const vC={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 yC(e){let t=xa(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 bC=S({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:vC,exampleArgs:[`--address bailian.agent.assistant --remote-id agent-abc123`],notes:G,async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=n.file??`agents.yaml`;if(t.dryRun){await q(async()=>{yC(n.address)}),O({would_import:n.address,remote_id:n.remoteId,resource_version:n.resourceVersion,config_file:i},r);return}await q(()=>J(async()=>{let t=yC(n.address),r=await K(e,i);await sa(r,t,n.remoteId,{resourceVersion:n.resourceVersion})})),r===`json`?O({imported:n.address,remote_id:n.remoteId},r):D(`Imported ${n.address} (remote_id: ${n.remoteId}) into state.`)}});function xC(e){return e.type!==`thinking`&&(e.type!==`message`||e.role!==`user`)}function SC(e,t){t||process.stderr.write(`\n[session ${e}]\n`)}function CC(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 wC(e,t){if(e===`failed`)throw new n(t??`Session failed.`,l.GENERAL)}async function TC(e,t,n={}){let r=[],i,a;for await(let n of e)if(t?r.push(n):EC(n),n.type===`error`&&n.content?.trim()&&(a=n.content),n.type===`status`&&la(n.status)){i=n.status,SC(n.status??``,t);break}t&&process.stdout.write(`${JSON.stringify({...n,events:Ya(r)},null,2)}\n`),wC(i,a)}function EC(e){if(xC(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(`
|
|
2877
2878
|
[session running]
|
|
2878
|
-
`):e.type===`error`&&process.stderr.write(`\n[error] ${e.content??`unknown error`}\n`)}}function TS(e,t,n={}){if(t)process.stdout.write(`${JSON.stringify({...n,events:Pa(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)wS(t);bS(e.terminalStatus,t)}SS(e.terminalStatus,xS(e.result.events))}function ES(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean):void 0}var DS=S({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:G,async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=n.file??`agents.yaml`;if(t.dryRun){O({would_create_session:{agent:n.agent??`auto`,provider:`bailian`,environment:n.environment,vault:n.vault,memory_stores:ES(n.memoryStores),title:n.title},config_file:i},r);return}let{agentName:a,session:o}=await q(()=>J(async()=>{let t=await K(e,i);return ki(t,{agent:n.agent,provider:`bailian`,environment:n.environment,vault:n.vault,memoryStores:ES(n.memoryStores),title:n.title})}));if(r===`json`){O({agent:a,session:o},r);return}D(`Session created: ${o.id}`),D(` Agent: ${a}`),D(` Environment: ${o.environment_id}`),D(` Status: ${o.status}`),o.vault_ids.length&&D(` Vaults: ${o.vault_ids.join(`, `)}`),o.memory_store_ids.length&&D(` Memory: ${o.memory_store_ids.join(`, `)}`)}});async function OS(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 Y={file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}},X={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 获取全部分页`}}},kS={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)`}}},AS={includeArchived:{type:`switch`,description:{"en-US":`Include archived resources`,"zh-CN":`包含已归档资源`}}};function jS(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 MS(e){if(!e)return;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t.length>0?t:void 0}function NS(e,...t){let n=e.trim().toLocaleLowerCase();return!n||t.some(e=>e!=null&&(typeof e==`string`?e:JSON.stringify(e)).toLocaleLowerCase().includes(n))}async function PS(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 FS(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`){O({[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){D(u);return}for(let e of cr(i,a))D(e);D(`\nTotal: ${r.length}`),c?D(`Search stopped at --page-limit; more pages remain.`):o&&D(`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}const IS={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:X.limit,page:X.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 时间戳`}}};var LS=S({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:IS,exampleArgs:[``,`--agent assistant`,`--all`],notes:G,validate:jS,async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=n.file??`agents.yaml`,{items:a,hasMore:o,nextPage:s}=await q(()=>J(async()=>{let t=await K(e,i);return OS(async e=>{let r=await aa(t,{agent:n.agent,provider:`bailian`,filter:{page:e,limit:n.limit,statuses:MS(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`){O({sessions:c,has_more:o,next_page:s},r);return}if(c.length===0){D(`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 cr(u,d))D(e);D(`\nTotal: ${c.length}`),o&&D(`More sessions available. Use --all to fetch all.`)}}),RS=S({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:G,async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=n.file??`agents.yaml`,a=await q(()=>J(async()=>{let t=await K(e,i);return Gi(t,n.sessionId,`bailian`)}));if(r===`json`){O(a,r);return}D(` ID: ${a.id}`),D(` Agent: ${a.agent_id}`),D(` Environment: ${a.environment_id}`),D(` Status: ${a.status}`),a.title&&D(` Title: ${a.title}`),D(` Created: ${a.created_at}`),D(` Updated: ${a.updated_at}`)}}),zS=S({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:G,async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=n.file??`agents.yaml`;if(t.dryRun){O({would_delete_session:n.sessionId,provider:`bailian`,config_file:i},r);return}await q(()=>J(async()=>{let t=await K(e,i);await Mi(t,n.sessionId,`bailian`)})),r===`json`?O({deleted:n.sessionId},r):D(`Session ${n.sessionId} deleted.`)}}),BS=S({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:[...G,{"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=C(t.output),i=n.file??`agents.yaml`,a=r===`json`,o={agent:n.agent,provider:`bailian`,environment:n.environment,vault:n.vault,memoryStores:ES(n.memoryStores),title:n.title};if(t.dryRun){O({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 q(()=>J(async()=>{let t=await K(e,i);if(n.noStream){let e=await ya(t,n.prompt,o);a||process.stderr.write(`Session created: ${e.session.id}\n`),TS(e,a,{session_id:e.session.id,provider:e.provider,agent:e.agentName})}else{let e=await va(t,n.prompt,o);a||process.stderr.write(`Session created: ${e.session.id}\n`),await CS(e.events,a,{session_id:e.session.id,provider:e.provider,agent:e.agentName})}}))}}),VS=S({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:G,async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=n.file??`agents.yaml`,a=r===`json`;if(t.dryRun){O({would_send:{session_id:n.sessionId,message:n.message,provider:`bailian`,mode:n.noStream?`polling`:`streaming`},config_file:i},r);return}await q(()=>J(async()=>{let t=await K(e,i);n.noStream?TS(await ha(t,n.sessionId,n.message,{provider:`bailian`}),a,{session_id:n.sessionId}):await CS(await ga(t,n.sessionId,n.message,{provider:`bailian`}),a,{session_id:n.sessionId})}))}});async function HS(e){return new Uint8Array(await di(M(e)))}async function US(e){let t=e.startsWith(`@`)?await di(M(e.slice(1)),`utf8`):e;try{return JSON.parse(t)}catch(e){let t=e instanceof Error?e.message:String(e);throw new n(`Invalid JSON input: ${t}`,l.USAGE)}}async function WS(e,t,r=!1){let i=M(e),a=Xr(i);await ui(a,{recursive:!0});let o=`${i}.${wr()}.tmp`;await hi(o,t,{flag:`wx`});try{if(r)await fi(o,i);else{try{await li(o,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 mi(o)}return i}catch(e){throw await mi(o).catch(()=>void 0),e}}function GS(e){let t=Yr(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 KS={sessionId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Session ID`,"zh-CN":`Session ID`}}},qS={...Y,...KS,...X,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":`创建时间不晚于该时间戳`}}},JS={...Y,...KS,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`}}},YS={...Y,...KS,afterId:{type:`string`,valueHint:`<event-id>`,description:{"en-US":`Resume after this event ID`,"zh-CN":`从该 Event ID 之后继续`}}};function XS(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 ZS(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=Si.safeParse(r);if(t.success)continue;let i=t.error.issues[0],a=i?.path.length?` at ${i.path.join(`.`)}`:``;throw new n(`Invalid event at index ${e}${a}: ${i?.message??`does not match the Session event schema`}.`,l.USAGE)}return t}const QS=S({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:qS,exampleArgs:[`--session-id sess_abc`,`--session-id sess_abc --all --output json`],notes:[...G,{"en-US":`--types is applied client-side to each page returned by the provider.`,"zh-CN":`--types 会在客户端对 Provider 返回的每一页结果进行过滤。`}],validate:jS,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return OS(async n=>{let r=await ia(t,e.flags.sessionId,{provider:`bailian`,limit:e.flags.limit,page_token:n,order:e.flags.order,types:MS(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)}));FS({format:t,key:`events`,items:Pa(n.items),headers:[`ID`,`TYPE`,`THREAD`,`CONTENT`],rows:XS(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No events found.`})}}),$S=S({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:JS,exampleArgs:[`--session-id sess_abc --event '{"type":"message","role":"user","content":[{"type":"text","text":"hello"}]}'`,`--session-id sess_abc --event @event.json`],notes:G,async run(e){let t=C(e.settings.output),n=ZS(await US(e.flags.event));if(e.settings.dryRun){O({would_send_events:n,session_id:e.flags.sessionId},t);return}let r=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return ma(t,e.flags.sessionId,n,{provider:`bailian`})}));t===`json`?O({session_id:e.flags.sessionId,...r},t):D(`Sent ${n.length} event(s): ${r.event_ids.join(`, `)}`)}}),eC=S({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:YS,exampleArgs:[`--session-id sess_abc`,`--session-id sess_abc --after-id evt_123 --output json`],notes:[...G,{"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=C(e.settings.output);await q(()=>J(async()=>{let n=await K(e,e.flags.file??`agents.yaml`),r=[];for await(let i of ba(n,e.flags.sessionId,{provider:`bailian`,after_id:e.flags.afterId}))if(r.push(i),t!==`json`&&D(JSON.stringify(Pa([i])[0])),i.type===`status`&&Ji(i.status))break;t===`json`&&O({session_id:e.flags.sessionId,events:Pa(r)},t)}))}}),tC={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`}}},nC={...Y,...X,...tC},rC={...Y,limit:X.limit,...kS,...tC},iC={...Y,skillId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Skill ID`,"zh-CN":`Skill ID`}}},aC={...iC,...X},oC={...iC,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 sC(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 cC(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 lC(e,t){return{source:e,skills:t.items,has_more:t.hasMore,next_page:t.nextPage}}async function uC(e,t,n){return OS(async r=>{let i=await na(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 dC=S({description:{"en-US":`List Managed Agent skills`,"zh-CN":`列出托管 Agent Skill`},auth:`apiKey`,usageArgs:`[--source custom|official|all] [--limit <n>] [--page <cursor>] [--all]`,flags:nC,exampleArgs:[``,`--source official`,`--source all --all --output json`],notes:[...G,{"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=>jS(e)??(e.source===`all`&&e.page?`--source all cannot be combined with --page.`:void 0),async run(e){let t=C(e.settings.output),n=e.flags.source??`custom`,r=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);if(n!==`all`)return uC(t,n,{limit:e.flags.limit,page:e.flags.page,all:e.flags.all});let[r,i]=await Promise.all([uC(t,`custom`,{limit:e.flags.limit,all:e.flags.all}),uC(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`){O(lC(n,r),t);return}FS({format:t,key:`skills`,items:r.items,headers:[`ID`,`NAME`,`SOURCE`,`STATUS`,`VERSION`,`UPDATED`],rows:sC(r.items),hasMore:r.hasMore,nextPage:r.nextPage,emptyMessage:`No skills found.`})}});const fC=[{"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 pC(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 mC(e,t=`resource`){return e.normalize(`NFKC`).trim().toLowerCase().replace(/[^\p{L}\p{N}]+/gu,`-`).replace(/^-+|-+$/g,``)||t}function hC(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=pC(e.candidate);for(let[r,i]of Object.entries(e.declarations))if(!(e.effectiveName(r,i)!==e.displayName||t.has(r))&&pC(i)===n)return{key:r,reusedPending:!0};let r=mC(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 gC(e,t){let r=await di(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 q(()=>_x(e,t,{credentials:`none`})),a=await di(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||dx(i.config.providers,[o]),hx(e);let s=new xi({configPath:i.configPath});return{...i,source:a,provider:o,stateBackend:s,stateScope:fx(i.configPath,i.projectName)}}async function _C(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 q(()=>fa(n,{projectName:e.project.projectName,basePath:Xr(e.project.configPath)}))).config[e.group]?.[t]??e.rawDeclaration}async function vC(e){let{project:t,host:r}=e,i=C(r.settings.output),a=await t.stateBackend.read(t.stateScope,n=>hC({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=ri(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 q(()=>J(()=>la(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`?O(c,i):(D(`Generated YAML key: ${o}`),SC(n.plan.actions,n.plan.diagnostics),D(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 yC(t.configPath,t.source,d);let m;try{m=await q(()=>J(()=>xa(p,{provider:t.provider,scope:{roots:[f]},mode:`create-only`,refresh:!0,quiet:i===`json`,policy:`block`})))}catch(t){throw Cx(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`?O(v,i):(D(`Wrote ${t.configPath} with ${e.resourceType} key '${o}'.`),_||D(`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 yC(e,t,r){let i=M(e);if(await di(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 pi(i),o=M(Xr(i),`.${Yr(i)}.${wr()}.tmp`);await hi(o,r,{flag:`wx`,mode:a.mode});try{await fi(o,i)}catch(e){throw await mi(o).catch(()=>void 0),e}}function bC(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 xC(e,t){let r=[];for(let i of e??[]){let e=i.startsWith(`@`)?await di(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 SC(e,t){for(let e of t)D(`[${e.severity}] ${e.code}: ${e.message}`);for(let t of e.filter(e=>e.action!==`no-op`)){let e=t.action===`create`?`+`:t.action===`update`?`~`:`-`;D(` ${e} ${Tx(t.address)}`)}}const CC={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 wC(e){return hC({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 TC(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 EC(e,t=`custom`){let r=/* @__PURE__ */ 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 DC(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 OC(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)&&DC(r)===DC(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{...hC({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 kC(e,t){let r={...e.config.skills??{}},i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ 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 q(()=>qi(t,{basePath:process.cwd()})),c=await pi(s.sourcePath);if(!(c.isDirectory()||c.isFile()&&Zr(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=Qr(Xr(e.configPath),s.sourcePath).split($r).join(`/`)||`.`,d={name:s.name,source:u,origin:`custom`,provider:e.provider},f=await _C({project:e,group:`skills`,rawDeclaration:d}),p=await e.stateBackend.read(e.stateScope,t=>OC({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 AC=S({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:CC,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:[...G,{"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=C(r.output),a=await gC(e,t.file??`agents.yaml`),o=a.provider,s=EC(t.skill,TC(t.type)),c=await kC(a,t.skillDir),u=[...s,...c.map(e=>e.key)],d=Di(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 _C({project:{...a,config:f},group:`agents`,rawDeclaration:d}),m=await a.stateBackend.read(a.stateScope,e=>wC({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=ri(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 q(()=>J(()=>la(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`)O(s,i);else{for(let e of c)D(`Generated Skill YAML key: ${e.key}`);D(`Generated Agent YAML key: ${h}`);for(let t of e.plan.diagnostics)D(`[${t.severity}] ${t.code}: ${t.message}`);for(let t of e.plan.actions.filter(e=>e.action!==`no-op`)){let e=t.action===`create`?`+`:t.action===`update`?`~`:`-`;D(` ${e} ${Tx(t.address)}`)}D(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 yC(a.configPath,a.source,_);let ee;try{ee=await q(()=>J(()=>xa(b,{provider:o,scope:{roots:y},refresh:!0,quiet:i===`json`,mode:`create-only`,policy:`block`})))}catch(e){throw Cx(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 x=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]))})),te=ee.execution?.results??[],ne=te.find(e=>e.status===`failed`),re=ne?`failed`:`completed`,ie={agent:{key:h,name:t.name.trim(),provider:o,remote_id:x.agentId,skills:u},local_skills:c.map(e=>({key:e.key,name:e.name,source:e.source,remote_id:x.skillIds[e.key],reused_pending:e.reusedPending,reused_tracked:e.reusedTracked})),config_file:a.configPath,yaml_written:!0,reused_pending:m.reusedPending,status:re,actions:ee.planned.plan.actions,diagnostics:ee.planned.plan.diagnostics,results:te,error:ne?.error};if(i===`json`?O(ie,i):(D(`Wrote ${a.configPath} with Agent key '${h}'${c.length?` and ${c.length} local Skill declaration(s)`:``}.`),D(re===`completed`?`Created Agent '${t.name.trim()}'.`:`Scoped create ${re}: ${ne?.error??`unknown error`}`)),ne)throw new n(ne.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.`)}});const jC={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:NC(`APT`),pip:NC(`pip`),npm:NC(`npm`),cargo:NC(`Cargo`),gem:NC(`Ruby gem`),go:NC(`Go`),file:PC(),yes:FC()};var MC=S({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:jC,exampleArgs:[`--name Development`,`--name Development --pip pandas --npm typescript --metadata owner=platform --yes`],notes:[...G,...fC,{"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 gC(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:bC(e.flags.metadata)},i=await _C({project:t,group:`environments`,rawDeclaration:r});await vC({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 NC(e){return{type:`array`,valueHint:`<package>`,description:{"en-US":`${e} package (repeatable)`,"zh-CN":`${e} 软件包(可重复)`}}}function PC(){return{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}}function FC(){return{type:`switch`,description:{"en-US":`Write YAML and run the scoped remote create`,"zh-CN":`写入 YAML 并执行定向远端创建`}}}var IC=S({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:[...G,...fC,{"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 gC(e,e.flags.file??`agents.yaml`),r=await qi(e.flags.source,{basePath:process.cwd()}),i=Qr(Xr(t.configPath),r.sourcePath).split($r).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 _C({project:t,group:`skills`,rawDeclaration:o});await vC({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})}}),LC=S({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:[...G,...fC,{"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 gC(e,e.flags.file??`agents.yaml`),n={display_name:e.flags.name.trim(),provider:t.provider,credentials:[],metadata:bC(e.flags.metadata)},r=await _C({project:t,group:`vaults`,rawDeclaration:n});await vC({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})}}),RC=S({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:[...G,...fC,{"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=C(e.settings.output);Ei();let r=process.env[e.flags.secretEnv],i=await gC(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=bC(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=ri(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||!zC(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 q(()=>fa(p,{projectName:i.projectName,basePath:Xr(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 q(()=>J(()=>ua(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`?O(r,t):(D(`Vault: ${e.flags.vault}`),D(`Credential: ${e.flags.name.trim()} (secret from ${e.flags.secretEnv})`),D(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 yC(i.configPath,i.source,_);let y;try{y=await q(()=>J(()=>Ai(v,e.flags.vault,e.flags.name.trim(),{provider:i.provider,refresh:!0,quiet:t===`json`})))}catch(e){throw Cx(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`?O(b,t):D(`Wrote ${i.configPath} and created Credential '${e.flags.name.trim()}'.`)}});function zC(e,t){return BC(e)===BC(t)}function BC(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 VC=S({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:[...G,...fC,{"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 gC(e,e.flags.file??`agents.yaml`),r=[...(e.flags.message??[]).map(e=>({type:`user.message`,content:e})),...HC(await xC(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=UC(await xC(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&&WC(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:bC(e.flags.metadata)},o=await _C({project:t,group:`deployments`,rawDeclaration:a});await vC({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 HC(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 UC(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 WC(e){try{new Intl.DateTimeFormat(`en-US`,{timeZone:e}).format()}catch{throw new n(`Invalid IANA timezone: ${e}`,l.USAGE)}}const GC={...Y,...X,...AS},KC={...Y,limit:X.limit,...kS,...AS},qC={...Y,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 版本`}}},JC={...Y,...X,agentId:qC.agentId};function YC(e){return e.map(e=>[e.id,Z(e.name),Z(e.version),Z(e.type),Z(e.updated_at)])}var XC=S({description:{"en-US":`Get a Managed Agent`,"zh-CN":`获取托管 Agent 详情`},auth:`apiKey`,usageArgs:`--agent-id <id> [--agent-version <n>] [--file <path>]`,flags:qC,exampleArgs:[`--agent-id agent_abc`,`--agent-id agent_abc --agent-version 3 --output json`],notes:G,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=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return zi(t,e.flags.agentId,{provider:`bailian`,version:e.flags.agentVersion})}));if(t===`json`){O(n,t);return}D(`ID: ${n.id}`),D(`Name: ${Z(n.name)}`),D(`Description: ${Z(n.description,120)}`),D(`Version: ${Z(n.version)}`),D(`Type: ${Z(n.type)}`),D(`Created: ${Z(n.created_at)}`),D(`Updated: ${Z(n.updated_at)}`)}}),ZC=S({description:{"en-US":`List Managed Agents`,"zh-CN":`列出托管 Agent`},auth:`apiKey`,usageArgs:`[--limit <n>] [--page <cursor>] [--all] [--include-archived] [--file <path>]`,flags:GC,exampleArgs:[``,`--limit 50`,`--all --include-archived --output json`],notes:G,validate:jS,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return OS(async n=>{let r=await Xi(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)}));FS({format:t,key:`agents`,items:n.items,headers:[`ID`,`NAME`,`VERSION`,`TYPE`,`UPDATED`],rows:YC(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No agents found.`})}}),QC=S({description:{"en-US":`Search Managed Agents`,"zh-CN":`搜索托管 Agent`},auth:`apiKey`,usageArgs:`--query <text> [--limit <n>] [--page-limit <n>] [--include-archived]`,flags:KC,exampleArgs:[`--query assistant`,`--query code --page-limit 20 --output json`],notes:G,validate:jS,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return PS(async n=>{let r=await Xi(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=>NS(e.flags.query,t.id,t.name,t.description),e.flags.pageLimit)}));FS({format:t,key:`agents`,items:n.items,headers:[`ID`,`NAME`,`VERSION`,`TYPE`,`UPDATED`],rows:YC(n.items),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching agents found.`})}}),$C=S({description:{"en-US":`List Managed Agent versions`,"zh-CN":`列出托管 Agent 版本`},auth:`apiKey`,usageArgs:`--agent-id <id> [--limit <n>] [--page <cursor>] [--all]`,flags:JC,exampleArgs:[`--agent-id agent_abc`,`--agent-id agent_abc --all --output json`],notes:G,validate:jS,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return OS(async n=>{let r=await Yi(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)}));FS({format:t,key:`versions`,items:n.items,headers:[`ID`,`NAME`,`VERSION`,`TYPE`,`UPDATED`],rows:YC(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No agent versions found.`})}});const ew={...Y,...X,...AS},tw={...Y,limit:X.limit,...kS,...AS},nw={...Y,environmentId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Environment ID`,"zh-CN":`Environment ID`}}};function rw(e){return e.map(e=>[e.id,Z(e.name),Z(e.scope),Z(e.version),Z(e.updated_at)])}var iw=S({description:{"en-US":`Get a Managed Agent environment`,"zh-CN":`获取托管 Agent 环境详情`},auth:`apiKey`,usageArgs:`--environment-id <id>`,flags:nw,exampleArgs:[`--environment-id env_abc`],notes:G,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return Hi(t,e.flags.environmentId,{provider:`bailian`})}));if(t===`json`){O(n,t);return}D(`ID: ${n.id}`),D(`Name: ${Z(n.name)}`),D(`Description: ${Z(n.description,120)}`),D(`Scope: ${Z(n.scope)}`),D(`Version: ${Z(n.version)}`),D(`Updated: ${Z(n.updated_at)}`)}}),aw=S({description:{"en-US":`List Managed Agent environments`,"zh-CN":`列出托管 Agent 环境`},auth:`apiKey`,usageArgs:`[--limit <n>] [--page <cursor>] [--all] [--include-archived]`,flags:ew,exampleArgs:[``,`--all --output json`],notes:G,validate:jS,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return OS(async n=>{let r=await $i(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)}));FS({format:t,key:`environments`,items:n.items,headers:[`ID`,`NAME`,`SCOPE`,`VERSION`,`UPDATED`],rows:rw(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No environments found.`})}}),ow=S({description:{"en-US":`Search Managed Agent environments`,"zh-CN":`搜索托管 Agent 环境`},auth:`apiKey`,usageArgs:`--query <text> [--limit <n>] [--page-limit <n>] [--include-archived]`,flags:tw,exampleArgs:[`--query sandbox`,`--query production --page-limit 20 --output json`],notes:G,validate:jS,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return PS(async n=>{let r=await $i(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=>NS(e.flags.query,t.id,t.name,t.description),e.flags.pageLimit)}));FS({format:t,key:`environments`,items:n.items,headers:[`ID`,`NAME`,`SCOPE`,`VERSION`,`UPDATED`],rows:rw(n.items),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching environments found.`})}}),sw=S({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:oC,exampleArgs:[`--skill-id skill_abc --skill-version 3 --output-file ./skill.zip`],notes:G,async run(e){let t=C(e.settings.output);if(e.settings.dryRun){O({would_download_skill:e.flags.skillId,version:e.flags.skillVersion,output_file:e.flags.outputFile},t);return}let n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return Fi(t,e.flags.skillId,e.flags.skillVersion,{provider:`bailian`})})),r=await WS(e.flags.outputFile,n,e.flags.force);t===`json`?O({downloaded:e.flags.skillId,version:e.flags.skillVersion,output_file:r},t):D(`Skill downloaded to ${r}`)}}),cw=S({description:{"en-US":`Get a Managed Agent skill`,"zh-CN":`获取托管 Agent Skill 详情`},auth:`apiKey`,usageArgs:`--skill-id <id>`,flags:iC,exampleArgs:[`--skill-id skill_abc`],notes:G,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return Ui(t,e.flags.skillId,{provider:`bailian`})}));if(t===`json`){O(n,t);return}D(`ID: ${n.id}`),D(`Name: ${n.name}`),D(`Description: ${Z(n.description,120)}`),D(`Source: ${n.source}`),D(`Status: ${n.status}`),D(`Version: ${Z(n.latest_version)}`)}}),lw=S({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:rC,exampleArgs:[`--query browser --source official`,`--query report --source all --output json`],notes:G,validate:jS,async run(e){let t=C(e.settings.output),n=e.flags.source??`custom`,r=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`),r=n=>PS(async r=>{let i=await na(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=>NS(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}}));FS({format:t,key:`skills`,items:r.items,headers:[`ID`,`NAME`,`SOURCE`,`STATUS`,`VERSION`,`UPDATED`],rows:sC(r.items),hasMore:r.hasMore,nextPage:r.nextPage,truncated:r.truncated,scannedPages:r.scannedPages,emptyMessage:`No matching skills found.`})}}),uw=S({description:{"en-US":`List Managed Agent skill versions`,"zh-CN":`列出托管 Agent Skill 版本`},auth:`apiKey`,usageArgs:`--skill-id <id> [--limit <n>] [--page <cursor>] [--all]`,flags:aC,exampleArgs:[`--skill-id skill_abc`,`--skill-id skill_abc --all --output json`],notes:G,validate:jS,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return OS(async n=>{let r=await ta(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)}));FS({format:t,key:`versions`,items:n.items,headers:[`VERSION`,`NAME`,`TYPE`,`STATUS`,`UPDATED`],rows:cC(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No skill versions found.`})}});const dw={...Y,...X,...AS},fw={...Y,limit:X.limit,...kS,...AS},pw={...Y,vaultId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Vault ID`,"zh-CN":`Vault ID`}}};function mw(e){return e.map(e=>[e.id,Z(e.display_name),Z(e.type),Z(e.created_at),Z(e.updated_at)])}var hw=S({description:{"en-US":`Get a Managed Agent vault`,"zh-CN":`获取托管 Agent Vault 详情`},auth:`apiKey`,usageArgs:`--vault-id <id>`,flags:pw,exampleArgs:[`--vault-id vault_abc`],notes:G,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return Wi(t,e.flags.vaultId,{provider:`bailian`})}));if(t===`json`){O(n,t);return}D(`ID: ${n.id}`),D(`Name: ${Z(n.display_name)}`),D(`Type: ${Z(n.type)}`),D(`Created: ${Z(n.created_at)}`),D(`Updated: ${Z(n.updated_at)}`)}}),gw=S({description:{"en-US":`List Managed Agent vaults`,"zh-CN":`列出托管 Agent Vault`},auth:`apiKey`,usageArgs:`[--limit <n>] [--page <cursor>] [--all] [--include-archived]`,flags:dw,exampleArgs:[``,`--all --output json`],notes:G,validate:jS,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return OS(async n=>{let r=await ra(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)}));FS({format:t,key:`vaults`,items:n.items,headers:[`ID`,`NAME`,`TYPE`,`CREATED`,`UPDATED`],rows:mw(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No vaults found.`})}}),_w=S({description:{"en-US":`Search Managed Agent vaults`,"zh-CN":`搜索托管 Agent Vault`},auth:`apiKey`,usageArgs:`--query <text> [--limit <n>] [--page-limit <n>] [--include-archived]`,flags:fw,exampleArgs:[`--query github`,`--query production --page-limit 20 --output json`],notes:G,validate:jS,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return PS(async n=>{let r=await ra(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=>NS(e.flags.query,t.id,t.display_name,t.metadata),e.flags.pageLimit)}));FS({format:t,key:`vaults`,items:n.items,headers:[`ID`,`NAME`,`TYPE`,`CREATED`,`UPDATED`],rows:mw(n.items),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching vaults found.`})}});const vw={deploymentId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Deployment ID`,"zh-CN":`Deployment ID`}}},yw={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 状态筛选`}},...AS,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":`创建时间不晚于该时间戳`}}},bw={...Y,...X,...yw},xw={...Y,...vw},Sw={...Y,...X,query:kS.query,...yw},Cw={...Y,...vw,...X},ww={...Y,runId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Deployment run ID`,"zh-CN":`Deployment Run ID`}}},Tw={...Y,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 Ew(e){if(!!e.deployment==!!e.deploymentId)return`Provide exactly one of --deployment or --deployment-id.`}function Dw(e){return e.map(e=>[Z(e.id),e.status,Z(e.schedule?.expression),Z(e.paused_reason?.type)])}function Ow(e){return e.map(e=>[e.id,Z(e.deployment_id),Z(e.session_id),Z(e.status),Z(e.created_at)])}async function kw(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 wi(`Deployment '${t.deployment}' is not tracked in state. Use --deployment-id or run managed-agent apply/import first.`);return n.remote_id}var Aw=S({description:{"en-US":`Get a Managed Agent deployment`,"zh-CN":`获取托管 Agent Deployment 详情`},auth:`apiKey`,usageArgs:`--deployment-id <id>`,flags:xw,exampleArgs:[`--deployment-id dep_abc`],notes:G,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return Bi(t,e.flags.deploymentId,{provider:`bailian`})}));t===`json`?O(n,t):(D(`ID: ${Z(n.id)}`),D(`Status: ${n.status}`),D(`Schedule:${Z(n.schedule?.expression)}`),D(`Paused: ${Z(n.paused_reason)}`))}}),jw=S({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:bw,exampleArgs:[``,`--status active --all --output json`],notes:G,validate:jS,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return OS(async n=>{let r=await Qi(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)}));FS({format:t,key:`deployments`,items:n.items,headers:[`ID`,`STATUS`,`SCHEDULE`,`PAUSED REASON`],rows:Dw(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No deployments found.`})}});function Mw(e){return S({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:Tw,exampleArgs:[`--deployment daily-report --dry-run`,`--deployment-id dep_abc --yes`],notes:G,validate:Ew,async run(t){let n=C(t.settings.output);if(t.settings.dryRun){O({[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 q(()=>J(async()=>{let n=await K(t,t.flags.file??`agents.yaml`),r=await kw(n,t.flags);return{deploymentId:r,deployment:await _a(n,r,e,{provider:`bailian`})}}));n===`json`?O({deployment_id:r.deploymentId,deployment:r.deployment},n):D(`Deployment ${r.deploymentId} ${e?`paused`:`unpaused`}.`)}})}var Nw=Mw(!0),Pw=S({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:Tw,exampleArgs:[`--deployment daily-report --dry-run`,`--deployment-id dep_abc --yes`],notes:G,validate:Ew,async run(e){let t=C(e.settings.output);if(e.settings.dryRun){O({would_run_deployment:e.flags.deploymentId??e.flags.deployment,target_kind:e.flags.deploymentId?`id`:`state_name`},t);return}let n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`),n=await kw(t,e.flags);return{deploymentId:n,run:await pa(t,n,{provider:`bailian`})}}));t===`json`?O({deployment_id:n.deploymentId,...n.run},t):D(`Deployment ${n.deploymentId} started. Run: ${n.run.run_id??`-`}`)}}),Fw=S({description:{"en-US":`Get a Managed Agent deployment run`,"zh-CN":`获取托管 Agent Deployment Run 详情`},auth:`apiKey`,usageArgs:`--run-id <id>`,flags:ww,exampleArgs:[`--run-id run_abc`],notes:G,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return Vi(t,e.flags.runId,{provider:`bailian`})}));t===`json`?O(n,t):(D(`ID: ${n.id}`),D(`Deployment: ${Z(n.deployment_id)}`),D(`Session: ${Z(n.session_id)}`),D(`Status: ${Z(n.status)}`),D(`Created: ${Z(n.created_at)}`),D(`Error: ${Z(n.error)}`))}}),Iw=S({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:Cw,exampleArgs:[`--deployment-id dep_abc`,`--deployment-id dep_abc --all --output json`],notes:G,validate:jS,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return OS(async n=>{let r=await Zi(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)}));FS({format:t,key:`runs`,items:n.items,headers:[`ID`,`DEPLOYMENT`,`SESSION`,`STATUS`,`CREATED`],rows:Ow(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No deployment runs found.`})}}),Lw=S({description:{"en-US":`Search Managed Agent deployments`,"zh-CN":`搜索托管 Agent Deployment`},auth:`apiKey`,usageArgs:`--query <text> [--limit <n>] [--page <cursor>] [--all]`,flags:Sw,exampleArgs:[`--query report`,`--query nightly --all --output json`],notes:[...G,{"en-US":`Deployment search maps --query to the provider's server-side keyword parameter.`,"zh-CN":`Deployment 搜索会把 --query 映射为 Provider 服务端 keyword 参数。`}],validate:jS,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return OS(async n=>{let r=await Qi(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)}));FS({format:t,key:`deployments`,items:n.items,headers:[`ID`,`STATUS`,`SCHEDULE`,`PAUSED REASON`],rows:Dw(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No matching deployments found.`})}}),Rw=Mw(!1);const zw={sessionId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Session ID`,"zh-CN":`Session ID`}}},Bw={...Y,limit:X.limit,...kS,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":`创建时间不晚于该时间戳`}}},Vw={...Y,...zw,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`}}},Hw={...Y,...zw};function Uw(e){return e.map(e=>[e.id,Z(e.title),Z(e.agent_id),e.status,Z(e.updated_at)])}async function Ww(e){if(!e)return;let t=await US(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 Gw=S({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:Bw,exampleArgs:[`--query debug`,`--query failed --statuses failed --output json`],notes:G,validate:jS,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return PS(async n=>{let r=await aa(t,{agent:e.flags.agent,provider:`bailian`,filter:{page:n,limit:e.flags.limit??100,statuses:MS(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=>NS(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);FS({format:t,key:`sessions`,items:r,headers:[`ID`,`TITLE`,`AGENT`,`STATUS`,`UPDATED`],rows:Uw(r),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching sessions found.`})}}),Kw=S({description:{"en-US":`Update a Managed Agent session`,"zh-CN":`更新托管 Agent Session`},auth:`apiKey`,usageArgs:`--session-id <id> [--title <title>] [--metadata <json|@path>]`,flags:Vw,exampleArgs:[`--session-id sess_abc --title 'investigation'`,`--session-id sess_abc --metadata @metadata.json`],notes:G,validate:e=>!e.title&&!e.metadata?`Provide --title or --metadata.`:void 0,async run(e){let t=C(e.settings.output),n={title:e.flags.title,metadata:await Ww(e.flags.metadata)};if(e.settings.dryRun){O({would_update_session:e.flags.sessionId,input:n},t);return}let r=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return Sa(t,e.flags.sessionId,n,{provider:`bailian`})}));t===`json`?O(r,t):D(`Session ${r.id} updated.`)}}),qw=S({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:Hw,exampleArgs:[`--session-id sess_abc --dry-run`,`--session-id sess_abc --yes`],notes:G,async run(e){let t=C(e.settings.output);if(e.settings.dryRun){O({would_archive_session:e.flags.sessionId},t);return}let n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return Ti(t,e.flags.sessionId,{provider:`bailian`})}));t===`json`?O({archived:e.flags.sessionId,session:n},t):D(`Session ${e.flags.sessionId} archived.`)}}),Jw={sessionId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Session ID`,"zh-CN":`Session ID`}}},Yw={...Y,...Jw},Xw={...Yw,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 Zw(e){return e instanceof Error?e.message:String(e)}async function Qw(e,t,n){let r=await Gi(e,t,n),i=n??(e.providers.size===1?Array.from(e.providers.keys())[0]:`bailian`),a=[],o=[],s=[];try{o=(await OS(async r=>{let i=await ia(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:Zw(e)})}try{s=(await OS(async r=>{let i=await ea(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:Zw(e)})}return{session:r,events:Pa(o),files:s,capabilities:Ri(i),errors:a}}const $w=String.raw`(?:api[_-]?key|access[_-]?key|private[_-]?key|secret|token|authorization|credential|password|signature|signed[_-]?url)`,eT=RegExp(`${$w}|tool[_-]?input`,`i`),tT=RegExp(`([?&][^=&#\\s]*(?:${$w})[^=&#\\s]*=)[^&#\\s"'<>),}\\]]*`,`gi`),nT=RegExp(`("[^"]*(?:${$w})[^"]*"\\s*:\\s*")[^"]*(")`,`gi`),rT=RegExp(`('[^']*(?:${$w})[^']*'\\s*:\\s*')[^']*(')`,`gi`),iT=RegExp(`(\\b[^\\s=:,;]*(?:${$w})[^\\s=:,;]*\\s*=\\s*)(?!\\[REDACTED\\])(?:"[^"]*"|'[^']*'|[^\\s,;&]+)`,`gi`),aT=/\b(authorization\s*:\s*)(?:bearer\s+)?[^\s,;]+/gi,oT=/\b(bearer\s+)[A-Za-z0-9._~+/=-]+/gi,sT=/\bsk-[A-Za-z0-9_-]{8,}\b/g;function cT(e){return e.replace(tT,`$1[REDACTED]`).replace(nT,`$1[REDACTED]$2`).replace(rT,`$1[REDACTED]$2`).replace(iT,`$1[REDACTED]`).replace(aT,`$1[REDACTED]`).replace(oT,`$1[REDACTED]`).replace(sT,`[REDACTED]`)}function lT(e){return Array.isArray(e)?e.map(lT):typeof e==`string`?cT(e):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,eT.test(e)?`[REDACTED]`:lT(t)]))}function uT(e){return new TextEncoder().encode(`${JSON.stringify(lT(e),null,2)}\n`)}function dT(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 fT(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 pT(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 mT(e){let t=new TextEncoder,n=[],r=[],i=0;for(let a of e){let e=t.encode(a.name),o=dT(a.content),s=fT([pT([[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=pT([[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(fT([c,e])),i+=s.length}let a=fT(r),o=pT([[101010256,4],[0,2],[0,2],[e.length,2],[e.length,2],[a.length,4],[i,4],[0,2]]);return fT([...n,a,o])}const hT=S({description:{"en-US":`Aggregate session diagnostics`,"zh-CN":`聚合 Session 诊断信息`},auth:`apiKey`,usageArgs:`--session-id <id>`,flags:Yw,exampleArgs:[`--session-id sess_abc`,`--session-id sess_abc --output json`],notes:G,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>Qw(await K(e,e.flags.file??`agents.yaml`),e.flags.sessionId,`bailian`))),r=lT(n);if(t===`json`){O(r,t);return}D(`Session: ${n.session.id} (${n.session.status})`),D(`Events: ${n.events.length}`),D(`Scoped files: ${n.files.length}`),D(`Partial errors: ${n.errors.length}`);for(let e of n.errors)D(` ${e.component}: ${e.message}`)}}),gT=S({description:{"en-US":`Export session diagnostics as a ZIP`,"zh-CN":`将 Session 诊断信息导出为 ZIP`},auth:`apiKey`,usageArgs:`--session-id <id> --output-file <path> [--force]`,flags:Xw,exampleArgs:[`--session-id sess_abc --output-file ./session-debug.zip`],notes:[...G,{"en-US":`The ZIP contains metadata only; file bodies and credential-like values are excluded/redacted.`,"zh-CN":`ZIP 仅包含元数据;不会包含文件正文,凭证类字段会被移除或脱敏。`}],async run(e){let t=C(e.settings.output);if(e.settings.dryRun){O({would_export_session:e.flags.sessionId,output_file:e.flags.outputFile},t);return}let n=await q(()=>J(async()=>Qw(await K(e,e.flags.file??`agents.yaml`),e.flags.sessionId,`bailian`))),r={schema_version:1,generated_at:(/* @__PURE__ */ 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=mT([{name:`manifest.json`,content:uT(r)},{name:`session.json`,content:uT(n.session)},{name:`events.json`,content:uT(n.events)},{name:`files.json`,content:uT(n.files)},{name:`capabilities.json`,content:uT(n.capabilities)},{name:`errors.json`,content:uT(n.errors)}]),a=await WS(e.flags.outputFile,i,e.flags.force);t===`json`?O({exported:n.session.id,output_file:a,partial:r.partial},t):D(`Session diagnostics exported to ${a}${r.partial?` (partial)`:``}`)}}),_T={fileId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Remote file ID`,"zh-CN":`远端 File ID`}}},vT={scopeId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by scope ID`,"zh-CN":`按 Scope ID 筛选`}}},yT={...Y,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 类型`}}},bT={...Y,...X,...vT},xT={...Y,limit:X.limit,...kS,...vT},ST={...Y,..._T},CT={...ST,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":`覆盖已存在的输出文件`}}},wT={...ST};function TT(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 ET=S({description:{"en-US":`Upload a Managed Agent file`,"zh-CN":`上传托管 Agent 文件`},auth:`apiKey`,usageArgs:`--path <path> [--filename <name>] [--mime-type <type>]`,flags:yT,exampleArgs:[`--path ./report.pdf`],notes:G,async run(e){let t=C(e.settings.output);if(e.settings.dryRun){O({would_upload_file:e.flags.path,filename:e.flags.filename??Yr(e.flags.path),mime_type:e.flags.mimeType??GS(e.flags.path)},t);return}let n=await HS(e.flags.path),r=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return Ca(t,n,e.flags.filename??Yr(e.flags.path),{provider:`bailian`,mimeType:e.flags.mimeType??GS(e.flags.path)})}));t===`json`?O(r,t):D(`File uploaded: ${r.id} (${r.filename})`)}}),DT=S({description:{"en-US":`List Managed Agent files`,"zh-CN":`列出托管 Agent 文件`},auth:`apiKey`,usageArgs:`[--scope-id <id>] [--limit <n>] [--page <cursor>] [--all]`,flags:bT,exampleArgs:[``,`--scope-id sess_abc --all --output json`],notes:G,validate:jS,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return OS(async n=>{let r=await ea(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)}));FS({format:t,key:`files`,items:n.items,headers:[`ID`,`FILENAME`,`STATUS`,`BYTES`,`SCOPE`,`CREATED`],rows:TT(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No files found.`})}}),OT=S({description:{"en-US":`Get Managed Agent file metadata`,"zh-CN":`获取托管 Agent 文件元数据`},auth:`apiKey`,usageArgs:`--file-id <id>`,flags:ST,exampleArgs:[`--file-id file_abc`],notes:G,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return Li(t,e.flags.fileId,{provider:`bailian`})}));t===`json`?O(n,t):(D(`ID: ${n.id}`),D(`Filename: ${n.filename}`),D(`MIME: ${n.mime_type}`),D(`Bytes: ${n.size_bytes}`),D(`Status: ${Z(n.status)}`),D(`Scope: ${Z(n.scope?.id)}`))}}),kT=S({description:{"en-US":`Search Managed Agent files`,"zh-CN":`搜索托管 Agent 文件`},auth:`apiKey`,usageArgs:`--query <text> [--scope-id <id>] [--limit <n>] [--page-limit <n>]`,flags:xT,exampleArgs:[`--query report`,`--query pdf --scope-id sess_abc --output json`],notes:G,validate:jS,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return PS(async n=>{let r=await ea(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=>NS(e.flags.query,t.id,t.filename,t.mime_type),e.flags.pageLimit)}));FS({format:t,key:`files`,items:n.items,headers:[`ID`,`FILENAME`,`STATUS`,`BYTES`,`SCOPE`,`CREATED`],rows:TT(n.items),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching files found.`})}}),AT=S({description:{"en-US":`Download Managed Agent file content`,"zh-CN":`下载托管 Agent 文件内容`},auth:`apiKey`,usageArgs:`--file-id <id> --output-file <path> [--force]`,flags:CT,exampleArgs:[`--file-id file_abc --output-file ./artifact.pdf`],notes:G,async run(e){let t=C(e.settings.output);if(e.settings.dryRun){O({would_download_file:e.flags.fileId,output_file:e.flags.outputFile},t);return}let n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return Pi(t,e.flags.fileId,{provider:`bailian`})})),r=await WS(e.flags.outputFile,n,e.flags.force);t===`json`?O({downloaded:e.flags.fileId,output_file:r},t):D(`File downloaded to ${r}`)}}),jT=S({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:wT,exampleArgs:[`--file-id file_abc --dry-run`,`--file-id file_abc --yes`],notes:G,async run(e){let t=C(e.settings.output);if(e.settings.dryRun){O({would_delete_file:e.flags.fileId},t);return}await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);await ji(t,e.flags.fileId,{provider:`bailian`})})),t===`json`?O({deleted:e.flags.fileId},t):D(`File ${e.flags.fileId} deleted.`)}}),MT={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`},NT={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(可选)`}}},PT=1e3;function FT(e){return new Promise(t=>setTimeout(t,e))}function IT(e){return e?.data?.DataV2?.data?.data}function LT(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 RT=S({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:NT,exampleArgs:[`--access-key-id LTAIxxxxx --access-key-secret xxxxx`],async run(e){let{settings:t,flags:r}=e,i=C(t.output);if(t.dryRun){O({apis:[{step:0,api:`GenerateCLIAccessToken`,description:`Generate CLI access token from AK/SK`},{step:1,api:MT.loginInfo,description:`Check login & workspace status`},{step:2,api:MT.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:MT.queryBuyResult,description:`Query postpaid order status`},{step:7,api:MT.commodityOrderInfo,description:`Query commodity activation status`},{step:8,api:MT.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 Je({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=w(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 me(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}};D(`Checking workspace status...`);let m=IT(await p(MT.loginInfo));m?.spaceInited===!0?D(`Workspace already initialized.`):(D(`Initializing workspace...`),await p(MT.initSpace),D(`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 ye({...g,reqDTO:{outerKey:h,nickName:h,userName:h}})}catch(e){if(!(e instanceof n)||!/already exists/i.test(e.message))throw e;D(`Console user already exists, continuing.`)}D(`Resolving workspace agent...`);let _=LT(await yt(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.`);D(`Authorizing user permissions...`),await cn({...g,outerKey:h,agentId:_,policyIndexList:[1]}),await zT(p,i)}});async function zT(e,t){D(`Checking service activation status...`);let r;for(let t=0;t<20;t++){let n=IT(await e(MT.queryBuyResult));if(r=typeof n==`string`?n:n?.result,r!==`buying`)break;t===0&&D(`Service activation in progress, polling...`),await FT(PT)}if(r===`fail`)throw new n(`Service activation failed.`,l.GENERAL);if(r===`success`){await HT(e,t);return}await VT(e,t)}function BT(e){let t=IT(e);return Array.isArray(t)?t:[]}async function VT(e,t){let n=BT(await e(MT.commodityOrderInfo)),r=n.filter(e=>e.status===11);if(r.length>0){D(`Warning: Some services are overdue:`);for(let e of r)D(` - ${e.commodityCode}`)}let i=n.filter(e=>e.status===1);if(i.length>0){D(`Activating ${i.length} postpaid services...`),await e(MT.buyCommodity),await HT(e,t);return}let a=n.filter(e=>e.status===10);O({status:`ready`,activeServices:a.map(e=>e.commodityCode)},t)}async function HT(e,t){D(`Waiting for services to activate...`);for(let n=0;n<20;n++){let n=BT(await e(MT.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){D(`Warning: Some services are overdue:`);for(let t of e)D(` - ${t.commodityCode}`)}let r=n.filter(e=>e.status===10);O({status:`ready`,activeServices:r.map(e=>e.commodityCode)},t);return}await FT(PT)}throw new n(`Timed out waiting for services to activate.`,l.TIMEOUT)}var UT=S({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){let t=await e.commandPacks.install(e.flags.package);O({installed:t},C(e.settings.output))}}),WT=S({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){let t=await e.commandPacks.link(e.flags.path);O({linked:t},C(e.settings.output))}}),GT=S({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=C(e.settings.output);if(n===`json`){O({command_packs:t},n);return}if(t.length===0){D(`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 cr([`NAME`,`VERSION`,`SOURCE`,`STATUS`,`COMMANDS / ERROR`],r))D(e)}}),KT=S({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),O({removed:e.flags.name},C(e.settings.output))}});function qT(e){return e.map(e=>({id:e.id,skillsDir:e.skillsDir}))}function JT(e){try{let t=Hr(e);return t.isSymbolicLink()?{exists:!0,kind:`symlink`,hasSkillMd:!1}:t.isDirectory()?{exists:!0,kind:`directory`,hasSkillMd:A(j(e,`SKILL.md`))}:{exists:!0,kind:`file`,hasSkillMd:!1}}catch{return{exists:!1,kind:`absent`,hasSkillMd:!1}}}function YT(e,t){return t.map(t=>{let n=j(t.skillsDir,e);return{agent:t.id,path:n,...JT(n)}})}var XT=S({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 Ue(),i=Object.keys(r.skills),a=e.flags.all?`all`:Kt(e.flags.name,!1),o=a===`all`?i:a,s=Ae();if(e.settings.dryRun){let e=o.map(e=>{let t=r.skills[e];return t?{name:e,status:`install`,publishedAt:t.publishedAt,links:YT(e,s)}:{name:e,status:`failed`,reason:`skill not found in registry`}});O({action:`skill.add`,registry:at(),agents:qT(s),skills:e},t);let i=e.filter(e=>e.status===`failed`);if(i.length>0)throw new n(`${i.length}/${e.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`);return}let c=tn(),u=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 ut(e,t,s,c.skills[e]?.links??[]);return c.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)}}}),d=await gn(u,3);if(Gn(c),t===`json`)O({registry:at(),agents:s.map(e=>e.id),skills:d},t);else if(d.length===0)D(`Skill registry is empty; no skills to install.`);else{let e=d.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 cr([`NAME`,`STATUS`,`PUBLISHED`,`AGENTS / REASON`],e))D(t)}let f=d.filter(e=>e.status===`failed`);if(f.length>0)throw new n(`${f.length}/${d.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`)}}),ZT=S({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`:Kt(e.flags.name,!1),i=await Ue(),a=tn(),o=new Set(Et()),s=Ae(),c=[],u=[];if(r===`all`)for(let[t,n]of Object.entries(a.skills)){let r=i.skills[t];if(!r){c.push({name:t,status:`skipped`,reason:`delisted from remote; local copy retained`});continue}if(r.contentHash===n.contentHash&&o.has(t)){if(e.settings.dryRun){c.push({name:t,status:`up-to-date`,publishedAt:n.publishedAt});continue}let r=Ie(t,s,n.links??[]);a.skills[t]={...n,links:r.links},c.push({name:t,status:`up-to-date`,publishedAt:n.publishedAt});continue}u.push(t)}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)}if(e.settings.dryRun){let e=c.map(e=>e.status===`up-to-date`?{name:e.name,status:`up-to-date`,publishedAt:e.publishedAt,links:YT(e.name,s)}:e.status===`skipped`?{name:e.name,status:`skipped`,publishedAt:e.publishedAt,reason:e.reason}:{name:e.name,status:`failed`,publishedAt:e.publishedAt,reason:e.reason});for(let t of u){let n=i.skills[t];if(!n){e.push({name:t,status:`failed`,reason:`skill not found in registry`});continue}e.push({name:t,status:`update`,publishedAt:n.publishedAt,links:YT(t,s)})}O({action:`skill.update`,registry:at(),agents:qT(s),skills:e},t);let r=e.filter(e=>e.status===`failed`);if(r.length>0)throw new n(`${r.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`);return}let d=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 ut(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)}}}),f=await gn(d,3);if(c.push(...f),Gn(a),t===`json`)O({registry:at(),skills:c},t);else if(c.length===0)D(`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 cr([`NAME`,`STATUS`,`PUBLISHED`],e))D(t);let t=c.filter(e=>(e.status===`skipped`||e.status===`failed`)&&e.reason);if(t.length>0){D(``);for(let e of t)D(` ${e.name}: ${e.reason}`)}}let p=c.filter(e=>e.status===`failed`);if(p.length>0)throw new n(`${p.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`)}}),QT=S({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=Kt(e.flags.name,!1),i=tn(),a=r===`all`?Object.keys(i.skills):r;if(a.length===0){O({skills:[]},t),t===`text`&&D(`No skills installed locally; nothing to remove.`);return}let o=new Set(Et()),s=ot();if(e.settings.dryRun){let e=a.map(e=>{let t=i.skills[e];return t?{name:e,status:`remove`,canonical:j(s,e),links:Yt(e,t.links??[])}:{name:e,status:`failed`,reason:o.has(e)?`directory not managed by bl skill (untracked); remove manually if needed`:`not installed`}});O({action:`skill.remove`,skills:e},t);let r=e.filter(e=>e.status===`failed`);if(r.length>0)throw new n(`${r.length}/${e.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`);return}let c=[];for(let e of a){let t=i.skills[e];if(!t){c.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=In(e,t.links??[]);on(e),delete i.skills[e],c.push({name:e,status:`removed`,removedLinks:n.length})}catch(t){c.push({name:e,status:`failed`,reason:t instanceof Error?t.message:String(t)})}}if(Gn(i),t===`json`)O({skills:c},t);else{let e=c.map(e=>[e.name,e.status,e.status===`removed`?`reclaimed ${e.removedLinks} agent link(s)`:e.reason??`-`]);for(let t of cr([`NAME`,`STATUS`,`DETAIL`],e))D(t)}let u=c.filter(e=>e.status===`failed`);if(u.length>0)throw new n(`${u.length}/${c.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 $T(e){return e?e.length>60?`${e.slice(0,59)}…`:e:`-`}var eE=S({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 Ue(),r=tn(),i=ve(n,r,Et());if(t===`json`){O({registry:at(),...n.updatedAt?{updatedAt:n.updatedAt}:{},skills:i},t);return}if(i.length===0){D(`Skill registry is empty and no skills are installed locally.`);return}let a=i.map(e=>[e.name,e.status,e.publishedAt?e.publishedAt.slice(0,19).replace(`T`,` `):`-`,$T(e.description)]);for(let e of cr([`NAME`,`STATUS`,`UPDATEDAT`,`DESCRIPTION`],a))D(e)}});const tE=`json`,nE={success:`success`,partial:`partial`,failed:`failed`};var rE=S({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:tE,r=await Ue(),i=Object.keys(r.skills).filter(e=>e.startsWith(`bailian-`)),a=Ae();if(e.settings.dryRun){O({action:`skill.init`,skills:i.map(e=>({name:e,links:YT(e,a)})),agents:qT(a)},t);return}let o=tn(),s=i.map(e=>async()=>{let t=r.skills[e];try{let n=await ut(e,t,a,o.skills[e]?.links??[]);return o.skills[e]=n.lockEntry,{name:e,status:nE.success}}catch(t){return{name:e,status:nE.failed,reason:t instanceof Error?t.message:String(t)}}}),c=await gn(s,3);Gn(o);let u=c.filter(e=>e.status===nE.success),d=c.filter(e=>e.status===nE.failed),f=d.length===0?nE.success:u.length===0?nE.failed:nE.partial;if(t===tE){let e=a.map(e=>e.id),n={status:f,skills:u.map(e=>e.name)};d.length>0&&(n.failed=d.map(t=>({name:t.name,reason:t.reason,agents:e}))),O(n,t)}else if(c.length===0)D(`No bailian-* skills found in the registry.`);else if(D(f===nE.success?`Installed ${u.length} bailian-* skills.`:`Installed ${u.length}/${c.length} bailian-* skills.`),d.length>0){D(`Failed:`);for(let e of d)D(` ${e.name}: ${e.reason}`)}if(d.length>0)throw new n(`${d.length}/${c.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 iE=[{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":`代码执行+浏览器双能力`}}],aE=iE.flatMap(e=>[e.id,e.imageName]),oE=iE.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 sE(e){let t=iE.find(t=>t.id===e||t.imageName===e);if(!t)throw new x(`Unknown built-in image / 未知内置镜像: ${e}. ${aE.join(`, `)}`);return t}const cE=S({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。`},...oE],async run(e){if(e.settings.quiet){for(let e of iE)D(e.id);return}if(C(e.settings.output)===`json`){O(iE,`json`);return}for(let e of iE)D(`${e.id} (${e.imageName})`),D(` ${e.imageUrl}`),D(` ${e.description[`en-US`]} / ${e.description[`zh-CN`]}`)}}),lE={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 时可省略`}}},uE={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 优先`}}},dE={instanceTimeout:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Sandbox lifetime after this operation (300-604800 seconds)`,"zh-CN":`本次操作后的 Sandbox 存活时间(300–604800 秒)`}}},fE={showCredentials:{type:`switch`,description:{"en-US":`Print envd and traffic access tokens instead of redacting them`,"zh-CN":`输出 envd 与流量访问 Token 原值,不进行脱敏`}}},pE={pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Template build polling interval (default: 5 seconds)`,"zh-CN":`模版构建轮询间隔(默认:5 秒)`}}},mE=[{"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 hE(e,t){return e.client.url(_n(t),()=>vn(gE(e)))}function gE(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 _E(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 vE(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 di(t,`utf8`);try{return _E(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 yE(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 bE(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 xE(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 SE(e,t){if(typeof e!=`number`||!Number.isInteger(e)||e<=0)throw new n(`${t} must be a positive integer.`,l.USAGE)}const CE=/* @__PURE__ */ new Set([`envdAccessToken`,`trafficAccessToken`]),wE=/(?:token|secret|password|credential|api[_-]?key)/i;function TE(e,t){if(Array.isArray(e))return e.map(e=>TE(e,t));if(typeof e!=`object`||!e)return e;let n={};for(let[r,i]of Object.entries(e)){if(CE.has(r)||wE.test(r)||t&&(r===`envVars`||r===`envConfig`)){n[r]=i==null?i:(r===`envVars`||r===`envConfig`)&&typeof i==`object`&&!Array.isArray(i)?Object.fromEntries(Object.keys(i).map(e=>[e,`[REDACTED]`])):`[REDACTED]`;continue}n[r]=TE(i,t)}return n}function EE(e){return TE(e,!1)}function DE(e){return TE(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 OE=`sandbox_template`,kE=S({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:{...lE,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(te(),()=>vn(gE(e))),r=e.flags.filename??Yr(e.flags.path),i=e.flags.mimeType??`application/octet-stream`,a=C(e.settings.output);if(e.settings.dryRun){O({method:`POST`,endpoint:t,request:{source:OE,file:{path:e.flags.path,filename:r,mimeType:i}}},a);return}let o=new Uint8Array(await di(e.flags.path)),s=new FormData;s.append(`source`,OE),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?D(c.id):O(EE(c),a)}}),AE={sandboxId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Sandbox instance ID`,"zh-CN":`Sandbox 实例 ID`}}},jE={...lE,...uE,templateId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Ready template ID; may alternatively be supplied as templateID in --body`,"zh-CN":`已就绪的模版 ID;也可通过 --body 中的 templateID 提供`}},...dE,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`}},...fE},ME={...lE,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)`}}},NE={...lE,...AE,...fE},PE={...lE,...AE},FE={...lE,...AE,...uE,...dE,...fE};async function IE(e){let t=await vE(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),bE(t,`metadata`,yE(e.metadata,`--metadata`)),bE(t,`envVars`,yE(e.env,`--env`));let r={};if(Q(r,`allowOut`,e.allowOut),Q(r,`denyOut`,e.denyOut),Q(r,`maskRequestHost`,e.maskRequestHost),bE(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 xE(t.timeout,`Sandbox timeout`,300,604800),t}async function LE(e){let t=await vE(e.body);return Q(t,`timeout`,e.instanceTimeout),xE(t.timeout,`Sandbox timeout`,300,604800),t}function RE(e,t){let n=t.showCredentials?e:EE(e);if(t.quiet){D($(e.sandboxID));return}O(n,t.format)}const zE=S({description:{"en-US":`Create a Sandbox instance`,"zh-CN":`创建 Sandbox 实例`},auth:`apiKey`,usageArgs:`(--template-id <id> | --body <json|@path>) [flags]`,flags:jE,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:mE,async run(e){let t=C(e.settings.output),n=hE(e,_.sandboxes),r=await IE(e.flags);if(e.settings.dryRun){O({method:`POST`,endpoint:n,request:DE(r)},t);return}RE(await e.client.requestJson({path:n,method:`POST`,body:r}),{format:t,quiet:e.settings.quiet,showCredentials:e.flags.showCredentials})}}),BE=S({description:{"en-US":`List Sandbox instances`,"zh-CN":`列出 Sandbox 实例`},auth:`apiKey`,usageArgs:`[--template-id <id>] [--sandbox-id <id>] [--state <state>] [--limit <n>]`,flags:ME,exampleArgs:[``,`--state running --limit 20`,`--template-id tpl-xxx --output json`],notes:mE,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(hE(e,_.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)D($(e.sandboxID));return}let r=C(e.settings.output);if(r===`json`){O(n,r);return}if(n.length===0){D(`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 cr([`ID`,`TEMPLATE`,`STATE`,`CPU`,`MEMORY_MB`,`STARTED_AT`,`END_AT`],i))D(e)}}),VE=S({description:{"en-US":`Get Sandbox instance details`,"zh-CN":`获取 Sandbox 实例详情`},auth:`apiKey`,usageArgs:`--sandbox-id <id> [--show-credentials]`,flags:NE,exampleArgs:[`--sandbox-id sbx-xxx`,`--sandbox-id sbx-xxx --show-credentials --output json`],notes:mE,async run(e){let t=hE(e,bn(e.flags.sandboxId));RE(await e.client.requestJson({path:t,method:`GET`}),{format:C(e.settings.output),quiet:e.settings.quiet,showCredentials:e.flags.showCredentials})}});function HE(e){let t=e===`connect`?`Connect to`:`Resume`,n=e===`connect`?`连接`:`恢复`;return S({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:FE,exampleArgs:[`--sandbox-id sbx-xxx --instance-timeout 3600`,`--sandbox-id sbx-xxx --show-credentials --output json`],notes:mE,async run(t){let n=C(t.settings.output),r=hE(t,yn(t.flags.sandboxId,e)),i=await LE(t.flags);if(t.settings.dryRun){O({method:`POST`,endpoint:r,request:DE(i)},n);return}RE(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 UE=HE(`connect`),WE=HE(`resume`),GE=S({description:{"en-US":`Pause a Sandbox instance`,"zh-CN":`暂停 Sandbox 实例`},auth:`apiKey`,usageArgs:`--sandbox-id <id>`,flags:PE,exampleArgs:[`--sandbox-id sbx-xxx`,`--sandbox-id sbx-xxx --dry-run --output json`],notes:mE,async run(e){let t=C(e.settings.output),n=hE(e,yn(e.flags.sandboxId,`pause`));if(e.settings.dryRun){O({method:`POST`,endpoint:n,request:null},t);return}await e.client.request({path:n,method:`POST`}),e.settings.quiet?D(e.flags.sandboxId):O({sandboxID:e.flags.sandboxId,paused:!0},t)}}),KE=S({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:PE,exampleArgs:[`--sandbox-id sbx-xxx --dry-run`,`--sandbox-id sbx-xxx --yes`],notes:mE,async run(e){let t=C(e.settings.output),n=hE(e,bn(e.flags.sandboxId));if(e.settings.dryRun){O({method:`DELETE`,endpoint:n,request:null},t);return}await e.client.request({path:n,method:`DELETE`}),e.settings.quiet?D(e.flags.sandboxId):O({sandboxID:e.flags.sandboxId,deleted:!0},t)}}),qE={async:{type:`switch`,description:{"en-US":`Return the submitted templateID/buildID immediately without polling`,"zh-CN":`提交后立即返回 templateID/buildID,不轮询构建状态`}}},JE={templateId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Sandbox template ID`,"zh-CN":`Sandbox 模版 ID`}}},YE={image:{type:`string`,valueHint:`<preset>`,choices:aE,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":`模版描述`}}},XE={...lE,...uE,...YE,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 模版别名`}},...qE,...pE},ZE={...lE,...JE,...uE,...YE,...qE,...pE},QE={...lE,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`}}},$E={...lE,...JE},eD={...lE,...JE,buildId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Template build ID`,"zh-CN":`模版构建 ID`}}};function tD(e,t){if(t.image!==void 0){let n=sE(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),bE(e,`envConfig`,yE(t.env,`--env`));let n={};Q(n,`allowOut`,t.allowOut),Q(n,`denyOut`,t.denyOut),bE(e,`networkConfig`,n)}function nD(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&&SE(e.cpuCount,`cpuCount`),i&&SE(e.memoryMB,`memoryMB`),xE(e.autoPauseTime,`autoPauseTime`,300,604800),xE(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 rD(e){let t=await vE(e.body);return tD(t,e),Q(t,`tags`,e.tag),Q(t,`alias`,e.alias),nD(t,!0),t}async function iD(e){let t=await vE(e.body);return tD(t,e),nD(t,!1),t}async function aD(e,t,r,i){let a=Date.now()+t.timeout*1e3,o=er(`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`){o.stop(`Template build failed.`);let e=c.reason?.message??(c.reason?.code===void 0?`Template build failed.`:`${c.reason.code}`);throw new n(e,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 oD(e){if(e.pollInterval!==void 0&&(!Number.isInteger(e.pollInterval)||e.pollInterval<=0))return`--poll-interval must be a positive integer.`}async function sD(e){let t=C(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?D(`${e.response.templateID}\t${e.response.buildID}`):O(e.response,t);return}let r=new URL(_n(xn(e.response.templateID,e.response.buildID)),e.endpoint).toString(),i;try{i=await aD(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(`
|
|
2879
|
-
`),{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?D($(e.response.templateID)):O({template:e.response,build:i},t)}const cD=S({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:XE,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:[...mE,...oE,{"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:oD,async run(e){let t=C(e.settings.output),n=hE(e,_.templateCreate),r=await rD(e.flags);if(e.settings.dryRun){O({method:`POST`,endpoint:n,request:DE(r)},t);return}await sD({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})}}),lD=S({description:{"en-US":`List Sandbox templates`,"zh-CN":`列出 Sandbox 模版`},auth:`apiKey`,usageArgs:`[--limit <n>] [--cursor <cursor>]`,flags:QE,exampleArgs:[``,`--limit 100 --output json`],notes:[...mE,{"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(hE(e,_.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)D($(e.templateID));return}let r=C(e.settings.output);if(r===`json`){O(n,r);return}if(n.length===0){D(`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 cr([`ID`,`NAME`,`CPU`,`MEMORY_MB`,`INSTANCES`,`BUILDS`,`UPDATED_AT`],i))D(e)}}),uD=S({description:{"en-US":`Get Sandbox template details`,"zh-CN":`获取 Sandbox 模版详情`},auth:`apiKey`,usageArgs:`--template-id <id>`,flags:$E,exampleArgs:[`--template-id tpl-xxx`,`--template-id tpl-xxx --output json`],notes:mE,async run(e){let t=hE(e,Sn(e.flags.templateId)),n=await e.client.requestJson({path:t,method:`GET`});e.settings.quiet?D($(n.templateID)):O(n,C(e.settings.output))}}),dD=S({description:{"en-US":`Update a Sandbox template`,"zh-CN":`更新 Sandbox 模版`},auth:`apiKey`,usageArgs:`--template-id <id> (--body <json|@path> | [fields])`,flags:ZE,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:[...mE,...oE,{"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:oD,async run(e){let t=C(e.settings.output),n=hE(e,Sn(e.flags.templateId)),r=await iD(e.flags);if(e.settings.dryRun){O({method:`PUT`,endpoint:n,request:DE(r)},t);return}await sD({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})}}),fD=S({description:{"en-US":`Get Sandbox template build status`,"zh-CN":`获取 Sandbox 模版构建状态`},auth:`apiKey`,usageArgs:`--template-id <id> --build-id <id>`,flags:eD,exampleArgs:[`--template-id tpl-xxx --build-id build-xxx`,`--template-id tpl-xxx --build-id build-xxx --output json`],notes:mE,async run(e){let t=hE(e,xn(e.flags.templateId,e.flags.buildId)),n=await e.client.requestJson({path:t,method:`GET`});e.settings.quiet?D($(n.status)):O(n,C(e.settings.output))}}),pD=S({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:$E,exampleArgs:[`--template-id tpl-xxx --dry-run`,`--template-id tpl-xxx --yes`],notes:[...mE,{"en-US":`The server rejects deletion while running or paused instances still use the template.`,"zh-CN":`仍有运行中或已暂停实例使用该模版时,服务端会拒绝删除。`}],async run(e){let t=C(e.settings.output),n=hE(e,Sn(e.flags.templateId));if(e.settings.dryRun){O({method:`DELETE`,endpoint:n,request:null},t);return}await e.client.request({path:n,method:`DELETE`}),e.settings.quiet?D(e.flags.templateId):O({templateID:e.flags.templateId,deleted:!0},t)}});export{Vh as advisorRecommend,Kv as alertCreate,Xv as alertDelete,$v as alertDisable,Zv as alertEnable,ny as alertHistory,Wv as alertList,jv as alertMetrics,Lv as alertTemplateCreate,Vv as alertTemplateDelete,Pv as alertTemplateList,zv as alertTemplateUpdate,Jv as alertUpdate,Au as appCall,Mu as appList,vo as authGenerateAccessToken,ho as authLogin,_o as authLogout,go as authStatus,Cu as configAgent,hs as configList,ms as configSet,ps as configShow,ql as configUi,gs as configUse,Bp as consoleCall,hy as datasetDelete,my as datasetGet,py as datasetList,fy as datasetUpload,gy as datasetValidate,ub as deployAudioCreate,_b as deployDelete,pb as deployGet,db as deployImageCreate,fb as deployList,mb as deployModels,vb as deployPause,yb as deployResume,hb as deployScale,lb as deployTextCreate,gb as deployUpdate,zp as fileUpload,jy as finetuneAudioCreate,zy as finetuneCancel,eb as finetuneCapability,Gy as finetuneCheckpoints,By as finetuneDelete,Ky as finetuneExport,Ry as finetuneGet,My as finetuneImageCreate,Fy as finetuneList,Wy as finetuneLogs,rb as finetunePrice,Ay as finetuneTextCreate,Py as finetuneVideoCreate,Zy as finetuneWatch,Ho as imageEdit,Lo as imageGenerate,Tf as knowledgeCategoryAdd,Df as knowledgeCategoryDelete,Cf as knowledgeCategoryList,ad as knowledgeChat,uf as knowledgeChunkAdd,vf as knowledgeChunkDelete,ff as knowledgeChunkList,hf as knowledgeChunkUpdate,Ff as knowledgeCollectionCreate,Lf as knowledgeCollectionGet,Fd as knowledgeDocDelete,zf as knowledgeDocImportOss,pd as knowledgeDocList,gd as knowledgeDocStatus,Ld as knowledgeDocTag,Ed as knowledgeDocUpload,Nf as knowledgeFileDelete,jf as knowledgeFileGet,kf as knowledgeFileList,kd as knowledgeKbCreate,Nd as knowledgeKbDelete,dd as knowledgeKbInfo,sd as knowledgeKbList,xf as knowledgeKbStats,jd as knowledgeKbUpdate,Bu as knowledgeRetrieve,$u as knowledgeSearch,sf as knowledgeServiceCopy,Kd as knowledgeServiceCreate,af as knowledgeServiceDelete,nf as knowledgeServiceDeploy,Wd as knowledgeServiceGet,Vd as knowledgeServiceList,ef as knowledgeServiceUpdate,ev as logAuditCount,nv as logAuditDisable,tv as logAuditEnable,Q_ as logAuditGet,Z_ as logAuditList,lv as logInferenceCount,dv as logInferenceDisable,uv as logInferenceEnable,sv as logInferenceGet,av as logInferenceList,Y_ as logStatus,vv as logTraceGet,hv as logTraceList,bv as logTraceStats,AC as managedAgentAgentCreate,XC as managedAgentAgentGet,ZC as managedAgentAgentList,QC as managedAgentAgentSearch,$C as managedAgentAgentVersions,Ox as managedAgentApply,VC as managedAgentDeploymentCreate,Aw as managedAgentDeploymentGet,jw as managedAgentDeploymentList,Nw as managedAgentDeploymentPause,Pw as managedAgentDeploymentRun,Fw as managedAgentDeploymentRunsGet,Iw as managedAgentDeploymentRunsList,Lw as managedAgentDeploymentSearch,Rw as managedAgentDeploymentUnpause,kx as managedAgentDestroy,MC as managedAgentEnvironmentCreate,iw as managedAgentEnvironmentGet,aw as managedAgentEnvironmentList,ow as managedAgentEnvironmentSearch,jT as managedAgentFileDelete,AT as managedAgentFileDownload,OT as managedAgentFileGet,DT as managedAgentFileList,kT as managedAgentFileSearch,ET as managedAgentFileUpload,tx as managedAgentInit,Dx as managedAgentPlan,Zx as managedAgentPlayground,tS as managedAgentProjectBuild,$x as managedAgentProjectInit,nS as managedAgentProjectPublish,eS as managedAgentProjectValidate,aS as managedAgentProjectVersionDisable,iS as managedAgentProjectVersionEnable,cS as managedAgentProjectVersionList,uS as managedAgentProjectVersionPreview,dS as managedAgentProjectVersionRestore,sS as managedAgentProjectVersionStatus,rS as managedAgentProjectWorkbench,qw as managedAgentSessionArchive,DS as managedAgentSessionCreate,hT as managedAgentSessionDebug,zS as managedAgentSessionDelete,QS as managedAgentSessionEventList,QS as managedAgentSessionEvents,$S as managedAgentSessionEventSend,eC as managedAgentSessionEventStream,gT as managedAgentSessionExport,RS as managedAgentSessionGet,LS as managedAgentSessionList,BS as managedAgentSessionRun,Gw as managedAgentSessionSearch,VS as managedAgentSessionSend,Kw as managedAgentSessionUpdate,IC as managedAgentSkillCreate,sw as managedAgentSkillDownload,cw as managedAgentSkillGet,dC as managedAgentSkillList,lw as managedAgentSkillSearch,uw as managedAgentSkillVersions,vS as managedAgentStateImport,pS as managedAgentStateList,hS as managedAgentStateRm,mS as managedAgentStateShow,wx as managedAgentValidate,LC as managedAgentVaultCreate,RC as managedAgentVaultCredentialCreate,hw as managedAgentVaultGet,gw as managedAgentVaultList,_w as managedAgentVaultSearch,Yf as mcpCall,Qf as mcpConnect,tp as mcpDisconnect,rp as mcpList,ip as mcpTools,Nu as memoryAdd,Lu as memoryDelete,Fu as memoryList,Ru as memoryProfileCreate,zu as memoryProfileGet,Pu as memorySearch,Iu as memoryUpdate,Eg as modelCode,ug as modelList,vg as modelSearch,E_ as monitorDeliveryDisable,w_ as monitorDeliveryEnable,v_ as monitorDeliveryStatus,g_ as monitorErrors,f_ as monitorMetrics,a_ as monitorModels,t_ as monitorOverview,uy as permissionGrant,ay as permissionList,dy as permissionRevoke,xh as pipelineRun,Eh as pipelineValidate,UT as pluginInstall,WT as pluginLink,GT as pluginList,KT as pluginRemove,Qg as quotaCheck,zg as quotaDelete,Gg as quotaHistory,Lg as quotaList,Rg as quotaUpdate,UE as sandboxConnect,zE as sandboxCreate,KE as sandboxDelete,kE as sandboxFileUpload,VE as sandboxGet,BE as sandboxList,cE as sandboxOfficialImages,GE as sandboxPause,WE as sandboxResume,fD as sandboxTemplateBuildStatus,cD as sandboxTemplateCreate,pD as sandboxTemplateDelete,uD as sandboxTemplateGet,lD as sandboxTemplateList,dD as sandboxTemplateUpdate,op as searchWeb,$p as securityAlerts,Xp as securityOverview,XT as skillAdd,rE as skillInit,eE as skillList,QT as skillRemove,ZT as skillUpdate,Sp as speechRecognize,gp as speechSynthesize,jp as speechVocabularyCreate,Rp as speechVocabularyDelete,Pp as speechVocabularyGet,Mp as speechVocabularyList,Ip as speechVocabularyUpdate,Oo as textChat,Fo as textOmni,Gb as tokenPlanAddMember,Vb as tokenPlanAssignSeats,Ib as tokenPlanCreateKey,$b as tokenPlanHarnessQuota,jb as tokenPlanListSeats,ku as update,yh as usageCodingPlan,Qm as usageFree,$m as usageFreetier,rh as usageStats,ih as usageSummary,fh as usageTokenPlan,Xo as videoDownload,qo as videoEdit,Ko as videoGenerate,Jo as videoRef,Yo as videoTaskGet,es as visionDescribe,RT as workspaceInit,jg as workspaceList};
|
|
2879
|
+
`):e.type===`error`&&process.stderr.write(`\n[error] ${e.content??`unknown error`}\n`)}}function DC(e,t,n={}){if(t)process.stdout.write(`${JSON.stringify({...n,events:Ya(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)EC(t);SC(e.terminalStatus,t)}wC(e.terminalStatus,CC(e.result.events))}function OC(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean):void 0}var kC=S({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:G,async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=n.file??`agents.yaml`;if(t.dryRun){O({would_create_session:{agent:n.agent??`auto`,provider:`bailian`,environment:n.environment,vault:n.vault,memory_stores:OC(n.memoryStores),title:n.title},config_file:i},r);return}let{agentName:a,session:o}=await q(()=>J(async()=>{let t=await K(e,i);return Wi(t,{agent:n.agent,provider:`bailian`,environment:n.environment,vault:n.vault,memoryStores:OC(n.memoryStores),title:n.title})}));if(r===`json`){O({agent:a,session:o},r);return}D(`Session created: ${o.id}`),D(` Agent: ${a}`),D(` Environment: ${o.environment_id}`),D(` Status: ${o.status}`),o.vault_ids.length&&D(` Vaults: ${o.vault_ids.join(`, `)}`),o.memory_store_ids.length&&D(` Memory: ${o.memory_store_ids.join(`, `)}`)}});async function AC(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 Y={file:{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}},X={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 获取全部分页`}}},jC={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)`}}},MC={includeArchived:{type:`switch`,description:{"en-US":`Include archived resources`,"zh-CN":`包含已归档资源`}}};function NC(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 PC(e){if(!e)return;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t.length>0?t:void 0}function FC(e,...t){let n=e.trim().toLocaleLowerCase();return!n||t.some(e=>e!=null&&(typeof e==`string`?e:JSON.stringify(e)).toLocaleLowerCase().includes(n))}async function IC(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 LC(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`){O({[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){D(u);return}for(let e of Sr(i,a))D(e);D(`\nTotal: ${r.length}`),c?D(`Search stopped at --page-limit; more pages remain.`):o&&D(`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}const RC={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:X.limit,page:X.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 时间戳`}}};var zC=S({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:RC,exampleArgs:[``,`--agent assistant`,`--all`],notes:G,validate:NC,async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=n.file??`agents.yaml`,{items:a,hasMore:o,nextPage:s}=await q(()=>J(async()=>{let t=await K(e,i);return AC(async e=>{let r=await ba(t,{agent:n.agent,provider:`bailian`,filter:{page:e,limit:n.limit,statuses:PC(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`){O({sessions:c,has_more:o,next_page:s},r);return}if(c.length===0){D(`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 Sr(u,d))D(e);D(`\nTotal: ${c.length}`),o&&D(`More sessions available. Use --all to fetch all.`)}}),BC=S({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:G,async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=n.file??`agents.yaml`,a=await q(()=>J(async()=>{let t=await K(e,i);return oa(t,n.sessionId,`bailian`)}));if(r===`json`){O(a,r);return}D(` ID: ${a.id}`),D(` Agent: ${a.agent_id}`),D(` Environment: ${a.environment_id}`),D(` Status: ${a.status}`),a.title&&D(` Title: ${a.title}`),D(` Created: ${a.created_at}`),D(` Updated: ${a.updated_at}`)}}),VC=S({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:G,async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=n.file??`agents.yaml`;if(t.dryRun){O({would_delete_session:n.sessionId,provider:`bailian`,config_file:i},r);return}await q(()=>J(async()=>{let t=await K(e,i);await qi(t,n.sessionId,`bailian`)})),r===`json`?O({deleted:n.sessionId},r):D(`Session ${n.sessionId} deleted.`)}}),HC=S({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:[...G,{"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=C(t.output),i=n.file??`agents.yaml`,a=r===`json`,o={agent:n.agent,provider:`bailian`,environment:n.environment,vault:n.vault,memoryStores:OC(n.memoryStores),title:n.title};if(t.dryRun){O({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 q(()=>J(async()=>{let t=await K(e,i);if(n.noStream){let e=await Pa(t,n.prompt,o);a||process.stderr.write(`Session created: ${e.session.id}\n`),DC(e,a,{session_id:e.session.id,provider:e.provider,agent:e.agentName})}else{let e=await Na(t,n.prompt,o);a||process.stderr.write(`Session created: ${e.session.id}\n`),await TC(e.events,a,{session_id:e.session.id,provider:e.provider,agent:e.agentName})}}))}}),UC=S({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:G,async run(e){let{settings:t,flags:n}=e,r=C(t.output),i=n.file??`agents.yaml`,a=r===`json`;if(t.dryRun){O({would_send:{session_id:n.sessionId,message:n.message,provider:`bailian`,mode:n.noStream?`polling`:`streaming`},config_file:i},r);return}await q(()=>J(async()=>{let t=await K(e,i);n.noStream?DC(await Aa(t,n.sessionId,n.message,{provider:`bailian`}),a,{session_id:n.sessionId}):await TC(await ja(t,n.sessionId,n.message,{provider:`bailian`}),a,{session_id:n.sessionId})}))}});async function WC(e){return new Uint8Array(await Ei(M(e)))}async function GC(e){let t=e.startsWith(`@`)?await Ei(M(e.slice(1)),`utf8`):e;try{return JSON.parse(t)}catch(e){let t=e instanceof Error?e.message:String(e);throw new n(`Invalid JSON input: ${t}`,l.USAGE)}}async function KC(e,t,r=!1){let i=M(e),a=di(i);await Ti(a,{recursive:!0});let o=`${i}.${zr()}.tmp`;await Ai(o,t,{flag:`wx`});try{if(r)await Di(o,i);else{try{await wi(o,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 ki(o)}return i}catch(e){throw await ki(o).catch(()=>void 0),e}}function qC(e){let t=ui(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 JC={sessionId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Session ID`,"zh-CN":`Session ID`}}},YC={...Y,...JC,...X,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":`创建时间不晚于该时间戳`}}},XC={...Y,...JC,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`}}},ZC={...Y,...JC,afterId:{type:`string`,valueHint:`<event-id>`,description:{"en-US":`Resume after this event ID`,"zh-CN":`从该 Event ID 之后继续`}}};function QC(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 $C(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=Li.safeParse(r);if(t.success)continue;let i=t.error.issues[0],a=i?.path.length?` at ${i.path.join(`.`)}`:``;throw new n(`Invalid event at index ${e}${a}: ${i?.message??`does not match the Session event schema`}.`,l.USAGE)}return t}const ew=S({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:YC,exampleArgs:[`--session-id sess_abc`,`--session-id sess_abc --all --output json`],notes:[...G,{"en-US":`--types is applied client-side to each page returned by the provider.`,"zh-CN":`--types 会在客户端对 Provider 返回的每一页结果进行过滤。`}],validate:NC,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return AC(async n=>{let r=await ya(t,e.flags.sessionId,{provider:`bailian`,limit:e.flags.limit,page_token:n,order:e.flags.order,types:PC(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)}));LC({format:t,key:`events`,items:Ya(n.items),headers:[`ID`,`TYPE`,`THREAD`,`CONTENT`],rows:QC(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No events found.`})}}),tw=S({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:XC,exampleArgs:[`--session-id sess_abc --event '{"type":"message","role":"user","content":[{"type":"text","text":"hello"}]}'`,`--session-id sess_abc --event @event.json`],notes:G,async run(e){let t=C(e.settings.output),n=$C(await GC(e.flags.event));if(e.settings.dryRun){O({would_send_events:n,session_id:e.flags.sessionId},t);return}let r=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return ka(t,e.flags.sessionId,n,{provider:`bailian`})}));t===`json`?O({session_id:e.flags.sessionId,...r},t):D(`Sent ${n.length} event(s): ${r.event_ids.join(`, `)}`)}}),nw=S({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:ZC,exampleArgs:[`--session-id sess_abc`,`--session-id sess_abc --after-id evt_123 --output json`],notes:[...G,{"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=C(e.settings.output);await q(()=>J(async()=>{let n=await K(e,e.flags.file??`agents.yaml`),r=[];for await(let i of Fa(n,e.flags.sessionId,{provider:`bailian`,after_id:e.flags.afterId}))if(r.push(i),t!==`json`&&D(JSON.stringify(Ya([i])[0])),i.type===`status`&&la(i.status))break;t===`json`&&O({session_id:e.flags.sessionId,events:Ya(r)},t)}))}}),rw={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`}}},iw={...Y,...X,...rw},aw={...Y,limit:X.limit,...jC,...rw},ow={...Y,skillId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Skill ID`,"zh-CN":`Skill ID`}}},sw={...ow,...X},cw={...ow,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 lw(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 uw(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 dw(e,t){return{source:e,skills:t.items,has_more:t.hasMore,next_page:t.nextPage}}async function fw(e,t,n){return AC(async r=>{let i=await _a(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 pw=S({description:{"en-US":`List Managed Agent skills`,"zh-CN":`列出托管 Agent Skill`},auth:`apiKey`,usageArgs:`[--source custom|official|all] [--limit <n>] [--page <cursor>] [--all]`,flags:iw,exampleArgs:[``,`--source official`,`--source all --all --output json`],notes:[...G,{"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=>NC(e)??(e.source===`all`&&e.page?`--source all cannot be combined with --page.`:void 0),async run(e){let t=C(e.settings.output),n=e.flags.source??`custom`,r=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);if(n!==`all`)return fw(t,n,{limit:e.flags.limit,page:e.flags.page,all:e.flags.all});let[r,i]=await Promise.all([fw(t,`custom`,{limit:e.flags.limit,all:e.flags.all}),fw(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`){O(dw(n,r),t);return}LC({format:t,key:`skills`,items:r.items,headers:[`ID`,`NAME`,`SOURCE`,`STATUS`,`VERSION`,`UPDATED`],rows:lw(r.items),hasMore:r.hasMore,nextPage:r.nextPage,emptyMessage:`No skills found.`})}});const mw=[{"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 hw(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 gw(e,t=`resource`){return e.normalize(`NFKC`).trim().toLowerCase().replace(/[^\p{L}\p{N}]+/gu,`-`).replace(/^-+|-+$/g,``)||t}function _w(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=hw(e.candidate);for(let[r,i]of Object.entries(e.declarations))if(!(e.effectiveName(r,i)!==e.displayName||t.has(r))&&hw(i)===n)return{key:r,reusedPending:!0};let r=gw(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 vw(e,t){let r=await Ei(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 q(()=>yS(e,t,{credentials:`none`})),a=await Ei(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||pS(i.config.providers,[o]),_S(e);let s=new Ii({configPath:i.configPath});return{...i,source:a,provider:o,stateBackend:s,stateScope:mS(i.configPath,i.projectName)}}async function yw(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 q(()=>Da(n,{projectName:e.project.projectName,basePath:di(e.project.configPath)}))).config[e.group]?.[t]??e.rawDeclaration}async function bw(e){let{project:t,host:r}=e,i=C(r.settings.output),a=await t.stateBackend.read(t.stateScope,n=>_w({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=vi(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 q(()=>J(()=>wa(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`?O(c,i):(D(`Generated YAML key: ${o}`),ww(n.plan.actions,n.plan.diagnostics),D(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 xw(t.configPath,t.source,d);let m;try{m=await q(()=>J(()=>Ia(p,{provider:t.provider,scope:{roots:[f]},mode:`create-only`,refresh:!0,quiet:i===`json`,policy:`block`})))}catch(t){throw TS(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`?O(v,i):(D(`Wrote ${t.configPath} with ${e.resourceType} key '${o}'.`),_||D(`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 xw(e,t,r){let i=M(e);if(await Ei(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 Oi(i),o=M(di(i),`.${ui(i)}.${zr()}.tmp`);await Ai(o,r,{flag:`wx`,mode:a.mode});try{await Di(o,i)}catch(e){throw await ki(o).catch(()=>void 0),e}}function Sw(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 Cw(e,t){let r=[];for(let i of e??[]){let e=i.startsWith(`@`)?await Ei(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 ww(e,t){for(let e of t)D(`[${e.severity}] ${e.code}: ${e.message}`);for(let t of e.filter(e=>e.action!==`no-op`)){let e=t.action===`create`?`+`:t.action===`update`?`~`:`-`;D(` ${e} ${DS(t.address)}`)}}const Tw={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 Ew(e){return _w({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 Dw(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 Ow(e,t=`custom`){let r=/* @__PURE__ */ 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 kw(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 Aw(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)&&kw(r)===kw(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{..._w({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 jw(e,t){let r={...e.config.skills??{}},i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ 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 q(()=>ca(t,{basePath:process.cwd()})),c=await Oi(s.sourcePath);if(!(c.isDirectory()||c.isFile()&&fi(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=pi(di(e.configPath),s.sourcePath).split(mi).join(`/`)||`.`,d={name:s.name,source:u,origin:`custom`,provider:e.provider},f=await yw({project:e,group:`skills`,rawDeclaration:d}),p=await e.stateBackend.read(e.stateScope,t=>Aw({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 Mw=S({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:Tw,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:[...G,{"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=C(r.output),a=await vw(e,t.file??`agents.yaml`),o=a.provider,s=Ow(t.skill,Dw(t.type)),c=await jw(a,t.skillDir),u=[...s,...c.map(e=>e.key)],d=Hi(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 yw({project:{...a,config:f},group:`agents`,rawDeclaration:d}),m=await a.stateBackend.read(a.stateScope,e=>Ew({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=vi(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 q(()=>J(()=>wa(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`)O(s,i);else{for(let e of c)D(`Generated Skill YAML key: ${e.key}`);D(`Generated Agent YAML key: ${h}`);for(let t of e.plan.diagnostics)D(`[${t.severity}] ${t.code}: ${t.message}`);for(let t of e.plan.actions.filter(e=>e.action!==`no-op`)){let e=t.action===`create`?`+`:t.action===`update`?`~`:`-`;D(` ${e} ${DS(t.address)}`)}D(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 xw(a.configPath,a.source,_);let ee;try{ee=await q(()=>J(()=>Ia(b,{provider:o,scope:{roots:y},refresh:!0,quiet:i===`json`,mode:`create-only`,policy:`block`})))}catch(e){throw TS(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 x=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]))})),te=ee.execution?.results??[],ne=te.find(e=>e.status===`failed`),re=ne?`failed`:`completed`,ie={agent:{key:h,name:t.name.trim(),provider:o,remote_id:x.agentId,skills:u},local_skills:c.map(e=>({key:e.key,name:e.name,source:e.source,remote_id:x.skillIds[e.key],reused_pending:e.reusedPending,reused_tracked:e.reusedTracked})),config_file:a.configPath,yaml_written:!0,reused_pending:m.reusedPending,status:re,actions:ee.planned.plan.actions,diagnostics:ee.planned.plan.diagnostics,results:te,error:ne?.error};if(i===`json`?O(ie,i):(D(`Wrote ${a.configPath} with Agent key '${h}'${c.length?` and ${c.length} local Skill declaration(s)`:``}.`),D(re===`completed`?`Created Agent '${t.name.trim()}'.`:`Scoped create ${re}: ${ne?.error??`unknown error`}`)),ne)throw new n(ne.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.`)}});const Nw={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:Fw(`APT`),pip:Fw(`pip`),npm:Fw(`npm`),cargo:Fw(`Cargo`),gem:Fw(`Ruby gem`),go:Fw(`Go`),file:Iw(),yes:Lw()};var Pw=S({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:Nw,exampleArgs:[`--name Development`,`--name Development --pip pandas --npm typescript --metadata owner=platform --yes`],notes:[...G,...mw,{"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 vw(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:Sw(e.flags.metadata)},i=await yw({project:t,group:`environments`,rawDeclaration:r});await bw({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 Fw(e){return{type:`array`,valueHint:`<package>`,description:{"en-US":`${e} package (repeatable)`,"zh-CN":`${e} 软件包(可重复)`}}}function Iw(){return{type:`string`,valueHint:`<path>`,description:{"en-US":`Config file path (default: agents.yaml)`,"zh-CN":`配置文件路径(默认:agents.yaml)`}}}function Lw(){return{type:`switch`,description:{"en-US":`Write YAML and run the scoped remote create`,"zh-CN":`写入 YAML 并执行定向远端创建`}}}var Rw=S({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:[...G,...mw,{"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 vw(e,e.flags.file??`agents.yaml`),r=await ca(e.flags.source,{basePath:process.cwd()}),i=pi(di(t.configPath),r.sourcePath).split(mi).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 yw({project:t,group:`skills`,rawDeclaration:o});await bw({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})}}),zw=S({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:[...G,...mw,{"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 vw(e,e.flags.file??`agents.yaml`),n={display_name:e.flags.name.trim(),provider:t.provider,credentials:[],metadata:Sw(e.flags.metadata)},r=await yw({project:t,group:`vaults`,rawDeclaration:n});await bw({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})}}),Bw=S({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:[...G,...mw,{"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=C(e.settings.output);Vi();let r=process.env[e.flags.secretEnv],i=await vw(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=Sw(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=vi(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||!Vw(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 q(()=>Da(p,{projectName:i.projectName,basePath:di(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 q(()=>J(()=>Ta(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`?O(r,t):(D(`Vault: ${e.flags.vault}`),D(`Credential: ${e.flags.name.trim()} (secret from ${e.flags.secretEnv})`),D(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 xw(i.configPath,i.source,_);let y;try{y=await q(()=>J(()=>Gi(v,e.flags.vault,e.flags.name.trim(),{provider:i.provider,refresh:!0,quiet:t===`json`})))}catch(e){throw TS(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`?O(b,t):D(`Wrote ${i.configPath} and created Credential '${e.flags.name.trim()}'.`)}});function Vw(e,t){return Hw(e)===Hw(t)}function Hw(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 Uw=S({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:[...G,...mw,{"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 vw(e,e.flags.file??`agents.yaml`),r=[...(e.flags.message??[]).map(e=>({type:`user.message`,content:e})),...Ww(await Cw(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=Gw(await Cw(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&&Kw(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:Sw(e.flags.metadata)},o=await yw({project:t,group:`deployments`,rawDeclaration:a});await bw({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 Ww(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 Gw(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 Kw(e){try{new Intl.DateTimeFormat(`en-US`,{timeZone:e}).format()}catch{throw new n(`Invalid IANA timezone: ${e}`,l.USAGE)}}const qw={...Y,...X,...MC},Jw={...Y,limit:X.limit,...jC,...MC},Yw={...Y,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 版本`}}},Xw={...Y,...X,agentId:Yw.agentId};function Zw(e){return e.map(e=>[e.id,Z(e.name),Z(e.version),Z(e.type),Z(e.updated_at)])}var Qw=S({description:{"en-US":`Get a Managed Agent`,"zh-CN":`获取托管 Agent 详情`},auth:`apiKey`,usageArgs:`--agent-id <id> [--agent-version <n>] [--file <path>]`,flags:Yw,exampleArgs:[`--agent-id agent_abc`,`--agent-id agent_abc --agent-version 3 --output json`],notes:G,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=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return ea(t,e.flags.agentId,{provider:`bailian`,version:e.flags.agentVersion})}));if(t===`json`){O(n,t);return}D(`ID: ${n.id}`),D(`Name: ${Z(n.name)}`),D(`Description: ${Z(n.description,120)}`),D(`Version: ${Z(n.version)}`),D(`Type: ${Z(n.type)}`),D(`Created: ${Z(n.created_at)}`),D(`Updated: ${Z(n.updated_at)}`)}}),$w=S({description:{"en-US":`List Managed Agents`,"zh-CN":`列出托管 Agent`},auth:`apiKey`,usageArgs:`[--limit <n>] [--page <cursor>] [--all] [--include-archived] [--file <path>]`,flags:qw,exampleArgs:[``,`--limit 50`,`--all --include-archived --output json`],notes:G,validate:NC,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return AC(async n=>{let r=await da(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)}));LC({format:t,key:`agents`,items:n.items,headers:[`ID`,`NAME`,`VERSION`,`TYPE`,`UPDATED`],rows:Zw(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No agents found.`})}}),eT=S({description:{"en-US":`Search Managed Agents`,"zh-CN":`搜索托管 Agent`},auth:`apiKey`,usageArgs:`--query <text> [--limit <n>] [--page-limit <n>] [--include-archived]`,flags:Jw,exampleArgs:[`--query assistant`,`--query code --page-limit 20 --output json`],notes:G,validate:NC,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return IC(async n=>{let r=await da(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=>FC(e.flags.query,t.id,t.name,t.description),e.flags.pageLimit)}));LC({format:t,key:`agents`,items:n.items,headers:[`ID`,`NAME`,`VERSION`,`TYPE`,`UPDATED`],rows:Zw(n.items),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching agents found.`})}}),tT=S({description:{"en-US":`List Managed Agent versions`,"zh-CN":`列出托管 Agent 版本`},auth:`apiKey`,usageArgs:`--agent-id <id> [--limit <n>] [--page <cursor>] [--all]`,flags:Xw,exampleArgs:[`--agent-id agent_abc`,`--agent-id agent_abc --all --output json`],notes:G,validate:NC,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return AC(async n=>{let r=await ua(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)}));LC({format:t,key:`versions`,items:n.items,headers:[`ID`,`NAME`,`VERSION`,`TYPE`,`UPDATED`],rows:Zw(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No agent versions found.`})}});const nT={...Y,...X,...MC},rT={...Y,limit:X.limit,...jC,...MC},iT={...Y,environmentId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Environment ID`,"zh-CN":`Environment ID`}}};function aT(e){return e.map(e=>[e.id,Z(e.name),Z(e.scope),Z(e.version),Z(e.updated_at)])}var oT=S({description:{"en-US":`Get a Managed Agent environment`,"zh-CN":`获取托管 Agent 环境详情`},auth:`apiKey`,usageArgs:`--environment-id <id>`,flags:iT,exampleArgs:[`--environment-id env_abc`],notes:G,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return ra(t,e.flags.environmentId,{provider:`bailian`})}));if(t===`json`){O(n,t);return}D(`ID: ${n.id}`),D(`Name: ${Z(n.name)}`),D(`Description: ${Z(n.description,120)}`),D(`Scope: ${Z(n.scope)}`),D(`Version: ${Z(n.version)}`),D(`Updated: ${Z(n.updated_at)}`)}}),sT=S({description:{"en-US":`List Managed Agent environments`,"zh-CN":`列出托管 Agent 环境`},auth:`apiKey`,usageArgs:`[--limit <n>] [--page <cursor>] [--all] [--include-archived]`,flags:nT,exampleArgs:[``,`--all --output json`],notes:G,validate:NC,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return AC(async n=>{let r=await ma(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)}));LC({format:t,key:`environments`,items:n.items,headers:[`ID`,`NAME`,`SCOPE`,`VERSION`,`UPDATED`],rows:aT(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No environments found.`})}}),cT=S({description:{"en-US":`Search Managed Agent environments`,"zh-CN":`搜索托管 Agent 环境`},auth:`apiKey`,usageArgs:`--query <text> [--limit <n>] [--page-limit <n>] [--include-archived]`,flags:rT,exampleArgs:[`--query sandbox`,`--query production --page-limit 20 --output json`],notes:G,validate:NC,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return IC(async n=>{let r=await ma(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=>FC(e.flags.query,t.id,t.name,t.description),e.flags.pageLimit)}));LC({format:t,key:`environments`,items:n.items,headers:[`ID`,`NAME`,`SCOPE`,`VERSION`,`UPDATED`],rows:aT(n.items),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching environments found.`})}}),lT=S({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:cw,exampleArgs:[`--skill-id skill_abc --skill-version 3 --output-file ./skill.zip`],notes:G,async run(e){let t=C(e.settings.output);if(e.settings.dryRun){O({would_download_skill:e.flags.skillId,version:e.flags.skillVersion,output_file:e.flags.outputFile},t);return}let n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return Xi(t,e.flags.skillId,e.flags.skillVersion,{provider:`bailian`})})),r=await KC(e.flags.outputFile,n,e.flags.force);t===`json`?O({downloaded:e.flags.skillId,version:e.flags.skillVersion,output_file:r},t):D(`Skill downloaded to ${r}`)}}),uT=S({description:{"en-US":`Get a Managed Agent skill`,"zh-CN":`获取托管 Agent Skill 详情`},auth:`apiKey`,usageArgs:`--skill-id <id>`,flags:ow,exampleArgs:[`--skill-id skill_abc`],notes:G,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return ia(t,e.flags.skillId,{provider:`bailian`})}));if(t===`json`){O(n,t);return}D(`ID: ${n.id}`),D(`Name: ${n.name}`),D(`Description: ${Z(n.description,120)}`),D(`Source: ${n.source}`),D(`Status: ${n.status}`),D(`Version: ${Z(n.latest_version)}`)}}),dT=S({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:aw,exampleArgs:[`--query browser --source official`,`--query report --source all --output json`],notes:G,validate:NC,async run(e){let t=C(e.settings.output),n=e.flags.source??`custom`,r=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`),r=n=>IC(async r=>{let i=await _a(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=>FC(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}}));LC({format:t,key:`skills`,items:r.items,headers:[`ID`,`NAME`,`SOURCE`,`STATUS`,`VERSION`,`UPDATED`],rows:lw(r.items),hasMore:r.hasMore,nextPage:r.nextPage,truncated:r.truncated,scannedPages:r.scannedPages,emptyMessage:`No matching skills found.`})}}),fT=S({description:{"en-US":`List Managed Agent skill versions`,"zh-CN":`列出托管 Agent Skill 版本`},auth:`apiKey`,usageArgs:`--skill-id <id> [--limit <n>] [--page <cursor>] [--all]`,flags:sw,exampleArgs:[`--skill-id skill_abc`,`--skill-id skill_abc --all --output json`],notes:G,validate:NC,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return AC(async n=>{let r=await ga(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)}));LC({format:t,key:`versions`,items:n.items,headers:[`VERSION`,`NAME`,`TYPE`,`STATUS`,`UPDATED`],rows:uw(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No skill versions found.`})}});const pT={...Y,...X,...MC},mT={...Y,limit:X.limit,...jC,...MC},hT={...Y,vaultId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Vault ID`,"zh-CN":`Vault ID`}}};function gT(e){return e.map(e=>[e.id,Z(e.display_name),Z(e.type),Z(e.created_at),Z(e.updated_at)])}var _T=S({description:{"en-US":`Get a Managed Agent vault`,"zh-CN":`获取托管 Agent Vault 详情`},auth:`apiKey`,usageArgs:`--vault-id <id>`,flags:hT,exampleArgs:[`--vault-id vault_abc`],notes:G,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return aa(t,e.flags.vaultId,{provider:`bailian`})}));if(t===`json`){O(n,t);return}D(`ID: ${n.id}`),D(`Name: ${Z(n.display_name)}`),D(`Type: ${Z(n.type)}`),D(`Created: ${Z(n.created_at)}`),D(`Updated: ${Z(n.updated_at)}`)}}),vT=S({description:{"en-US":`List Managed Agent vaults`,"zh-CN":`列出托管 Agent Vault`},auth:`apiKey`,usageArgs:`[--limit <n>] [--page <cursor>] [--all] [--include-archived]`,flags:pT,exampleArgs:[``,`--all --output json`],notes:G,validate:NC,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return AC(async n=>{let r=await va(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)}));LC({format:t,key:`vaults`,items:n.items,headers:[`ID`,`NAME`,`TYPE`,`CREATED`,`UPDATED`],rows:gT(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No vaults found.`})}}),yT=S({description:{"en-US":`Search Managed Agent vaults`,"zh-CN":`搜索托管 Agent Vault`},auth:`apiKey`,usageArgs:`--query <text> [--limit <n>] [--page-limit <n>] [--include-archived]`,flags:mT,exampleArgs:[`--query github`,`--query production --page-limit 20 --output json`],notes:G,validate:NC,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return IC(async n=>{let r=await va(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=>FC(e.flags.query,t.id,t.display_name,t.metadata),e.flags.pageLimit)}));LC({format:t,key:`vaults`,items:n.items,headers:[`ID`,`NAME`,`TYPE`,`CREATED`,`UPDATED`],rows:gT(n.items),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching vaults found.`})}});const bT={deploymentId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Deployment ID`,"zh-CN":`Deployment ID`}}},xT={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 状态筛选`}},...MC,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":`创建时间不晚于该时间戳`}}},ST={...Y,...X,...xT},CT={...Y,...bT},wT={...Y,...X,query:jC.query,...xT},TT={...Y,...bT,...X},ET={...Y,runId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Deployment run ID`,"zh-CN":`Deployment Run ID`}}},DT={...Y,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 OT(e){if(!!e.deployment==!!e.deploymentId)return`Provide exactly one of --deployment or --deployment-id.`}function kT(e){return e.map(e=>[Z(e.id),e.status,Z(e.schedule?.expression),Z(e.paused_reason?.type)])}function AT(e){return e.map(e=>[e.id,Z(e.deployment_id),Z(e.session_id),Z(e.status),Z(e.created_at)])}async function jT(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 zi(`Deployment '${t.deployment}' is not tracked in state. Use --deployment-id or run managed-agent apply/import first.`);return n.remote_id}var MT=S({description:{"en-US":`Get a Managed Agent deployment`,"zh-CN":`获取托管 Agent Deployment 详情`},auth:`apiKey`,usageArgs:`--deployment-id <id>`,flags:CT,exampleArgs:[`--deployment-id dep_abc`],notes:G,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return ta(t,e.flags.deploymentId,{provider:`bailian`})}));t===`json`?O(n,t):(D(`ID: ${Z(n.id)}`),D(`Status: ${n.status}`),D(`Schedule:${Z(n.schedule?.expression)}`),D(`Paused: ${Z(n.paused_reason)}`))}}),NT=S({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:ST,exampleArgs:[``,`--status active --all --output json`],notes:G,validate:NC,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return AC(async n=>{let r=await pa(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)}));LC({format:t,key:`deployments`,items:n.items,headers:[`ID`,`STATUS`,`SCHEDULE`,`PAUSED REASON`],rows:kT(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No deployments found.`})}});function PT(e){return S({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:DT,exampleArgs:[`--deployment daily-report --dry-run`,`--deployment-id dep_abc --yes`],notes:G,validate:OT,async run(t){let n=C(t.settings.output);if(t.settings.dryRun){O({[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 q(()=>J(async()=>{let n=await K(t,t.flags.file??`agents.yaml`),r=await jT(n,t.flags);return{deploymentId:r,deployment:await Ma(n,r,e,{provider:`bailian`})}}));n===`json`?O({deployment_id:r.deploymentId,deployment:r.deployment},n):D(`Deployment ${r.deploymentId} ${e?`paused`:`unpaused`}.`)}})}var FT=PT(!0),IT=S({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:DT,exampleArgs:[`--deployment daily-report --dry-run`,`--deployment-id dep_abc --yes`],notes:G,validate:OT,async run(e){let t=C(e.settings.output);if(e.settings.dryRun){O({would_run_deployment:e.flags.deploymentId??e.flags.deployment,target_kind:e.flags.deploymentId?`id`:`state_name`},t);return}let n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`),n=await jT(t,e.flags);return{deploymentId:n,run:await Oa(t,n,{provider:`bailian`})}}));t===`json`?O({deployment_id:n.deploymentId,...n.run},t):D(`Deployment ${n.deploymentId} started. Run: ${n.run.run_id??`-`}`)}}),LT=S({description:{"en-US":`Get a Managed Agent deployment run`,"zh-CN":`获取托管 Agent Deployment Run 详情`},auth:`apiKey`,usageArgs:`--run-id <id>`,flags:ET,exampleArgs:[`--run-id run_abc`],notes:G,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return na(t,e.flags.runId,{provider:`bailian`})}));t===`json`?O(n,t):(D(`ID: ${n.id}`),D(`Deployment: ${Z(n.deployment_id)}`),D(`Session: ${Z(n.session_id)}`),D(`Status: ${Z(n.status)}`),D(`Created: ${Z(n.created_at)}`),D(`Error: ${Z(n.error)}`))}}),RT=S({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:TT,exampleArgs:[`--deployment-id dep_abc`,`--deployment-id dep_abc --all --output json`],notes:G,validate:NC,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return AC(async n=>{let r=await fa(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)}));LC({format:t,key:`runs`,items:n.items,headers:[`ID`,`DEPLOYMENT`,`SESSION`,`STATUS`,`CREATED`],rows:AT(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No deployment runs found.`})}}),zT=S({description:{"en-US":`Search Managed Agent deployments`,"zh-CN":`搜索托管 Agent Deployment`},auth:`apiKey`,usageArgs:`--query <text> [--limit <n>] [--page <cursor>] [--all]`,flags:wT,exampleArgs:[`--query report`,`--query nightly --all --output json`],notes:[...G,{"en-US":`Deployment search maps --query to the provider's server-side keyword parameter.`,"zh-CN":`Deployment 搜索会把 --query 映射为 Provider 服务端 keyword 参数。`}],validate:NC,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return AC(async n=>{let r=await pa(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)}));LC({format:t,key:`deployments`,items:n.items,headers:[`ID`,`STATUS`,`SCHEDULE`,`PAUSED REASON`],rows:kT(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No matching deployments found.`})}}),BT=PT(!1);const VT={sessionId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Session ID`,"zh-CN":`Session ID`}}},HT={...Y,limit:X.limit,...jC,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":`创建时间不晚于该时间戳`}}},UT={...Y,...VT,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`}}},WT={...Y,...VT};function GT(e){return e.map(e=>[e.id,Z(e.title),Z(e.agent_id),e.status,Z(e.updated_at)])}async function KT(e){if(!e)return;let t=await GC(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 qT=S({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:HT,exampleArgs:[`--query debug`,`--query failed --statuses failed --output json`],notes:G,validate:NC,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return IC(async n=>{let r=await ba(t,{agent:e.flags.agent,provider:`bailian`,filter:{page:n,limit:e.flags.limit??100,statuses:PC(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=>FC(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);LC({format:t,key:`sessions`,items:r,headers:[`ID`,`TITLE`,`AGENT`,`STATUS`,`UPDATED`],rows:GT(r),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching sessions found.`})}}),JT=S({description:{"en-US":`Update a Managed Agent session`,"zh-CN":`更新托管 Agent Session`},auth:`apiKey`,usageArgs:`--session-id <id> [--title <title>] [--metadata <json|@path>]`,flags:UT,exampleArgs:[`--session-id sess_abc --title 'investigation'`,`--session-id sess_abc --metadata @metadata.json`],notes:G,validate:e=>!e.title&&!e.metadata?`Provide --title or --metadata.`:void 0,async run(e){let t=C(e.settings.output),n={title:e.flags.title,metadata:await KT(e.flags.metadata)};if(e.settings.dryRun){O({would_update_session:e.flags.sessionId,input:n},t);return}let r=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return La(t,e.flags.sessionId,n,{provider:`bailian`})}));t===`json`?O(r,t):D(`Session ${r.id} updated.`)}}),YT=S({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:WT,exampleArgs:[`--session-id sess_abc --dry-run`,`--session-id sess_abc --yes`],notes:G,async run(e){let t=C(e.settings.output);if(e.settings.dryRun){O({would_archive_session:e.flags.sessionId},t);return}let n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return Bi(t,e.flags.sessionId,{provider:`bailian`})}));t===`json`?O({archived:e.flags.sessionId,session:n},t):D(`Session ${e.flags.sessionId} archived.`)}}),XT={sessionId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Session ID`,"zh-CN":`Session ID`}}},ZT={...Y,...XT},QT={...ZT,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 $T(e){return e instanceof Error?e.message:String(e)}async function eE(e,t,n){let r=await oa(e,t,n),i=n??(e.providers.size===1?Array.from(e.providers.keys())[0]:`bailian`),a=[],o=[],s=[];try{o=(await AC(async r=>{let i=await ya(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:$T(e)})}try{s=(await AC(async r=>{let i=await ha(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:$T(e)})}return{session:r,events:Ya(o),files:s,capabilities:$i(i),errors:a}}const tE=String.raw`(?:api[_-]?key|access[_-]?key|private[_-]?key|secret|token|authorization|credential|password|signature|signed[_-]?url)`,nE=RegExp(`${tE}|tool[_-]?input`,`i`),rE=RegExp(`([?&][^=&#\\s]*(?:${tE})[^=&#\\s]*=)[^&#\\s"'<>),}\\]]*`,`gi`),iE=RegExp(`("[^"]*(?:${tE})[^"]*"\\s*:\\s*")[^"]*(")`,`gi`),aE=RegExp(`('[^']*(?:${tE})[^']*'\\s*:\\s*')[^']*(')`,`gi`),oE=RegExp(`(\\b[^\\s=:,;]*(?:${tE})[^\\s=:,;]*\\s*=\\s*)(?!\\[REDACTED\\])(?:"[^"]*"|'[^']*'|[^\\s,;&]+)`,`gi`),sE=/\b(authorization\s*:\s*)(?:bearer\s+)?[^\s,;]+/gi,cE=/\b(bearer\s+)[A-Za-z0-9._~+/=-]+/gi,lE=/\bsk-[A-Za-z0-9_-]{8,}\b/g;function uE(e){return e.replace(rE,`$1[REDACTED]`).replace(iE,`$1[REDACTED]$2`).replace(aE,`$1[REDACTED]$2`).replace(oE,`$1[REDACTED]`).replace(sE,`$1[REDACTED]`).replace(cE,`$1[REDACTED]`).replace(lE,`[REDACTED]`)}function dE(e){return Array.isArray(e)?e.map(dE):typeof e==`string`?uE(e):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,nE.test(e)?`[REDACTED]`:dE(t)]))}function fE(e){return new TextEncoder().encode(`${JSON.stringify(dE(e),null,2)}\n`)}function pE(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 mE(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 hE(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 gE(e){let t=new TextEncoder,n=[],r=[],i=0;for(let a of e){let e=t.encode(a.name),o=pE(a.content),s=mE([hE([[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=hE([[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(mE([c,e])),i+=s.length}let a=mE(r),o=hE([[101010256,4],[0,2],[0,2],[e.length,2],[e.length,2],[a.length,4],[i,4],[0,2]]);return mE([...n,a,o])}const _E=S({description:{"en-US":`Aggregate session diagnostics`,"zh-CN":`聚合 Session 诊断信息`},auth:`apiKey`,usageArgs:`--session-id <id>`,flags:ZT,exampleArgs:[`--session-id sess_abc`,`--session-id sess_abc --output json`],notes:G,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>eE(await K(e,e.flags.file??`agents.yaml`),e.flags.sessionId,`bailian`))),r=dE(n);if(t===`json`){O(r,t);return}D(`Session: ${n.session.id} (${n.session.status})`),D(`Events: ${n.events.length}`),D(`Scoped files: ${n.files.length}`),D(`Partial errors: ${n.errors.length}`);for(let e of n.errors)D(` ${e.component}: ${e.message}`)}}),vE=S({description:{"en-US":`Export session diagnostics as a ZIP`,"zh-CN":`将 Session 诊断信息导出为 ZIP`},auth:`apiKey`,usageArgs:`--session-id <id> --output-file <path> [--force]`,flags:QT,exampleArgs:[`--session-id sess_abc --output-file ./session-debug.zip`],notes:[...G,{"en-US":`The ZIP contains metadata only; file bodies and credential-like values are excluded/redacted.`,"zh-CN":`ZIP 仅包含元数据;不会包含文件正文,凭证类字段会被移除或脱敏。`}],async run(e){let t=C(e.settings.output);if(e.settings.dryRun){O({would_export_session:e.flags.sessionId,output_file:e.flags.outputFile},t);return}let n=await q(()=>J(async()=>eE(await K(e,e.flags.file??`agents.yaml`),e.flags.sessionId,`bailian`))),r={schema_version:1,generated_at:(/* @__PURE__ */ 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=gE([{name:`manifest.json`,content:fE(r)},{name:`session.json`,content:fE(n.session)},{name:`events.json`,content:fE(n.events)},{name:`files.json`,content:fE(n.files)},{name:`capabilities.json`,content:fE(n.capabilities)},{name:`errors.json`,content:fE(n.errors)}]),a=await KC(e.flags.outputFile,i,e.flags.force);t===`json`?O({exported:n.session.id,output_file:a,partial:r.partial},t):D(`Session diagnostics exported to ${a}${r.partial?` (partial)`:``}`)}}),yE={fileId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Remote file ID`,"zh-CN":`远端 File ID`}}},bE={scopeId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Filter by scope ID`,"zh-CN":`按 Scope ID 筛选`}}},xE={...Y,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 类型`}}},SE={...Y,...X,...bE},CE={...Y,limit:X.limit,...jC,...bE},wE={...Y,...yE},TE={...wE,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":`覆盖已存在的输出文件`}}},EE={...wE};function DE(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 OE=S({description:{"en-US":`Upload a Managed Agent file`,"zh-CN":`上传托管 Agent 文件`},auth:`apiKey`,usageArgs:`--path <path> [--filename <name>] [--mime-type <type>]`,flags:xE,exampleArgs:[`--path ./report.pdf`],notes:G,async run(e){let t=C(e.settings.output);if(e.settings.dryRun){O({would_upload_file:e.flags.path,filename:e.flags.filename??ui(e.flags.path),mime_type:e.flags.mimeType??qC(e.flags.path)},t);return}let n=await WC(e.flags.path),r=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return Ra(t,n,e.flags.filename??ui(e.flags.path),{provider:`bailian`,mimeType:e.flags.mimeType??qC(e.flags.path)})}));t===`json`?O(r,t):D(`File uploaded: ${r.id} (${r.filename})`)}}),kE=S({description:{"en-US":`List Managed Agent files`,"zh-CN":`列出托管 Agent 文件`},auth:`apiKey`,usageArgs:`[--scope-id <id>] [--limit <n>] [--page <cursor>] [--all]`,flags:SE,exampleArgs:[``,`--scope-id sess_abc --all --output json`],notes:G,validate:NC,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return AC(async n=>{let r=await ha(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)}));LC({format:t,key:`files`,items:n.items,headers:[`ID`,`FILENAME`,`STATUS`,`BYTES`,`SCOPE`,`CREATED`],rows:DE(n.items),hasMore:n.hasMore,nextPage:n.nextPage,emptyMessage:`No files found.`})}}),AE=S({description:{"en-US":`Get Managed Agent file metadata`,"zh-CN":`获取托管 Agent 文件元数据`},auth:`apiKey`,usageArgs:`--file-id <id>`,flags:wE,exampleArgs:[`--file-id file_abc`],notes:G,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return Qi(t,e.flags.fileId,{provider:`bailian`})}));t===`json`?O(n,t):(D(`ID: ${n.id}`),D(`Filename: ${n.filename}`),D(`MIME: ${n.mime_type}`),D(`Bytes: ${n.size_bytes}`),D(`Status: ${Z(n.status)}`),D(`Scope: ${Z(n.scope?.id)}`))}}),jE=S({description:{"en-US":`Search Managed Agent files`,"zh-CN":`搜索托管 Agent 文件`},auth:`apiKey`,usageArgs:`--query <text> [--scope-id <id>] [--limit <n>] [--page-limit <n>]`,flags:CE,exampleArgs:[`--query report`,`--query pdf --scope-id sess_abc --output json`],notes:G,validate:NC,async run(e){let t=C(e.settings.output),n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return IC(async n=>{let r=await ha(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=>FC(e.flags.query,t.id,t.filename,t.mime_type),e.flags.pageLimit)}));LC({format:t,key:`files`,items:n.items,headers:[`ID`,`FILENAME`,`STATUS`,`BYTES`,`SCOPE`,`CREATED`],rows:DE(n.items),hasMore:n.hasMore,nextPage:n.nextPage,truncated:n.truncated,scannedPages:n.scannedPages,emptyMessage:`No matching files found.`})}}),ME=S({description:{"en-US":`Download Managed Agent file content`,"zh-CN":`下载托管 Agent 文件内容`},auth:`apiKey`,usageArgs:`--file-id <id> --output-file <path> [--force]`,flags:TE,exampleArgs:[`--file-id file_abc --output-file ./artifact.pdf`],notes:G,async run(e){let t=C(e.settings.output);if(e.settings.dryRun){O({would_download_file:e.flags.fileId,output_file:e.flags.outputFile},t);return}let n=await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);return Yi(t,e.flags.fileId,{provider:`bailian`})})),r=await KC(e.flags.outputFile,n,e.flags.force);t===`json`?O({downloaded:e.flags.fileId,output_file:r},t):D(`File downloaded to ${r}`)}}),NE=S({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:EE,exampleArgs:[`--file-id file_abc --dry-run`,`--file-id file_abc --yes`],notes:G,async run(e){let t=C(e.settings.output);if(e.settings.dryRun){O({would_delete_file:e.flags.fileId},t);return}await q(()=>J(async()=>{let t=await K(e,e.flags.file??`agents.yaml`);await Ki(t,e.flags.fileId,{provider:`bailian`})})),t===`json`?O({deleted:e.flags.fileId},t):D(`File ${e.flags.fileId} deleted.`)}}),PE={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`},FE={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(可选)`}}},IE=1e3;function LE(e){return new Promise(t=>setTimeout(t,e))}function RE(e){return e?.data?.DataV2?.data?.data}function zE(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 BE=S({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:FE,exampleArgs:[`--access-key-id LTAIxxxxx --access-key-secret xxxxx`],async run(e){let{settings:t,flags:r}=e,i=C(t.output);if(t.dryRun){O({apis:[{step:0,api:`GenerateCLIAccessToken`,description:`Generate CLI access token from AK/SK`},{step:1,api:PE.loginInfo,description:`Check login & workspace status`},{step:2,api:PE.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:PE.queryBuyResult,description:`Query postpaid order status`},{step:7,api:PE.commodityOrderInfo,description:`Query commodity activation status`},{step:8,api:PE.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 Qe({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=w(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 ge(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}};D(`Checking workspace status...`);let m=RE(await p(PE.loginInfo));m?.spaceInited===!0?D(`Workspace already initialized.`):(D(`Initializing workspace...`),await p(PE.initSpace),D(`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 xe({...g,reqDTO:{outerKey:h,nickName:h,userName:h}})}catch(e){if(!(e instanceof n)||!/already exists/i.test(e.message))throw e;D(`Console user already exists, continuing.`)}D(`Resolving workspace agent...`);let _=zE(await Et(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.`);D(`Authorizing user permissions...`),await _n({...g,outerKey:h,agentId:_,policyIndexList:[1]}),await VE(p,i)}});async function VE(e,t){D(`Checking service activation status...`);let r;for(let t=0;t<20;t++){let n=RE(await e(PE.queryBuyResult));if(r=typeof n==`string`?n:n?.result,r!==`buying`)break;t===0&&D(`Service activation in progress, polling...`),await LE(IE)}if(r===`fail`)throw new n(`Service activation failed.`,l.GENERAL);if(r===`success`){await WE(e,t);return}await UE(e,t)}function HE(e){let t=RE(e);return Array.isArray(t)?t:[]}async function UE(e,t){let n=HE(await e(PE.commodityOrderInfo)),r=n.filter(e=>e.status===11);if(r.length>0){D(`Warning: Some services are overdue:`);for(let e of r)D(` - ${e.commodityCode}`)}let i=n.filter(e=>e.status===1);if(i.length>0){D(`Activating ${i.length} postpaid services...`),await e(PE.buyCommodity),await WE(e,t);return}let a=n.filter(e=>e.status===10);O({status:`ready`,activeServices:a.map(e=>e.commodityCode)},t)}async function WE(e,t){D(`Waiting for services to activate...`);for(let n=0;n<20;n++){let n=HE(await e(PE.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){D(`Warning: Some services are overdue:`);for(let t of e)D(` - ${t.commodityCode}`)}let r=n.filter(e=>e.status===10);O({status:`ready`,activeServices:r.map(e=>e.commodityCode)},t);return}await LE(IE)}throw new n(`Timed out waiting for services to activate.`,l.TIMEOUT)}var GE=S({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){let t=await e.commandPacks.install(e.flags.package);O({installed:t},C(e.settings.output))}}),KE=S({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){let t=await e.commandPacks.link(e.flags.path);O({linked:t},C(e.settings.output))}}),qE=S({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=C(e.settings.output);if(n===`json`){O({command_packs:t},n);return}if(t.length===0){D(`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 Sr([`NAME`,`VERSION`,`SOURCE`,`STATUS`,`COMMANDS / ERROR`],r))D(e)}}),JE=S({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),O({removed:e.flags.name},C(e.settings.output))}});function YE(e){return e.map(e=>({id:e.id,skillsDir:e.skillsDir}))}function XE(e){try{let t=ri(e);return t.isSymbolicLink()?{exists:!0,kind:`symlink`,hasSkillMd:!1}:t.isDirectory()?{exists:!0,kind:`directory`,hasSkillMd:A(j(e,`SKILL.md`))}:{exists:!0,kind:`file`,hasSkillMd:!1}}catch{return{exists:!1,kind:`absent`,hasSkillMd:!1}}}function ZE(e,t){return t.map(t=>{let n=j(t.skillsDir,e);return{agent:t.id,path:n,...XE(n)}})}var QE=S({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 qe(),i=Object.keys(r.skills),a=e.flags.all?`all`:en(e.flags.name,!1),o=a===`all`?i:a,s=Pe();if(e.settings.dryRun){let e=o.map(e=>{let t=r.skills[e];return t?{name:e,status:`install`,publishedAt:t.publishedAt,links:ZE(e,s)}:{name:e,status:`failed`,reason:`skill not found in registry`}});O({action:`skill.add`,registry:dt(),agents:YE(s),skills:e},t);let i=e.filter(e=>e.status===`failed`);if(i.length>0)throw new n(`${i.length}/${e.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`);return}let c=un(),u=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 _t(e,t,s,c.skills[e]?.links??[]);return c.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)}}}),d=await Tn(u,3);if(ar(c),t===`json`)O({registry:dt(),agents:s.map(e=>e.id),skills:d},t);else if(d.length===0)D(`Skill registry is empty; no skills to install.`);else{let e=d.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 Sr([`NAME`,`STATUS`,`PUBLISHED`,`AGENTS / REASON`],e))D(t)}let f=d.filter(e=>e.status===`failed`);if(f.length>0)throw new n(`${f.length}/${d.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`)}}),$E=S({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`:en(e.flags.name,!1),i=await qe(),a=un(),o=new Set(Pt()),s=Pe(),c=[],u=[];if(r===`all`)for(let[t,n]of Object.entries(a.skills)){let r=i.skills[t];if(!r){c.push({name:t,status:`skipped`,reason:`delisted from remote; local copy retained`});continue}if(r.contentHash===n.contentHash&&o.has(t)){if(e.settings.dryRun){c.push({name:t,status:`up-to-date`,publishedAt:n.publishedAt});continue}let r=Be(t,s,n.links??[]);a.skills[t]={...n,links:r.links},c.push({name:t,status:`up-to-date`,publishedAt:n.publishedAt});continue}u.push(t)}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)}if(e.settings.dryRun){let e=c.map(e=>e.status===`up-to-date`?{name:e.name,status:`up-to-date`,publishedAt:e.publishedAt,links:ZE(e.name,s)}:e.status===`skipped`?{name:e.name,status:`skipped`,publishedAt:e.publishedAt,reason:e.reason}:{name:e.name,status:`failed`,publishedAt:e.publishedAt,reason:e.reason});for(let t of u){let n=i.skills[t];if(!n){e.push({name:t,status:`failed`,reason:`skill not found in registry`});continue}e.push({name:t,status:`update`,publishedAt:n.publishedAt,links:ZE(t,s)})}O({action:`skill.update`,registry:dt(),agents:YE(s),skills:e},t);let r=e.filter(e=>e.status===`failed`);if(r.length>0)throw new n(`${r.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`);return}let d=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 _t(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)}}}),f=await Tn(d,3);if(c.push(...f),ar(a),t===`json`)O({registry:dt(),skills:c},t);else if(c.length===0)D(`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 Sr([`NAME`,`STATUS`,`PUBLISHED`],e))D(t);let t=c.filter(e=>(e.status===`skipped`||e.status===`failed`)&&e.reason);if(t.length>0){D(``);for(let e of t)D(` ${e.name}: ${e.reason}`)}}let p=c.filter(e=>e.status===`failed`);if(p.length>0)throw new n(`${p.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`)}}),eD=S({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=en(e.flags.name,!1),i=un(),a=r===`all`?Object.keys(i.skills):r;if(a.length===0){O({skills:[]},t),t===`text`&&D(`No skills installed locally; nothing to remove.`);return}let o=new Set(Pt()),s=ft();if(e.settings.dryRun){let e=a.map(e=>{let t=i.skills[e];return t?{name:e,status:`remove`,canonical:j(s,e),links:rn(e,t.links??[])}:{name:e,status:`failed`,reason:o.has(e)?`directory not managed by bl skill (untracked); remove manually if needed`:`not installed`}});O({action:`skill.remove`,skills:e},t);let r=e.filter(e=>e.status===`failed`);if(r.length>0)throw new n(`${r.length}/${e.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`);return}let c=[];for(let e of a){let t=i.skills[e];if(!t){c.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=Kn(e,t.links??[]);mn(e),delete i.skills[e],c.push({name:e,status:`removed`,removedLinks:n.length})}catch(t){c.push({name:e,status:`failed`,reason:t instanceof Error?t.message:String(t)})}}if(ar(i),t===`json`)O({skills:c},t);else{let e=c.map(e=>[e.name,e.status,e.status===`removed`?`reclaimed ${e.removedLinks} agent link(s)`:e.reason??`-`]);for(let t of Sr([`NAME`,`STATUS`,`DETAIL`],e))D(t)}let u=c.filter(e=>e.status===`failed`);if(u.length>0)throw new n(`${u.length}/${c.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 tD(e){return e?e.length>60?`${e.slice(0,59)}…`:e:`-`}var nD=S({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 qe(),r=un(),i=be(n,r,Pt());if(t===`json`){O({registry:dt(),...n.updatedAt?{updatedAt:n.updatedAt}:{},skills:i},t);return}if(i.length===0){D(`Skill registry is empty and no skills are installed locally.`);return}let a=i.map(e=>[e.name,e.status,e.publishedAt?e.publishedAt.slice(0,19).replace(`T`,` `):`-`,tD(e.description)]);for(let e of Sr([`NAME`,`STATUS`,`UPDATEDAT`,`DESCRIPTION`],a))D(e)}});const rD=`json`,iD={success:`success`,partial:`partial`,failed:`failed`};var aD=S({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:rD,r=await qe(),i=Object.keys(r.skills).filter(e=>e.startsWith(`bailian-`)),a=Pe();if(e.settings.dryRun){O({action:`skill.init`,skills:i.map(e=>({name:e,links:ZE(e,a)})),agents:YE(a)},t);return}let o=un(),s=i.map(e=>async()=>{let t=r.skills[e];try{let n=await _t(e,t,a,o.skills[e]?.links??[]);return o.skills[e]=n.lockEntry,{name:e,status:iD.success}}catch(t){return{name:e,status:iD.failed,reason:t instanceof Error?t.message:String(t)}}}),c=await Tn(s,3);ar(o);let u=c.filter(e=>e.status===iD.success),d=c.filter(e=>e.status===iD.failed),f=d.length===0?iD.success:u.length===0?iD.failed:iD.partial;if(t===rD){let e=a.map(e=>e.id),n={status:f,skills:u.map(e=>e.name)};d.length>0&&(n.failed=d.map(t=>({name:t.name,reason:t.reason,agents:e}))),O(n,t)}else if(c.length===0)D(`No bailian-* skills found in the registry.`);else if(D(f===iD.success?`Installed ${u.length} bailian-* skills.`:`Installed ${u.length}/${c.length} bailian-* skills.`),d.length>0){D(`Failed:`);for(let e of d)D(` ${e.name}: ${e.reason}`)}if(d.length>0)throw new n(`${d.length}/${c.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 oD=[{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":`代码执行+浏览器双能力`}}],sD=oD.flatMap(e=>[e.id,e.imageName]),cD=oD.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 lD(e){let t=oD.find(t=>t.id===e||t.imageName===e);if(!t)throw new x(`Unknown built-in image / 未知内置镜像: ${e}. ${sD.join(`, `)}`);return t}const uD=S({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。`},...cD],async run(e){if(e.settings.quiet){for(let e of oD)D(e.id);return}if(C(e.settings.output)===`json`){O(oD,`json`);return}for(let e of oD)D(`${e.id} (${e.imageName})`),D(` ${e.imageUrl}`),D(` ${e.description[`en-US`]} / ${e.description[`zh-CN`]}`)}}),dD={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 时可省略`}}},fD={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 优先`}}},pD={instanceTimeout:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Sandbox lifetime after this operation (300-604800 seconds)`,"zh-CN":`本次操作后的 Sandbox 存活时间(300–604800 秒)`}}},mD={showCredentials:{type:`switch`,description:{"en-US":`Print envd and traffic access tokens instead of redacting them`,"zh-CN":`输出 envd 与流量访问 Token 原值,不进行脱敏`}}},hD={pollInterval:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Template build polling interval (default: 5 seconds)`,"zh-CN":`模版构建轮询间隔(默认:5 秒)`}}},gD=[{"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 _D(e,t){return e.client.url(En(t),()=>Dn(vD(e)))}function vD(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 yD(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 bD(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 Ei(t,`utf8`);try{return yD(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 xD(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 SD(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 CD(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 wD(e,t){if(typeof e!=`number`||!Number.isInteger(e)||e<=0)throw new n(`${t} must be a positive integer.`,l.USAGE)}const TD=/* @__PURE__ */ new Set([`envdAccessToken`,`trafficAccessToken`]),ED=/(?:token|secret|password|credential|api[_-]?key)/i;function DD(e,t){if(Array.isArray(e))return e.map(e=>DD(e,t));if(typeof e!=`object`||!e)return e;let n={};for(let[r,i]of Object.entries(e)){if(TD.has(r)||ED.test(r)||t&&(r===`envVars`||r===`envConfig`)){n[r]=i==null?i:(r===`envVars`||r===`envConfig`)&&typeof i==`object`&&!Array.isArray(i)?Object.fromEntries(Object.keys(i).map(e=>[e,`[REDACTED]`])):`[REDACTED]`;continue}n[r]=DD(i,t)}return n}function OD(e){return DD(e,!1)}function kD(e){return DD(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 AD=`sandbox_template`,jD=S({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:{...dD,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(te(),()=>Dn(vD(e))),r=e.flags.filename??ui(e.flags.path),i=e.flags.mimeType??`application/octet-stream`,a=C(e.settings.output);if(e.settings.dryRun){O({method:`POST`,endpoint:t,request:{source:AD,file:{path:e.flags.path,filename:r,mimeType:i}}},a);return}let o=new Uint8Array(await Ei(e.flags.path)),s=new FormData;s.append(`source`,AD),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?D(c.id):O(OD(c),a)}}),MD={sandboxId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Sandbox instance ID`,"zh-CN":`Sandbox 实例 ID`}}},ND={...dD,...fD,templateId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Ready template ID; may alternatively be supplied as templateID in --body`,"zh-CN":`已就绪的模版 ID;也可通过 --body 中的 templateID 提供`}},...pD,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`}},...mD},PD={...dD,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)`}}},FD={...dD,...MD,...mD},ID={...dD,...MD},LD={...dD,...MD,...fD,...pD,...mD};async function RD(e){let t=await bD(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),SD(t,`metadata`,xD(e.metadata,`--metadata`)),SD(t,`envVars`,xD(e.env,`--env`));let r={};if(Q(r,`allowOut`,e.allowOut),Q(r,`denyOut`,e.denyOut),Q(r,`maskRequestHost`,e.maskRequestHost),SD(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 CD(t.timeout,`Sandbox timeout`,300,604800),t}async function zD(e){let t=await bD(e.body);return Q(t,`timeout`,e.instanceTimeout),CD(t.timeout,`Sandbox timeout`,300,604800),t}function BD(e,t){let n=t.showCredentials?e:OD(e);if(t.quiet){D($(e.sandboxID));return}O(n,t.format)}const VD=S({description:{"en-US":`Create a Sandbox instance`,"zh-CN":`创建 Sandbox 实例`},auth:`apiKey`,usageArgs:`(--template-id <id> | --body <json|@path>) [flags]`,flags:ND,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:gD,async run(e){let t=C(e.settings.output),n=_D(e,_.sandboxes),r=await RD(e.flags);if(e.settings.dryRun){O({method:`POST`,endpoint:n,request:kD(r)},t);return}BD(await e.client.requestJson({path:n,method:`POST`,body:r}),{format:t,quiet:e.settings.quiet,showCredentials:e.flags.showCredentials})}}),HD=S({description:{"en-US":`List Sandbox instances`,"zh-CN":`列出 Sandbox 实例`},auth:`apiKey`,usageArgs:`[--template-id <id>] [--sandbox-id <id>] [--state <state>] [--limit <n>]`,flags:PD,exampleArgs:[``,`--state running --limit 20`,`--template-id tpl-xxx --output json`],notes:gD,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(_D(e,_.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)D($(e.sandboxID));return}let r=C(e.settings.output);if(r===`json`){O(n,r);return}if(n.length===0){D(`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 Sr([`ID`,`TEMPLATE`,`STATE`,`CPU`,`MEMORY_MB`,`STARTED_AT`,`END_AT`],i))D(e)}}),UD=S({description:{"en-US":`Get Sandbox instance details`,"zh-CN":`获取 Sandbox 实例详情`},auth:`apiKey`,usageArgs:`--sandbox-id <id> [--show-credentials]`,flags:FD,exampleArgs:[`--sandbox-id sbx-xxx`,`--sandbox-id sbx-xxx --show-credentials --output json`],notes:gD,async run(e){let t=_D(e,kn(e.flags.sandboxId));BD(await e.client.requestJson({path:t,method:`GET`}),{format:C(e.settings.output),quiet:e.settings.quiet,showCredentials:e.flags.showCredentials})}});function WD(e){let t=e===`connect`?`Connect to`:`Resume`,n=e===`connect`?`连接`:`恢复`;return S({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:LD,exampleArgs:[`--sandbox-id sbx-xxx --instance-timeout 3600`,`--sandbox-id sbx-xxx --show-credentials --output json`],notes:gD,async run(t){let n=C(t.settings.output),r=_D(t,On(t.flags.sandboxId,e)),i=await zD(t.flags);if(t.settings.dryRun){O({method:`POST`,endpoint:r,request:kD(i)},n);return}BD(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 GD=WD(`connect`),KD=WD(`resume`),qD=S({description:{"en-US":`Pause a Sandbox instance`,"zh-CN":`暂停 Sandbox 实例`},auth:`apiKey`,usageArgs:`--sandbox-id <id>`,flags:ID,exampleArgs:[`--sandbox-id sbx-xxx`,`--sandbox-id sbx-xxx --dry-run --output json`],notes:gD,async run(e){let t=C(e.settings.output),n=_D(e,On(e.flags.sandboxId,`pause`));if(e.settings.dryRun){O({method:`POST`,endpoint:n,request:null},t);return}await e.client.request({path:n,method:`POST`}),e.settings.quiet?D(e.flags.sandboxId):O({sandboxID:e.flags.sandboxId,paused:!0},t)}}),JD=S({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:ID,exampleArgs:[`--sandbox-id sbx-xxx --dry-run`,`--sandbox-id sbx-xxx --yes`],notes:gD,async run(e){let t=C(e.settings.output),n=_D(e,kn(e.flags.sandboxId));if(e.settings.dryRun){O({method:`DELETE`,endpoint:n,request:null},t);return}await e.client.request({path:n,method:`DELETE`}),e.settings.quiet?D(e.flags.sandboxId):O({sandboxID:e.flags.sandboxId,deleted:!0},t)}}),YD={async:{type:`switch`,description:{"en-US":`Return the submitted templateID/buildID immediately without polling`,"zh-CN":`提交后立即返回 templateID/buildID,不轮询构建状态`}}},XD={templateId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Sandbox template ID`,"zh-CN":`Sandbox 模版 ID`}}},ZD={image:{type:`string`,valueHint:`<preset>`,choices:sD,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":`模版描述`}}},QD={...dD,...fD,...ZD,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 模版别名`}},...YD,...hD},$D={...dD,...XD,...fD,...ZD,...YD,...hD},eO={...dD,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`}}},tO={...dD,...XD},nO={...dD,...XD,buildId:{type:`string`,valueHint:`<id>`,required:!0,description:{"en-US":`Template build ID`,"zh-CN":`模版构建 ID`}}};function rO(e,t){if(t.image!==void 0){let n=lD(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),SD(e,`envConfig`,xD(t.env,`--env`));let n={};Q(n,`allowOut`,t.allowOut),Q(n,`denyOut`,t.denyOut),SD(e,`networkConfig`,n)}function iO(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&&wD(e.cpuCount,`cpuCount`),i&&wD(e.memoryMB,`memoryMB`),CD(e.autoPauseTime,`autoPauseTime`,300,604800),CD(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 aO(e){let t=await bD(e.body);return rO(t,e),Q(t,`tags`,e.tag),Q(t,`alias`,e.alias),iO(t,!0),t}async function oO(e){let t=await bD(e.body);return rO(t,e),iO(t,!1),t}async function sO(e,t,r,i){let a=Date.now()+t.timeout*1e3,o=mr(`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`){o.stop(`Template build failed.`);let e=c.reason?.message??(c.reason?.code===void 0?`Template build failed.`:`${c.reason.code}`);throw new n(e,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 cO(e){if(e.pollInterval!==void 0&&(!Number.isInteger(e.pollInterval)||e.pollInterval<=0))return`--poll-interval must be a positive integer.`}async function lO(e){let t=C(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?D(`${e.response.templateID}\t${e.response.buildID}`):O(e.response,t);return}let r=new URL(En(An(e.response.templateID,e.response.buildID)),e.endpoint).toString(),i;try{i=await sO(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(`
|
|
2880
|
+
`),{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?D($(e.response.templateID)):O({template:e.response,build:i},t)}const uO=S({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:QD,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:[...gD,...cD,{"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:cO,async run(e){let t=C(e.settings.output),n=_D(e,_.templateCreate),r=await aO(e.flags);if(e.settings.dryRun){O({method:`POST`,endpoint:n,request:kD(r)},t);return}await lO({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})}}),dO=S({description:{"en-US":`List Sandbox templates`,"zh-CN":`列出 Sandbox 模版`},auth:`apiKey`,usageArgs:`[--limit <n>] [--cursor <cursor>]`,flags:eO,exampleArgs:[``,`--limit 100 --output json`],notes:[...gD,{"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(_D(e,_.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)D($(e.templateID));return}let r=C(e.settings.output);if(r===`json`){O(n,r);return}if(n.length===0){D(`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 Sr([`ID`,`NAME`,`CPU`,`MEMORY_MB`,`INSTANCES`,`BUILDS`,`UPDATED_AT`],i))D(e)}}),fO=S({description:{"en-US":`Get Sandbox template details`,"zh-CN":`获取 Sandbox 模版详情`},auth:`apiKey`,usageArgs:`--template-id <id>`,flags:tO,exampleArgs:[`--template-id tpl-xxx`,`--template-id tpl-xxx --output json`],notes:gD,async run(e){let t=_D(e,jn(e.flags.templateId)),n=await e.client.requestJson({path:t,method:`GET`});e.settings.quiet?D($(n.templateID)):O(n,C(e.settings.output))}}),pO=S({description:{"en-US":`Update a Sandbox template`,"zh-CN":`更新 Sandbox 模版`},auth:`apiKey`,usageArgs:`--template-id <id> (--body <json|@path> | [fields])`,flags:$D,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:[...gD,...cD,{"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:cO,async run(e){let t=C(e.settings.output),n=_D(e,jn(e.flags.templateId)),r=await oO(e.flags);if(e.settings.dryRun){O({method:`PUT`,endpoint:n,request:kD(r)},t);return}await lO({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})}}),mO=S({description:{"en-US":`Get Sandbox template build status`,"zh-CN":`获取 Sandbox 模版构建状态`},auth:`apiKey`,usageArgs:`--template-id <id> --build-id <id>`,flags:nO,exampleArgs:[`--template-id tpl-xxx --build-id build-xxx`,`--template-id tpl-xxx --build-id build-xxx --output json`],notes:gD,async run(e){let t=_D(e,An(e.flags.templateId,e.flags.buildId)),n=await e.client.requestJson({path:t,method:`GET`});e.settings.quiet?D($(n.status)):O(n,C(e.settings.output))}}),hO=S({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:tO,exampleArgs:[`--template-id tpl-xxx --dry-run`,`--template-id tpl-xxx --yes`],notes:[...gD,{"en-US":`The server rejects deletion while running or paused instances still use the template.`,"zh-CN":`仍有运行中或已暂停实例使用该模版时,服务端会拒绝删除。`}],async run(e){let t=C(e.settings.output),n=_D(e,jn(e.flags.templateId));if(e.settings.dryRun){O({method:`DELETE`,endpoint:n,request:null},t);return}await e.client.request({path:n,method:`DELETE`}),e.settings.quiet?D(e.flags.templateId):O({templateID:e.flags.templateId,deleted:!0},t)}});export{ag as advisorRecommend,uy as alertCreate,my as alertDelete,_y as alertDisable,hy as alertEnable,by as alertHistory,cy as alertList,Yv as alertMetrics,ty as alertTemplateCreate,ay as alertTemplateDelete,Qv as alertTemplateList,ry as alertTemplateUpdate,fy as alertUpdate,Ju as appCall,Xu as appList,No as authGenerateAccessToken,Ao as authLogin,Mo as authLogout,jo as authStatus,Vu as configAgent,Ns as configList,Ms as configSet,js as configShow,du as configUi,Ps as configUse,im as consoleCall,Ny as datasetDelete,My as datasetGet,jy as datasetList,Ay as datasetUpload,Py as datasetValidate,Xb as deployAudioCreate,ix as deployCapacityCreate,ux as deployCapacityDelete,nx as deployCapacityGet,tx as deployCapacityList,cx as deployCapacityRenew,ox as deployCapacityScale,dx as deployCapacityUnsubscribe,yx as deployDelete,$b as deployGet,Zb as deployImageCreate,Qb as deployList,mx as deployModels,px as deployOperationGet,Mb as deployOperationWait,fx as deployOverflow,bx as deployPause,xx as deployResume,_x as deployScale,Yb as deployTextCreate,vx as deployUpdate,rm as fileUpload,Yy as finetuneAudioCreate,rb as finetuneCancel,vb as finetuneCapability,lb as finetuneCheckpoints,ib as finetuneDelete,ub as finetuneExport,nb as finetuneGet,Xy as finetuneImageCreate,$y as finetuneList,cb as finetuneLogs,xb as finetunePrice,Jy as finetuneTextCreate,Qy as finetuneVideoCreate,hb as finetuneWatch,os as imageEdit,ts as imageGenerate,Uf as knowledgeCategoryAdd,Gf as knowledgeCategoryDelete,Vf as knowledgeCategoryList,Cd as knowledgeChat,Of as knowledgeChunkAdd,If as knowledgeChunkDelete,Af as knowledgeChunkList,Nf as knowledgeChunkUpdate,$f as knowledgeCollectionCreate,tp as knowledgeCollectionGet,$d as knowledgeDocDelete,rp as knowledgeDocImportOss,jd as knowledgeDocList,Pd as knowledgeDocStatus,tf as knowledgeDocTag,Wd as knowledgeDocUpload,Zf as knowledgeFileDelete,Yf as knowledgeFileGet,qf as knowledgeFileList,qd as knowledgeKbCreate,Zd as knowledgeKbDelete,kd as knowledgeKbInfo,Td as knowledgeKbList,zf as knowledgeKbStats,Yd as knowledgeKbUpdate,id as knowledgeRetrieve,_d as knowledgeSearch,Tf as knowledgeServiceCopy,df as knowledgeServiceCreate,Cf as knowledgeServiceDelete,xf as knowledgeServiceDeploy,lf as knowledgeServiceGet,of as knowledgeServiceList,yf as knowledgeServiceUpdate,vv as logAuditCount,bv as logAuditDisable,yv as logAuditEnable,gv as logAuditGet,hv as logAuditList,Dv as logInferenceCount,kv as logInferenceDisable,Ov as logInferenceEnable,Tv as logInferenceGet,Cv as logInferenceList,pv as logStatus,Iv as logTraceGet,Nv as logTraceList,Rv as logTraceStats,Mw as managedAgentAgentCreate,Qw as managedAgentAgentGet,$w as managedAgentAgentList,eT as managedAgentAgentSearch,tT as managedAgentAgentVersions,AS as managedAgentApply,Uw as managedAgentDeploymentCreate,MT as managedAgentDeploymentGet,NT as managedAgentDeploymentList,FT as managedAgentDeploymentPause,IT as managedAgentDeploymentRun,LT as managedAgentDeploymentRunsGet,RT as managedAgentDeploymentRunsList,zT as managedAgentDeploymentSearch,BT as managedAgentDeploymentUnpause,jS as managedAgentDestroy,Pw as managedAgentEnvironmentCreate,oT as managedAgentEnvironmentGet,sT as managedAgentEnvironmentList,cT as managedAgentEnvironmentSearch,NE as managedAgentFileDelete,ME as managedAgentFileDownload,AE as managedAgentFileGet,kE as managedAgentFileList,jE as managedAgentFileSearch,OE as managedAgentFileUpload,rS as managedAgentInit,kS as managedAgentPlan,$S as managedAgentPlayground,rC as managedAgentProjectBuild,tC as managedAgentProjectInit,iC as managedAgentProjectPublish,nC as managedAgentProjectValidate,sC as managedAgentProjectVersionDisable,oC as managedAgentProjectVersionEnable,uC as managedAgentProjectVersionList,fC as managedAgentProjectVersionPreview,pC as managedAgentProjectVersionRestore,lC as managedAgentProjectVersionStatus,aC as managedAgentProjectWorkbench,YT as managedAgentSessionArchive,kC as managedAgentSessionCreate,_E as managedAgentSessionDebug,VC as managedAgentSessionDelete,ew as managedAgentSessionEventList,ew as managedAgentSessionEvents,tw as managedAgentSessionEventSend,nw as managedAgentSessionEventStream,vE as managedAgentSessionExport,BC as managedAgentSessionGet,zC as managedAgentSessionList,HC as managedAgentSessionRun,qT as managedAgentSessionSearch,UC as managedAgentSessionSend,JT as managedAgentSessionUpdate,Rw as managedAgentSkillCreate,lT as managedAgentSkillDownload,uT as managedAgentSkillGet,pw as managedAgentSkillList,dT as managedAgentSkillSearch,fT as managedAgentSkillVersions,bC as managedAgentStateImport,hC as managedAgentStateList,_C as managedAgentStateRm,gC as managedAgentStateShow,ES as managedAgentValidate,zw as managedAgentVaultCreate,Bw as managedAgentVaultCredentialCreate,_T as managedAgentVaultGet,vT as managedAgentVaultList,yT as managedAgentVaultSearch,pp as mcpCall,gp as mcpConnect,yp as mcpDisconnect,xp as mcpList,Sp as mcpTools,Zu as memoryAdd,td as memoryDelete,$u as memoryList,nd as memoryProfileCreate,rd as memoryProfileGet,Qu as memorySearch,ed as memoryUpdate,Wg as modelCode,Og as modelList,Ig as modelSearch,W_ as monitorDeliveryDisable,H_ as monitorDeliveryEnable,I_ as monitorDeliveryStatus,P_ as monitorErrors,A_ as monitorMetrics,C_ as monitorModels,y_ as monitorOverview,Oy as permissionGrant,Cy as permissionList,ky as permissionRevoke,zh as pipelineRun,Wh as pipelineValidate,GE as pluginInstall,KE as pluginLink,qE as pluginList,JE as pluginRemove,g_ as quotaCheck,r_ as quotaDelete,l_ as quotaHistory,t_ as quotaList,n_ as quotaUpdate,GD as sandboxConnect,VD as sandboxCreate,JD as sandboxDelete,jD as sandboxFileUpload,UD as sandboxGet,HD as sandboxList,uD as sandboxOfficialImages,qD as sandboxPause,KD as sandboxResume,mO as sandboxTemplateBuildStatus,uO as sandboxTemplateCreate,hO as sandboxTemplateDelete,fO as sandboxTemplateGet,dO as sandboxTemplateList,pO as sandboxTemplateUpdate,wp as searchWeb,_m as securityAlerts,mm as securityOverview,QE as skillAdd,aD as skillInit,nD as skillList,eD as skillRemove,$E as skillUpdate,Bp as speechRecognize,Pp as speechSynthesize,Yp as speechVocabularyCreate,nm as speechVocabularyDelete,Qp as speechVocabularyGet,Xp as speechVocabularyList,em as speechVocabularyUpdate,Ko as textChat,$o as textOmni,qx as tokenPlanAddMember,Ux as tokenPlanAssignSeats,Rx as tokenPlanCreateKey,tS as tokenPlanHarnessQuota,Nx as tokenPlanListSeats,qu as update,Lh as usageCodingPlan,gh as usageFree,_h as usageFreetier,xh as usageStats,Sh as usageSummary,Ah as usageTokenPlan,ms as videoDownload,ds as videoEdit,us as videoGenerate,fs as videoRef,ps as videoTaskGet,vs as visionDescribe,BE as workspaceInit,Yg as workspaceList};
|