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
3 changes: 2 additions & 1 deletion docs/agents/telemetry-change.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ AEM 映射:
| `c5` | request ID |
| `c6` | `bizFrom` 业务来源(全局 `--biz-from`,归一化标量;专用扁平列,直接筛选/分组) |

远端发送是 best-effort,不得阻塞命令或改变退出码。正常退出最多等待 1 秒,SIGINT 最多等待 500 ms。
远端发送是 best-effort,不得阻塞命令或改变退出码。正常退出最多等待 1 秒,SIGINT 最多等待 500 ms。`flushTelemetry` 同时等待在途本地 JSONL 落盘与远端发送,共享同一超时预算;超时只取消远端,本地写不可取消但仍不得无限阻塞退出。

## 必查清单

Expand Down Expand Up @@ -213,6 +213,7 @@ AEM 映射:
- [ ] `remoteSink` 从调用到 `remoteSendEvent` 入队之间不得出现 `await`(flush 只排空已入队事件)
- [ ] 测试中调用 `remoteSink` 的用例必须使用 `enterIsolatedHome()`,避免写入真实配置目录
- [ ] 遥测发送的 DNS/HTTP/响应体必须受可取消预算控制;flush 超时必须取消在途操作,不能只停止等待,也不能修改全局 DNS/dispatcher 或强制退出宿主
- [ ] `localSink` 在途写入须登记并由 `flushTelemetry` 等待(即使无远端 in-flight);命令路径仍可 fire-and-forget,不得因本地写失败改退出码;用 `telemetry-sink` 单测覆盖「无远端也落盘」和「本地卡住仍按时返回」,并用 `telemetry-exit` e2e 的 `fast-run-to-exit` 子进程用例守住「远端立即响应 + `runToExit` 强制退出仍落盘」
- [ ] 退出生命周期变更保留真实子进程回归:挂起响应头/响应体、DNS 预查询和关闭遥测;检查实际退出及进程仍存活时的连接释放,不以 flush Promise 返回代替验收
- [ ] 错误字段不得额外拼接 token、请求体、prompt 或本地路径

Expand Down
28 changes: 15 additions & 13 deletions packages/cli/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createCli } from "bailian-cli-runtime";
import { createCli, runToExit } from "bailian-cli-runtime";
import { commandAliases, commands } from "./commands.ts";
import { commandPackPolicy } from "./command-pack-policy.ts";
import pkg from "../package.json" with { type: "json" };
Expand All @@ -12,15 +12,17 @@ const quickStartTasks = [
"介绍一下 Bailian CLI 能帮我完成哪些任务,并根据我的需求推荐使用方式。\n Explain what Bailian CLI can help me accomplish, and recommend how to use it based on my needs.",
] as const;

void createCli(
{ ...commands, ...commandAliases },
{
binName: "bl",
...resolveAliyunIntegration(process.env),
version: pkg.version,
clientName: "bailian-cli",
npmPackage: "bailian-cli",
quickStartTasks,
commandPacks: commandPackPolicy,
},
).run();
void runToExit(
createCli(
{ ...commands, ...commandAliases },
{
binName: "bl",
...resolveAliyunIntegration(process.env),
version: pkg.version,
clientName: "bailian-cli",
npmPackage: "bailian-cli",
quickStartTasks,
commandPacks: commandPackPolicy,
},
),
);
22 changes: 18 additions & 4 deletions packages/core/src/telemetry/sink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ interface PendingSend {
promise: Promise<void>;
}
const inflightSends = new Set<PendingSend>();
/** In-flight local JSONL writes; flush must wait so process.exit cannot drop them. */
const inflightLocalWrites = new Set<Promise<void>>();
let remoteClient: any = undefined;
let remoteInitialized = false;

Expand Down Expand Up @@ -83,11 +85,12 @@ function initRemote(): void {
}

/**
* Best-effort wait for all in-flight telemetry sends.
* Best-effort wait for in-flight local JSONL writes and remote sends.
*
* 1. Call `_sendAll` to drain the tracker's debounce queue so events still in
* the 500ms merge window are pushed to the network immediately.
* 2. Wait for sends within the budget; on timeout, cancel DNS/HTTP/body work.
* 2. Wait for local writes and remote sends within the budget; on timeout,
* cancel DNS/HTTP/body work (local writes are not cancellable).
*
* Telemetry must never block the CLI: callers should pass a short timeout
* (e.g. 1000ms) and always race against it. Errors and timeouts are swallowed.
Expand All @@ -106,9 +109,11 @@ export async function flushTelemetry(timeoutMs = 1000): Promise<void> {
// flush itself must never throw
}
}
if (inflightSends.size === 0) return;
const localWrites = [...inflightLocalWrites];
const remotePromises = [...inflightSends].map((pending) => pending.promise);
if (localWrites.length === 0 && remotePromises.length === 0) return;
await Promise.race([
Promise.allSettled([...inflightSends].map((pending) => pending.promise)),
Promise.allSettled([...localWrites, ...remotePromises]),
new Promise<void>((resolve) => {
deadline = setTimeout(() => {
for (const pending of inflightSends) pending.controller.abort();
Expand All @@ -125,6 +130,15 @@ export async function flushTelemetry(timeoutMs = 1000): Promise<void> {
}

export async function localSink(event: TrackingEvent | FirstInstallEvent): Promise<void> {
let pending!: Promise<void>;
pending = writeLocalEvent(event).finally(() => {
inflightLocalWrites.delete(pending);
});
inflightLocalWrites.add(pending);
await pending;
}

async function writeLocalEvent(event: TrackingEvent | FirstInstallEvent): Promise<void> {
try {
await ensureConfigDir();
const path = TELEMETRY_FILE();
Expand Down
41 changes: 40 additions & 1 deletion packages/core/tests/telemetry-sink.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { existsSync } from "node:fs";
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, beforeEach, expect, test, vi } from "vite-plus/test";
import type { TrackingEvent } from "../src/telemetry/event.ts";
import { enterIsolatedHome, type IsolatedHomeHandle } from "./helpers/isolation.ts";
Expand Down Expand Up @@ -39,6 +40,7 @@ afterEach(() => {
iso.restore();
vi.clearAllTimers();
vi.useRealTimers();
vi.doUnmock("../src/config/paths.ts");
vi.resetModules();
fixture.signals = [];
fixture.complete = false;
Expand Down Expand Up @@ -100,3 +102,40 @@ test("importing sink without reporting does not create the uid file", async () =
const { getUidPath } = await import("../src/telemetry/uid.ts");
expect(existsSync(getUidPath())).toBe(false);
});

test("flush waits for in-flight local writes even when no remote send is pending", async () => {
const { localSink, flushTelemetry } = await import("../src/telemetry/sink.ts");
// Fire-and-forget as trackCommandExecution does; flush must still persist the line.
void localSink({ command: "local-only" } as TrackingEvent);
await flushTelemetry(1000);
const path = join(iso.configDir, "telemetry.jsonl");
expect(existsSync(path)).toBe(true);
expect(readFileSync(path, "utf8")).toContain('"command":"local-only"');
});

test("flush returns within its budget when a local write stalls", async () => {
vi.useFakeTimers();
vi.doMock("../src/config/paths.ts", async () => {
const actual =
await vi.importActual<typeof import("../src/config/paths.ts")>("../src/config/paths.ts");
return {
...actual,
ensureConfigDir: () => new Promise<void>(() => {}),
};
});
const { localSink, flushTelemetry } = await import("../src/telemetry/sink.ts");
void localSink({ command: "stalled-local" } as TrackingEvent);
const pending = flushTelemetry(50);
await vi.advanceTimersByTimeAsync(49);
// Still within budget: flush must not have resolved by hanging on local I/O alone.
let settled = false;
void pending.then(() => {
settled = true;
});
await Promise.resolve();
expect(settled).toBe(false);
await vi.advanceTimersByTimeAsync(1);
await pending;
expect(settled).toBe(true);
expect(vi.getTimerCount()).toBe(0);
});
16 changes: 9 additions & 7 deletions packages/kscli/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { createCli } from "bailian-cli-runtime";
import { createCli, runToExit } from "bailian-cli-runtime";
import { commands } from "./commands.ts";
import pkg from "../package.json" with { type: "json" };

void createCli(commands, {
binName: "kscli",
version: pkg.version,
clientName: "knowledge-studio-cli",
npmPackage: "knowledge-studio-cli",
}).run();
void runToExit(
createCli(commands, {
binName: "kscli",
version: pkg.version,
clientName: "knowledge-studio-cli",
npmPackage: "knowledge-studio-cli",
}),
);
72 changes: 65 additions & 7 deletions packages/runtime/src/create-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import {
} from "bailian-cli-core";
import { setupProxyFromEnv } from "./proxy.ts";
import { handleError } from "./error-handler.ts";
import { flushOutput, INTERRUPT_FLUSH_TIMEOUT_MS, trackStreamWrites } from "./output/flush.ts";
import { type OutputReporter, createOutputReporter } from "./output/reporter.ts";
import { loadCommandPacks } from "./command-packs/load.ts";
import { createCommandPackManager } from "./command-packs/manager.ts";
Expand Down Expand Up @@ -120,10 +121,13 @@ function presentationFlags(argv: string[]): Partial<SourceFlags> {
interface ProcessOutputContext {
getReporter: () => OutputReporter;
localize: (text: LocalizedText) => string;
getOutputFormat: () => "text" | "json";
}

const activeProcessOutputs = new Set<ProcessOutputContext>();
const managedInterruptHandlers = new Set<() => void>();
/** True while the default SIGINT path is flushing before exit(130). */
let interruptExiting = false;

/** Let a command cancel asynchronous work and finish cleanup before the runtime exits. */
export function registerInterruptHandler(handler: () => void): () => void {
Expand All @@ -139,8 +143,14 @@ export function registerInterruptHandler(handler: () => void): () => void {
/** One process event produces one error, using the first still-active invocation. */
function handleInterrupt(): void {
if (managedInterruptHandlers.size > 0) return;
// Second Ctrl-C during flush: exit immediately instead of waiting out the short timeout.
if (interruptExiting) {
process.exit(130);
return;
}
const active = activeProcessOutputs.values().next().value;
if (!active) return;
interruptExiting = true;
active
.getReporter()
.error(
Expand All @@ -149,27 +159,47 @@ function handleInterrupt(): void {
130 as ExitCode,
),
);
void flushTelemetry(500).finally(() => process.exit(130));
void flushTelemetry(500)
.catch(() => undefined)
.then(() =>
flushOutput(INTERRUPT_FLUSH_TIMEOUT_MS, {
mode: "deadline",
format: active.getOutputFormat(),
}),
)
.finally(() => process.exit(130));
}

/** Keep EPIPE protection after run() returns, without retaining completed invocations. */
function handleStdoutPipeError(error: NodeJS.ErrnoException): void {
// Broken pipe: further flush cannot deliver data and may wait out the timeout.
if (error.code === "EPIPE") process.exit(0);
const active = activeProcessOutputs.values().next().value;
if (active) process.exit(active.getReporter().error(error));
if (active) {
const code = active.getReporter().error(error);
void flushOutput(INTERRUPT_FLUSH_TIMEOUT_MS, {
mode: "deadline",
format: active.getOutputFormat(),
}).finally(() => process.exit(code));
return;
}
// Outside an invocation, let other listeners handle errors or retain Node's failure behavior.
if (process.stdout.listenerCount("error") === 1) throw error;
}

function installProcessHandlers(
getReporter: () => OutputReporter,
localize: (text: LocalizedText) => string,
getOutputFormat: () => "text" | "json",
): () => void {
if (!process.stdout.listeners("error").includes(handleStdoutPipeError)) {
process.stdout.on("error", handleStdoutPipeError);
}
if (activeProcessOutputs.size === 0) process.on("SIGINT", handleInterrupt);
const context = { getReporter, localize };
if (activeProcessOutputs.size === 0) {
interruptExiting = false;
process.on("SIGINT", handleInterrupt);
}
const context = { getReporter, localize, getOutputFormat };
activeProcessOutputs.add(context);
return () => {
activeProcessOutputs.delete(context);
Expand Down Expand Up @@ -374,20 +404,27 @@ export function createCli(commands: Record<string, AnyCommand>, opts: CliOptions
let translator = createTranslator(DEFAULT_LANGUAGE);
const localize = (text: LocalizedText) => translator.localize(text);
const initialSettings = buildOutputSettings({ flags, env: process.env });
let outputFormat: "text" | "json" = initialSettings.output;
let reporter = createOutputReporter({
settings: initialSettings,
localize,
commandPrefix,
hasCommand,
});
const warnings: OutputDiagnostic[] = [];
const cleanup = installProcessHandlers(() => reporter, localize);
const cleanup = installProcessHandlers(
() => reporter,
localize,
() => outputFormat,
);
try {
const sources = buildSources(flags, (warning) => warnings.push(warning));
const recoveryConfigName = resolveRecoveryConfigName(sources);
translator = createTranslator(sources.file.language ?? DEFAULT_LANGUAGE);
const sourceSettings = buildOutputSettings(sources);
outputFormat = sourceSettings.output;
reporter = createOutputReporter({
settings: buildOutputSettings(sources),
settings: sourceSettings,
localize,
commandPrefix,
hasCommand,
Expand All @@ -396,6 +433,7 @@ export function createCli(commands: Record<string, AnyCommand>, opts: CliOptions
setupProxyFromEnv();
const registry = await getRegistry(translator);
await dispatch(registry, argv, localize, sources, (settings) => {
outputFormat = settings.output;
reporter = createOutputReporter({
settings,
localize,
Expand All @@ -409,10 +447,30 @@ export function createCli(commands: Record<string, AnyCommand>, opts: CliOptions
} catch (error) {
for (const warning of warnings.splice(0)) reporter.output.warning(warning);
await flushTelemetry(1000);
handleError(error, reporter);
await handleError(error, reporter);
} finally {
cleanup();
}
},
};
}

/**
* Product entry helper: await the invocation, flush tracked stdout/stderr, then
* exit. Forces the process to leave after a successful run so Bun keep-alive
* sockets cannot linger (~50 s on Windows release binaries).
*
* `run()` itself stays unchanged for in-process harnesses. Install write
* tracking before `run()` so every real write's callback is awaited; an empty
* `write("")` flush is not reliable on Bun when stdout is a pipe.
*
* Success-path flush waits until writes complete (no hard timeout) so slow
* readers such as `| less` are not truncated.
*/
export async function runToExit(cli: Cli, argv?: string[]): Promise<void> {
trackStreamWrites(process.stdout);
trackStreamWrites(process.stderr);
await cli.run(argv);
await flushOutput(null);
process.exit(process.exitCode ?? 0);
}
13 changes: 10 additions & 3 deletions packages/runtime/src/error-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,19 @@ import {
type LocalizedText,
} from "bailian-cli-core";
import type { OutputReporter } from "./output/reporter.ts";
import { flushOutput } from "./output/flush.ts";
import { sanitizeDiagnosticDetails } from "./output/diagnostics.ts";
import { API_KEY_PAGE } from "./urls.ts";

/** The invocation owns rendering; this boundary owns process termination. */
export function handleError(error: unknown, reporter: Pick<OutputReporter, "error">): never {
process.exit(reporter.error(error));
/** Render the error, flush tracked stderr/stdout, then terminate. */
export async function handleError(
error: unknown,
reporter: Pick<OutputReporter, "error">,
): Promise<never> {
const code = reporter.error(error);
// Wait until writes complete; no timeout, so format-based warnings do not apply.
await flushOutput(null);
process.exit(code);
}

export function normalizeError(
Expand Down
9 changes: 8 additions & 1 deletion packages/runtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,17 @@
// each entrypoint (bl / rag / …) injects its own command set via createCli().

// Entrypoint factory + identity
export { createCli, registerInterruptHandler } from "./create-cli.ts";
export { createCli, registerInterruptHandler, runToExit } from "./create-cli.ts";
export { buildCommandSchema, serializeCommandSchema } from "./introspect.ts";
export type { CommandSchema, CommandSchemaNode } from "./introspect.ts";
export type { Cli, CliOptions } from "./create-cli.ts";
export {
DEFAULT_FLUSH_TIMEOUT_MS,
flushOutput,
INTERRUPT_FLUSH_TIMEOUT_MS,
trackStreamWrites,
type FlushOutputOptions,
} from "./output/flush.ts";

// Command Pack product policy
export type {
Expand Down
Loading