bailian-cli-runtime 1.13.0 → 1.14.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.
@@ -0,0 +1 @@
1
+ import{d as e,i as t}from"./binary-update-Dxwl7hbM.mjs";export{t as fetchBinaryChannelVersion,e as performBinaryUpdate};
@@ -0,0 +1,2 @@
1
+ import{BINARY_PRODUCT_CLIENT_NAME as e,binaryAssetFileName as t,binaryInnerFileName as n,channelManifestUrl as r,detectBinaryPlatform as i,extractZipEntryToFile as a,getConfigDir as o,releaseAssetUrl as s,writeInstallMethodSync as c}from"bailian-cli-core";import{chmod as l,copyFile as u,lstat as d,mkdir as f,readdir as p,readlink as m,rename as h,rm as g,unlink as _,writeFile as v}from"node:fs/promises";import{dirname as y,join as b}from"node:path";import{homedir as x}from"node:os";import{createHash as S}from"node:crypto";function C(){return process.env.BAILIAN_SHARE_DIR?process.env.BAILIAN_SHARE_DIR:process.platform===`win32`?b(process.env.LOCALAPPDATA||b(x(),`AppData`,`Local`),`bailian-cli`):b(x(),`.local`,`share`,`bailian-cli`)}function w(){return process.env.BAILIAN_BIN_DIR?process.env.BAILIAN_BIN_DIR:process.platform===`win32`?b(C(),`bin`):b(x(),`.local`,`bin`)}function T(){return b(C(),`versions`)}function E(){return b(C(),`current`)}async function D(e=`latest`,t=5e3){try{let n=await fetch(r(e),{signal:AbortSignal.timeout(t)});return n.ok?(await n.json()).version??null:null}catch{return null}}async function O(e=`latest`,t=8e3){try{let n=await fetch(r(e),{signal:AbortSignal.timeout(t)});return n.ok?await n.json():null}catch{return null}}function k(e){let t=e.trim();return/^v\d/i.test(t)?t.slice(1):t}const A=/^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;function j(e){let t=e.trim();return t?A.test(t):!1}async function M(e,t,n=8e3){try{let r=await fetch(s(e,`SHA256SUMS`),{signal:AbortSignal.timeout(n)});if(!r.ok)return;let i=await r.text();for(let e of i.split(`
2
+ `)){let n=e.trim().match(/^([a-fA-F0-9]{64})\s+(\S+)$/);if(n?.[2]===t)return n[1].toLowerCase()}}catch{}}async function N(e){let r=k(e),{os:a,arch:o,fileSuffix:c}=i(),l=c===`.exe`,u=t(r,a,o,l),d=n(r,a,o,l),f=s(r,u),p=await M(r,u);if(!p){let e=await O(`latest`);e?.version===r&&(p=e.assets?.[`${a}-${o}`]?.sha256)}return{zipName:u,innerName:d,url:f,expectedSha:p}}async function P(e,t){let n=await fetch(e,{signal:AbortSignal.timeout(12e4)});if(!n.ok||!n.body)throw Error(`Download failed (${n.status}): ${e}`);let r=await n.arrayBuffer(),i=Buffer.from(r);return await f(y(t),{recursive:!0}),await v(t,i),i}function F(e){return S(`sha256`).update(e).digest(`hex`)}function I(){return process.platform===`win32`?`bl.exe`:`bl`}function L(){return process.platform===`win32`?`bailian.exe`:`bailian`}async function R(){let e=E();try{let t=await m(e);return t.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(t)?t:b(y(e),t)}catch{return null}}function z(e){let t=T(),n=e.replaceAll(`\\`,`/`),r=t.replaceAll(`\\`,`/`).replace(/\/$/,``);if(!n.startsWith(`${r}/`)&&n!==r){let t=e.replaceAll(`\\`,`/`).split(`/`).pop();return t&&t!==`versions`?t:null}return n.slice(r.length+1).split(`/`)[0]??null}async function B(e){let t=b(T(),e),n=E();await f(C(),{recursive:!0});try{await _(n)}catch{try{await g(n,{recursive:!0,force:!0})}catch{}}let{symlink:r}=await import(`node:fs/promises`);return process.platform===`win32`?await r(t,n,`junction`):await r(t,n),t}async function V(e){let t=b(T(),e),n=I(),r=b(E(),n),i=w();if(process.platform===`win32`){await U(i);let e=b(t,n),r=b(t,L());try{await d(r)}catch{try{let{link:t}=await import(`node:fs/promises`);await t(e,r)}catch{await u(e,r)}}return}await f(i,{recursive:!0});let{symlink:a}=await import(`node:fs/promises`);for(let e of[`bl`,`bailian`]){let t=b(i,e);try{await _(t)}catch{}await a(r,t)}}function H(e){return e&&typeof e==`object`&&`code`in e?String(e.code??``):``}async function U(e){let t=E(),{symlink:n,rename:r}=await import(`node:fs/promises`),i=null;try{let n=await d(e);if(n.isSymbolicLink()){let n=await m(e);if((n.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(n)?n:b(y(e),n)).replaceAll(`\\`,`/`).toLowerCase()===t.replaceAll(`\\`,`/`).toLowerCase())return;await _(e)}else if(n.isDirectory()){i=`${e}.migrating.${process.pid}`;try{await r(e,i)}catch(t){try{await g(e,{recursive:!0,force:!0}),i=null}catch(n){let r=H(t)||H(n)||`EACCES`;throw Error(`Failed to migrate ${e} to a junction pointing at current (${r}). Close other bl sessions and re-run update, or re-run the install script once.`,{cause:n})}}}else await _(e).catch(()=>g(e,{recursive:!0,force:!0}))}catch(t){let n=H(t);if(n&&n!==`ENOENT`)throw t instanceof Error&&t.message.includes(`Failed to migrate`)?t:Error(`Failed to migrate ${e} to a junction pointing at current (${n}). Close other bl sessions and re-run update, or re-run the install script once.`,{cause:t})}await f(y(e),{recursive:!0}),await n(t,e,`junction`),i&&await g(i,{recursive:!0,force:!0}).catch(()=>{})}async function W(e){let t=T(),n=new Set(e.filter(Boolean)),r=await R(),i=r?z(r):null;i&&n.add(i);let a;try{a=await p(t)}catch{return}for(let e of a){if(e.startsWith(`.`)){await g(b(t,e),{recursive:!0,force:!0}).catch(()=>{});continue}n.has(e)||await g(b(t,e),{recursive:!0,force:!0}).catch(()=>{})}}async function G(t){let n=k(t),{zipName:r,innerName:i,url:s,expectedSha:d}=await N(n),p=C(),m=T();await f(b(p,`.tmp`),{recursive:!0}),await f(m,{recursive:!0});let v=await R(),y=v?z(v):null,x=b(p,`.tmp`,r),S=F(await P(s,x));if(d&&d!==S)throw await _(x).catch(()=>{}),Error(`Checksum mismatch for ${r}`);let w=b(m,`.staging.${n}.${process.pid}`);await g(w,{recursive:!0,force:!0}).catch(()=>{}),await f(w,{recursive:!0});let E=I(),D=b(w,E),O=b(p,`.tmp`,`${E}.${process.pid}`);if(await a(x,O,i),await _(x).catch(()=>{}),await h(O,D),process.platform!==`win32`)await l(D,493);else{let e=b(w,L());try{let{link:t}=await import(`node:fs/promises`);await t(D,e)}catch{await u(D,e)}}let A=b(m,n);await g(A,{recursive:!0,force:!0}).catch(()=>{}),await h(w,A),await B(n),await V(n);let j=[n];return y&&y!==n&&j.push(y),await W(j),c(`binary`,{clientName:e}),await f(o(),{recursive:!0}),n}export{w as a,T as c,G as d,W as f,B as h,D as i,j as l,N as m,U as n,E as o,R as p,O as r,C as s,V as t,k as u};
package/dist/index.d.mts CHANGED
@@ -221,6 +221,14 @@ declare function emitResult(data: unknown, format: OutputFormat): void;
221
221
  * Used in --quiet mode or when the result is a single scalar.
222
222
  */
223
223
  declare function emitBare(value: string): void;
224
+ /**
225
+ * Surface a server request id for text-mode output. Written to stderr (the
226
+ * diagnostic channel) so it never corrupts the primary stdout result, mirroring
227
+ * the request_id line the verbose HTTP logger prints. No-op when the id is
228
+ * absent (e.g. dry-run) or in --quiet mode (which owes callers a bare scalar).
229
+ * JSON output surfaces request_id inside the payload instead of calling this.
230
+ */
231
+ declare function emitRequestId(requestId: string | undefined, quiet: boolean): void;
224
232
  //#endregion
225
233
  //#region src/output/table.d.ts
226
234
  /**
@@ -380,7 +388,71 @@ declare const NPM_REGISTRY = "https://registry.npmjs.org";
380
388
  declare const NPM_PACKAGE = "bailian-cli";
381
389
  declare function fetchLatestVersion(timeoutMs?: number, npmPackage?: string): Promise<string | null>;
382
390
  declare function getPendingUpdateNotification(): string | null;
383
- declare function checkForUpdate(currentVersion: string, npmPackage?: string): Promise<void>;
391
+ declare function checkForUpdate(currentVersion: string, npmPackage?: string, clientName?: string): Promise<void>;
392
+ //#endregion
393
+ //#region src/utils/binary-update.d.ts
394
+ interface ChannelManifest {
395
+ version: string;
396
+ assets?: Record<string, {
397
+ file?: string;
398
+ sha256?: string;
399
+ url?: string;
400
+ inner?: string;
401
+ }>;
402
+ }
403
+ /** Product share root: versions/, current, and (on Windows) bin/. */
404
+ declare function getBinaryShareRoot(): string;
405
+ /** PATH directory that should expose `bl` / `bailian`. */
406
+ declare function getBinaryBinRoot(): string;
407
+ declare function getBinaryVersionsDir(): string;
408
+ declare function getBinaryCurrentPath(): string;
409
+ declare function fetchBinaryChannelVersion(channel?: string, timeoutMs?: number): Promise<string | null>;
410
+ declare function fetchBinaryChannelManifest(channel?: string, timeoutMs?: number): Promise<ChannelManifest | null>;
411
+ /** Strip a leading `v` from release-style tags (`v1.2.3` → `1.2.3`). */
412
+ declare function normalizeBinaryVersion(raw: string): string;
413
+ /** True if `raw` is a usable `--to` target after trim (optional `v` prefix). */
414
+ declare function isValidUpdateTargetVersion(raw: string): boolean;
415
+ interface BinaryDownloadSpec {
416
+ zipName: string;
417
+ innerName: string;
418
+ url: string;
419
+ expectedSha?: string;
420
+ }
421
+ /**
422
+ * Resolve download URL / names for an exact binary version.
423
+ * Always targets `v{version}/` assets; never reuses another version's rolling
424
+ * manifest `url` / `file`. Checksum prefers per-version SHA256SUMS, then the
425
+ * latest rolling manifest only when it points at the same version.
426
+ */
427
+ declare function resolveBinaryDownloadSpec(targetVersion: string): Promise<BinaryDownloadSpec>;
428
+ /** Resolve which version directory `current` points at, if any. */
429
+ declare function readCurrentVersionDir(): Promise<string | null>;
430
+ /**
431
+ * Point `shareRoot/current` at `versions/<version>/`.
432
+ * Unix: directory symlink. Windows: directory junction.
433
+ * Retargets in place so PATH entries that go through `current` keep working.
434
+ */
435
+ declare function switchCurrentToVersion(version: string): Promise<string>;
436
+ /**
437
+ * Ensure PATH bin entries resolve through `current` (Codex-style).
438
+ * - Unix: `~/.local/bin/{bl,bailian}` → `current/bl`
439
+ * - Windows: `shareRoot/bin` is a junction → `current` (contains bl.exe + bailian.exe)
440
+ */
441
+ declare function ensureBinaryPathEntries(version: string): Promise<void>;
442
+ /**
443
+ * Keep only the listed version directory names under `versions/`.
444
+ * Always preserves directories that are still the live `current` target.
445
+ */
446
+ declare function pruneBinaryVersions(keepVersions: string[]): Promise<void>;
447
+ /**
448
+ * Download and install a newer standalone binary using Codex-style layout:
449
+ * `versions/<ver>/` + retarget `current` + path entries through `current`.
450
+ * After a successful switch, prune so only current + previous version remain.
451
+ *
452
+ * Does not overwrite a running executable image: old version files stay locked
453
+ * by the current process; the next invocation follows the updated pointer.
454
+ */
455
+ declare function performBinaryUpdate(targetVersion: string): Promise<string>;
384
456
  //#endregion
385
457
  //#region src/utils/flag-descriptions.d.ts
386
458
  /** Shared --foo <bool> help text; keep wording consistent with actual CLI/request behavior. */
@@ -693,4 +765,4 @@ declare function collectPipelineHints(pipeline: PipelineDefinition, dispatcher?:
693
765
  declare function executePipeline(pipeline: PipelineDefinition, runtimeInput?: Record<string, unknown>, options?: ExecutePipelineOptions): Promise<PipelineExecutionReport>;
694
766
  declare function streamPipelineEvents(pipeline: PipelineDefinition, runtimeInput?: Record<string, unknown>, options?: Pick<ExecutePipelineOptions, "concurrency" | "basePath" | "dryRun" | "signal" | "timeoutSeconds" | "blRequestTimeoutSeconds" | "stepDispatcher">): AsyncGenerator<PipelineLifecycleEvent>;
695
767
  //#endregion
696
- export { API_KEY_PAGE, type AnsiStyles, BAILIAN_CONSOLE, BAILIAN_CONSOLE_ROOT, BOOL_FLAG_PROMPT_EXTEND_API_DEFAULT, BOOL_FLAG_PROMPT_EXTEND_CLI_TRUE, BOOL_FLAG_PROMPT_EXTEND_IMAGE_GENERATE, BOOL_FLAG_WATERMARK, type BarColumn, type BoxTableOptions, CLI_VERSION, type Cli, type CliOptions, type Command, type CommandPackCredentialAccess, type CommandPackDefinition, type CommandPackPolicy, CommandRegistry, type FlagDef, type LocateResult, MCP_WEBSEARCH_PAGE, type Middleware, NPM_PACKAGE, NPM_REGISTRY, type ParsePathResult, type PipelineDefinition, type PipelineLifecycleEvent, type Resolution, type RunContext, TOKEN_PLAN_PAGE, type TextStyle, VOICE_TTS_PAGE, ansi, checkForUpdate, collectPipelineHints, collectPipelineIssues, compose, createCli, createProgressBar, createSpinner, displayWidth, downloadFile, downloadParallel, emitBare, emitResult, executePipeline, fetchLatestVersion, formatBytes, formatTable, getConcurrency, getPendingUpdateNotification, handleError, initPipelineSteps, isTerminal, maybeShowStatusBar, mcpMarketplaceDetailPage, padEnd, parseFlags, parsePath, poll, printQuickStart, printWelcomeBanner, renderBoxTable, resolve, resolveImageSize, runConcurrent, setupProxyFromEnv, streamPipelineEvents, supportsColor };
768
+ export { API_KEY_PAGE, type AnsiStyles, BAILIAN_CONSOLE, BAILIAN_CONSOLE_ROOT, BOOL_FLAG_PROMPT_EXTEND_API_DEFAULT, BOOL_FLAG_PROMPT_EXTEND_CLI_TRUE, BOOL_FLAG_PROMPT_EXTEND_IMAGE_GENERATE, BOOL_FLAG_WATERMARK, type BarColumn, type BoxTableOptions, CLI_VERSION, type Cli, type CliOptions, type Command, type CommandPackCredentialAccess, type CommandPackDefinition, type CommandPackPolicy, CommandRegistry, type FlagDef, type LocateResult, MCP_WEBSEARCH_PAGE, type Middleware, NPM_PACKAGE, NPM_REGISTRY, type ParsePathResult, type PipelineDefinition, type PipelineLifecycleEvent, type Resolution, type RunContext, TOKEN_PLAN_PAGE, type TextStyle, VOICE_TTS_PAGE, ansi, checkForUpdate, collectPipelineHints, collectPipelineIssues, compose, createCli, createProgressBar, createSpinner, displayWidth, downloadFile, downloadParallel, emitBare, emitRequestId, emitResult, ensureBinaryPathEntries, executePipeline, fetchBinaryChannelManifest, fetchBinaryChannelVersion, fetchLatestVersion, formatBytes, formatTable, getBinaryBinRoot, getBinaryCurrentPath, getBinaryShareRoot, getBinaryVersionsDir, getConcurrency, getPendingUpdateNotification, handleError, initPipelineSteps, isTerminal, isValidUpdateTargetVersion, maybeShowStatusBar, mcpMarketplaceDetailPage, normalizeBinaryVersion, padEnd, parseFlags, parsePath, performBinaryUpdate, poll, printQuickStart, printWelcomeBanner, pruneBinaryVersions, readCurrentVersionDir, renderBoxTable, resolve, resolveBinaryDownloadSpec, resolveImageSize, runConcurrent, setupProxyFromEnv, streamPipelineEvents, supportsColor, switchCurrentToVersion };