diff --git a/docs/agents/telemetry-change.md b/docs/agents/telemetry-change.md index 1d8867b5..5aca305f 100644 --- a/docs/agents/telemetry-change.md +++ b/docs/agents/telemetry-change.md @@ -102,6 +102,25 @@ source-config 只用于百炼 / DashScope API 侧消费,不发送到通用网 - `bizFrom`:全局 `--biz-from` 声明的业务来源(可选);经 `normalizeBizFrom` 归一化(缺省省略,空白/非法 → `"unknown"`),与 `callerName` 独立;映射到 AEM `c6` 专用扁平列 - 失败时的 `errorMessage`、`exitCode`、`httpStatus`、`requestId` - 安全 allowlist 过滤后的 `params` +- 仅 `npmPackage=bailian-cli`:已有合法 `~/.bailian/install.json` 时,命令事件带 `installChannel`,不带安装日,也不发 `first_install`。新用户的 `first_installed_at` 在安装成功写盘后单独发一条事件名 `first_install` 的事件,`ext` 里是 `firstInstalledAt`、`installChannel`、`timestamp`(上报时刻)和 `cliVersion`。每个安装日只入队一次,次数记在 `~/.bailian/first-install-reported.json`;远端入队失败不计入,也不改由后续命令补发。`DO_NOT_TRACK=1` 和配置 `telemetry: false` 都不写文件、不发事件,与普通命令同一个开关。没有安装日的老用户不发 `first_install`。命令不创建、不修补 `install.json`。`kscli` 不读这份文件。bootstrap 事件也不读取它 + +`first_install` 由安装成功路径拉起,不经过命令 middleware: + +```text +install.sh report_first_install +install.ps1 Send-FirstInstallReport +postinstall.js launchFirstInstallReport + └─ bl / dist/bailian.mjs --bailian-first-install-report + 环境变量 BAILIAN_FIRST_INSTALL_REPORT=1,最多等 8 秒 + create-cli.ts run + setupProxyFromEnv()(失败则直连,不让安装失败) + tracker.ts reportFirstInstallNow + event.ts createFirstInstallEvent + sink.ts remoteSink → remoteSendEvent("first_install", ...) + first-install.ts noteFirstInstallReportQueued +``` + +普通 `bl` 命令的 `trackCommandExecution` 只把 `installChannel` 放进命令事件。 `bizFrom` 是调用方(skill/agent/产品)通过全局 `--biz-from` 主动声明的来源标签,用于按来源区分命令调用的 PV/UV。它走 `GLOBAL_FLAGS` → `buildSettings` → `settings.bizFrom` → `trackCommandExecution` 读取,不经命令自有 flag,也不进 `PARAM_ALLOWLIST`(c1)。归一化复用 caller 的 `NAME_PATTERN`(小写、空格/下划线转连字符, bounded charset)防 PII。AEM 侧除随 `ext` 上报外,另映射到专用扁平列 `c6`(标量字符串),无需 JSON 解析维度配置即可直接按 `c6` 筛选/分组:PV=事件计数,UV=distinct `uid`;按命令路径(如 `flow-agent *`)过滤即得某命令组的来源 PV/UV。`bizFrom` 与 `callerType`/`callerName`(宿主归因)是独立维度,不得混用。 @@ -148,17 +167,17 @@ source-config 只用于百炼 / DashScope API 侧消费,不发送到通用网 AEM 映射: -| AEM 字段 | 内容 | -| ---------- | ------------------------------------------------------------------------------------------------- | -| event name | 命令路径 | -| `et` | `EXP` | -| `ext` | 除 `command`、`params` 外的结构化事件字段,含 `commandPrefix`、`callerType` 与失败时的 `exitCode` | -| `c1` | allowlist 参数 | -| `c2` | `success` / `failure` | -| `c3` | HTTP status | -| `c4` | 错误文案,最多 500 字符 | -| `c5` | request ID | -| `c6` | `bizFrom` 业务来源(全局 `--biz-from`,归一化标量;专用扁平列,直接筛选/分组) | +| AEM 字段 | 内容 | +| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| event name | 命令路径 | +| `et` | `EXP` | +| `ext` | 除 `command`、`params` 外的结构化事件字段,含 `commandPrefix`、`callerType`、失败时的 `exitCode`,以及读到的 `installChannel`。安装日不在命令事件里 | +| `c1` | allowlist 参数 | +| `c2` | `success` / `failure` | +| `c3` | HTTP status | +| `c4` | 错误文案,最多 500 字符 | +| `c5` | request ID | +| `c6` | `bizFrom` 业务来源(全局 `--biz-from`,归一化标量;专用扁平列,直接筛选/分组) | 远端发送是 best-effort,不得阻塞命令或改变退出码。正常退出最多等待 1 秒,SIGINT 最多等待 500 ms。 @@ -189,6 +208,7 @@ AEM 映射: - [ ] 调用方字段经 `readCaller` → `TrackingDeps.caller` → 事件;显式 `agent` / `ai_agent` → `agent`,显式 `script` → `script`,其余 → `unknown` - [ ] 成功与失败均覆盖;遥测异常必须静默且不改变业务退出码 - [ ] runtime 本地语义错误应记录 `exitCode`;新增字段默认随 AEM `ext` 上报,无需占用新的 `c1`—`c5` +- [ ] 安装日只在新用户安装成功写盘后,由 `BAILIAN_FIRST_INSTALL_REPORT=1` 且参数 `--bailian-first-install-report` 进入 `reportFirstInstallNow`,事件名 `first_install`。只剩环境变量时普通命令照常执行。拉起最多等 8 秒。这条入口先 `setupProxyFromEnv()`,代理无效则直连且安装继续;并遵守 `DO_NOT_TRACK=1` 与 `telemetry: false`。命令事件只带 `installChannel`。缺失或无法识别时不创建 `install.json`,不把当前时间补进 `firstInstalledAt`。每个安装日只入队一次;入队失败不记次数,也不改由后续命令补发。`kscli` 和 bootstrap 都不发这条事件 - [ ] 检查 `DO_NOT_TRACK=1` 与 `telemetry: false` 两个关闭入口 - [ ] `remoteSink` 从调用到 `remoteSendEvent` 入队之间不得出现 `await`(flush 只排空已入队事件) - [ ] 测试中调用 `remoteSink` 的用例必须使用 `enterIsolatedHome()`,避免写入真实配置目录 diff --git a/packages/cli/postinstall.d.ts b/packages/cli/postinstall.d.ts new file mode 100644 index 00000000..ccc1e36a --- /dev/null +++ b/packages/cli/postinstall.d.ts @@ -0,0 +1,2 @@ +/** Types for the published postinstall script. Not shipped as a runtime file. */ +export function recordNpmInstall(options?: { launchFirstInstallReport?: () => void }): void; diff --git a/packages/cli/postinstall.js b/packages/cli/postinstall.js index 6050035b..60ce9638 100644 --- a/packages/cli/postinstall.js +++ b/packages/cli/postinstall.js @@ -15,12 +15,17 @@ * 5. Write ~/.bailian/wiki-sync-state.json * 6. Write ~/.bailian/skills/skill-lock.json record (same ledger as bl skill) * + * Before any of that, a global npm install records ~/.bailian/install.json once. + * A new user's file is followed by one first_install report. Wiki download failure + * must not remove the file, and a failure to write or report it must not fail npm install. + * * Design constraints: * - Unconditional overwrite: every install fully replaces, no version comparison * - Silent failure: any step failure → console.warn → process.exit(0), never blocks install * - Standalone implementation: does not import bailian-cli-core, avoiding ESM path issues after bundling * - Depends on Node built-in modules + tar-stream (consistent with sync.ts / publisher skills-publish.mjs) */ +import { spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; import { copyFileSync, @@ -30,12 +35,14 @@ import { mkdirSync, readdirSync, readFileSync, + realpathSync, renameSync, rmSync, writeFileSync, } from "node:fs"; import { homedir } from "node:os"; import { dirname, join, relative } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; import { Readable } from "node:stream"; import { pipeline } from "node:stream/promises"; import { createBrotliDecompress } from "node:zlib"; @@ -52,6 +59,19 @@ const LEGACY_ASSET_NAME = "skill.tar.br"; /** Same strict shape check as core registry.ts: only a valid object name may enter the URL */ const OBJECT_FILE_RE = /^sha256-[0-9a-f]{64}\.tar\.br$/; +const INSTALL_RECORD_FILE = "install.json"; +const INSTALL_CHANNEL = "npm"; +/** Same prior-use files the binary installer treats as an existing machine. */ +const EXISTING_INSTALL_MARKERS = [ + "config.json", + "credentials.json", + "telemetry-uid", + "telemetry.jsonl", + "wiki-sync-state.json", + "install-method", + "install-method.bailian-cli", +]; + const INDEX_TIMEOUT_MS = 3000; const DOWNLOAD_TIMEOUT_MS = 30000; const WINDOWS_LEGACY_MAX_PATH = 259; @@ -61,6 +81,102 @@ function getConfigDir() { return join(homedir(), CONFIG_DIR_NAME); } +function isGlobalNpmInstall() { + return process.env.npm_config_global === "true"; +} + +function readOwnPackageVersion() { + try { + const packagePath = join(dirname(fileURLToPath(import.meta.url)), "package.json"); + const parsed = JSON.parse(readFileSync(packagePath, "utf8")); + return typeof parsed.version === "string" ? parsed.version.trim() : ""; + } catch { + return ""; + } +} + +function machineAlreadyUsed(configDir) { + return EXISTING_INSTALL_MARKERS.some((name) => existsSync(join(configDir, name))); +} + +function launchFirstInstallReport() { + try { + const entry = join(dirname(fileURLToPath(import.meta.url)), "dist", "bailian.mjs"); + if (!existsSync(entry)) return; + spawnSync(process.execPath, [entry, "--bailian-first-install-report"], { + env: { ...process.env, BAILIAN_FIRST_INSTALL_REPORT: "1" }, + timeout: 8000, + stdio: "ignore", + windowsHide: true, + }); + } catch { + /* reporting must not fail npm install */ + } +} + +/** + * Write install.json once, before wiki state exists. + * Global installs only. DO_NOT_TRACK=1 writes nothing. + * An existing or unreadable file is left untouched so an upgrade cannot become today's install. + * A newly written first install then launches one first_install report. + */ +export function recordNpmInstall(options = {}) { + const launch = options.launchFirstInstallReport ?? launchFirstInstallReport; + let reportNewInstall = false; + try { + if (process.env.DO_NOT_TRACK === "1") return; + if (!isGlobalNpmInstall()) return; + + const configDir = getConfigDir(); + const recordPath = join(configDir, INSTALL_RECORD_FILE); + if (existsSync(recordPath)) return; + + const observedAt = new Date().toISOString(); + const existing = machineAlreadyUsed(configDir); + const firstVersion = readOwnPackageVersion(); + if (!existing && !firstVersion) return; + + const record = existing + ? { + version: 1, + observed_at: observedAt, + install_channel: INSTALL_CHANNEL, + } + : { + version: 1, + first_installed_at: observedAt, + observed_at: observedAt, + first_version: firstVersion, + install_channel: INSTALL_CHANNEL, + }; + + mkdirSync(configDir, { recursive: true, mode: 0o700 }); + if (existsSync(recordPath)) return; + + const temporaryPath = `${recordPath}.${process.pid}.tmp`; + try { + writeFileSync(temporaryPath, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 }); + if (existsSync(recordPath)) return; + renameSync(temporaryPath, recordPath); + reportNewInstall = !existing; + } finally { + try { + if (existsSync(temporaryPath)) rmSync(temporaryPath, { force: true }); + } catch { + /* a leftover temp file is not an install failure */ + } + } + } catch { + /* permission and disk errors must not fail npm install */ + } + if (!reportNewInstall || process.env.npm_lifecycle_event !== "postinstall") return; + try { + launch(); + } catch { + /* reporting must not fail npm install */ + } +} + function getCatalogDir() { return join(getConfigDir(), SKILL_DIR_NAME); } @@ -285,6 +401,8 @@ function atomicSwap(tmpDir, catalogDir) { } async function main() { + recordNpmInstall(); + // 1. Download skills/index.json and get the wiki entry const index = await fetchJson(`${REGISTRY_BASE_URL}/${INDEX_KEY}`, INDEX_TIMEOUT_MS); const entry = index?.skills?.[WIKI_SKILL_NAME]; @@ -345,14 +463,26 @@ async function main() { process.stdout.write(`bailian-cli: wiki data ready (${entry.publishedAt ?? "latest"})\n`); } -main().catch((err) => { - // Unconditional pass-through: install-time network/permission issues should not block npm install; - // sync.ts will fall back to syncing on the first `bl advisor recommend`. - const msg = err instanceof Error ? err.message : String(err); - process.stderr.write( - `bailian-cli: wiki data pre-download skipped (${msg}); will sync automatically on first use.\n`, - ); - // Force a success exit code so a download failure never fails `npm install`. - // eslint-disable-next-line unicorn/no-process-exit - process.exit(0); -}); +function isDirectExecution() { + const entry = process.argv[1]; + if (!entry) return false; + try { + return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(entry); + } catch { + return pathToFileURL(entry).href === import.meta.url; + } +} + +if (isDirectExecution()) { + main().catch((err) => { + // Unconditional pass-through: install-time network/permission issues should not block npm install; + // sync.ts will fall back to syncing on the first `bl advisor recommend`. + const msg = err instanceof Error ? err.message : String(err); + process.stderr.write( + `bailian-cli: wiki data pre-download skipped (${msg}); will sync automatically on first use.\n`, + ); + // Force a success exit code so a download failure never fails `npm install`. + // eslint-disable-next-line unicorn/no-process-exit + process.exit(0); + }); +} diff --git a/packages/cli/tests/postinstall-install-record.test.ts b/packages/cli/tests/postinstall-install-record.test.ts new file mode 100644 index 00000000..7c924b3a --- /dev/null +++ b/packages/cli/tests/postinstall-install-record.test.ts @@ -0,0 +1,167 @@ +import { spawnSync } from "node:child_process"; +import { + chmodSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { expect, test } from "vite-plus/test"; +import pkg from "../package.json" with { type: "json" }; +import { recordNpmInstall } from "../postinstall.js"; + +const postinstallPath = fileURLToPath(new URL("../postinstall.js", import.meta.url)); + +function withInstallEnv(run: (configDir: string) => void): void { + const savedConfigDir = process.env.BAILIAN_CONFIG_DIR; + const savedGlobal = process.env.npm_config_global; + const savedDoNotTrack = process.env.DO_NOT_TRACK; + const configDir = mkdtempSync(join(tmpdir(), "bl-postinstall-record-")); + process.env.BAILIAN_CONFIG_DIR = configDir; + process.env.npm_config_global = "true"; + delete process.env.DO_NOT_TRACK; + try { + run(configDir); + } finally { + if (savedConfigDir === undefined) delete process.env.BAILIAN_CONFIG_DIR; + else process.env.BAILIAN_CONFIG_DIR = savedConfigDir; + if (savedGlobal === undefined) delete process.env.npm_config_global; + else process.env.npm_config_global = savedGlobal; + if (savedDoNotTrack === undefined) delete process.env.DO_NOT_TRACK; + else process.env.DO_NOT_TRACK = savedDoNotTrack; + chmodSync(configDir, 0o700); + rmSync(configDir, { recursive: true, force: true }); + } +} + +test("global install writes a fresh npm record once", () => { + withInstallEnv((configDir) => { + const savedLifecycle = process.env.npm_lifecycle_event; + process.env.npm_lifecycle_event = "postinstall"; + let launches = 0; + const launchFirstInstallReport = () => { + launches += 1; + }; + try { + recordNpmInstall({ launchFirstInstallReport }); + const recordPath = join(configDir, "install.json"); + const record = JSON.parse(readFileSync(recordPath, "utf8")) as { + install_channel: string; + first_version: string; + first_installed_at: string; + observed_at: string; + }; + expect(record).toMatchObject({ + version: 1, + install_channel: "npm", + first_version: pkg.version, + }); + expect(record).not.toHaveProperty("anchor"); + expect(record.first_installed_at).toBe(record.observed_at); + expect(statSync(recordPath).mode & 0o777).toBe(0o600); + expect(launches).toBe(1); + + record.first_installed_at = "2020-01-02T03:04:05.000Z"; + record.observed_at = "2020-01-02T03:04:05.000Z"; + writeFileSync(recordPath, `${JSON.stringify(record, null, 2)}\n`); + recordNpmInstall({ launchFirstInstallReport }); + const again = JSON.parse(readFileSync(recordPath, "utf8")) as { first_installed_at: string }; + expect(again.first_installed_at).toBe("2020-01-02T03:04:05.000Z"); + expect(launches).toBe(1); + } finally { + if (savedLifecycle === undefined) delete process.env.npm_lifecycle_event; + else process.env.npm_lifecycle_event = savedLifecycle; + } + }); +}); + +test("an existing config directory is not counted as a new install", () => { + withInstallEnv((configDir) => { + const savedLifecycle = process.env.npm_lifecycle_event; + process.env.npm_lifecycle_event = "postinstall"; + let launches = 0; + try { + writeFileSync(join(configDir, "install-method"), "binary\n"); + recordNpmInstall({ + launchFirstInstallReport: () => { + launches += 1; + }, + }); + const record = JSON.parse(readFileSync(join(configDir, "install.json"), "utf8")) as Record< + string, + unknown + >; + expect(record.install_channel).toBe("npm"); + expect(record).not.toHaveProperty("anchor"); + expect(record).not.toHaveProperty("first_installed_at"); + expect(launches).toBe(0); + } finally { + if (savedLifecycle === undefined) delete process.env.npm_lifecycle_event; + else process.env.npm_lifecycle_event = savedLifecycle; + } + }); +}); + +test("non-global install, opt-out, and a broken file do not create or repair a record", () => { + withInstallEnv((configDir) => { + process.env.npm_config_global = "false"; + recordNpmInstall(); + expect(() => statSync(join(configDir, "install.json"))).toThrow(); + + process.env.npm_config_global = "true"; + process.env.DO_NOT_TRACK = "1"; + recordNpmInstall(); + expect(() => statSync(join(configDir, "install.json"))).toThrow(); + + delete process.env.DO_NOT_TRACK; + writeFileSync(join(configDir, "install.json"), "{"); + recordNpmInstall(); + expect(readFileSync(join(configDir, "install.json"), "utf8")).toBe("{"); + }); +}); + +test("an unwritable config directory does not throw", () => { + if (typeof process.getuid === "function" && process.getuid() === 0) return; + withInstallEnv((configDir) => { + chmodSync(configDir, 0o500); + expect(() => recordNpmInstall()).not.toThrow(); + expect(() => statSync(join(configDir, "install.json"))).toThrow(); + }); +}); + +test("wiki download failure still leaves the install record and exits 0", () => { + const root = mkdtempSync(join(tmpdir(), "bl-postinstall-spawn-")); + const configDir = join(root, "config"); + mkdirSync(configDir); + const preloadPath = join(root, "offline.mjs"); + writeFileSync(preloadPath, "globalThis.fetch = async () => { throw new Error('offline'); };\n"); + const env: NodeJS.ProcessEnv = { + ...process.env, + npm_config_global: "true", + BAILIAN_CONFIG_DIR: configDir, + }; + delete env.DO_NOT_TRACK; + + try { + const result = spawnSync(process.execPath, ["--import", preloadPath, postinstallPath], { + env, + encoding: "utf8", + }); + expect(result.status).toBe(0); + expect(result.stderr).toContain("wiki data pre-download skipped"); + const record = JSON.parse(readFileSync(join(configDir, "install.json"), "utf8")) as { + install_channel: string; + first_installed_at: string; + }; + expect(record).not.toHaveProperty("origin"); + expect(record.install_channel).toBe("npm"); + expect(record.first_installed_at).toMatch(/^\d{4}-\d{2}-\d{2}T/); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/packages/core/src/install/index.ts b/packages/core/src/install/index.ts index 9e9d8ea8..afe69965 100644 --- a/packages/core/src/install/index.ts +++ b/packages/core/src/install/index.ts @@ -22,3 +22,9 @@ export { releaseAssetUrl, } from "./cdn.ts"; export { extractZipEntryToFile } from "./unzip-asset.ts"; +export { + INSTALL_RECORD_FILE, + installAttributionFromUnknown, + readInstallAttribution, + type InstallAttribution, +} from "./record.ts"; diff --git a/packages/core/src/install/record.ts b/packages/core/src/install/record.ts new file mode 100644 index 00000000..e59566dc --- /dev/null +++ b/packages/core/src/install/record.ts @@ -0,0 +1,66 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { getConfigDir } from "../config/paths.ts"; + +/** On-disk first-install record. Writers live in the install scripts and postinstall. */ +export const INSTALL_RECORD_FILE = "install.json"; + +const UTC_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/; +const FIRST_VERSION = /^[0-9A-Za-z][0-9A-Za-z._+-]{0,63}$/; + +export interface InstallAttribution { + installChannel: "npm" | "binary"; + /** Present when the file recorded a first install time. Absent for a machine already in use. */ + firstInstalledAt?: string; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function isUtcTimestamp(value: unknown): value is string { + return ( + typeof value === "string" && UTC_TIMESTAMP.test(value) && Number.isFinite(Date.parse(value)) + ); +} + +/** + * Read a valid install record. Missing, unreadable, and unrecognized files + * return undefined. This never creates or rewrites the file. + */ +export function readInstallAttribution(): InstallAttribution | undefined { + let raw: string; + try { + raw = readFileSync(join(getConfigDir(), INSTALL_RECORD_FILE), "utf8"); + } catch { + return undefined; + } + + try { + return installAttributionFromUnknown(JSON.parse(raw)); + } catch { + return undefined; + } +} + +export function installAttributionFromUnknown(value: unknown): InstallAttribution | undefined { + if (!isRecord(value)) return undefined; + if (value.version !== 1) return undefined; + + const channel = value.install_channel; + if (channel !== "npm" && channel !== "binary") return undefined; + + if (!isUtcTimestamp(value.observed_at)) return undefined; + + const attribution: InstallAttribution = { + installChannel: channel, + }; + if (!("first_installed_at" in value)) return attribution; + + if (!isUtcTimestamp(value.first_installed_at)) return undefined; + if (typeof value.first_version !== "string" || !FIRST_VERSION.test(value.first_version)) { + return undefined; + } + attribution.firstInstalledAt = value.first_installed_at; + return attribution; +} diff --git a/packages/core/src/telemetry/event.ts b/packages/core/src/telemetry/event.ts index 37c0260e..b81f6d41 100644 --- a/packages/core/src/telemetry/event.ts +++ b/packages/core/src/telemetry/event.ts @@ -1,4 +1,5 @@ import type { Identity } from "../config/schema.ts"; +import type { InstallAttribution } from "../install/record.ts"; import { formatCommand } from "../output/command.ts"; import type { AuthRequirement } from "../types/command.ts"; import type { CallerAttribution } from "./caller.ts"; @@ -23,6 +24,8 @@ export interface TrackingEvent { callerName?: string; skillName?: string; skillVersion?: string; + /** Channel from install.json. The install day is a separate event. */ + installChannel?: InstallAttribution["installChannel"]; /** Caller-declared call source (--biz-from), normalized; reported as AEM c6. */ bizFrom?: string; } @@ -36,6 +39,8 @@ export function createTrackingEvent(opts: { authMethod?: AuthRequirement; params?: Record; caller: CallerAttribution; + /** Already-read install record. Callers must not create the file to fill this in. */ + install?: InstallAttribution; bizFrom?: string; }): TrackingEvent { const event: TrackingEvent = { @@ -77,9 +82,58 @@ export function createTrackingEvent(opts: { event.params = opts.params; } + if (opts.install) { + event.installChannel = opts.install.installChannel; + } + return event; } +/** Event name for a machine's first install day. Not a command path. */ +export const FIRST_INSTALL_EVENT_NAME = "first_install"; + +export interface FirstInstallEvent { + kind: typeof FIRST_INSTALL_EVENT_NAME; + /** When this report was queued, not the install day. */ + timestamp: string; + firstInstalledAt: string; + installChannel: InstallAttribution["installChannel"]; + cliVersion: string; +} + +export function isFirstInstallEvent( + event: TrackingEvent | FirstInstallEvent, +): event is FirstInstallEvent { + return "kind" in event && event.kind === FIRST_INSTALL_EVENT_NAME; +} + +export function createFirstInstallEvent(opts: { + firstInstalledAt: string; + installChannel: InstallAttribution["installChannel"]; + cliVersion: string; + reportedAt?: Date; +}): FirstInstallEvent { + return { + kind: FIRST_INSTALL_EVENT_NAME, + timestamp: (opts.reportedAt ?? new Date()).toISOString(), + firstInstalledAt: opts.firstInstalledAt, + installChannel: opts.installChannel, + cliVersion: opts.cliVersion, + }; +} + +export function buildFirstInstallAemOptions(event: FirstInstallEvent): Record { + return { + et: "EXP", + ext: { + timestamp: event.timestamp, + firstInstalledAt: event.firstInstalledAt, + installChannel: event.installChannel, + cliVersion: event.cliVersion, + }, + }; +} + const AEM_TEXT_MAX = 500; function aemText(value: unknown): string | undefined { diff --git a/packages/core/src/telemetry/first-install.ts b/packages/core/src/telemetry/first-install.ts new file mode 100644 index 00000000..246ddd8e --- /dev/null +++ b/packages/core/src/telemetry/first-install.ts @@ -0,0 +1,62 @@ +import { readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { getConfigDir } from "../config/paths.ts"; + +/** Separate from install.json so a report attempt cannot rewrite the install day. */ +export const FIRST_INSTALL_REPORT_FILE = "first-install-reported.json"; + +/** One queued report per install day. A later command does not send it again. */ +export const FIRST_INSTALL_REPORT_ATTEMPTS = 1; + +/** + * Installers pass this with BAILIAN_FIRST_INSTALL_REPORT=1. + * The variable alone must not turn a later user command into a silent report. + */ +export const FIRST_INSTALL_REPORT_ARGUMENT = "--bailian-first-install-report"; + +export function isFirstInstallReportLaunch(argv: readonly string[]): boolean { + return ( + process.env.BAILIAN_FIRST_INSTALL_REPORT === "1" && + argv.length === 1 && + argv[0] === FIRST_INSTALL_REPORT_ARGUMENT + ); +} + +interface FirstInstallReport { + attempts: number; + firstInstalledAt: string; +} + +function isReport(value: unknown): value is FirstInstallReport { + if (typeof value !== "object" || value === null || Array.isArray(value)) return false; + const report = value as Record; + return ( + typeof report.firstInstalledAt === "string" && + typeof report.attempts === "number" && + Number.isInteger(report.attempts) && + report.attempts >= 0 + ); +} + +/** How many times this install day was queued. A missing or different record counts as zero. */ +export function readFirstInstallReportAttempts(firstInstalledAt: string): number { + try { + const parsed: unknown = JSON.parse( + readFileSync(join(getConfigDir(), FIRST_INSTALL_REPORT_FILE), "utf8"), + ); + if (!isReport(parsed) || parsed.firstInstalledAt !== firstInstalledAt) return 0; + return parsed.attempts; + } catch { + return 0; + } +} + +/** Record one queued attempt. Failures throw so the caller can skip the increment. */ +export function noteFirstInstallReportQueued(firstInstalledAt: string): void { + const attempts = readFirstInstallReportAttempts(firstInstalledAt) + 1; + writeFileSync( + join(getConfigDir(), FIRST_INSTALL_REPORT_FILE), + `${JSON.stringify({ attempts, firstInstalledAt })}\n`, + { mode: 0o600 }, + ); +} diff --git a/packages/core/src/telemetry/index.ts b/packages/core/src/telemetry/index.ts index e70ea5fb..793d4fb8 100644 --- a/packages/core/src/telemetry/index.ts +++ b/packages/core/src/telemetry/index.ts @@ -3,5 +3,6 @@ export { readCaller } from "./caller.ts"; export type { TrackingEvent } from "./event.ts"; export { createTrackingEvent } from "./event.ts"; export { localSink, remoteSink, flushTelemetry } from "./sink.ts"; -export { trackCommandExecution } from "./tracker.ts"; +export { reportFirstInstallNow, trackCommandExecution } from "./tracker.ts"; +export { FIRST_INSTALL_REPORT_ARGUMENT, isFirstInstallReportLaunch } from "./first-install.ts"; export type { TrackingDeps } from "./tracker.ts"; diff --git a/packages/core/src/telemetry/sink.ts b/packages/core/src/telemetry/sink.ts index de823700..9735627b 100644 --- a/packages/core/src/telemetry/sink.ts +++ b/packages/core/src/telemetry/sink.ts @@ -1,7 +1,14 @@ import { appendFileSync, statSync, unlinkSync } from "fs"; import { join } from "path"; import { getConfigDir, ensureConfigDir } from "../config/paths.ts"; -import { buildRemoteAemOptions, type TrackingEvent } from "./event.ts"; +import { + buildFirstInstallAemOptions, + buildRemoteAemOptions, + FIRST_INSTALL_EVENT_NAME, + isFirstInstallEvent, + type FirstInstallEvent, + type TrackingEvent, +} from "./event.ts"; import { detectEnv } from "./env.ts"; import { ensureUid, loadUid } from "./uid.ts"; import Tracker from "../../lib/remote-telemetry/tracker.cjs"; @@ -117,7 +124,7 @@ export async function flushTelemetry(timeoutMs = 1000): Promise { } } -export async function localSink(event: TrackingEvent): Promise { +export async function localSink(event: TrackingEvent | FirstInstallEvent): Promise { try { await ensureConfigDir(); const path = TELEMETRY_FILE(); @@ -141,12 +148,19 @@ export async function localSink(event: TrackingEvent): Promise { } } -export async function remoteSink(event: TrackingEvent): Promise { +/** Returns whether the event was queued. Callers must not await before this function enqueues. */ +export async function remoteSink(event: TrackingEvent | FirstInstallEvent): Promise { try { initRemote(); - if (!remoteSendEvent) return; - remoteSendEvent(event.command, buildRemoteAemOptions(event)); + if (!remoteSendEvent) return false; + if (isFirstInstallEvent(event)) { + remoteSendEvent(FIRST_INSTALL_EVENT_NAME, buildFirstInstallAemOptions(event)); + } else { + remoteSendEvent(event.command, buildRemoteAemOptions(event)); + } + return true; } catch { // Telemetry must never affect the CLI main flow + return false; } } diff --git a/packages/core/src/telemetry/tracker.ts b/packages/core/src/telemetry/tracker.ts index 91ce35e6..148c0b18 100644 --- a/packages/core/src/telemetry/tracker.ts +++ b/packages/core/src/telemetry/tracker.ts @@ -1,9 +1,17 @@ +import { buildSettings, buildSources } from "../config/loader.ts"; import type { Identity, Settings } from "../config/schema.ts"; import { BailianError } from "../errors/base.ts"; +import { BINARY_PRODUCT_CLIENT_NAME } from "../install/method.ts"; +import { readInstallAttribution, type InstallAttribution } from "../install/record.ts"; import type { AuthRequirement } from "../types/command.ts"; import { normalizeBizFrom, type CallerAttribution } from "./caller.ts"; -import { createTrackingEvent } from "./event.ts"; -import { localSink, remoteSink } from "./sink.ts"; +import { createFirstInstallEvent, createTrackingEvent } from "./event.ts"; +import { + FIRST_INSTALL_REPORT_ATTEMPTS, + noteFirstInstallReportQueued, + readFirstInstallReportAttempts, +} from "./first-install.ts"; +import { flushTelemetry, localSink, remoteSink } from "./sink.ts"; const GLOBAL_FLAG_KEYS = new Set([ "apiKey", @@ -71,6 +79,19 @@ const PARAM_ALLOWLIST = new Set([ "diarization", ]); +/** + * bailian-cli reads an existing install.json. kscli does not. + * A missing or broken file stays unreported, and this never creates one. + */ +function readCommandInstallAttribution(identity: Identity): InstallAttribution | undefined { + if (identity.npmPackage !== BINARY_PRODUCT_CLIENT_NAME) return undefined; + try { + return readInstallAttribution(); + } catch { + return undefined; + } +} + function extractParams(flags: Record): Record { const params: Record = {}; for (const [key, value] of Object.entries(flags)) { @@ -85,6 +106,59 @@ function extractParams(flags: Record): Record return params; } +/** + * Queue the install-day event once, when install has just succeeded. + * A failed queue does not consume the attempt. Nothing here may fail install. + */ +async function reportFirstInstall( + identity: Identity, + install: InstallAttribution | undefined, +): Promise { + if (!install?.firstInstalledAt) return; + const firstInstalledAt = install.firstInstalledAt; + try { + if (readFirstInstallReportAttempts(firstInstalledAt) >= FIRST_INSTALL_REPORT_ATTEMPTS) return; + const report = createFirstInstallEvent({ + firstInstalledAt, + installChannel: install.installChannel, + cliVersion: identity.version, + }); + localSink(report).catch(() => {}); + const queued = await remoteSink(report); + if (queued) noteFirstInstallReportQueued(firstInstalledAt); + } catch { + // Telemetry must never affect the CLI main flow + } +} + +/** + * Same switch as a normal command: `DO_NOT_TRACK=1` or `telemetry: false`. + * A config that cannot be read does not enable a report and must not throw. + */ +function installReportTelemetryEnabled(): boolean { + if (process.env.DO_NOT_TRACK === "1") return false; + try { + return buildSettings(buildSources({})).telemetry; + } catch { + return false; + } +} + +/** + * Called by the installer as soon as a new user's install.json is on disk. + * Not used by ordinary command telemetry. + */ +export async function reportFirstInstallNow(identity: Identity): Promise { + if (!installReportTelemetryEnabled()) return; + if (identity.npmPackage !== BINARY_PRODUCT_CLIENT_NAME) return; + try { + await reportFirstInstall(identity, readCommandInstallAttribution(identity)); + await flushTelemetry(1000); + } catch { + // A report failure must not fail installation. + } +} + /** 遥测只记录命令声明的鉴权域,不接触具体凭证能力。 */ export interface TrackingDeps { identity: Identity; @@ -127,6 +201,7 @@ export async function trackCommandExecution( throw err; } finally { const durationMs = Math.round(performance.now() - start); + const install = readCommandInstallAttribution(deps.identity); const event = createTrackingEvent({ command: commandPath.join(" "), @@ -137,10 +212,11 @@ export async function trackCommandExecution( authMethod: deps.authMethod, params: extractParams(flags), caller: deps.caller, + install, bizFrom: normalizeBizFrom(deps.settings.bizFrom), }); - // Fire-and-forget — never block the CLI exit or mask errors + // The install day is reported when install succeeds, not from this command. localSink(event).catch(() => {}); remoteSink(event).catch(() => {}); } diff --git a/packages/core/tests/install-record.test.ts b/packages/core/tests/install-record.test.ts new file mode 100644 index 00000000..49245bff --- /dev/null +++ b/packages/core/tests/install-record.test.ts @@ -0,0 +1,95 @@ +import { chmodSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vite-plus/test"; +import { installAttributionFromUnknown, readInstallAttribution } from "../src/install/record.ts"; + +const freshRecord = { + version: 1, + first_installed_at: "2020-01-02T03:04:05Z", + observed_at: "2020-01-02T03:04:05Z", + first_version: "1.2.3", + install_channel: "binary", +}; + +function withConfigDir(run: (configDir: string) => void): void { + const saved = process.env.BAILIAN_CONFIG_DIR; + const configDir = mkdtempSync(join(tmpdir(), "bl-install-record-")); + process.env.BAILIAN_CONFIG_DIR = configDir; + try { + run(configDir); + } finally { + if (saved === undefined) delete process.env.BAILIAN_CONFIG_DIR; + else process.env.BAILIAN_CONFIG_DIR = saved; + rmSync(configDir, { recursive: true, force: true }); + } +} + +test("reads a dated install record without treating it as the current time", () => { + expect(installAttributionFromUnknown(freshRecord)).toEqual({ + installChannel: "binary", + firstInstalledAt: "2020-01-02T03:04:05Z", + }); +}); + +test("reads an already-used machine without an install time", () => { + expect( + installAttributionFromUnknown({ + version: 1, + observed_at: "2020-01-02T03:04:05.000Z", + install_channel: "npm", + }), + ).toEqual({ + installChannel: "npm", + }); +}); + +test("rejects a dated record that is missing first_version", () => { + expect( + installAttributionFromUnknown({ + version: 1, + first_installed_at: "2020-01-02T03:04:05Z", + observed_at: "2020-01-02T03:04:05Z", + install_channel: "binary", + }), + ).toBeUndefined(); +}); + +test("rejects unrecognized install records", () => { + expect(installAttributionFromUnknown(null)).toBeUndefined(); + expect(installAttributionFromUnknown({ version: 2 })).toBeUndefined(); + expect( + installAttributionFromUnknown({ ...freshRecord, first_installed_at: "today" }), + ).toBeUndefined(); + expect( + installAttributionFromUnknown({ ...freshRecord, install_channel: "brew" }), + ).toBeUndefined(); +}); + +test("a missing install.json stays missing", () => { + withConfigDir((configDir) => { + expect(readInstallAttribution()).toBeUndefined(); + expect(statSync(configDir).isDirectory()).toBe(true); + expect(() => statSync(join(configDir, "install.json"))).toThrow(); + }); +}); + +test("a broken install.json is not repaired", () => { + withConfigDir((configDir) => { + const recordPath = join(configDir, "install.json"); + writeFileSync(recordPath, "{"); + chmodSync(recordPath, 0o600); + expect(readInstallAttribution()).toBeUndefined(); + expect(readFileSync(recordPath, "utf8")).toBe("{"); + }); +}); + +test("reads the on-disk record from BAILIAN_CONFIG_DIR", () => { + withConfigDir((configDir) => { + writeFileSync(join(configDir, "install.json"), `${JSON.stringify(freshRecord, null, 2)}\n`); + expect(readInstallAttribution()).toEqual({ + installChannel: "binary", + firstInstalledAt: "2020-01-02T03:04:05Z", + }); + }); +}); diff --git a/packages/core/tests/telemetry-tracker.test.ts b/packages/core/tests/telemetry-tracker.test.ts index 6a6c6d15..2c2777f4 100644 --- a/packages/core/tests/telemetry-tracker.test.ts +++ b/packages/core/tests/telemetry-tracker.test.ts @@ -1,22 +1,43 @@ -import { expect, test, vi } from "vite-plus/test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, expect, test, vi } from "vite-plus/test"; import type { Identity, Settings } from "../src/config/schema.ts"; import { BailianError } from "../src/errors/base.ts"; import { ExitCode } from "../src/errors/codes.ts"; import type { CallerAttribution } from "../src/telemetry/caller.ts"; import { + buildFirstInstallAemOptions, buildRemoteAemOptions, createTrackingEvent, + isFirstInstallEvent, + type FirstInstallEvent, type TrackingEvent, } from "../src/telemetry/event.ts"; +import { + FIRST_INSTALL_REPORT_ARGUMENT, + FIRST_INSTALL_REPORT_FILE, + isFirstInstallReportLaunch, +} from "../src/telemetry/first-install.ts"; + +type ReportedEvent = TrackingEvent | FirstInstallEvent; const sinkMocks = vi.hoisted(() => ({ - localSink: vi.fn<(event: TrackingEvent) => Promise>(async () => {}), - remoteSink: vi.fn<(event: TrackingEvent) => Promise>(async () => {}), + localSink: vi.fn<(event: ReportedEvent) => Promise>(async () => {}), + remoteSink: vi.fn<(event: ReportedEvent) => Promise>(async () => false), + flushTelemetry: vi.fn(async () => {}), })); vi.mock("../src/telemetry/sink.ts", () => sinkMocks); -import { trackCommandExecution } from "../src/telemetry/tracker.ts"; +import { reportFirstInstallNow, trackCommandExecution } from "../src/telemetry/tracker.ts"; + +function asCommand(event: ReportedEvent): TrackingEvent { + if (isFirstInstallEvent(event)) { + throw new Error("expected a command event"); + } + return event; +} const identity: Identity = { binName: "bl", @@ -37,6 +58,39 @@ const scriptCaller: CallerAttribution = { callerName: "cursor", }; +const savedConfigDir = process.env.BAILIAN_CONFIG_DIR; +let isolatedConfigDir = ""; + +beforeEach(() => { + isolatedConfigDir = mkdtempSync(join(tmpdir(), "bl-telemetry-home-")); + process.env.BAILIAN_CONFIG_DIR = isolatedConfigDir; +}); + +afterEach(() => { + if (savedConfigDir === undefined) delete process.env.BAILIAN_CONFIG_DIR; + else process.env.BAILIAN_CONFIG_DIR = savedConfigDir; + rmSync(isolatedConfigDir, { recursive: true, force: true }); + sinkMocks.remoteSink.mockReset(); + sinkMocks.remoteSink.mockImplementation(async () => false); +}); + +test("the install report launch requires both the env var and its argument", () => { + const saved = process.env.BAILIAN_FIRST_INSTALL_REPORT; + try { + delete process.env.BAILIAN_FIRST_INSTALL_REPORT; + expect(isFirstInstallReportLaunch([FIRST_INSTALL_REPORT_ARGUMENT])).toBe(false); + expect(isFirstInstallReportLaunch([])).toBe(false); + process.env.BAILIAN_FIRST_INSTALL_REPORT = "1"; + expect(isFirstInstallReportLaunch([])).toBe(false); + expect(isFirstInstallReportLaunch(["skill", "init"])).toBe(false); + expect(isFirstInstallReportLaunch([FIRST_INSTALL_REPORT_ARGUMENT, "--version"])).toBe(false); + expect(isFirstInstallReportLaunch([FIRST_INSTALL_REPORT_ARGUMENT])).toBe(true); + } finally { + if (saved === undefined) delete process.env.BAILIAN_FIRST_INSTALL_REPORT; + else process.env.BAILIAN_FIRST_INSTALL_REPORT = saved; + } +}); + test("derives event version and prefix from identity", () => { const event = createTrackingEvent({ command: "config show", @@ -106,8 +160,8 @@ test.each( expect(sinkMocks.localSink).toHaveBeenCalledOnce(); expect(sinkMocks.remoteSink).toHaveBeenCalledOnce(); - const localEvent = sinkMocks.localSink.mock.calls[0]![0]; - const remoteEvent = sinkMocks.remoteSink.mock.calls[0]![0]; + const localEvent = asCommand(sinkMocks.localSink.mock.calls[0]![0]); + const remoteEvent = asCommand(sinkMocks.remoteSink.mock.calls[0]![0]); expect(localEvent).toMatchObject({ ...entry.expected, command: "config show", @@ -142,7 +196,7 @@ test("ignores obsolete display overrides when deriving the entry", async () => { {}, async () => {}, ); - const event = sinkMocks.localSink.mock.calls[0]![0]; + const event = asCommand(sinkMocks.localSink.mock.calls[0]![0]); expect(event).toMatchObject({ commandPrefix: "bl" }); expect(buildRemoteAemOptions(event)).toMatchObject({ ext: { commandPrefix: "bl" }, @@ -171,7 +225,7 @@ test("records BailianError exitCode in local events and AEM ext", async () => { ).rejects.toBe(error); expect(sinkMocks.localSink).toHaveBeenCalledOnce(); - const event = sinkMocks.localSink.mock.calls[0]![0]; + const event = asCommand(sinkMocks.localSink.mock.calls[0]![0]); expect(event).toMatchObject({ command: "knowledge doc delete", success: false, @@ -214,8 +268,8 @@ test.each([ expect(sinkMocks.localSink).toHaveBeenCalledOnce(); expect(sinkMocks.remoteSink).toHaveBeenCalledOnce(); - const localEvent = sinkMocks.localSink.mock.calls[0]![0]; - const remoteEvent = sinkMocks.remoteSink.mock.calls[0]![0]; + const localEvent = asCommand(sinkMocks.localSink.mock.calls[0]![0]); + const remoteEvent = asCommand(sinkMocks.remoteSink.mock.calls[0]![0]); expect(localEvent.params).toEqual(expectedParams); expect(remoteEvent.params).toEqual(expectedParams); expect(buildRemoteAemOptions(remoteEvent).c1).toEqual(expectedParams); @@ -238,7 +292,7 @@ test("keeps agent attribution on success and in AEM ext", async () => { async () => {}, ); - const event = sinkMocks.localSink.mock.calls[0]![0]; + const event = asCommand(sinkMocks.localSink.mock.calls[0]![0]); expect(event).toMatchObject({ success: true, callerType: "agent", @@ -273,7 +327,7 @@ test("keeps script attribution with callerName and without skill leak", async () async () => {}, ); - const event = sinkMocks.localSink.mock.calls[0]![0]; + const event = asCommand(sinkMocks.localSink.mock.calls[0]![0]); expect(event).toMatchObject({ success: true, callerType: "script", @@ -291,6 +345,237 @@ test("keeps script attribution with callerName and without skill leak", async () expect(remoteExt).not.toHaveProperty("skillVersion"); }); +test("a command keeps the install channel and does not send first_install", async () => { + sinkMocks.localSink.mockClear(); + sinkMocks.remoteSink.mockClear(); + sinkMocks.remoteSink.mockResolvedValue(true); + const installedAt = "2020-01-02T03:04:05.000Z"; + const recordPath = join(isolatedConfigDir, "install.json"); + const recordText = `${JSON.stringify({ + version: 1, + first_installed_at: installedAt, + observed_at: installedAt, + first_version: "2.8.6", + install_channel: "npm", + })}\n`; + writeFileSync(recordPath, recordText); + + await trackCommandExecution( + { + identity, + settings: { telemetry: true } as Settings, + authMethod: "none", + caller: unknownCaller, + }, + ["skill", "init"], + {}, + async () => {}, + ); + + const commandEvent = asCommand(sinkMocks.localSink.mock.calls[0]![0]); + expect(isFirstInstallEvent(commandEvent)).toBe(false); + if (isFirstInstallEvent(commandEvent)) return; + expect(commandEvent.command).toBe("skill init"); + expect(commandEvent.installChannel).toBe("npm"); + expect(commandEvent.timestamp).not.toBe(installedAt); + expect(commandEvent).not.toHaveProperty("firstInstalledAt"); + expect(buildRemoteAemOptions(commandEvent).ext).not.toHaveProperty("firstInstalledAt"); + expect(readFileSync(recordPath, "utf8")).toBe(recordText); + expect(sinkMocks.localSink).toHaveBeenCalledOnce(); + expect(existsSync(join(isolatedConfigDir, FIRST_INSTALL_REPORT_FILE))).toBe(false); +}); + +test("reports first_install once when install has just succeeded", async () => { + sinkMocks.localSink.mockClear(); + sinkMocks.remoteSink.mockClear(); + sinkMocks.remoteSink.mockResolvedValue(true); + const installedAt = "2020-01-02T03:04:05.000Z"; + writeFileSync( + join(isolatedConfigDir, "install.json"), + `${JSON.stringify({ + version: 1, + first_installed_at: installedAt, + observed_at: installedAt, + first_version: "2.8.6", + install_channel: "binary", + })}\n`, + ); + + await reportFirstInstallNow(identity); + await reportFirstInstallNow(identity); + + const installReports = sinkMocks.localSink.mock.calls + .map(([event]) => event) + .filter(isFirstInstallEvent); + expect(installReports).toHaveLength(1); + const installEvent = installReports[0]!; + expect(installEvent.firstInstalledAt).toBe(installedAt); + expect(installEvent.installChannel).toBe("binary"); + expect(installEvent.cliVersion).toBe(identity.version); + expect(installEvent.timestamp).not.toBe(installedAt); + expect(buildFirstInstallAemOptions(installEvent)).toEqual({ + et: "EXP", + ext: { + timestamp: installEvent.timestamp, + firstInstalledAt: installedAt, + installChannel: "binary", + cliVersion: identity.version, + }, + }); + expect( + JSON.parse(readFileSync(join(isolatedConfigDir, FIRST_INSTALL_REPORT_FILE), "utf8")), + ).toEqual({ + attempts: 1, + firstInstalledAt: installedAt, + }); +}); + +test("omits install fields when the file is missing or the product is not bailian-cli", async () => { + sinkMocks.localSink.mockClear(); + sinkMocks.remoteSink.mockClear(); + const saved = process.env.BAILIAN_CONFIG_DIR; + const configDir = mkdtempSync(join(tmpdir(), "bl-install-telemetry-empty-")); + mkdirSync(configDir, { recursive: true }); + process.env.BAILIAN_CONFIG_DIR = configDir; + + try { + await trackCommandExecution( + { + identity, + settings: { telemetry: true } as Settings, + authMethod: "none", + caller: unknownCaller, + }, + ["config", "show"], + {}, + async () => {}, + ); + const missing = asCommand(sinkMocks.localSink.mock.calls[0]![0]); + expect(isFirstInstallEvent(missing)).toBe(false); + if (!isFirstInstallEvent(missing)) { + expect(missing.installChannel).toBeUndefined(); + expect(missing).not.toHaveProperty("firstInstalledAt"); + } + expect(sinkMocks.localSink).toHaveBeenCalledOnce(); + + writeFileSync( + join(configDir, "install.json"), + `${JSON.stringify({ + version: 1, + observed_at: "2020-01-02T03:04:05Z", + install_channel: "binary", + })}\n`, + ); + sinkMocks.localSink.mockClear(); + await trackCommandExecution( + { + identity, + settings: { telemetry: true } as Settings, + authMethod: "none", + caller: unknownCaller, + }, + ["config", "show"], + {}, + async () => {}, + ); + const existing = asCommand(sinkMocks.localSink.mock.calls[0]![0]); + expect(isFirstInstallEvent(existing)).toBe(false); + if (!isFirstInstallEvent(existing)) { + expect(existing.installChannel).toBe("binary"); + expect(existing).not.toHaveProperty("firstInstalledAt"); + } + expect(sinkMocks.localSink).toHaveBeenCalledOnce(); + + sinkMocks.localSink.mockClear(); + await trackCommandExecution( + { + identity: { + ...identity, + npmPackage: "knowledge-studio-cli", + clientName: "knowledge-studio-cli", + }, + settings: { telemetry: true } as Settings, + authMethod: "none", + caller: unknownCaller, + }, + ["config", "show"], + {}, + async () => {}, + ); + const kscliEvent = asCommand(sinkMocks.localSink.mock.calls[0]![0]); + expect(isFirstInstallEvent(kscliEvent)).toBe(false); + if (!isFirstInstallEvent(kscliEvent)) { + expect(kscliEvent.installChannel).toBeUndefined(); + expect(kscliEvent).not.toHaveProperty("firstInstalledAt"); + } + expect(sinkMocks.localSink).toHaveBeenCalledOnce(); + } finally { + if (saved === undefined) delete process.env.BAILIAN_CONFIG_DIR; + else process.env.BAILIAN_CONFIG_DIR = saved; + rmSync(configDir, { recursive: true, force: true }); + } +}); + +test("a failed install report does not consume the one attempt", async () => { + sinkMocks.localSink.mockClear(); + sinkMocks.remoteSink.mockClear(); + const installedAt = "2020-01-02T03:04:05Z"; + writeFileSync( + join(isolatedConfigDir, "install.json"), + `${JSON.stringify({ + version: 1, + first_installed_at: installedAt, + observed_at: installedAt, + first_version: "2.8.6", + install_channel: "npm", + })}\n`, + ); + + await reportFirstInstallNow(identity); + expect(existsSync(join(isolatedConfigDir, FIRST_INSTALL_REPORT_FILE))).toBe(false); + + sinkMocks.remoteSink.mockResolvedValue(true); + await reportFirstInstallNow(identity); + + const installReports = sinkMocks.localSink.mock.calls + .map(([event]) => event) + .filter(isFirstInstallEvent); + expect(installReports).toHaveLength(2); + expect( + JSON.parse(readFileSync(join(isolatedConfigDir, FIRST_INSTALL_REPORT_FILE), "utf8")), + ).toEqual({ + attempts: 1, + firstInstalledAt: installedAt, + }); +}); + +test("a first-install report respects telemetry: false", async () => { + sinkMocks.localSink.mockClear(); + sinkMocks.remoteSink.mockClear(); + sinkMocks.remoteSink.mockResolvedValue(true); + const installedAt = "2020-01-02T03:04:05.000Z"; + writeFileSync( + join(isolatedConfigDir, "config.json"), + `${JSON.stringify({ telemetry: false })}\n`, + ); + writeFileSync( + join(isolatedConfigDir, "install.json"), + `${JSON.stringify({ + version: 1, + first_installed_at: installedAt, + observed_at: installedAt, + first_version: "2.8.6", + install_channel: "binary", + })}\n`, + ); + + await reportFirstInstallNow(identity); + + expect(sinkMocks.localSink).not.toHaveBeenCalled(); + expect(sinkMocks.remoteSink).not.toHaveBeenCalled(); + expect(existsSync(join(isolatedConfigDir, FIRST_INSTALL_REPORT_FILE))).toBe(false); +}); + test("does not call sinks when telemetry is disabled", async () => { sinkMocks.localSink.mockClear(); sinkMocks.remoteSink.mockClear(); @@ -311,6 +596,7 @@ test("does not call sinks when telemetry is disabled", async () => { expect(next).toHaveBeenCalledOnce(); expect(sinkMocks.localSink).not.toHaveBeenCalled(); expect(sinkMocks.remoteSink).not.toHaveBeenCalled(); + expect(existsSync(join(isolatedConfigDir, FIRST_INSTALL_REPORT_FILE))).toBe(false); }); test("reports bizFrom as a structured field and dedicated AEM c6 column", () => { @@ -362,7 +648,7 @@ test.each([ {}, async () => {}, ); - const event = sinkMocks.remoteSink.mock.calls[0]![0]; + const event = asCommand(sinkMocks.remoteSink.mock.calls[0]![0]); expect(event.bizFrom).toBe(expected); expect(buildRemoteAemOptions(event).c6).toBe(expected); }); @@ -381,7 +667,7 @@ test("absent settings.bizFrom omits the field and c6", async () => { {}, async () => {}, ); - const event = sinkMocks.remoteSink.mock.calls[0]![0]; + const event = asCommand(sinkMocks.remoteSink.mock.calls[0]![0]); expect(event.bizFrom).toBeUndefined(); expect(buildRemoteAemOptions(event)).not.toHaveProperty("c6"); }); diff --git a/packages/runtime/src/create-cli.ts b/packages/runtime/src/create-cli.ts index 99ee94ca..4969e9ac 100644 --- a/packages/runtime/src/create-cli.ts +++ b/packages/runtime/src/create-cli.ts @@ -38,6 +38,8 @@ import { makeConfigStore, makeAuthStore, flushTelemetry, + reportFirstInstallNow, + isFirstInstallReportLaunch, Client, } from "bailian-cli-core"; import { setupProxyFromEnv } from "./proxy.ts"; @@ -357,6 +359,17 @@ export function createCli(commands: Record, opts: CliOptions return { async run(argv: string[] = process.argv.slice(2)) { + // Installers launch `bl --bailian-first-install-report` with the env var + // after a new user's install.json is written. Either one alone is a normal run. + if (isFirstInstallReportLaunch(argv)) { + try { + setupProxyFromEnv(); + } catch { + // An invalid proxy must not fail installation. The report then uses a direct connection. + } + await reportFirstInstallNow(identity); + return; + } const flags = presentationFlags(argv); let translator = createTranslator(DEFAULT_LANGUAGE); const localize = (text: LocalizedText) => translator.localize(text); diff --git a/packages/runtime/tests/proxy.test.ts b/packages/runtime/tests/proxy.test.ts index 3615e507..8e10aa00 100644 --- a/packages/runtime/tests/proxy.test.ts +++ b/packages/runtime/tests/proxy.test.ts @@ -1,4 +1,10 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { expect, test } from "vite-plus/test"; +import { FIRST_INSTALL_REPORT_ARGUMENT } from "bailian-cli-core"; +import { EnvHttpProxyAgent, getGlobalDispatcher, setGlobalDispatcher } from "undici"; +import { createCli } from "../src/create-cli.ts"; import { readProxyEnv } from "../src/proxy.ts"; test("readProxyEnv: 未设置任何代理变量时全部为 undefined", () => { @@ -51,6 +57,56 @@ test("readProxyEnv: 小写变量兜底(macOS/Linux 习惯)", () => { }); }); +test("first-install launch installs the proxy and ignores an invalid proxy", async () => { + const previousDispatcher = getGlobalDispatcher(); + const configDir = mkdtempSync(join(tmpdir(), "bl-first-install-proxy-")); + const savedConfigDir = process.env.BAILIAN_CONFIG_DIR; + const savedHttpsProxy = process.env.HTTPS_PROXY; + const savedHttpProxy = process.env.HTTP_PROXY; + const savedHttpsProxyLower = process.env.https_proxy; + const savedHttpProxyLower = process.env.http_proxy; + const savedReport = process.env.BAILIAN_FIRST_INSTALL_REPORT; + const launch = () => + createCli( + {}, + { + binName: "bl", + version: "0.0.0-test", + clientName: "bailian-cli", + npmPackage: "bailian-cli", + }, + ).run([FIRST_INSTALL_REPORT_ARGUMENT]); + try { + process.env.BAILIAN_CONFIG_DIR = configDir; + process.env.BAILIAN_FIRST_INSTALL_REPORT = "1"; + delete process.env.HTTP_PROXY; + delete process.env.http_proxy; + delete process.env.https_proxy; + process.env.HTTPS_PROXY = "http://127.0.0.1:9"; + + await launch(); + expect(getGlobalDispatcher()).toBeInstanceOf(EnvHttpProxyAgent); + + process.env.HTTPS_PROXY = "::::not-a-url"; + await expect(launch()).resolves.toBeUndefined(); + } finally { + setGlobalDispatcher(previousDispatcher); + if (savedConfigDir === undefined) delete process.env.BAILIAN_CONFIG_DIR; + else process.env.BAILIAN_CONFIG_DIR = savedConfigDir; + if (savedHttpsProxy === undefined) delete process.env.HTTPS_PROXY; + else process.env.HTTPS_PROXY = savedHttpsProxy; + if (savedHttpProxy === undefined) delete process.env.HTTP_PROXY; + else process.env.HTTP_PROXY = savedHttpProxy; + if (savedHttpsProxyLower === undefined) delete process.env.https_proxy; + else process.env.https_proxy = savedHttpsProxyLower; + if (savedHttpProxyLower === undefined) delete process.env.http_proxy; + else process.env.http_proxy = savedHttpProxyLower; + if (savedReport === undefined) delete process.env.BAILIAN_FIRST_INSTALL_REPORT; + else process.env.BAILIAN_FIRST_INSTALL_REPORT = savedReport; + rmSync(configDir, { recursive: true, force: true }); + } +}); + test("readProxyEnv: 大写优先于小写", () => { const result = readProxyEnv({ HTTPS_PROXY: "http://upper.example.com:8080",