Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/agents/telemetry-change.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ source-config 只用于百炼 / DashScope API 侧消费,不发送到通用网

底层 Node tracker 还会附加公共设备字段:OS 类型/版本、Node 应用名与版本、平台,以及内置的 `device_id`(本机网卡 MAC 的 MD5,保持不变)。稳定匿名 install id 写入 AEM 的 `uid`:来自 `~/.bailian/telemetry-uid`,首次远端上报时生成随机 UUID v4,以 0600 权限原子发布;生成失败时不上报 `uid`。遥测关闭时不生成该文件。本地 `telemetry.jsonl` 每行附带同名 `uid`。注意:这不是账号用户 ID,只是上报到 AEM `uid` 字段的匿名标识;与 Tracker 内置 `device_id` 无关。

`ensureUid` 无锁(对齐 qwen-code `InstallationManager`):稳态只读;缺失或损坏时同目录 temp 写满后 `rename` 发布(内容原子替换;并发首次创建时后写覆盖先写,磁盘最终为一个 UUID)。失败则省略 `uid`,不阻塞业务退出。
`ensureUid` 无锁:稳态只读;缺失或损坏时同目录 temp 写满后 `rename` 发布(内容原子替换;并发首次创建时后写覆盖先写,磁盘最终为一个 UUID)。失败则省略 `uid`,不阻塞业务退出。

从 2.8.2 起,每条命令事件通过 `commandPrefix` 显式记录调用入口,三种入口仍共用 `pid=bailian-cli-node`:

Expand Down
2 changes: 1 addition & 1 deletion packages/cli/tests/e2e/registry.smoke.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ describe("e2e: bl registry smoke", () => {
expect(stderr).toMatch(/--console-region <region>/);
expect(stderr).toMatch(/--model <model>/);
expect(stderr).toMatch(/--period <minutes>/);
expect(stderr).toMatch(/--output <format>/);
expect(stderr).toMatch(/--output <text\|json>/);
expect(stderr).not.toMatch(/API region \(default: cn-beijing\)/);
});

Expand Down
3 changes: 1 addition & 2 deletions packages/commands/src/commands/auth/login-api-key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ export interface ApiKeyValidationResult {
kind: ApiKeyEndpointKind;
}

const API_KEY_VALIDATION_TIMEOUT_SECONDS = 5;
const ORDINARY_WORKSPACE_REGIONS = [
"cn-beijing",
"ap-southeast-1",
Expand Down Expand Up @@ -197,7 +196,7 @@ export async function validateApiKey(
await requestJson<unknown>(deps, {
url: candidate.modelsUrl,
headers: { Authorization: `Bearer ${key}` },
timeout: Math.min(deps.settings.timeout, API_KEY_VALIDATION_TIMEOUT_SECONDS),
timeout: deps.settings.timeout,
});
return { candidate };
} catch (error) {
Expand Down
6 changes: 5 additions & 1 deletion packages/commands/src/commands/usage/free.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,11 @@ export default defineCommand({
};

if (settings.dryRun) {
ctx.output.result({ api: FREE_TIER_API, data: requestData });
ctx.output.result({
api: FREE_TIER_API,
data: requestData,
...(!modelFlag ? { scope: "all", models_resolved: false } : {}),
});
return;
}

Expand Down
2 changes: 2 additions & 0 deletions packages/commands/src/commands/usage/freetier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,11 @@ export default defineCommand({
: "BatchActivateFreeTierOnlyRequest";

if (settings.dryRun) {
const unresolvedAll = Boolean(flags.all) && !modelFlag;
ctx.output.result({
api,
data: { [requestKey]: { models } },
...(unresolvedAll ? { scope: "all", models_resolved: false } : {}),
});
return;
}
Expand Down
44 changes: 43 additions & 1 deletion packages/commands/tests/auth-api-key.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { httpTransport } from "bailian-cli-core";
import { BailianError, ExitCode, type Identity, type Settings } from "bailian-cli-core";
import { expect, test } from "vite-plus/test";
import { expect, test, vi } from "vite-plus/test";
import {
apiKeyValidationCandidates,
validateApiKey,
Expand Down Expand Up @@ -334,3 +334,45 @@ test("同一优先级的 HTTP 错误保持候选顺序", async () => {
httpTransport.fetch = originalFetch;
}
});

test("API Key 校验超时跟随 settings.timeout,不再被 5 秒硬顶截断", async () => {
const originalFetch = httpTransport.fetch;
httpTransport.fetch = async (_input, init) => {
const signal = init?.signal;
return await new Promise<never>((_resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason ?? new Error("aborted"));
return;
}
signal?.addEventListener(
"abort",
() => {
reject(signal.reason ?? new Error("aborted"));
},
{ once: true },
);
});
};

vi.useFakeTimers({ toFake: ["setTimeout"] });
try {
const pending = validateApiKey(
{ identity, settings: { ...settings, timeout: 60 } },
"sk-placeholder",
{ explicitBaseUrl: "https://ws-explicit.ap-southeast-1.maas.aliyuncs.com" },
).then(
() => "resolved" as const,
() => "rejected" as const,
);

// 旧硬顶是 5 秒:若仍封顶,这里应已结束;跟随 settings.timeout=60 时仍应挂起
await vi.advanceTimersByTimeAsync(5_000);
expect(await Promise.race([pending, Promise.resolve("pending")])).toBe("pending");

await vi.advanceTimersByTimeAsync(55_000);
expect(await pending).toBe("rejected");
} finally {
vi.useRealTimers();
httpTransport.fetch = originalFetch;
}
});
2 changes: 1 addition & 1 deletion packages/commands/tests/e2e/command-help.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ test("captureCommandHelp 用 topic 最小路由渲染真实命令帮助", async
expect(helpOutput).toContain("Usage: bl quota list");
expect(helpOutput).toContain("--model <model>");
expect(helpOutput).toContain("--name <name>");
expect(helpOutput).toContain("--output <format>");
expect(helpOutput).toContain("--output <text|json>");
});

test("runCommandHelp 保持 commands E2E 的 stderr 与 exitCode 断言接口", async () => {
Expand Down
22 changes: 22 additions & 0 deletions packages/commands/tests/e2e/usage-free.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
isConsoleAuthFailure,
parseStdoutJson,
runCommandHelp,
runCommandInProcess,
runConsoleCommandE2e,
} from "./helpers.ts";
import { USAGE_ROUTES } from "./topic-routes.ts";
Expand All @@ -22,6 +23,27 @@ describe("e2e: usage free", () => {
expect(stderr).toContain("bl usage free --model qwen3-max");
expect(stderr).toContain("bl usage free --model qwen3-max,qwen-turbo");
});

test("usage free --dry-run 无 --model 标注全量范围未解析", async () => {
const { stdout, stderr, exitCode } = await runCommandInProcess(USAGE_ROUTES, [
"usage",
"free",
"--dry-run",
"--output",
"json",
]);
expect(exitCode, stderr).toBe(0);
const data = parseStdoutJson<{
api: string;
scope: string;
models_resolved: boolean;
data: { queryFreeTierQuotaRequest: { models: string[] } };
}>(stdout);
expect(data.api).toContain("queryFreeTierQuota");
expect(data.scope).toBe("all");
expect(data.models_resolved).toBe(false);
expect(data.data.queryFreeTierQuotaRequest.models).toEqual([]);
});
});

describe.skipIf(!isConsoleE2EReady())("e2e: usage free(Console)", () => {
Expand Down
22 changes: 22 additions & 0 deletions packages/commands/tests/e2e/usage-freetier.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,26 @@ describe("e2e: usage freetier", () => {
expect(data.api).toBe("zeldaEasy.bailian-commerce.freeTrial.batchDeactivateFreeTierOnly");
expect(data.data.BatchDeactivateFreeTierOnlyRequest.models).toEqual(["qwen-plus"]);
});

test("usage freetier --all --dry-run 标注全量范围未解析,不把空列表当执行计划", async () => {
const { stdout, stderr, exitCode } = await runCommandInProcess(USAGE_ROUTES, [
"usage",
"freetier",
"--all",
"--dry-run",
"--output",
"json",
]);
expect(exitCode, stderr).toBe(0);
const data = parseStdoutJson<{
api: string;
scope: string;
models_resolved: boolean;
data: { BatchActivateFreeTierOnlyRequest: { models: string[] } };
}>(stdout);
expect(data.api).toBe("zeldaEasy.bailian-commerce.freeTrial.batchActivateFreeTierOnly");
expect(data.scope).toBe("all");
expect(data.models_resolved).toBe(false);
expect(data.data.BatchActivateFreeTierOnlyRequest.models).toEqual([]);
});
});
45 changes: 45 additions & 0 deletions packages/commands/tests/output/usage-output.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,51 @@ test.each(cases)("$name dry-run is one JSON result without API calls", async (sc
expect(calls).toEqual([]);
expect(openCalls).toEqual([]);
});

test.each(["text", "json"] as const)(
"auto-stop --all dry-run marks unresolved full scope in %s",
async (format) => {
const result = await invoke(
{ ...cases[1]!, flags: { all: true } },
{ format, quiet: true, dryRun: true },
);
expect(result.exitCode, result.stderr).toBe(0);
expect(result.strayOut + result.strayErr).toBe("");
expect(calls).toEqual([]);
const preview = {
api: "zeldaEasy.bailian-commerce.freeTrial.batchActivateFreeTierOnly",
scope: "all",
models_resolved: false,
data: { BatchActivateFreeTierOnlyRequest: { models: [] } },
};
if (format === "json") expect(JSON.parse(result.stdout)).toMatchObject(preview);
else {
expect(result.stdout).toContain("scope: all");
expect(result.stdout).toContain("models_resolved: false");
}
},
);

test.each(["text", "json"] as const)(
"usage free dry-run without --model marks unresolved full scope in %s",
async (format) => {
const result = await invoke({ ...cases[0]!, flags: {} }, { format, quiet: true, dryRun: true });
expect(result.exitCode, result.stderr).toBe(0);
expect(result.strayOut + result.strayErr).toBe("");
expect(calls).toEqual([]);
const preview = {
api: "zeldaEasy.bailian-commerce.freeTrial.queryFreeTierQuota",
scope: "all",
models_resolved: false,
data: { queryFreeTierQuotaRequest: { models: [] } },
};
if (format === "json") expect(JSON.parse(result.stdout)).toMatchObject(preview);
else {
expect(result.stdout).toContain("scope: all");
expect(result.stdout).toContain("models_resolved: false");
}
},
);
test.each(cases)("$name failure is one structured error", async (scenario) => {
failure = true;
const result = await invoke(scenario, { format: "json", quiet: true });
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/types/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ export const GLOBAL_FLAGS = {
},
output: {
type: "string",
valueHint: "<format>",
valueHint: "<text|json>",
choices: ["text", "json"] as const,
description: { "en-US": "Output format: text, json", "zh-CN": "输出格式:text、json" },
},
timeout: {
Expand Down
37 changes: 26 additions & 11 deletions packages/runtime/src/create-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,19 +83,34 @@ function presentationFlags(argv: string[]): Partial<SourceFlags> {
for (let index = 0; index < argv.length; index++) {
const argument = argv[index]!;
if (argument === "--") break;
if (argument === "--quiet") flags.quiet = true;
else if (argument === "--verbose") flags.verbose = true;
else
for (const key of ["output", "config"] as const) {
if (argument.startsWith(`--${key}=`)) flags[key] = argument.slice(key.length + 3);
else if (argument === `--${key}`) {
const value = argv[index + 1];
if (value !== undefined && !value.startsWith("--")) {
flags[key] = value;
index++;
}
if (argument === "--quiet") {
flags.quiet = true;
continue;
}
if (argument === "--verbose") {
flags.verbose = true;
continue;
}

for (const key of ["output", "config"] as const) {
let value: string | undefined;
if (argument.startsWith(`--${key}=`)) value = argument.slice(key.length + 3);
else if (argument === `--${key}`) {
const next = argv[index + 1];
if (next !== undefined && !next.startsWith("--")) {
value = next;
index++;
}
} else continue;

if (value === undefined) continue;
if (key === "config") {
flags.config = value;
continue;
}
// Only accept legal formats here; illegal values are rejected by parseFlags.
if (value === "text" || value === "json") flags.output = value;
}
}
return flags;
}
Expand Down
15 changes: 15 additions & 0 deletions packages/runtime/tests/args.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,21 @@ test("parseFlags validates number flags", () => {
);
});

test("parseFlags rejects illegal --output values", () => {
expect(() => parseFlags(["--prompt", "x", "--output", "yaml"], OPTS)).toThrowError(
expect.objectContaining({
name: "UsageError",
exitCode: ExitCode.USAGE,
message: expect.stringContaining("Flag --output must be one of: text, json"),
}),
);
});

test("parseFlags accepts legal --output values", () => {
expect(parseFlags(["--prompt", "x", "--output", "json"], OPTS).output).toBe("json");
expect(parseFlags(["--prompt", "x", "--output", "text"], OPTS).output).toBe("text");
});

test("parseFlags throws UsageError when a required flag is missing", () => {
expect(() => parseFlags(["--model", "qwen-image-2.0"], OPTS)).toThrowError(
expect.objectContaining({
Expand Down
7 changes: 7 additions & 0 deletions packages/runtime/tests/runtime-output.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,13 @@ test.each(
expect(diagnostics(result.stderr)[0].error.code).toBe(2);
});

test("illegal --output value is a usage error instead of silent text fallback", async () => {
const result = await invoke(["probe", "--output", "yaml"]);
expect(result.exitCode).toBe(2);
expect(result.stdout).toBe("");
expect(result.stderr).toContain("Flag --output must be one of: text, json");
});

test("corrupt configuration preserves defaults with a structured warning", async () => {
const result = await invoke(["probe", "--output", "json"], {
corrupt: true,
Expand Down
22 changes: 11 additions & 11 deletions skills/bailian-cli/reference/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,17 +159,17 @@ Use this index for the skill-scoped quick index and global flags.

Available on every command (in addition to command-specific flags):

| Flag | Type | Required | Description |
| --------------------- | ------ | -------- | --------------------------------------------------------- |
| `--introspect` | switch | no | Print the machine-readable command schema (JSON) and exit |
| `--output <format>` | string | no | Output format: text, json |
| `--timeout <seconds>` | number | no | Request timeout |
| `--quiet` | switch | no | Suppress non-essential output |
| `--verbose` | switch | no | Print HTTP request/response details |
| `--dry-run` | switch | no | Dry run mode |
| `--config <name>` | string | no | Use a config profile for this command |
| `--help` | switch | no | Show help |
| `--version` | switch | no | Print version |
| Flag | Type | Required | Description |
| ----------------------- | ------ | -------- | --------------------------------------------------------- |
| `--introspect` | switch | no | Print the machine-readable command schema (JSON) and exit |
| `--output <text\|json>` | string | no | Output format: text, json |
| `--timeout <seconds>` | number | no | Request timeout |
| `--quiet` | switch | no | Suppress non-essential output |
| `--verbose` | switch | no | Print HTTP request/response details |
| `--dry-run` | switch | no | Dry run mode |
| `--config <name>` | string | no | Use a config profile for this command |
| `--help` | switch | no | Show help |
| `--version` | switch | no | Print version |

## Model auth flags

Expand Down
22 changes: 11 additions & 11 deletions skills/bailian-finetune/reference/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,17 +77,17 @@ Use this index for the skill-scoped quick index and global flags.

Available on every command (in addition to command-specific flags):

| Flag | Type | Required | Description |
| --------------------- | ------ | -------- | --------------------------------------------------------- |
| `--introspect` | switch | no | Print the machine-readable command schema (JSON) and exit |
| `--output <format>` | string | no | Output format: text, json |
| `--timeout <seconds>` | number | no | Request timeout |
| `--quiet` | switch | no | Suppress non-essential output |
| `--verbose` | switch | no | Print HTTP request/response details |
| `--dry-run` | switch | no | Dry run mode |
| `--config <name>` | string | no | Use a config profile for this command |
| `--help` | switch | no | Show help |
| `--version` | switch | no | Print version |
| Flag | Type | Required | Description |
| ----------------------- | ------ | -------- | --------------------------------------------------------- |
| `--introspect` | switch | no | Print the machine-readable command schema (JSON) and exit |
| `--output <text\|json>` | string | no | Output format: text, json |
| `--timeout <seconds>` | number | no | Request timeout |
| `--quiet` | switch | no | Suppress non-essential output |
| `--verbose` | switch | no | Print HTTP request/response details |
| `--dry-run` | switch | no | Dry run mode |
| `--config <name>` | string | no | Use a config profile for this command |
| `--help` | switch | no | Show help |
| `--version` | switch | no | Print version |

## Model auth flags

Expand Down
Loading
Loading