From 046f2f569a45bd539afceafaca6538791fdc1797 Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Tue, 24 Nov 2026 17:27:22 +0800 Subject: [PATCH 1/6] feat: route AEM telemetry by domestic/intl site --- docs/agents/telemetry-change.md | 80 +++++--- .../src/commands/auth/login-api-key.ts | 26 +-- packages/core/src/client/client.ts | 20 ++ packages/core/src/config/index.ts | 12 ++ packages/core/src/config/model-endpoints.ts | 104 +++++++++++ packages/core/src/telemetry/event.ts | 12 ++ packages/core/src/telemetry/index.ts | 11 +- packages/core/src/telemetry/sink.ts | 68 ++++--- packages/core/src/telemetry/site.ts | 94 ++++++++++ packages/core/src/telemetry/tracker.ts | 17 ++ .../tests/client-last-resolved-origin.test.ts | 83 +++++++++ packages/core/tests/telemetry-sink.test.ts | 40 +++- packages/core/tests/telemetry-site.test.ts | 175 ++++++++++++++++++ packages/core/tests/telemetry-tracker.test.ts | 58 +++++- packages/runtime/src/middleware.ts | 8 + .../runtime/tests/telemetry-stage.test.ts | 52 +++++- 16 files changed, 781 insertions(+), 79 deletions(-) create mode 100644 packages/core/src/config/model-endpoints.ts create mode 100644 packages/core/src/telemetry/site.ts create mode 100644 packages/core/tests/client-last-resolved-origin.test.ts create mode 100644 packages/core/tests/telemetry-site.test.ts diff --git a/docs/agents/telemetry-change.md b/docs/agents/telemetry-change.md index 5aca305f9..ef8f7fb93 100644 --- a/docs/agents/telemetry-change.md +++ b/docs/agents/telemetry-change.md @@ -14,8 +14,8 @@ ```text 命令进入 run ├─ telemetryStage - │ ├─ ~/.bailian/telemetry.jsonl - │ └─ AEM(pid=bailian-cli-node, event name=命令路径) + │ ├─ ~/.bailian/telemetry.jsonl(含 site / siteReason) + │ └─ AEM(按 site 分流 pid + endpoint;event name=命令路径) │ └─ confirmationStage └─ versionCheckStage → authStage @@ -27,12 +27,12 @@ ### 1. 三套鉴权与埋点标识 -| 命令声明 | 凭证 / 请求域 | 主要请求出口 | 后端埋点标识 | 前端埋点标识(AEM) | -| ----------------- | --------------------------------------------------- | ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------ | -| `auth: "apiKey"` | API Key;DashScope / OpenAI-compatible 模型域 | `Client.request/requestJson`、`McpClient`、Managed Agent / Advisor instrumented fetch、上传策略 | 有:`User-Agent`、`x-dashscope-source-config`、`X-Dashscope-Service: bailian-cli` | 有:`pid=bailian-cli-node`、`authMethod=apiKey` | -| `auth: "console"` | Console access token;Bailian Console Gateway | `callConsoleGateway()` → `/cli/api.json` | 有:Console Gateway 后端直接标识 | 有:`pid=bailian-cli-node`、`authMethod=console` | -| `auth: "openapi"` | AccessKey ID/Secret,可选 STS token;阿里云 OpenAPI | `Client.openApiJson()` | 有:`x-dashscope-source-config`、`X-Dashscope-Service: bailian-cli` | 有:`pid=bailian-cli-node`、`authMethod=openapi` | -| `auth: "none"` | 无凭证域 | 本地逻辑或命令自行管理的登录/配置流程 | 无 | 有:`pid=bailian-cli-node`、`authMethod=none` | +| 命令声明 | 凭证 / 请求域 | 主要请求出口 | 后端埋点标识 | 前端埋点标识(AEM) | +| ----------------- | --------------------------------------------------- | ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| `auth: "apiKey"` | API Key;DashScope / OpenAI-compatible 模型域 | `Client.request/requestJson`、`McpClient`、Managed Agent / Advisor instrumented fetch、上传策略 | 有:`User-Agent`、`x-dashscope-source-config`、`X-Dashscope-Service: bailian-cli` | 有:按模型 host 分流 `bailian-cli-node` / `bailian-cli-node-intl`、`authMethod=apiKey` | +| `auth: "console"` | Console access token;Bailian Console Gateway | `callConsoleGateway()` → `/cli/api.json` | 有:Console Gateway 后端直接标识 | 有:按 `consoleSite` 分流 pid、`authMethod=console` | +| `auth: "openapi"` | AccessKey ID/Secret,可选 STS token;阿里云 OpenAPI | `Client.openApiJson()` | 有:`x-dashscope-source-config`、`X-Dashscope-Service: bailian-cli` | 有:按模型域 baseUrl 分流 pid、`authMethod=openapi`(不用 ACS host) | +| `auth: "none"` | 无凭证域 | 本地逻辑或命令自行管理的登录/配置流程 | 无 | 有:`consoleSite` ∨ 模型 host OR 分流、`authMethod=none` | `authMethod` 记录的是命令声明的鉴权域,不是凭证来源。它不会区分 API Key 来自 flag、env 还是 config。 鉴权域是命令的准入门槛和主请求域,不保证命令内部只有一种网络出口;例如部分 `apiKey` 命令也可能读取匿名 Console 公共目录,Managed Agent 还可能访问其他 provider。 @@ -140,18 +140,42 @@ postinstall.js launchFirstInstallReport 事件写入两处: -1. 本地 `~/.bailian/telemetry.jsonl`:权限 `0600`,超过 5 MB 后重建;每行附带 `uid`(只读已有文件,不创建) -2. AEM:`pid=bailian-cli-node`,源码运行自动使用 `env=dev`,npm 安装或编译二进制使用 `env=prod` +1. 本地 `~/.bailian/telemetry.jsonl`:权限 `0600`,超过 5 MB 后重建;每行附带 `uid`(只读已有文件,不创建)以及 `site` / 可选 `siteReason` +2. AEM:按 `site` 分流(见下节),源码运行自动使用 `env=dev`,npm 安装或编译二进制使用 `env=prod` + +#### 国内 / 国际 AEM 分流(best-effort) + +命令事件按声明口径分流到国内或新加坡采集集群;**不是**「国际相关数据绝不出境」的硬保证。后端渠道头(`x-dashscope-source-config` / `User-Agent`)**不**随本分流改动。 + +| 站点 | AEM pid | 采集端点 | +| ------------- | ----------------------- | ------------------------------- | +| domestic | `bailian-cli-node` | `https://gm.mmstat.com/aes.1.1` | +| international | `bailian-cli-node-intl` | `https://sg.mmstat.com/aes.1.1` | + +判定(D4=B:console=账号站,模型=host/region): + +| `auth` | 信号 | 国际条件 | 缺省 | +| -------------------- | ------------------------------------------------------- | ---------------------------------------- | ---------------------------------------------------------- | +| `console` | `settings.consoleSite`(不看 `consoleRegion`) | `international` | domestic | +| `apiKey` / `openapi` | `Client.lastResolvedOrigin` 优先,否则 `client.baseUrl` | 已知国际 host/region(含 `cn-hongkong`) | domestic;未知 host → domestic + `siteReason=unknown-host` | +| `none` | consoleSite **或** 模型 host(OR) | 任一侧国际 | domestic | + +- 模型 host 分类清单上收在 `packages/core/src/config/model-endpoints.ts`(与 API Key 登录候选共用);`site.ts` 只调用 helper,禁止再写第四份。 +- `lastResolvedOrigin` 仅在 `Client.url()` / upload 的 `defaultBaseUrl` 回调路径记录;主流量仍靠 `baseUrl`。runtime **禁止**泛化读取各命令 `flags.region`。 +- openapi **禁止**用 ACS `opts.host` 分类。 +- `remoteSink` 按 site 使用 keyed `Map` 持有 Tracker;同进程可同时存在国内与国际实例。`uid` / tracker `device_id` **跨站同值**。 +- vendored tracker 仅保留本仓对 `send` 的本地改造(登记于此);国际 path 与国内同为 `/aes.1.1`,**不加** `endpointPath` patch。升级 SDK 时必须保留 `send` 改造。 +- 已知残留:未知/反代 host、残缺配置、登录写盘前首条 `none`、managed-agent 外部拼 host、旧版 CLI、账号站与模型地域混维拆站、`first_install` 固定报国内站(安装阶段没有 auth / Client 上下文)。 编译二进制的 `env=prod` 由 `BAILIAN_COMPILED=1` 决定,并且必须先于 `NODE_ENV`。`bun build --compile`(当前 pin 1.3.14)会把点访问 `process.env.NODE_ENV` 内联成构建机的值,未设置时是 `"development"`;`tools/release/lib/binary-compile.mjs` 同时 `--define process.env.NODE_ENV="production"`。这两处读取必须写成 `process.env.*`,包进别的变量后 `--define` 匹配不到。 旁路状态:`~/.bailian/telemetry-uid`(遵循 `BAILIAN_CONFIG_DIR`)由 `ensureUid` 在首次远端上报时生成,不是事件落盘目标。 -底层 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` 无关。 +底层 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` 无关。国内/国际两站共用同一 `uid` / `device_id`。 `ensureUid` 无锁:稳态只读;缺失或损坏时同目录 temp 写满后 `rename` 发布(内容原子替换;并发首次创建时后写覆盖先写,磁盘最终为一个 UUID)。失败则省略 `uid`,不阻塞业务退出。 -从 2.8.2 起,每条命令事件通过 `commandPrefix` 显式记录调用入口,三种入口仍共用 `pid=bailian-cli-node`: +从 2.8.2 起,每条命令事件通过 `commandPrefix` 显式记录调用入口;pid 按上表 `site` 分流,三种入口仍靠 `commandPrefix` 区分: | 调用入口 | `commandPrefix` | | ----------- | --------------- | @@ -167,17 +191,19 @@ postinstall.js launchFirstInstallReport AEM 映射: -| 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`,归一化标量;专用扁平列,直接筛选/分组) | +| AEM 字段 | 内容 | +| ---------- | ---- | +| event name | 命令路径 | +| `et` | `EXP` | +| `ext` | 除 `command`、`params` 外的结构化事件字段,含 `commandPrefix`、`callerType`、`site`、可选 `siteReason`、失败时的 `exitCode`,以及读到的 `installChannel`。安装日不在命令事件里 | +| `c1` | allowlist 参数 | +| `c2` | `success` / `failure` | +| `c3` | HTTP status | +| `c4` | 错误文案,最多 500 字符 | +| `c5` | request ID | +| `c6` | `bizFrom` 业务来源(全局 `--biz-from`,归一化标量;专用扁平列,直接筛选/分组) | + +`siteReason` 为粗粒度枚举(`positive-domestic` / `positive-international` / `default-fallback` / `unknown-host`),**禁止**带原始 host。漏判量化用国内站 `siteReason` 兜底类占比;不要用「国内 pid 出现 `site=international`」做告警(国际事件不会进国内 pid)。 远端发送是 best-effort,不得阻塞命令或改变退出码。正常退出最多等待 1 秒,SIGINT 最多等待 500 ms。 @@ -220,9 +246,9 @@ AEM 映射: ```sh rg -n "trackingHeaders|x-dashscope-source-config|User-Agent" packages --glob '*.ts' -rg -n "trackCommandExecution|PARAM_ALLOWLIST|buildRemoteAemOptions|readCaller" packages/core packages/runtime --glob '*.ts' +rg -n "trackCommandExecution|PARAM_ALLOWLIST|buildRemoteAemOptions|readCaller|resolveTelemetrySite|classifyModelHost" packages/core packages/runtime --glob '*.ts' vp check -vp test packages/core/tests/telemetry-uid.test.ts packages/core/tests/telemetry-sink.test.ts packages/core/tests/telemetry-tracker.test.ts packages/core/tests/telemetry-send.test.ts packages/runtime/tests/telemetry-stage.test.ts packages/commands/tests/e2e/auth.e2e.test.ts +vp test packages/core/tests/telemetry-uid.test.ts packages/core/tests/telemetry-sink.test.ts packages/core/tests/telemetry-tracker.test.ts packages/core/tests/telemetry-send.test.ts packages/core/tests/telemetry-site.test.ts packages/core/tests/client-last-resolved-origin.test.ts packages/runtime/tests/telemetry-stage.test.ts packages/commands/tests/e2e/auth.e2e.test.ts ``` ## 常见漏点 @@ -235,3 +261,7 @@ vp test packages/core/tests/telemetry-uid.test.ts packages/core/tests/telemetry- - ✗ 只改 `bl` 入口,导致 `kscli` 的产品名或版本标签错误 - ✗ 把帮助、版本或参数校验失败算进“全部命令”;这些路径当前没有进入 telemetry middleware - ✗ 把 `NODE_ENV` 判断放在 `BAILIAN_COMPILED` 前面。Bun 编译会把 `process.env.NODE_ENV` 折成 `"development"`,二进制流量全部进 `env=dev`,生产看板为空 +- ✗ 在 runtime 里泛化读取 `flags.region` 做站点判定;必须用 `baseUrl` / `lastResolvedOrigin` / `consoleSite` +- ✗ 用 openapi ACS host 或「非 cn- 前缀」推断国际站(`cn-hongkong` 是国际) +- ✗ 把 AEM 分流叙事写成「国际数据绝不出境」硬保证;实际是 best-effort 声明口径 +- ✗ 升级 vendored AEM tracker 时丢掉本仓 `send` 改造 diff --git a/packages/commands/src/commands/auth/login-api-key.ts b/packages/commands/src/commands/auth/login-api-key.ts index 81f9b2e4b..598f9fcc8 100644 --- a/packages/commands/src/commands/auth/login-api-key.ts +++ b/packages/commands/src/commands/auth/login-api-key.ts @@ -1,7 +1,9 @@ import { BailianError, getApiKeyLoginKind, + KNOWN_MODEL_BASE_URLS, normalizeModelBaseUrl, + ORDINARY_WORKSPACE_REGIONS, requestJson, type ApiKeyLoginKind, type AuthPersistPatch, @@ -51,28 +53,6 @@ export interface ApiKeyValidationResult { kind: ApiKeyEndpointKind; } -const ORDINARY_WORKSPACE_REGIONS = [ - "cn-beijing", - "ap-southeast-1", - "cn-hongkong", - "ap-northeast-1", - "eu-central-1", - "us-east-1", -] as const; - -const KNOWN_BASE_URLS: Readonly> = { - ordinary: [ - "https://dashscope.aliyuncs.com", - "https://dashscope-intl.aliyuncs.com", - "https://dashscope-us.aliyuncs.com", - "https://cn-hongkong.dashscope.aliyuncs.com", - ], - "token-plan": [ - "https://token-plan.cn-beijing.maas.aliyuncs.com", - "https://token-plan.ap-southeast-1.maas.aliyuncs.com", - ], -}; - function usesCompatibleModelsApi(baseUrl: string, kind: ApiKeyEndpointKind): boolean { const hostname = new URL(normalizeModelBaseUrl(baseUrl)).hostname; return kind === "token-plan" || hostname.endsWith(".maas.aliyuncs.com"); @@ -155,7 +135,7 @@ export function apiKeyValidationCandidates( } for (const kind of kinds) { - for (const baseUrl of KNOWN_BASE_URLS[kind]) { + for (const baseUrl of KNOWN_MODEL_BASE_URLS[kind]) { addCandidate(candidates, seenUrls, baseUrl, kind); } } diff --git a/packages/core/src/client/client.ts b/packages/core/src/client/client.ts index 8e4ca1538..b0c44bfe7 100644 --- a/packages/core/src/client/client.ts +++ b/packages/core/src/client/client.ts @@ -77,6 +77,8 @@ export interface OpenApiResponse { */ export class Client { private consoleSession: ConsoleSession; + /** Last origin from url()/upload defaultBaseUrl resolution (telemetry only). */ + private recordedOrigin: string | undefined; constructor(private readonly deps: ClientDeps) { this.consoleSession = new ConsoleSession(deps); @@ -108,6 +110,23 @@ export class Client { return this.deps.apiCred?.baseUrl ?? this.deps.baseUrl; } + /** + * Origin last selected by {@link url} / upload defaultBaseUrl callbacks. + * Used by telemetry site routing; undefined when no valid origin was recorded. + */ + get lastResolvedOrigin(): string | undefined { + return this.recordedOrigin; + } + + private rememberResolvedOrigin(baseUrl: string): void { + try { + const origin = new URL(baseUrl).origin; + if (origin && origin !== "null") this.recordedOrigin = origin; + } catch { + // Invalid or empty callback origins (e.g. managed-agent) are ignored. + } + } + /** * Export the model-domain credential for delegation to an embedded SDK that * owns its own transport (e.g. @openagentpack/sdk). Deliberate escape hatch: @@ -138,6 +157,7 @@ export class Client { */ url(path: string, defaultBaseUrl?: () => string): string { const baseUrl = this.deps.baseUrlIsDefault && defaultBaseUrl ? defaultBaseUrl() : this.baseUrl; + this.rememberResolvedOrigin(baseUrl); return baseUrl + path; } diff --git a/packages/core/src/config/index.ts b/packages/core/src/config/index.ts index 3b90bbcda..a3b12ef30 100644 --- a/packages/core/src/config/index.ts +++ b/packages/core/src/config/index.ts @@ -36,4 +36,16 @@ export { type ApiKeyLoginKind, } from "./profile-presets.ts"; export { normalizeModelBaseUrl } from "./model-base-url.ts"; +export { + ORDINARY_WORKSPACE_REGIONS, + DOMESTIC_WORKSPACE_REGIONS, + INTERNATIONAL_WORKSPACE_REGIONS, + KNOWN_MODEL_BASE_URLS, + classifyModelHost, + hostnameOf, + type OrdinaryWorkspaceRegion, + type DomesticWorkspaceRegion, + type ApiKeyEndpointKind as ModelEndpointKind, + type ModelHostClass, +} from "./model-endpoints.ts"; export { validateTimeout } from "./validation.ts"; diff --git a/packages/core/src/config/model-endpoints.ts b/packages/core/src/config/model-endpoints.ts new file mode 100644 index 000000000..e10610c1f --- /dev/null +++ b/packages/core/src/config/model-endpoints.ts @@ -0,0 +1,104 @@ +/** + * Official model-domain hosts and workspace regions. + * Shared by API-key login candidate generation and telemetry site classification. + */ + +export const ORDINARY_WORKSPACE_REGIONS = [ + "cn-beijing", + "ap-southeast-1", + "cn-hongkong", + "ap-northeast-1", + "eu-central-1", + "us-east-1", +] as const; + +export type OrdinaryWorkspaceRegion = (typeof ORDINARY_WORKSPACE_REGIONS)[number]; + +/** Mainland China regions treated as domestic for telemetry and routing. */ +export const DOMESTIC_WORKSPACE_REGIONS = ["cn-beijing"] as const; + +export type DomesticWorkspaceRegion = (typeof DOMESTIC_WORKSPACE_REGIONS)[number]; + +export const INTERNATIONAL_WORKSPACE_REGIONS = ORDINARY_WORKSPACE_REGIONS.filter( + (region) => !(DOMESTIC_WORKSPACE_REGIONS as readonly string[]).includes(region), +); + +export type ApiKeyEndpointKind = "ordinary" | "token-plan"; + +export const KNOWN_MODEL_BASE_URLS: Readonly> = { + ordinary: [ + "https://dashscope.aliyuncs.com", + "https://dashscope-intl.aliyuncs.com", + "https://dashscope-us.aliyuncs.com", + "https://cn-hongkong.dashscope.aliyuncs.com", + ], + "token-plan": [ + "https://token-plan.cn-beijing.maas.aliyuncs.com", + "https://token-plan.ap-southeast-1.maas.aliyuncs.com", + ], +}; + +const DOMESTIC_REGION_SET = new Set(DOMESTIC_WORKSPACE_REGIONS); +const INTERNATIONAL_REGION_SET = new Set(INTERNATIONAL_WORKSPACE_REGIONS); + +const DOMESTIC_HOSTS = new Set(["dashscope.aliyuncs.com"]); +const INTERNATIONAL_HOSTS = new Set([ + "dashscope-intl.aliyuncs.com", + "dashscope-us.aliyuncs.com", + "cn-hongkong.dashscope.aliyuncs.com", +]); + +/** Extract a hostname from a URL or bare host string. */ +export function hostnameOf(input: string | undefined): string | undefined { + if (input === undefined) return undefined; + const trimmed = input.trim(); + if (!trimmed) return undefined; + try { + if (/^https?:\/\//i.test(trimmed)) { + return new URL(trimmed).hostname.toLowerCase(); + } + const hostPart = trimmed.split("/")[0]?.split("?")[0]; + if (!hostPart) return undefined; + return hostPart.toLowerCase(); + } catch { + return undefined; + } +} + +export type ModelHostClass = "domestic" | "international" | "unknown"; + +/** + * Classify a model-domain host: mainland whitelist → domestic; + * known official international (incl. Hong Kong) → international; + * everything else → unknown (callers typically fall back to domestic). + */ +export function classifyModelHost(hostOrUrl: string | undefined): ModelHostClass { + const hostname = hostnameOf(hostOrUrl); + if (!hostname) return "unknown"; + + if (DOMESTIC_HOSTS.has(hostname)) return "domestic"; + if (INTERNATIONAL_HOSTS.has(hostname)) return "international"; + + const tokenPlanMatch = hostname.match(/^token-plan\.([a-z0-9-]+)\.maas\.aliyuncs\.com$/i); + if (tokenPlanMatch) { + return classifyWorkspaceRegion(tokenPlanMatch[1]!); + } + + const workspaceMaasMatch = hostname.match(/^[a-z0-9-]+\.([a-z0-9-]+)\.maas\.aliyuncs\.com$/i); + if (workspaceMaasMatch) { + return classifyWorkspaceRegion(workspaceMaasMatch[1]!); + } + + const regionalDashscopeMatch = hostname.match(/^([a-z0-9-]+)\.dashscope\.aliyuncs\.com$/i); + if (regionalDashscopeMatch) { + return classifyWorkspaceRegion(regionalDashscopeMatch[1]!); + } + + return "unknown"; +} + +function classifyWorkspaceRegion(region: string): ModelHostClass { + if (DOMESTIC_REGION_SET.has(region)) return "domestic"; + if (INTERNATIONAL_REGION_SET.has(region)) return "international"; + return "unknown"; +} diff --git a/packages/core/src/telemetry/event.ts b/packages/core/src/telemetry/event.ts index b81f6d41f..b29fb9e3c 100644 --- a/packages/core/src/telemetry/event.ts +++ b/packages/core/src/telemetry/event.ts @@ -3,6 +3,7 @@ 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"; +import type { TelemetrySite, TelemetrySiteReason } from "./site.ts"; export interface TrackingEvent { command: string; @@ -28,6 +29,10 @@ export interface TrackingEvent { installChannel?: InstallAttribution["installChannel"]; /** Caller-declared call source (--biz-from), normalized; reported as AEM c6. */ bizFrom?: string; + /** AEM reporting site (domestic vs international). */ + site: TelemetrySite; + /** Coarse site resolution reason; never includes raw hosts. */ + siteReason?: TelemetrySiteReason; } export function createTrackingEvent(opts: { @@ -42,6 +47,8 @@ export function createTrackingEvent(opts: { /** Already-read install record. Callers must not create the file to fill this in. */ install?: InstallAttribution; bizFrom?: string; + site?: TelemetrySite; + siteReason?: TelemetrySiteReason; }): TrackingEvent { const event: TrackingEvent = { command: opts.command, @@ -53,6 +60,7 @@ export function createTrackingEvent(opts: { nodeVersion: process.version, os: process.platform, callerType: opts.caller.callerType, + site: opts.site ?? "domestic", }; if (opts.caller.callerType === "agent") { @@ -86,6 +94,10 @@ export function createTrackingEvent(opts: { event.installChannel = opts.install.installChannel; } + if (opts.siteReason) { + event.siteReason = opts.siteReason; + } + return event; } diff --git a/packages/core/src/telemetry/index.ts b/packages/core/src/telemetry/index.ts index 793d4fb86..ff0fad5fe 100644 --- a/packages/core/src/telemetry/index.ts +++ b/packages/core/src/telemetry/index.ts @@ -2,7 +2,16 @@ export type { CallerAttribution } from "./caller.ts"; export { readCaller } from "./caller.ts"; export type { TrackingEvent } from "./event.ts"; export { createTrackingEvent } from "./event.ts"; -export { localSink, remoteSink, flushTelemetry } from "./sink.ts"; +export { localSink, remoteSink, flushTelemetry, resetRemoteTelemetryForTests } from "./sink.ts"; export { reportFirstInstallNow, trackCommandExecution } from "./tracker.ts"; export { FIRST_INSTALL_REPORT_ARGUMENT, isFirstInstallReportLaunch } from "./first-install.ts"; export type { TrackingDeps } from "./tracker.ts"; +export { + resolveTelemetrySite, + telemetryRemoteTarget, + type TelemetrySite, + type TelemetrySiteReason, + type TelemetrySiteResolution, + type ResolveTelemetrySiteInput, + type TelemetryRemoteTarget, +} from "./site.ts"; diff --git a/packages/core/src/telemetry/sink.ts b/packages/core/src/telemetry/sink.ts index 9735627b1..818d923cd 100644 --- a/packages/core/src/telemetry/sink.ts +++ b/packages/core/src/telemetry/sink.ts @@ -11,6 +11,7 @@ import { } from "./event.ts"; import { detectEnv } from "./env.ts"; import { ensureUid, loadUid } from "./uid.ts"; +import { telemetryRemoteTarget, type TelemetrySite } from "./site.ts"; import Tracker from "../../lib/remote-telemetry/tracker.cjs"; import EventPlugin from "../../lib/remote-telemetry/event-plugin.cjs"; @@ -18,8 +19,6 @@ const TELEMETRY_FILE = () => join(getConfigDir(), "telemetry.jsonl"); const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5 MB -let remoteSendEvent: ((name: string, opts: Record) => void) | undefined; - // Track in-flight remote sends so we can wait for them before process exit. // The underlying tracker is fire-and-forget (fetch starts without holding the promise); // without tracking, short commands or SIGINT can exit before the request hits the network. @@ -31,24 +30,36 @@ interface PendingSend { promise: Promise; } const inflightSends = new Set(); -let remoteClient: any = undefined; -let remoteInitialized = false; + +interface RemoteSiteClient { + client: { + _sendAll?: () => void; + send: (payload: string, options?: { signal?: AbortSignal }) => unknown; + }; + sendEvent: (name: string, opts: Record) => void; +} + +/** One Tracker per telemetry site so domestic/intl never share pid/endpoint. */ +const remoteBySite = new Map(); /** - * Construct the tracker on first remote report so disabled telemetry neither - * constructs the tracker nor creates the uid file. Fully synchronous; see ensureUid. + * Construct the tracker on first remote report for a site so disabled telemetry + * neither constructs the tracker nor creates the uid file. Fully synchronous; see ensureUid. */ -function initRemote(): void { - if (remoteInitialized) return; - remoteInitialized = true; +function initRemoteForSite(site: TelemetrySite): RemoteSiteClient | undefined { + const existing = remoteBySite.get(site); + if (existing) return existing; try { const uid = ensureUid(); + const target = telemetryRemoteTarget(site); // `env` on the Tracker top-level config becomes a URL query param; AEM's // "environment" column (raw field `env`) reads it. Allowed values: // prod/pre/daily/dev. We currently use only prod/dev. // anonymous install id as `uid`, which AEM exposes as a dashboard field. + // Cross-site uid/device_id stay shared (compliance-accepted). const client = new Tracker({ - pid: "bailian-cli-node", + pid: target.pid, + endpoint: target.endpoint, env: detectEnv(), ...(uid ? { uid } : {}), }); @@ -75,18 +86,23 @@ function initRemote(): void { inflightSends.add(pending); return pending.promise; }; - remoteClient = client; - remoteSendEvent = client.use(EventPlugin); + const entry: RemoteSiteClient = { + client, + sendEvent: client.use(EventPlugin), + }; + remoteBySite.set(site, entry); + return entry; } catch { // Telemetry must never affect the CLI main flow + return undefined; } } /** * Best-effort wait for all in-flight telemetry 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. + * 1. Call `_sendAll` on every site tracker to drain the 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. * * Telemetry must never block the CLI: callers should pass a short timeout @@ -95,12 +111,10 @@ function initRemote(): void { export async function flushTelemetry(timeoutMs = 1000): Promise { let deadline: ReturnType | undefined; try { - if (remoteClient) { + for (const entry of remoteBySite.values()) { try { - // Drain the debounce queue so events stuck in the 500ms merge window - // are sent immediately (each send is appended to inflightSends). - if (typeof remoteClient._sendAll === "function") { - remoteClient._sendAll(); + if (typeof entry.client._sendAll === "function") { + entry.client._sendAll(); } } catch { // flush itself must never throw @@ -151,12 +165,14 @@ export async function localSink(event: TrackingEvent | FirstInstallEvent): Promi /** 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 false; + // first_install has no command/auth context; it always reports domestic (best-effort). + const site: TelemetrySite = isFirstInstallEvent(event) ? "domestic" : (event.site ?? "domestic"); + const entry = initRemoteForSite(site); + if (!entry) return false; if (isFirstInstallEvent(event)) { - remoteSendEvent(FIRST_INSTALL_EVENT_NAME, buildFirstInstallAemOptions(event)); + entry.sendEvent(FIRST_INSTALL_EVENT_NAME, buildFirstInstallAemOptions(event)); } else { - remoteSendEvent(event.command, buildRemoteAemOptions(event)); + entry.sendEvent(event.command, buildRemoteAemOptions(event)); } return true; } catch { @@ -164,3 +180,9 @@ export async function remoteSink(event: TrackingEvent | FirstInstallEvent): Prom return false; } } + +/** Test-only: drop site trackers so the next remoteSink rebuilds them. */ +export function resetRemoteTelemetryForTests(): void { + remoteBySite.clear(); + inflightSends.clear(); +} diff --git a/packages/core/src/telemetry/site.ts b/packages/core/src/telemetry/site.ts new file mode 100644 index 000000000..1203254df --- /dev/null +++ b/packages/core/src/telemetry/site.ts @@ -0,0 +1,94 @@ +import { classifyModelHost, hostnameOf } from "../config/model-endpoints.ts"; +import type { AuthRequirement } from "../types/command.ts"; + +export type TelemetrySite = "domestic" | "international"; + +/** Coarse reason for site resolution; never includes raw hosts. */ +export type TelemetrySiteReason = + | "positive-domestic" + | "positive-international" + | "default-fallback" + | "unknown-host"; + +export interface TelemetrySiteResolution { + site: TelemetrySite; + siteReason: TelemetrySiteReason; +} + +export interface ResolveTelemetrySiteInput { + auth: AuthRequirement; + consoleSite?: "domestic" | "international"; + /** Origin recorded from Client.url() / upload defaultBaseUrl paths. */ + lastResolvedOrigin?: string; + /** Model-domain base URL (or its host). */ + baseUrl?: string; +} + +export interface TelemetryRemoteTarget { + site: TelemetrySite; + endpoint: string; + pid: string; +} + +const REMOTE_TARGETS: Record = { + domestic: { + site: "domestic", + endpoint: "gm.mmstat.com", + pid: "bailian-cli-node", + }, + international: { + site: "international", + endpoint: "sg.mmstat.com", + pid: "bailian-cli-node-intl", + }, +}; + +export function telemetryRemoteTarget(site: TelemetrySite): TelemetryRemoteTarget { + return REMOTE_TARGETS[site]; +} + +/** + * Resolve AEM reporting site (D4=B): console → consoleSite; + * apiKey/openapi → model host/region; none → OR of both. + */ +export function resolveTelemetrySite(input: ResolveTelemetrySiteInput): TelemetrySiteResolution { + if (input.auth === "console") { + if (input.consoleSite === "international") { + return { site: "international", siteReason: "positive-international" }; + } + return { site: "domestic", siteReason: "default-fallback" }; + } + + if (input.auth === "apiKey" || input.auth === "openapi") { + return classifyFromModelOrigin(input.lastResolvedOrigin, input.baseUrl); + } + + // auth: none — OR + if (input.consoleSite === "international") { + return { site: "international", siteReason: "positive-international" }; + } + return classifyFromModelOrigin(input.lastResolvedOrigin, input.baseUrl); +} + +function classifyFromModelOrigin( + lastResolvedOrigin: string | undefined, + baseUrl: string | undefined, +): TelemetrySiteResolution { + const host = hostnameOf(lastResolvedOrigin) ?? hostnameOf(baseUrl); + if (!host) { + return { site: "domestic", siteReason: "default-fallback" }; + } + const classification = classifyModelHost(host); + switch (classification) { + case "domestic": + return { site: "domestic", siteReason: "positive-domestic" }; + case "international": + return { site: "international", siteReason: "positive-international" }; + case "unknown": + return { site: "domestic", siteReason: "unknown-host" }; + default: { + const _exhaustive: never = classification; + return _exhaustive; + } + } +} diff --git a/packages/core/src/telemetry/tracker.ts b/packages/core/src/telemetry/tracker.ts index 148c0b18c..4353339bc 100644 --- a/packages/core/src/telemetry/tracker.ts +++ b/packages/core/src/telemetry/tracker.ts @@ -12,6 +12,7 @@ import { readFirstInstallReportAttempts, } from "./first-install.ts"; import { flushTelemetry, localSink, remoteSink } from "./sink.ts"; +import type { TelemetrySiteResolution } from "./site.ts"; const GLOBAL_FLAG_KEYS = new Set([ "apiKey", @@ -166,6 +167,11 @@ export interface TrackingDeps { authMethod?: AuthRequirement; /** From `readCaller(process.env)` in telemetryStage. */ caller: CallerAttribution; + /** + * Lazy site resolution invoked in `finally` so Client.url() callback origins + * and authStage Client replacement are visible. + */ + resolveSite?: () => TelemetrySiteResolution; } export async function trackCommandExecution( @@ -202,6 +208,15 @@ export async function trackCommandExecution( } finally { const durationMs = Math.round(performance.now() - start); const install = readCommandInstallAttribution(deps.identity); + let siteResolution: TelemetrySiteResolution = { + site: "domestic", + siteReason: "default-fallback", + }; + try { + if (deps.resolveSite) siteResolution = deps.resolveSite(); + } catch { + // Site resolution must never mask command errors or block telemetry. + } const event = createTrackingEvent({ command: commandPath.join(" "), @@ -214,6 +229,8 @@ export async function trackCommandExecution( caller: deps.caller, install, bizFrom: normalizeBizFrom(deps.settings.bizFrom), + site: siteResolution.site, + siteReason: siteResolution.siteReason, }); // The install day is reported when install succeeds, not from this command. diff --git a/packages/core/tests/client-last-resolved-origin.test.ts b/packages/core/tests/client-last-resolved-origin.test.ts new file mode 100644 index 000000000..4906d9b73 --- /dev/null +++ b/packages/core/tests/client-last-resolved-origin.test.ts @@ -0,0 +1,83 @@ +import { expect, test } from "vite-plus/test"; +import { Client } from "../src/client/client.ts"; +import type { Identity, Settings } from "../src/config/schema.ts"; + +const identity: Identity = { + binName: "bl", + version: "0.0.0-test", + clientName: "bailian-cli-test", + npmPackage: "bailian-cli", +}; + +const settings = { telemetry: true, timeout: 30 } as Settings; + +test("url records lastResolvedOrigin for defaultBaseUrl callbacks", () => { + const client = new Client({ + identity, + settings, + baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: true, + apiCred: { + token: "sk-test", + baseUrl: "https://dashscope.aliyuncs.com", + source: "config", + }, + }); + expect(client.lastResolvedOrigin).toBeUndefined(); + expect(client.url("/decision", () => "https://ws.ap-southeast-1.maas.aliyuncs.com")).toBe( + "https://ws.ap-southeast-1.maas.aliyuncs.com/decision", + ); + expect(client.lastResolvedOrigin).toBe("https://ws.ap-southeast-1.maas.aliyuncs.com"); +}); + +test("configured baseUrl wins over callback and is still recorded", () => { + const client = new Client({ + identity, + settings, + baseUrl: "https://dashscope-intl.aliyuncs.com", + baseUrlIsDefault: false, + apiCred: { + token: "sk-test", + baseUrl: "https://dashscope-intl.aliyuncs.com", + source: "config", + }, + }); + expect(client.url("/service", () => "https://ws.ap-southeast-1.maas.aliyuncs.com")).toBe( + "https://dashscope-intl.aliyuncs.com/service", + ); + expect(client.lastResolvedOrigin).toBe("https://dashscope-intl.aliyuncs.com"); +}); + +test("empty managed-agent callback does not record an origin", () => { + const client = new Client({ + identity, + settings, + baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: true, + apiCred: { + token: "sk-test", + baseUrl: "https://dashscope.aliyuncs.com", + source: "config", + }, + }); + expect(client.url("", () => "")).toBe(""); + expect(client.lastResolvedOrigin).toBeUndefined(); +}); + +test("uploadFile path records origin via url()", async () => { + const client = new Client({ + identity, + settings, + baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: true, + apiCred: { + token: "sk-test", + baseUrl: "https://dashscope.aliyuncs.com", + source: "config", + }, + }); + // Non-local source short-circuits before upload but still goes through url when local. + // Calling url directly mirrors uploadFile's baseUrl resolution. + client.url("", () => "https://ws.cn-hongkong.maas.aliyuncs.com"); + expect(client.lastResolvedOrigin).toBe("https://ws.cn-hongkong.maas.aliyuncs.com"); +}); diff --git a/packages/core/tests/telemetry-sink.test.ts b/packages/core/tests/telemetry-sink.test.ts index 77dbc8ed8..066fbedeb 100644 --- a/packages/core/tests/telemetry-sink.test.ts +++ b/packages/core/tests/telemetry-sink.test.ts @@ -29,6 +29,10 @@ vi.mock("../lib/remote-telemetry/tracker.cjs", () => ({ }, })); +function fixtureEvent(site: "domestic" | "international" = "domestic"): TrackingEvent { + return { command: "fixture", site } as TrackingEvent; +} + let iso: IsolatedHomeHandle; beforeEach(() => { @@ -48,7 +52,7 @@ afterEach(() => { test("flush cancels in-flight work when its shorter shutdown budget expires", async () => { vi.useFakeTimers(); const { remoteSink, flushTelemetry } = await import("../src/telemetry/sink.ts"); - await remoteSink({ command: "fixture" } as TrackingEvent); + await remoteSink(fixtureEvent()); const pending = flushTelemetry(50); await vi.advanceTimersByTimeAsync(49); expect(fixture.signals).toHaveLength(1); @@ -62,7 +66,7 @@ test("flush cancels in-flight work when its shorter shutdown budget expires", as test("send has a bounded lifetime even when a host does not flush", async () => { vi.useFakeTimers(); const { remoteSink } = await import("../src/telemetry/sink.ts"); - await remoteSink({ command: "fixture" } as TrackingEvent); + await remoteSink(fixtureEvent()); await vi.advanceTimersByTimeAsync(999); expect(fixture.signals[0]?.aborted).toBe(false); await vi.advanceTimersByTimeAsync(1); @@ -74,7 +78,7 @@ test("successful sending and repeated flushes leave no deadlines behind", async vi.useFakeTimers(); fixture.complete = true; const { remoteSink, flushTelemetry } = await import("../src/telemetry/sink.ts"); - await remoteSink({ command: "fixture" } as TrackingEvent); + await remoteSink(fixtureEvent()); await flushTelemetry(50); await flushTelemetry(50); expect(fixture.signals[0]?.aborted).toBe(true); @@ -84,17 +88,43 @@ test("successful sending and repeated flushes leave no deadlines behind", async test("first remoteSink constructs the tracker once with persisted uid, not device_id", async () => { const { remoteSink } = await import("../src/telemetry/sink.ts"); expect(fixture.configs).toHaveLength(0); - await remoteSink({ command: "fixture" } as TrackingEvent); - await remoteSink({ command: "fixture" } as TrackingEvent); + await remoteSink(fixtureEvent()); + await remoteSink(fixtureEvent()); expect(fixture.configs).toHaveLength(1); const { loadUid } = await import("../src/telemetry/uid.ts"); expect(fixture.configs[0]).toMatchObject({ pid: "bailian-cli-node", + endpoint: "gm.mmstat.com", uid: loadUid(), }); expect(fixture.configs[0]).not.toHaveProperty("device_id"); }); +test("keyed-by-site Map builds separate trackers for domestic and international", async () => { + fixture.complete = true; + const { remoteSink, flushTelemetry, resetRemoteTelemetryForTests } = + await import("../src/telemetry/sink.ts"); + await remoteSink(fixtureEvent("domestic")); + await remoteSink(fixtureEvent("international")); + await remoteSink(fixtureEvent("international")); + expect(fixture.configs).toHaveLength(2); + expect(fixture.configs[0]).toMatchObject({ + pid: "bailian-cli-node", + endpoint: "gm.mmstat.com", + }); + expect(fixture.configs[1]).toMatchObject({ + pid: "bailian-cli-node-intl", + endpoint: "sg.mmstat.com", + }); + const { loadUid } = await import("../src/telemetry/uid.ts"); + expect(fixture.configs[0]?.uid).toBe(loadUid()); + expect(fixture.configs[1]?.uid).toBe(loadUid()); + await flushTelemetry(50); + resetRemoteTelemetryForTests(); + await remoteSink(fixtureEvent("domestic")); + expect(fixture.configs).toHaveLength(3); +}); + test("importing sink without reporting does not create the uid file", async () => { await import("../src/telemetry/sink.ts"); const { getUidPath } = await import("../src/telemetry/uid.ts"); diff --git a/packages/core/tests/telemetry-site.test.ts b/packages/core/tests/telemetry-site.test.ts new file mode 100644 index 000000000..f7b800093 --- /dev/null +++ b/packages/core/tests/telemetry-site.test.ts @@ -0,0 +1,175 @@ +import { expect, test } from "vite-plus/test"; +import { classifyModelHost, hostnameOf } from "../src/config/model-endpoints.ts"; +import { resolveTelemetrySite, telemetryRemoteTarget } from "../src/telemetry/site.ts"; + +test.each([ + ["https://dashscope.aliyuncs.com", "dashscope.aliyuncs.com"], + ["dashscope-intl.aliyuncs.com", "dashscope-intl.aliyuncs.com"], + [" https://CN-HongKong.dashscope.aliyuncs.com/path ", "cn-hongkong.dashscope.aliyuncs.com"], + ["", undefined], + [undefined, undefined], +])("hostnameOf(%j) → %j", (input, expected) => { + expect(hostnameOf(input)).toBe(expected); +}); + +test.each([ + ["dashscope.aliyuncs.com", "domestic"], + ["https://dashscope.aliyuncs.com/api/v1", "domestic"], + ["token-plan.cn-beijing.maas.aliyuncs.com", "domestic"], + ["ws-abc.cn-beijing.maas.aliyuncs.com", "domestic"], + ["dashscope-intl.aliyuncs.com", "international"], + ["dashscope-us.aliyuncs.com", "international"], + ["cn-hongkong.dashscope.aliyuncs.com", "international"], + ["token-plan.ap-southeast-1.maas.aliyuncs.com", "international"], + ["ws-abc.ap-southeast-1.maas.aliyuncs.com", "international"], + ["ws-abc.cn-hongkong.maas.aliyuncs.com", "international"], + ["ws-abc.eu-central-1.maas.aliyuncs.com", "international"], + ["ws-abc.us-east-1.maas.aliyuncs.com", "international"], + ["ws-abc.ap-northeast-1.maas.aliyuncs.com", "international"], + ["custom.proxy.example.com", "unknown"], + ["token-plan.unknown-region.maas.aliyuncs.com", "unknown"], + [undefined, "unknown"], + ["", "unknown"], +])("classifyModelHost(%j) → %j", (host, expected) => { + expect(classifyModelHost(host)).toBe(expected); +}); + +test("console auth uses consoleSite only (D4=B)", () => { + expect( + resolveTelemetrySite({ + auth: "console", + consoleSite: "international", + baseUrl: "https://dashscope.aliyuncs.com", + }), + ).toEqual({ site: "international", siteReason: "positive-international" }); + + expect( + resolveTelemetrySite({ + auth: "console", + consoleSite: "domestic", + baseUrl: "https://dashscope-intl.aliyuncs.com", + }), + ).toEqual({ site: "domestic", siteReason: "default-fallback" }); + + expect( + resolveTelemetrySite({ + auth: "console", + baseUrl: "https://dashscope-intl.aliyuncs.com", + }), + ).toEqual({ site: "domestic", siteReason: "default-fallback" }); +}); + +test("apiKey prefers lastResolvedOrigin over baseUrl", () => { + expect( + resolveTelemetrySite({ + auth: "apiKey", + lastResolvedOrigin: "https://ws.ap-southeast-1.maas.aliyuncs.com", + baseUrl: "https://dashscope.aliyuncs.com", + }), + ).toEqual({ site: "international", siteReason: "positive-international" }); + + expect( + resolveTelemetrySite({ + auth: "apiKey", + baseUrl: "https://dashscope.aliyuncs.com", + }), + ).toEqual({ site: "domestic", siteReason: "positive-domestic" }); +}); + +test("openapi classifies model-domain baseUrl, not ACS hosts", () => { + expect( + resolveTelemetrySite({ + auth: "openapi", + baseUrl: "https://dashscope-intl.aliyuncs.com", + }), + ).toEqual({ site: "international", siteReason: "positive-international" }); + + // ACS hosts must not be passed as baseUrl; if they were, they fall back as unknown→domestic + expect( + resolveTelemetrySite({ + auth: "openapi", + baseUrl: "https://modelstudio.ap-southeast-1.aliyuncs.com", + }), + ).toEqual({ site: "domestic", siteReason: "unknown-host" }); +}); + +test("cn-hongkong is international", () => { + expect( + resolveTelemetrySite({ + auth: "apiKey", + baseUrl: "https://cn-hongkong.dashscope.aliyuncs.com", + }), + ).toEqual({ site: "international", siteReason: "positive-international" }); +}); + +test("unknown host falls back to domestic with unknown-host reason", () => { + expect( + resolveTelemetrySite({ + auth: "apiKey", + baseUrl: "https://my-reverse-proxy.example.com", + }), + ).toEqual({ site: "domestic", siteReason: "unknown-host" }); +}); + +test("auth none ORs consoleSite with model host", () => { + expect( + resolveTelemetrySite({ + auth: "none", + consoleSite: "international", + baseUrl: "https://dashscope.aliyuncs.com", + }), + ).toEqual({ site: "international", siteReason: "positive-international" }); + + expect( + resolveTelemetrySite({ + auth: "none", + consoleSite: "domestic", + baseUrl: "https://dashscope-intl.aliyuncs.com", + }), + ).toEqual({ site: "international", siteReason: "positive-international" }); + + expect( + resolveTelemetrySite({ + auth: "none", + lastResolvedOrigin: "https://ws.ap-southeast-1.maas.aliyuncs.com", + baseUrl: "https://dashscope.aliyuncs.com", + }), + ).toEqual({ site: "international", siteReason: "positive-international" }); + + expect( + resolveTelemetrySite({ + auth: "none", + baseUrl: "https://dashscope.aliyuncs.com", + }), + ).toEqual({ site: "domestic", siteReason: "positive-domestic" }); +}); + +test("mixed profile: console domestic does not force apiKey domestic", () => { + expect( + resolveTelemetrySite({ + auth: "apiKey", + consoleSite: "domestic", + baseUrl: "https://dashscope-intl.aliyuncs.com", + }), + ).toEqual({ site: "international", siteReason: "positive-international" }); +}); + +test("missing baseUrl defaults domestic", () => { + expect(resolveTelemetrySite({ auth: "apiKey" })).toEqual({ + site: "domestic", + siteReason: "default-fallback", + }); +}); + +test("telemetryRemoteTarget maps site to endpoint and pid", () => { + expect(telemetryRemoteTarget("domestic")).toEqual({ + site: "domestic", + endpoint: "gm.mmstat.com", + pid: "bailian-cli-node", + }); + expect(telemetryRemoteTarget("international")).toEqual({ + site: "international", + endpoint: "sg.mmstat.com", + pid: "bailian-cli-node-intl", + }); +}); diff --git a/packages/core/tests/telemetry-tracker.test.ts b/packages/core/tests/telemetry-tracker.test.ts index 2c2777f4f..3ba6c759d 100644 --- a/packages/core/tests/telemetry-tracker.test.ts +++ b/packages/core/tests/telemetry-tracker.test.ts @@ -103,9 +103,65 @@ test("derives event version and prefix from identity", () => { command: "config show", cliVersion: "identity-version", commandPrefix: "bl", + site: "domestic", }); expect(buildRemoteAemOptions(event)).toMatchObject({ - ext: { cliVersion: "identity-version", commandPrefix: "bl" }, + ext: { cliVersion: "identity-version", commandPrefix: "bl", site: "domestic" }, + }); +}); + +test("resolveSite runs in finally and attaches site fields", async () => { + sinkMocks.localSink.mockClear(); + sinkMocks.remoteSink.mockClear(); + let calledAfterCommand = false; + await trackCommandExecution( + { + identity, + settings: { telemetry: true } as Settings, + authMethod: "apiKey", + caller: unknownCaller, + resolveSite: () => { + calledAfterCommand = true; + return { site: "international", siteReason: "positive-international" }; + }, + }, + ["text", "chat"], + {}, + async () => { + expect(calledAfterCommand).toBe(false); + }, + ); + expect(calledAfterCommand).toBe(true); + const event = sinkMocks.localSink.mock.calls[0]![0]; + expect(event).toMatchObject({ + site: "international", + siteReason: "positive-international", + }); + expect(buildRemoteAemOptions(event).ext).toMatchObject({ + site: "international", + siteReason: "positive-international", + }); +}); + +test("resolveSite failure still emits domestic event", async () => { + sinkMocks.localSink.mockClear(); + sinkMocks.remoteSink.mockClear(); + await trackCommandExecution( + { + identity, + settings: { telemetry: true } as Settings, + caller: unknownCaller, + resolveSite: () => { + throw new Error("resolve boom"); + }, + }, + ["config", "show"], + {}, + async () => {}, + ); + expect(sinkMocks.localSink.mock.calls[0]![0]).toMatchObject({ + site: "domestic", + siteReason: "default-fallback", }); }); diff --git a/packages/runtime/src/middleware.ts b/packages/runtime/src/middleware.ts index 3b3d26f8b..ed3dee499 100644 --- a/packages/runtime/src/middleware.ts +++ b/packages/runtime/src/middleware.ts @@ -28,6 +28,7 @@ import { readCaller, resolveModelBaseUrlState, resolveModelConnectionProvenance, + resolveTelemetrySite, selectApiKeyResolutionSources, trackCommandExecution, } from "bailian-cli-core"; @@ -293,6 +294,13 @@ export const telemetryStage: Middleware = (ctx, next) => { settings: ctx.settings, authMethod: ctx.command.auth, caller: readCaller(process.env), + resolveSite: () => + resolveTelemetrySite({ + auth: ctx.command.auth, + consoleSite: ctx.settings.consoleSite, + lastResolvedOrigin: ctx.client.lastResolvedOrigin, + baseUrl: ctx.client.baseUrl, + }), }, ctx.path, ctx.flags, diff --git a/packages/runtime/tests/telemetry-stage.test.ts b/packages/runtime/tests/telemetry-stage.test.ts index 77f5ec655..5b7e9887b 100644 --- a/packages/runtime/tests/telemetry-stage.test.ts +++ b/packages/runtime/tests/telemetry-stage.test.ts @@ -24,7 +24,7 @@ vi.mock("bailian-cli-core", async () => { import { telemetryStage, type RunContext } from "../src/middleware.ts"; -function makeContext(): RunContext { +function makeContext(overrides: Record = {}): RunContext { return { identity: { binName: "bl", @@ -36,6 +36,7 @@ function makeContext(): RunContext { command: { auth: "none" }, settings: { telemetry: true }, flags: {}, + ...overrides, } as RunContext; } @@ -60,6 +61,7 @@ test("wires process.env through readCaller into trackCommandExecution", async () const deps = trackerMocks.trackCommandExecution.mock.calls[0]![0] as { caller: CallerAttribution; authMethod: string; + resolveSite?: () => { site: string; siteReason: string }; }; expect(deps.caller).toEqual({ callerType: "agent", @@ -68,9 +70,57 @@ test("wires process.env through readCaller into trackCommandExecution", async () skillVersion: "2.5.0", }); expect(deps.authMethod).toBe("none"); + expect(typeof deps.resolveSite).toBe("function"); expect(next).toHaveBeenCalledOnce(); }); +test("resolveSite uses client lastResolvedOrigin and settings.consoleSite", async () => { + const next = vi.fn(async () => {}); + const context = makeContext({ + command: { auth: "apiKey" }, + client: { + baseUrl: "https://dashscope.aliyuncs.com", + lastResolvedOrigin: "https://ws.ap-southeast-1.maas.aliyuncs.com", + }, + settings: { telemetry: true, consoleSite: "domestic" }, + }); + + await telemetryStage(context, next); + + const deps = trackerMocks.trackCommandExecution.mock.calls[0]![0] as { + resolveSite: () => { site: string; siteReason: string }; + }; + expect(deps.resolveSite()).toEqual({ + site: "international", + siteReason: "positive-international", + }); +}); + +test("resolveSite for console auth ignores model baseUrl (D4=B)", async () => { + const next = vi.fn(async () => {}); + const context = makeContext({ + command: { auth: "console" }, + client: { + baseUrl: "https://dashscope-intl.aliyuncs.com", + lastResolvedOrigin: undefined, + }, + settings: { + telemetry: true, + consoleSite: "international", + }, + }); + + await telemetryStage(context, next); + + const deps = trackerMocks.trackCommandExecution.mock.calls[0]![0] as { + resolveSite: () => { site: string; siteReason: string }; + }; + expect(deps.resolveSite()).toEqual({ + site: "international", + siteReason: "positive-international", + }); +}); + test("defaults to unknown when caller env is unset", async () => { vi.stubEnv("BAILIAN_CALLER_TYPE", undefined); vi.stubEnv("BAILIAN_CALLER_NAME", undefined); From 3dfe17bdce24b49869c78a85f8c596a6aff9de07 Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Thu, 26 Nov 2026 10:49:59 +0800 Subject: [PATCH 2/6] fix(telemetry): narrow sink mock events with asCommand After rebasing onto first-install ReportedEvent unions, site routing tests must use asCommand before buildRemoteAemOptions. --- packages/core/tests/telemetry-tracker.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/tests/telemetry-tracker.test.ts b/packages/core/tests/telemetry-tracker.test.ts index 3ba6c759d..e2639cd2e 100644 --- a/packages/core/tests/telemetry-tracker.test.ts +++ b/packages/core/tests/telemetry-tracker.test.ts @@ -132,7 +132,7 @@ test("resolveSite runs in finally and attaches site fields", async () => { }, ); expect(calledAfterCommand).toBe(true); - const event = sinkMocks.localSink.mock.calls[0]![0]; + const event = asCommand(sinkMocks.localSink.mock.calls[0]![0]); expect(event).toMatchObject({ site: "international", siteReason: "positive-international", @@ -159,7 +159,7 @@ test("resolveSite failure still emits domestic event", async () => { {}, async () => {}, ); - expect(sinkMocks.localSink.mock.calls[0]![0]).toMatchObject({ + expect(asCommand(sinkMocks.localSink.mock.calls[0]![0])).toMatchObject({ site: "domestic", siteReason: "default-fallback", }); From 4f45997eaa8100c617cbf230b5f03c5affce0148 Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Thu, 26 Nov 2026 11:45:20 +0800 Subject: [PATCH 3/6] fix(telemetry): distinguish default-fallback from positive-domestic siteReason --- docs/agents/telemetry-change.md | 38 +++++++------ packages/core/src/client/client.ts | 5 ++ packages/core/src/telemetry/sink.ts | 4 +- packages/core/src/telemetry/site.ts | 26 ++++++--- packages/core/tests/telemetry-site.test.ts | 53 ++++++++++++++++++- packages/runtime/src/middleware.ts | 1 + .../runtime/tests/telemetry-stage.test.ts | 25 +++++++++ 7 files changed, 128 insertions(+), 24 deletions(-) diff --git a/docs/agents/telemetry-change.md b/docs/agents/telemetry-change.md index ef8f7fb93..438bdac52 100644 --- a/docs/agents/telemetry-change.md +++ b/docs/agents/telemetry-change.md @@ -152,19 +152,27 @@ postinstall.js launchFirstInstallReport | domestic | `bailian-cli-node` | `https://gm.mmstat.com/aes.1.1` | | international | `bailian-cli-node-intl` | `https://sg.mmstat.com/aes.1.1` | +端点已端到端实测(2026-11-24 手工上报,在 `bailian-cli-node-intl` 查到 4 条,`event_category` 分别是 `text chat` / `config show` / `usage free`,覆盖 `apiKey` / `console` / `none` 三个鉴权域,`ext` 里 `site=international`、`siteReason=positive-international`):国际站**不需要** `sg.mmstat.com/alicloud/aes.1.1` 变体 —— `/alicloud` 是阿里云国际站**页面**经 A+ 上报的通道,Node 直连 POST 用裸 `sg.mmstat.com` 即可落库。 + +mmstat 网关对任何 POST 都返回 `200` + GIF,端点或 pid 写错不会报错、不会重试,只会让看板永远为空。改端点 / 换 pid 后必须重新做一次落库验证,不能只看 HTTP 状态码。 + +国际站数据在 [AEM 新加坡站](https://sg.aem.alibaba-inc.com/) 查看;用 `aem` CLI 取数必须带 `--region sg`(AK 按 region 隔离存储),否则查的是 cn 租户 —— "查不到数据"不等于"埋点坏了"。 + 判定(D4=B:console=账号站,模型=host/region): -| `auth` | 信号 | 国际条件 | 缺省 | -| -------------------- | ------------------------------------------------------- | ---------------------------------------- | ---------------------------------------------------------- | -| `console` | `settings.consoleSite`(不看 `consoleRegion`) | `international` | domestic | -| `apiKey` / `openapi` | `Client.lastResolvedOrigin` 优先,否则 `client.baseUrl` | 已知国际 host/region(含 `cn-hongkong`) | domestic;未知 host → domestic + `siteReason=unknown-host` | -| `none` | consoleSite **或** 模型 host(OR) | 任一侧国际 | domestic | +| `auth` | 信号 | 国际条件 | 缺省 | +| -------------------- | ------------------------------------------------------------- | ---------------------------------------- | -------------------------------------------------------------------------------------------- | +| `console` | `settings.consoleSite`(不看 `consoleRegion`) | `international` | 未设置 → domestic + `default-fallback`;显式 `domestic` → `positive-domestic` | +| `apiKey` / `openapi` | `Client.lastResolvedOrigin` 优先,否则非默认 `client.baseUrl` | 已知国际 host/region(含 `cn-hongkong`) | 无有效 host / `baseUrlIsDefault` → domestic + `default-fallback`;未知 host → `unknown-host` | +| `none` | consoleSite **或** 模型 host(OR) | 任一侧国际 | 同上两侧兜底 | +- `siteReason`:`positive-*` 仅表示有明确信号(显式 consoleSite / 非默认 model host / `lastResolvedOrigin`);内置默认 `baseUrl`(`baseUrlIsDefault`)不计为 positive,走 `default-fallback`。 - 模型 host 分类清单上收在 `packages/core/src/config/model-endpoints.ts`(与 API Key 登录候选共用);`site.ts` 只调用 helper,禁止再写第四份。 - `lastResolvedOrigin` 仅在 `Client.url()` / upload 的 `defaultBaseUrl` 回调路径记录;主流量仍靠 `baseUrl`。runtime **禁止**泛化读取各命令 `flags.region`。 - openapi **禁止**用 ACS `opts.host` 分类。 - `remoteSink` 按 site 使用 keyed `Map` 持有 Tracker;同进程可同时存在国内与国际实例。`uid` / tracker `device_id` **跨站同值**。 - vendored tracker 仅保留本仓对 `send` 的本地改造(登记于此);国际 path 与国内同为 `/aes.1.1`,**不加** `endpointPath` patch。升级 SDK 时必须保留 `send` 改造。 +- 看板元数据还没跟上:`site` / `siteReason` 两站都未建自定义维度;`callerType` / `callerName` / `cliVersion` / `cliVersionCode` / `commandPrefix` 国内项目有、国际项目一个都没有。数据已经在 `ext` 里,但国际站要做筛选/聚合(含 Agent 调用率、入口区分)必须先补这些维度。 - 已知残留:未知/反代 host、残缺配置、登录写盘前首条 `none`、managed-agent 外部拼 host、旧版 CLI、账号站与模型地域混维拆站、`first_install` 固定报国内站(安装阶段没有 auth / Client 上下文)。 编译二进制的 `env=prod` 由 `BAILIAN_COMPILED=1` 决定,并且必须先于 `NODE_ENV`。`bun build --compile`(当前 pin 1.3.14)会把点访问 `process.env.NODE_ENV` 内联成构建机的值,未设置时是 `"development"`;`tools/release/lib/binary-compile.mjs` 同时 `--define process.env.NODE_ENV="production"`。这两处读取必须写成 `process.env.*`,包进别的变量后 `--define` 匹配不到。 @@ -191,17 +199,17 @@ postinstall.js launchFirstInstallReport AEM 映射: -| AEM 字段 | 内容 | -| ---------- | ---- | -| event name | 命令路径 | -| `et` | `EXP` | +| AEM 字段 | 内容 | +| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| event name | 命令路径 | +| `et` | `EXP` | | `ext` | 除 `command`、`params` 外的结构化事件字段,含 `commandPrefix`、`callerType`、`site`、可选 `siteReason`、失败时的 `exitCode`,以及读到的 `installChannel`。安装日不在命令事件里 | -| `c1` | allowlist 参数 | -| `c2` | `success` / `failure` | -| `c3` | HTTP status | -| `c4` | 错误文案,最多 500 字符 | -| `c5` | request ID | -| `c6` | `bizFrom` 业务来源(全局 `--biz-from`,归一化标量;专用扁平列,直接筛选/分组) | +| `c1` | allowlist 参数 | +| `c2` | `success` / `failure` | +| `c3` | HTTP status | +| `c4` | 错误文案,最多 500 字符 | +| `c5` | request ID | +| `c6` | `bizFrom` 业务来源(全局 `--biz-from`,归一化标量;专用扁平列,直接筛选/分组) | `siteReason` 为粗粒度枚举(`positive-domestic` / `positive-international` / `default-fallback` / `unknown-host`),**禁止**带原始 host。漏判量化用国内站 `siteReason` 兜底类占比;不要用「国内 pid 出现 `site=international`」做告警(国际事件不会进国内 pid)。 diff --git a/packages/core/src/client/client.ts b/packages/core/src/client/client.ts index b0c44bfe7..88cb79479 100644 --- a/packages/core/src/client/client.ts +++ b/packages/core/src/client/client.ts @@ -110,6 +110,11 @@ export class Client { return this.deps.apiCred?.baseUrl ?? this.deps.baseUrl; } + /** True when the model base URL came from the built-in default (nothing configured). */ + get baseUrlIsDefault(): boolean { + return this.deps.baseUrlIsDefault === true; + } + /** * Origin last selected by {@link url} / upload defaultBaseUrl callbacks. * Used by telemetry site routing; undefined when no valid origin was recorded. diff --git a/packages/core/src/telemetry/sink.ts b/packages/core/src/telemetry/sink.ts index 818d923cd..2c53fbb5c 100644 --- a/packages/core/src/telemetry/sink.ts +++ b/packages/core/src/telemetry/sink.ts @@ -166,7 +166,9 @@ export async function localSink(event: TrackingEvent | FirstInstallEvent): Promi export async function remoteSink(event: TrackingEvent | FirstInstallEvent): Promise { try { // first_install has no command/auth context; it always reports domestic (best-effort). - const site: TelemetrySite = isFirstInstallEvent(event) ? "domestic" : (event.site ?? "domestic"); + const site: TelemetrySite = isFirstInstallEvent(event) + ? "domestic" + : (event.site ?? "domestic"); const entry = initRemoteForSite(site); if (!entry) return false; if (isFirstInstallEvent(event)) { diff --git a/packages/core/src/telemetry/site.ts b/packages/core/src/telemetry/site.ts index 1203254df..00da429d4 100644 --- a/packages/core/src/telemetry/site.ts +++ b/packages/core/src/telemetry/site.ts @@ -22,6 +22,8 @@ export interface ResolveTelemetrySiteInput { lastResolvedOrigin?: string; /** Model-domain base URL (or its host). */ baseUrl?: string; + /** baseUrl is the built-in default, not a user signal. */ + baseUrlIsDefault?: boolean; } export interface TelemetryRemoteTarget { @@ -56,25 +58,35 @@ export function resolveTelemetrySite(input: ResolveTelemetrySiteInput): Telemetr if (input.consoleSite === "international") { return { site: "international", siteReason: "positive-international" }; } + if (input.consoleSite === "domestic") { + return { site: "domestic", siteReason: "positive-domestic" }; + } return { site: "domestic", siteReason: "default-fallback" }; } if (input.auth === "apiKey" || input.auth === "openapi") { - return classifyFromModelOrigin(input.lastResolvedOrigin, input.baseUrl); + return classifyFromModelOrigin(input); } // auth: none — OR if (input.consoleSite === "international") { return { site: "international", siteReason: "positive-international" }; } - return classifyFromModelOrigin(input.lastResolvedOrigin, input.baseUrl); + const modelResolution = classifyFromModelOrigin(input); + if (modelResolution.site === "international") { + return modelResolution; + } + if (input.consoleSite === "domestic") { + return { site: "domestic", siteReason: "positive-domestic" }; + } + return modelResolution; } -function classifyFromModelOrigin( - lastResolvedOrigin: string | undefined, - baseUrl: string | undefined, -): TelemetrySiteResolution { - const host = hostnameOf(lastResolvedOrigin) ?? hostnameOf(baseUrl); +function classifyFromModelOrigin(input: ResolveTelemetrySiteInput): TelemetrySiteResolution { + // lastResolvedOrigin is a real per-command choice and wins over the shared base URL. + const host = + hostnameOf(input.lastResolvedOrigin) ?? + (input.baseUrlIsDefault ? undefined : hostnameOf(input.baseUrl)); if (!host) { return { site: "domestic", siteReason: "default-fallback" }; } diff --git a/packages/core/tests/telemetry-site.test.ts b/packages/core/tests/telemetry-site.test.ts index f7b800093..800ef00df 100644 --- a/packages/core/tests/telemetry-site.test.ts +++ b/packages/core/tests/telemetry-site.test.ts @@ -49,7 +49,7 @@ test("console auth uses consoleSite only (D4=B)", () => { consoleSite: "domestic", baseUrl: "https://dashscope-intl.aliyuncs.com", }), - ).toEqual({ site: "domestic", siteReason: "default-fallback" }); + ).toEqual({ site: "domestic", siteReason: "positive-domestic" }); expect( resolveTelemetrySite({ @@ -65,6 +65,7 @@ test("apiKey prefers lastResolvedOrigin over baseUrl", () => { auth: "apiKey", lastResolvedOrigin: "https://ws.ap-southeast-1.maas.aliyuncs.com", baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: true, }), ).toEqual({ site: "international", siteReason: "positive-international" }); @@ -72,15 +73,43 @@ test("apiKey prefers lastResolvedOrigin over baseUrl", () => { resolveTelemetrySite({ auth: "apiKey", baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: false, }), ).toEqual({ site: "domestic", siteReason: "positive-domestic" }); }); +test("default model baseUrl is a fallback, not positive domestic", () => { + expect( + resolveTelemetrySite({ + auth: "openapi", + baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: true, + }), + ).toEqual({ site: "domestic", siteReason: "default-fallback" }); + + expect( + resolveTelemetrySite({ + auth: "apiKey", + baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: true, + }), + ).toEqual({ site: "domestic", siteReason: "default-fallback" }); + + expect( + resolveTelemetrySite({ + auth: "openapi", + baseUrl: "https://dashscope-intl.aliyuncs.com", + baseUrlIsDefault: false, + }), + ).toEqual({ site: "international", siteReason: "positive-international" }); +}); + test("openapi classifies model-domain baseUrl, not ACS hosts", () => { expect( resolveTelemetrySite({ auth: "openapi", baseUrl: "https://dashscope-intl.aliyuncs.com", + baseUrlIsDefault: false, }), ).toEqual({ site: "international", siteReason: "positive-international" }); @@ -89,6 +118,7 @@ test("openapi classifies model-domain baseUrl, not ACS hosts", () => { resolveTelemetrySite({ auth: "openapi", baseUrl: "https://modelstudio.ap-southeast-1.aliyuncs.com", + baseUrlIsDefault: false, }), ).toEqual({ site: "domestic", siteReason: "unknown-host" }); }); @@ -117,6 +147,7 @@ test("auth none ORs consoleSite with model host", () => { auth: "none", consoleSite: "international", baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: true, }), ).toEqual({ site: "international", siteReason: "positive-international" }); @@ -125,14 +156,25 @@ test("auth none ORs consoleSite with model host", () => { auth: "none", consoleSite: "domestic", baseUrl: "https://dashscope-intl.aliyuncs.com", + baseUrlIsDefault: false, }), ).toEqual({ site: "international", siteReason: "positive-international" }); + expect( + resolveTelemetrySite({ + auth: "none", + consoleSite: "domestic", + baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: true, + }), + ).toEqual({ site: "domestic", siteReason: "positive-domestic" }); + expect( resolveTelemetrySite({ auth: "none", lastResolvedOrigin: "https://ws.ap-southeast-1.maas.aliyuncs.com", baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: true, }), ).toEqual({ site: "international", siteReason: "positive-international" }); @@ -140,8 +182,17 @@ test("auth none ORs consoleSite with model host", () => { resolveTelemetrySite({ auth: "none", baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: false, }), ).toEqual({ site: "domestic", siteReason: "positive-domestic" }); + + expect( + resolveTelemetrySite({ + auth: "none", + baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: true, + }), + ).toEqual({ site: "domestic", siteReason: "default-fallback" }); }); test("mixed profile: console domestic does not force apiKey domestic", () => { diff --git a/packages/runtime/src/middleware.ts b/packages/runtime/src/middleware.ts index ed3dee499..8254be2c8 100644 --- a/packages/runtime/src/middleware.ts +++ b/packages/runtime/src/middleware.ts @@ -300,6 +300,7 @@ export const telemetryStage: Middleware = (ctx, next) => { consoleSite: ctx.settings.consoleSite, lastResolvedOrigin: ctx.client.lastResolvedOrigin, baseUrl: ctx.client.baseUrl, + baseUrlIsDefault: ctx.client.baseUrlIsDefault, }), }, ctx.path, diff --git a/packages/runtime/tests/telemetry-stage.test.ts b/packages/runtime/tests/telemetry-stage.test.ts index 5b7e9887b..d7205789b 100644 --- a/packages/runtime/tests/telemetry-stage.test.ts +++ b/packages/runtime/tests/telemetry-stage.test.ts @@ -80,6 +80,7 @@ test("resolveSite uses client lastResolvedOrigin and settings.consoleSite", asyn command: { auth: "apiKey" }, client: { baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: true, lastResolvedOrigin: "https://ws.ap-southeast-1.maas.aliyuncs.com", }, settings: { telemetry: true, consoleSite: "domestic" }, @@ -102,6 +103,7 @@ test("resolveSite for console auth ignores model baseUrl (D4=B)", async () => { command: { auth: "console" }, client: { baseUrl: "https://dashscope-intl.aliyuncs.com", + baseUrlIsDefault: false, lastResolvedOrigin: undefined, }, settings: { @@ -121,6 +123,29 @@ test("resolveSite for console auth ignores model baseUrl (D4=B)", async () => { }); }); +test("resolveSite treats default baseUrl as fallback", async () => { + const next = vi.fn(async () => {}); + const context = makeContext({ + command: { auth: "openapi" }, + client: { + baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: true, + lastResolvedOrigin: undefined, + }, + settings: { telemetry: true }, + }); + + await telemetryStage(context, next); + + const deps = trackerMocks.trackCommandExecution.mock.calls[0]![0] as { + resolveSite: () => { site: string; siteReason: string }; + }; + expect(deps.resolveSite()).toEqual({ + site: "domestic", + siteReason: "default-fallback", + }); +}); + test("defaults to unknown when caller env is unset", async () => { vi.stubEnv("BAILIAN_CALLER_TYPE", undefined); vi.stubEnv("BAILIAN_CALLER_NAME", undefined); From 1c7e88071291c4600b9837101f7e559323f73e25 Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Fri, 27 Nov 2026 09:55:49 +0800 Subject: [PATCH 4/6] fix(telemetry): attribute AEM site by product, not configured host --- docs/agents/telemetry-change.md | 64 ++-- packages/core/src/client/client.ts | 63 +++- packages/core/src/client/index.ts | 9 + packages/core/src/client/request-signals.ts | 74 +++++ packages/core/src/client/service-planes.ts | 116 ++++++++ packages/core/src/telemetry/event.ts | 13 + packages/core/src/telemetry/site.ts | 37 ++- packages/core/src/telemetry/tracker.ts | 3 + .../tests/client-last-resolved-origin.test.ts | 53 +++- .../tests/telemetry-service-planes.test.ts | 275 ++++++++++++++++++ packages/core/tests/telemetry-site.test.ts | 82 ++++++ packages/core/tests/telemetry-tracker.test.ts | 43 +++ packages/runtime/src/create-cli.ts | 5 + packages/runtime/src/middleware.ts | 8 + .../runtime/tests/telemetry-stage.test.ts | 29 ++ 15 files changed, 824 insertions(+), 50 deletions(-) create mode 100644 packages/core/src/client/request-signals.ts create mode 100644 packages/core/src/client/service-planes.ts create mode 100644 packages/core/tests/telemetry-service-planes.test.ts diff --git a/docs/agents/telemetry-change.md b/docs/agents/telemetry-change.md index 438bdac52..952e2e3f4 100644 --- a/docs/agents/telemetry-change.md +++ b/docs/agents/telemetry-change.md @@ -27,12 +27,12 @@ ### 1. 三套鉴权与埋点标识 -| 命令声明 | 凭证 / 请求域 | 主要请求出口 | 后端埋点标识 | 前端埋点标识(AEM) | -| ----------------- | --------------------------------------------------- | ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -| `auth: "apiKey"` | API Key;DashScope / OpenAI-compatible 模型域 | `Client.request/requestJson`、`McpClient`、Managed Agent / Advisor instrumented fetch、上传策略 | 有:`User-Agent`、`x-dashscope-source-config`、`X-Dashscope-Service: bailian-cli` | 有:按模型 host 分流 `bailian-cli-node` / `bailian-cli-node-intl`、`authMethod=apiKey` | -| `auth: "console"` | Console access token;Bailian Console Gateway | `callConsoleGateway()` → `/cli/api.json` | 有:Console Gateway 后端直接标识 | 有:按 `consoleSite` 分流 pid、`authMethod=console` | -| `auth: "openapi"` | AccessKey ID/Secret,可选 STS token;阿里云 OpenAPI | `Client.openApiJson()` | 有:`x-dashscope-source-config`、`X-Dashscope-Service: bailian-cli` | 有:按模型域 baseUrl 分流 pid、`authMethod=openapi`(不用 ACS host) | -| `auth: "none"` | 无凭证域 | 本地逻辑或命令自行管理的登录/配置流程 | 无 | 有:`consoleSite` ∨ 模型 host OR 分流、`authMethod=none` | +| 命令声明 | 凭证 / 请求域 | 主要请求出口 | 后端埋点标识 | 前端埋点标识(AEM) | +| ----------------- | --------------------------------------------------- | ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| `auth: "apiKey"` | API Key;DashScope / OpenAI-compatible 模型域 | `Client.request/requestJson`、`McpClient`、Managed Agent / Advisor instrumented fetch、上传策略 | 有:`User-Agent`、`x-dashscope-source-config`、`X-Dashscope-Service: bailian-cli` | 有:先按 service plane 产品归属、否则按模型 host 分流 `bailian-cli-node` / `bailian-cli-node-intl`、`authMethod=apiKey` | +| `auth: "console"` | Console access token;Bailian Console Gateway | `callConsoleGateway()` → `/cli/api.json` | 有:Console Gateway 后端直接标识 | 有:按 `consoleSite` 分流 pid、`authMethod=console` | +| `auth: "openapi"` | AccessKey ID/Secret,可选 STS token;阿里云 OpenAPI | `Client.openApiJson()` | 有:`x-dashscope-source-config`、`X-Dashscope-Service: bailian-cli` | 有:按模型域 baseUrl 分流 pid、`authMethod=openapi`(不用 ACS host) | +| `auth: "none"` | 无凭证域 | 本地逻辑或命令自行管理的登录/配置流程 | 无 | 有:service plane ∨ `consoleSite` ∨ 模型 host 分流、`authMethod=none` | `authMethod` 记录的是命令声明的鉴权域,不是凭证来源。它不会区分 API Key 来自 flag、env 还是 config。 鉴权域是命令的准入门槛和主请求域,不保证命令内部只有一种网络出口;例如部分 `apiKey` 命令也可能读取匿名 Console 公共目录,Managed Agent 还可能访问其他 provider。 @@ -158,22 +158,27 @@ mmstat 网关对任何 POST 都返回 `200` + GIF,端点或 pid 写错不会 国际站数据在 [AEM 新加坡站](https://sg.aem.alibaba-inc.com/) 查看;用 `aem` CLI 取数必须带 `--region sg`(AK 按 region 隔离存储),否则查的是 cn 租户 —— "查不到数据"不等于"埋点坏了"。 -判定(D4=B:console=账号站,模型=host/region): +判定(D4=B + 产品归属优先:console=账号站;其余先 service plane 产品归属,再模型 host/region): -| `auth` | 信号 | 国际条件 | 缺省 | -| -------------------- | ------------------------------------------------------------- | ---------------------------------------- | -------------------------------------------------------------------------------------------- | -| `console` | `settings.consoleSite`(不看 `consoleRegion`) | `international` | 未设置 → domestic + `default-fallback`;显式 `domestic` → `positive-domestic` | -| `apiKey` / `openapi` | `Client.lastResolvedOrigin` 优先,否则非默认 `client.baseUrl` | 已知国际 host/region(含 `cn-hongkong`) | 无有效 host / `baseUrlIsDefault` → domestic + `default-fallback`;未知 host → `unknown-host` | -| `none` | consoleSite **或** 模型 host(OR) | 任一侧国际 | 同上两侧兜底 | +| `auth` | 信号 | 国际条件 | 缺省 | +| ------------------------------------------ | ------------------------------------------------------------- | ---------------------------------------------- | -------------------------------------------------------------------------------------------- | +| **任意(`console` 除外,优先于下面各行)** | `Client.productSite`(`service-planes.ts` 产品声明) | 声明 `international` → `product-international` | 声明 `domestic` → `product-domestic`;无声明(`follow` 面、纯模型域)→ 落到下面各行 | +| `console` | `settings.consoleSite`(不看 `consoleRegion`) | `international` | 未设置 → domestic + `default-fallback`;显式 `domestic` → `positive-domestic` | +| `apiKey` / `openapi` | `Client.lastResolvedOrigin` 优先,否则非默认 `client.baseUrl` | 已知国际 host/region(含 `cn-hongkong`) | 无有效 host / `baseUrlIsDefault` → domestic + `default-fallback`;未知 host → `unknown-host` | +| `none` | consoleSite **或** 模型 host(OR) | 任一侧国际 | 同上两侧兜底 | - `siteReason`:`positive-*` 仅表示有明确信号(显式 consoleSite / 非默认 model host / `lastResolvedOrigin`);内置默认 `baseUrl`(`baseUrlIsDefault`)不计为 positive,走 `default-fallback`。 - 模型 host 分类清单上收在 `packages/core/src/config/model-endpoints.ts`(与 API Key 登录候选共用);`site.ts` 只调用 helper,禁止再写第四份。 -- `lastResolvedOrigin` 仅在 `Client.url()` / upload 的 `defaultBaseUrl` 回调路径记录;主流量仍靠 `baseUrl`。runtime **禁止**泛化读取各命令 `flags.region`。 +- `lastResolvedOrigin` 记录**每一次实际请求**的 origin:`Client.url()` / upload 的 `defaultBaseUrl` 回调,以及 `request` / `requestJson` 收到的绝对 URL 与相对 `path`(#349 的漏记点正是绝对 URL 没记)。origin 与 `baseUrl` 同 host 时不算额外信号,内置默认仍走 `default-fallback`。runtime **禁止**泛化读取各命令 `flags.region`。 +- 产品归属表在 `packages/core/src/client/service-planes.ts`,按请求 pathname 命名空间识别,且只覆盖 CLI 自己构造的绝对 URL:`domestic` = 出口固定在国内、用户无法覆盖的面(RAG admin 面 / knowledge search+chat / memory / 公共 DashScope 定制模型导入);`follow` = 允许 `--base-url` 或 region 覆盖的面(ParseX / AgentStudio sandbox+security / 模型域),由实际 host 判定。**新增绝对 URL 出口必须同步该表**,漂移守卫见 `packages/core/tests/telemetry-service-planes.test.ts`。 +- `siteReason` 新增 `product-domestic` / `product-international`:归属来自产品声明,不是用户配置;`positive-*` 继续只表示用户侧信号。 +- 记录对象 `RequestSignals` 每次命令运行创建一份,由 `authStage` 注入 `ClientDeps`;`Client.withConsoleSwitchAgent()` 派生的新 Client 继承同一份,否则内层请求对外层 telemetry 不可见。 +- **dry-run 没有产品归属信号**:`--dry-run` 在拼出 endpoint 后就 `output.result` 返回,不经过 `request` / `requestJson` / `url()`,`RequestSignals` 为空,站点只能由用户配置的 `baseUrl` 决定。所以国际 baseUrl 下 `bl knowledge list --dry-run` 报 `international`,尽管它预览的是北京 workspace 出口。这类事件由 `dryRun=true` 标出:在国内-only 的 family(knowledge / memory / cmodel)里,`dryRun=true`、或 `siteReason` 不是 `product-*`,都说明**这条不是真实调用量**,不能读成「国际站对该产品有需求」。`follow` 面(ParseX / Sandbox / Security / 模型域)的 dry-run 按 baseUrl 判本来就是正确口径,不在此列。 - openapi **禁止**用 ACS `opts.host` 分类。 - `remoteSink` 按 site 使用 keyed `Map` 持有 Tracker;同进程可同时存在国内与国际实例。`uid` / tracker `device_id` **跨站同值**。 - vendored tracker 仅保留本仓对 `send` 的本地改造(登记于此);国际 path 与国内同为 `/aes.1.1`,**不加** `endpointPath` patch。升级 SDK 时必须保留 `send` 改造。 - 看板元数据还没跟上:`site` / `siteReason` 两站都未建自定义维度;`callerType` / `callerName` / `cliVersion` / `cliVersionCode` / `commandPrefix` 国内项目有、国际项目一个都没有。数据已经在 `ext` 里,但国际站要做筛选/聚合(含 Agent 调用率、入口区分)必须先补这些维度。 -- 已知残留:未知/反代 host、残缺配置、登录写盘前首条 `none`、managed-agent 外部拼 host、旧版 CLI、账号站与模型地域混维拆站、`first_install` 固定报国内站(安装阶段没有 auth / Client 上下文)。 +- 已知残留:未知/反代 host、残缺配置、登录写盘前首条 `none`、managed-agent 外部拼 host、旧版 CLI、账号站与模型地域混维拆站、`first_install` 固定报国内站(安装阶段没有 auth / Client 上下文)、pipeline 步骤的 Client 未注入 `RequestSignals`(`packages/runtime/src/pipeline/bl-config.ts`,步骤请求不进命令事件)、`mcp --url` 覆盖时记录的是默认 httpUrl 而非实际目标、**国内-only family 的 dry-run 事件按用户 baseUrl 归站**(见上条,用 `dryRun` 字段剔除)。 编译二进制的 `env=prod` 由 `BAILIAN_COMPILED=1` 决定,并且必须先于 `NODE_ENV`。`bun build --compile`(当前 pin 1.3.14)会把点访问 `process.env.NODE_ENV` 内联成构建机的值,未设置时是 `"development"`;`tools/release/lib/binary-compile.mjs` 同时 `--define process.env.NODE_ENV="production"`。这两处读取必须写成 `process.env.*`,包进别的变量后 `--define` 匹配不到。 @@ -199,19 +204,19 @@ mmstat 网关对任何 POST 都返回 `200` + GIF,端点或 pid 写错不会 AEM 映射: -| AEM 字段 | 内容 | -| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| event name | 命令路径 | -| `et` | `EXP` | -| `ext` | 除 `command`、`params` 外的结构化事件字段,含 `commandPrefix`、`callerType`、`site`、可选 `siteReason`、失败时的 `exitCode`,以及读到的 `installChannel`。安装日不在命令事件里 | -| `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`、`site`、可选 `siteReason`、可选 `dryRun`(仅 `--dry-run` 时为 `true`)、失败时的 `exitCode`,以及读到的 `installChannel`。安装日不在命令事件里 | +| `c1` | allowlist 参数 | +| `c2` | `success` / `failure` | +| `c3` | HTTP status | +| `c4` | 错误文案,最多 500 字符 | +| `c5` | request ID | +| `c6` | `bizFrom` 业务来源(全局 `--biz-from`,归一化标量;专用扁平列,直接筛选/分组) | -`siteReason` 为粗粒度枚举(`positive-domestic` / `positive-international` / `default-fallback` / `unknown-host`),**禁止**带原始 host。漏判量化用国内站 `siteReason` 兜底类占比;不要用「国内 pid 出现 `site=international`」做告警(国际事件不会进国内 pid)。 +`siteReason` 为粗粒度枚举(`product-domestic` / `product-international` / `positive-domestic` / `positive-international` / `default-fallback` / `unknown-host`),**禁止**带原始 host。`product-*` 表示归属来自产品声明,`positive-*` 表示来自用户配置信号,两者不能混算。漏判量化用国内站 `siteReason` 兜底类占比;不要用「国内 pid 出现 `site=international`」做告警(国际事件不会进国内 pid)。 远端发送是 best-effort,不得阻塞命令或改变退出码。正常退出最多等待 1 秒,SIGINT 最多等待 500 ms。 @@ -255,8 +260,9 @@ AEM 映射: ```sh rg -n "trackingHeaders|x-dashscope-source-config|User-Agent" packages --glob '*.ts' rg -n "trackCommandExecution|PARAM_ALLOWLIST|buildRemoteAemOptions|readCaller|resolveTelemetrySite|classifyModelHost" packages/core packages/runtime --glob '*.ts' +rg -n "classifyServicePlane|productSiteOf|createRequestSignals|requestSignals" packages/core packages/runtime --glob '*.ts' vp check -vp test packages/core/tests/telemetry-uid.test.ts packages/core/tests/telemetry-sink.test.ts packages/core/tests/telemetry-tracker.test.ts packages/core/tests/telemetry-send.test.ts packages/core/tests/telemetry-site.test.ts packages/core/tests/client-last-resolved-origin.test.ts packages/runtime/tests/telemetry-stage.test.ts packages/commands/tests/e2e/auth.e2e.test.ts +vp test packages/core/tests/telemetry-uid.test.ts packages/core/tests/telemetry-sink.test.ts packages/core/tests/telemetry-tracker.test.ts packages/core/tests/telemetry-send.test.ts packages/core/tests/telemetry-site.test.ts packages/core/tests/telemetry-service-planes.test.ts packages/core/tests/client-last-resolved-origin.test.ts packages/runtime/tests/telemetry-stage.test.ts packages/commands/tests/e2e/auth.e2e.test.ts ``` ## 常见漏点 @@ -270,6 +276,10 @@ vp test packages/core/tests/telemetry-uid.test.ts packages/core/tests/telemetry- - ✗ 把帮助、版本或参数校验失败算进“全部命令”;这些路径当前没有进入 telemetry middleware - ✗ 把 `NODE_ENV` 判断放在 `BAILIAN_COMPILED` 前面。Bun 编译会把 `process.env.NODE_ENV` 折成 `"development"`,二进制流量全部进 `env=dev`,生产看板为空 - ✗ 在 runtime 里泛化读取 `flags.region` 做站点判定;必须用 `baseUrl` / `lastResolvedOrigin` / `consoleSite` +- ✗ 新增绝对 URL 出口(workspace 网关、硬编码公共 host)却没登记 `service-planes.ts`,产品归属静默丢失——#349 的 bug 类 +- ✗ 把国内-only 产品的站点归到用户配置的模型域名上;判定顺序是产品声明 → 实际 host → baseUrl +- ✗ 把允许 `--base-url` / region 覆盖的面声明成 `domestic`,等于替用户否认他显式选择的海外站点 - ✗ 用 openapi ACS host 或「非 cn- 前缀」推断国际站(`cn-hongkong` 是国际) - ✗ 把 AEM 分流叙事写成「国际数据绝不出境」硬保证;实际是 best-effort 声明口径 +- ✗ 把国内-only family 里 `dryRun=true`(或 `siteReason` 非 `product-*`)的事件算进真实调用量,进而误判国际站产品需求 - ✗ 升级 vendored AEM tracker 时丢掉本仓 `send` 改造 diff --git a/packages/core/src/client/client.ts b/packages/core/src/client/client.ts index 88cb79479..a161923c1 100644 --- a/packages/core/src/client/client.ts +++ b/packages/core/src/client/client.ts @@ -17,6 +17,8 @@ import { ConsoleSession } from "./console-session.ts"; import { debugRequest, debugResponse } from "./diagnostics.ts"; import { getApiKeyLoginKind } from "../config/profile-presets.ts"; import { trackingHeaders } from "./headers.ts"; +import type { ProductSite } from "./service-planes.ts"; +import { createRequestSignals, type RequestSignals } from "./request-signals.ts"; /** Client 的结构化依赖:身份 + 有效配置 + 各域凭证(按命令的 auth 注入)。 */ export interface ClientDeps { @@ -27,6 +29,12 @@ export interface ClientDeps { baseUrl: string; /** True only when the shared URL chain used its default; explicit origins win over service defaults. */ baseUrlIsDefault?: boolean; + /** + * Per-run record of the origins and service planes this command actually + * touched. Shared by reference with derived Clients, so a request made + * through a copy is never invisible to the outer telemetry stage. + */ + requestSignals?: RequestSignals; apiCred?: ApiKeyCredential; consoleCred?: ConsoleCredential; /** Lazily resolve AK/SK only when the Console token is missing or expired. */ @@ -77,11 +85,14 @@ export interface OpenApiResponse { */ export class Client { private consoleSession: ConsoleSession; - /** Last origin from url()/upload defaultBaseUrl resolution (telemetry only). */ - private recordedOrigin: string | undefined; + private readonly requestSignals: RequestSignals; constructor(private readonly deps: ClientDeps) { this.consoleSession = new ConsoleSession(deps); + // Callers that do not track attribution (installer, embedded SDK adapters, + // tests) still get a coherent private record. The per-run record injected + // by authStage is preferred, because derived Clients must share it. + this.requestSignals = deps.requestSignals ?? createRequestSignals(); } private get http(): HttpDeps { @@ -116,20 +127,32 @@ export class Client { } /** - * Origin last selected by {@link url} / upload defaultBaseUrl callbacks. - * Used by telemetry site routing; undefined when no valid origin was recorded. + * Origin last used by this command run. + * + * Recorded for every request URL, including the absolute URLs commands pass + * as `path` (RAG admin plane, memory, ParseX, AgentStudio). Before those were + * recorded, site routing fell back to the shared model base URL and + * attributed those products to whatever host the user had configured. + * Overwritten per request, so a multi-origin run reports the origin actually + * used last rather than the first-seen one. Used by telemetry only; undefined + * when nothing valid was recorded. */ get lastResolvedOrigin(): string | undefined { - return this.recordedOrigin; + return this.requestSignals.lastOrigin(); } - private rememberResolvedOrigin(baseUrl: string): void { - try { - const origin = new URL(baseUrl).origin; - if (origin && origin !== "null") this.recordedOrigin = origin; - } catch { - // Invalid or empty callback origins (e.g. managed-agent) are ignored. - } + /** + * Product verdict from the fixed service planes this run touched (telemetry + * only). Undefined when the run touched only `follow` planes or made no + * recorded request. + */ + get productSite(): ProductSite | undefined { + return this.requestSignals.productSite(); + } + + /** Note where a request actually went. Best-effort and never throws. */ + private recordRequest(requestUrl: string): void { + this.requestSignals.record(requestUrl); } /** @@ -162,15 +185,21 @@ export class Client { */ url(path: string, defaultBaseUrl?: () => string): string { const baseUrl = this.deps.baseUrlIsDefault && defaultBaseUrl ? defaultBaseUrl() : this.baseUrl; - this.rememberResolvedOrigin(baseUrl); - return baseUrl + path; + const requestUrl = baseUrl + path; + this.recordRequest(requestUrl); + return requestUrl; } private toOpts({ path, ...rest }: ClientRequestOpts): RequestOpts { const cred = this.requireApi(); + const requestUrl = /^https?:\/\//.test(path) ? path : cred.baseUrl + path; + // An absolute `path` is a real per-command choice, so record it exactly + // like a URL built through {@link url}; otherwise the request's own origin + // is lost and telemetry classifies the product by the shared base URL. + this.recordRequest(requestUrl); return { ...rest, - url: /^https?:\/\//.test(path) ? path : cred.baseUrl + path, + url: requestUrl, headers: { ...rest.headers, Authorization: `Bearer ${cred.token}` }, }; } @@ -276,6 +305,10 @@ export class Client { withConsoleSwitchAgent(switchAgent: number): Client { const client = new Client({ ...this.deps, + // Always inherit the parent's record — including a private one — so the + // requests this derived Client makes stay visible to whoever reads the + // parent's attribution (the outer telemetry stage). + requestSignals: this.requestSignals, settings: { ...this.deps.settings, consoleSwitchAgent: switchAgent }, }); client.consoleSession = this.consoleSession.withSwitchAgent(switchAgent); diff --git a/packages/core/src/client/index.ts b/packages/core/src/client/index.ts index 4490f8a79..844d2de4c 100644 --- a/packages/core/src/client/index.ts +++ b/packages/core/src/client/index.ts @@ -95,6 +95,15 @@ export { type ClientOpenApiQueryOpts, type ClientOpenApiJsonOpts, } from "./client.ts"; +export { + SERVICE_PLANES, + classifyServicePlane, + productSiteOf, + type PlaneSite, + type ProductSite, + type ServicePlane, +} from "./service-planes.ts"; +export { createRequestSignals, type RequestSignals } from "./request-signals.ts"; export { createBailianControlUser, listBailianControlWorkspaces, diff --git a/packages/core/src/client/request-signals.ts b/packages/core/src/client/request-signals.ts new file mode 100644 index 000000000..62c09fbd0 --- /dev/null +++ b/packages/core/src/client/request-signals.ts @@ -0,0 +1,74 @@ +import { + classifyServicePlane, + productSiteOf, + type ProductSite, + type ServicePlane, +} from "./service-planes.ts"; + +/** + * Bound the distinct-origin list so a pathological retry loop cannot grow it + * without limit. Only the debug/inspection list is capped — `lastOrigin` and + * the plane verdict are always kept up to date. + */ +const MAX_RECORDED_ORIGINS = 8; + +/** + * Mutable record of the network surfaces one command run actually touched. + * + * Created once per run and handed to every `Client` through `ClientDeps` **by + * reference**, so Clients derived from another one keep writing into the same + * record — `Client.withConsoleSwitchAgent()` builds a new `Client`, and the + * outer telemetry stage only ever reads the one attached to the run context. + * Without a shared record that derived client's origins were invisible, which + * is the same class of silent misattribution as passing an absolute URL + * through `request({ path })` without recording it. + */ +export interface RequestSignals { + /** Distinct origins in first-seen order, capped for inspection only. */ + readonly origins: readonly string[]; + /** Distinct service planes touched, in first-seen order. */ + readonly planes: readonly ServicePlane[]; + /** Best-effort: never throws, ignores anything without a valid origin. */ + record(requestUrl: string): void; + /** + * Origin of the most recent recorded request, overwritten on every record. + * Kept separate from the capped `origins` list so a long multi-origin run + * cannot hide the origin that actually decides the site. + */ + lastOrigin(): string | undefined; + /** Product verdict from the fixed service planes touched so far. */ + productSite(): ProductSite | undefined; +} + +export function createRequestSignals(): RequestSignals { + const origins = new Set(); + const planes = new Set(); + let lastOrigin: string | undefined; + return { + get origins(): readonly string[] { + return [...origins]; + }, + get planes(): readonly ServicePlane[] { + return [...planes]; + }, + record(requestUrl: string): void { + let origin: string; + try { + origin = new URL(requestUrl).origin; + } catch { + return; + } + if (!origin || origin === "null") return; + lastOrigin = origin; + if (origins.has(origin) || origins.size < MAX_RECORDED_ORIGINS) origins.add(origin); + const plane = classifyServicePlane(requestUrl); + if (plane) planes.add(plane); + }, + lastOrigin(): string | undefined { + return lastOrigin; + }, + productSite(): ProductSite | undefined { + return productSiteOf(planes); + }, + }; +} diff --git a/packages/core/src/client/service-planes.ts b/packages/core/src/client/service-planes.ts new file mode 100644 index 000000000..cdc92fe5b --- /dev/null +++ b/packages/core/src/client/service-planes.ts @@ -0,0 +1,116 @@ +/** + * Service-plane attribution table for telemetry site routing. + * + * The reporting site follows the **product**, not the domain the user happened + * to configure: a plane the CLI only ever serves from the mainland workspace + * gateway is domestic even when `DASHSCOPE_BASE_URL` points at an + * international host (issue #349). Planes marked `follow` carry no product + * verdict — there the resolved host decides, which is the pre-existing + * behaviour for the shared model gateway and for planes that honour an + * explicit base URL override. + * + * This table is classification only. It must never influence which URL a + * command requests; endpoint routing stays owned by `endpoints.ts`. + * + * Invariant: classification looks at the request pathname only, never the + * host. That is sound because every plane below is reached through an absolute + * URL the CLI builds itself — `workspaceEndpoint()` pins the mainland workspace + * host, and the custom-model import endpoint hardcodes the public mainland host + * — so no command can put one of these paths on another origin. The guard test + * in `tests/telemetry-service-planes.test.ts` keeps that true. A plane whose + * host a user may override (`--base-url`, region flags) is therefore declared + * `follow`, not `domestic`. + */ + +export type PlaneSite = "domestic" | "international" | "follow"; + +/** Plane sites that carry a product verdict. */ +export type ProductSite = Exclude; + +export interface ServicePlane { + /** Stable identifier; consumed by the coverage guard test and the telemetry docs. */ + key: string; + site: PlaneSite; + /** Request pathname prefixes, matched longest-first. */ + prefixes: readonly string[]; +} + +export const SERVICE_PLANES: readonly ServicePlane[] = [ + { + key: "rag-workspace", + // Knowledge base admin plane, data center, knowledge search and knowledge + // chat. `workspaceEndpoint()` pins these to + // .cn-beijing.maas.aliyuncs.com and ignores the configured base + // URL entirely, so the product is domestic by construction. Flip this to + // "follow" if the plane ever ships outside the mainland. + site: "domestic", + prefixes: ["/api/v1/indices/", "/api/v1/connector/", "/api/v2/apps/knowledge/"], + }, + { + key: "memory", + // Long-term memory v2 shares the mainland workspace gateway. + site: "domestic", + prefixes: ["/api/v2/apps/memory/"], + }, + { + key: "parsex", + // Defaults to the mainland workspace host, but --base-url / + // DASHSCOPE_BASE_URL is an explicit supported override, so the host in use + // decides. + site: "follow", + prefixes: ["/api/v2/apps/parse-x/", "/api/v2/apps/pre-parse-x/"], + }, + { + key: "agentstudio", + // AgentStudio control planes (sandbox, security center, workspace files) + // default to the mainland workspace host and accept a --base-url override. + site: "follow", + prefixes: ["/api/v1/agentstudio/"], + }, + { + key: "custom-model-import", + // `CUSTOM_MODEL_IMPORT_ENDPOINT` hardcodes the public mainland DashScope + // host because workspace hosts answer HTTP 404 for this API family. The + // product is mainland-only even when the credential's base URL is + // international, so the verdict comes from the product, not the host. + site: "domestic", + prefixes: ["/api/v1/custom_models/"], + }, +]; + +// Longest prefix first so a specific namespace wins over a broader one. +const PREFIX_ENTRIES = SERVICE_PLANES.flatMap((plane) => + plane.prefixes.map((prefix) => ({ prefix, plane })), +).sort((left, right) => right.prefix.length - left.prefix.length); + +/** + * Identify the service plane a request URL belongs to. Total function: an + * unparseable URL or a path outside the table returns undefined, which means + * "no product verdict" — never an error, because telemetry must not be able to + * break a business request. + */ +export function classifyServicePlane(requestUrl: string): ServicePlane | undefined { + let pathname: string; + try { + pathname = new URL(requestUrl).pathname; + } catch { + return undefined; + } + return PREFIX_ENTRIES.find((entry) => pathname.startsWith(entry.prefix))?.plane; +} + +/** + * Product verdict for the planes a command touched. Fixed planes decide the + * site and `follow` planes contribute nothing. If two fixed planes ever + * disagree, domestic wins — the same conservative default the host classifier + * already uses for unknown hosts. + */ +export function productSiteOf(planes: Iterable): ProductSite | undefined { + const verdicts = new Set(); + for (const plane of planes) { + if (plane.site !== "follow") verdicts.add(plane.site); + } + if (verdicts.has("domestic")) return "domestic"; + if (verdicts.has("international")) return "international"; + return undefined; +} diff --git a/packages/core/src/telemetry/event.ts b/packages/core/src/telemetry/event.ts index b29fb9e3c..6b3f0291c 100644 --- a/packages/core/src/telemetry/event.ts +++ b/packages/core/src/telemetry/event.ts @@ -33,6 +33,14 @@ export interface TrackingEvent { site: TelemetrySite; /** Coarse site resolution reason; never includes raw hosts. */ siteReason?: TelemetrySiteReason; + /** + * The run was a `--dry-run` preview, so it sent no business request and + * recorded no request origin or service plane. Sparse — only reported when + * true. This is what separates preview events from real calls: a real call's + * site comes from the product it touched, a preview's can only come from the + * configured base URL. + */ + dryRun?: true; } export function createTrackingEvent(opts: { @@ -49,6 +57,7 @@ export function createTrackingEvent(opts: { bizFrom?: string; site?: TelemetrySite; siteReason?: TelemetrySiteReason; + dryRun?: boolean; }): TrackingEvent { const event: TrackingEvent = { command: opts.command, @@ -98,6 +107,10 @@ export function createTrackingEvent(opts: { event.siteReason = opts.siteReason; } + if (opts.dryRun) { + event.dryRun = true; + } + return event; } diff --git a/packages/core/src/telemetry/site.ts b/packages/core/src/telemetry/site.ts index 00da429d4..980ee0c1e 100644 --- a/packages/core/src/telemetry/site.ts +++ b/packages/core/src/telemetry/site.ts @@ -5,6 +5,8 @@ export type TelemetrySite = "domestic" | "international"; /** Coarse reason for site resolution; never includes raw hosts. */ export type TelemetrySiteReason = + | "product-domestic" + | "product-international" | "positive-domestic" | "positive-international" | "default-fallback" @@ -18,7 +20,13 @@ export interface TelemetrySiteResolution { export interface ResolveTelemetrySiteInput { auth: AuthRequirement; consoleSite?: "domestic" | "international"; - /** Origin recorded from Client.url() / upload defaultBaseUrl paths. */ + /** + * Site declared by the product(s) the command actually called — the + * service-plane table, not anything the user configured. For every non-console + * auth domain this outranks all host-derived signals. + */ + productSite?: TelemetrySite; + /** Origin of the last recorded request (Client.url(), upload, absolute paths). */ lastResolvedOrigin?: string; /** Model-domain base URL (or its host). */ baseUrl?: string; @@ -50,8 +58,12 @@ export function telemetryRemoteTarget(site: TelemetrySite): TelemetryRemoteTarge } /** - * Resolve AEM reporting site (D4=B): console → consoleSite; - * apiKey/openapi → model host/region; none → OR of both. + * Resolve the AEM reporting site. The product decides first: a service plane + * the CLI only ever serves domestically reports domestic no matter which base + * URL is configured (issue #349). Console keeps the account-site axis because + * for that gateway the account site *is* the product site. Only when there is + * no product verdict do user-side signals decide: consoleSite for console, + * model host/region for apiKey/openapi, OR of both for none. */ export function resolveTelemetrySite(input: ResolveTelemetrySiteInput): TelemetrySiteResolution { if (input.auth === "console") { @@ -64,6 +76,13 @@ export function resolveTelemetrySite(input: ResolveTelemetrySiteInput): Telemetr return { site: "domestic", siteReason: "default-fallback" }; } + if (input.productSite) { + return { + site: input.productSite, + siteReason: input.productSite === "domestic" ? "product-domestic" : "product-international", + }; + } + if (input.auth === "apiKey" || input.auth === "openapi") { return classifyFromModelOrigin(input); } @@ -83,10 +102,14 @@ export function resolveTelemetrySite(input: ResolveTelemetrySiteInput): Telemetr } function classifyFromModelOrigin(input: ResolveTelemetrySiteInput): TelemetrySiteResolution { - // lastResolvedOrigin is a real per-command choice and wins over the shared base URL. - const host = - hostnameOf(input.lastResolvedOrigin) ?? - (input.baseUrlIsDefault ? undefined : hostnameOf(input.baseUrl)); + const baseHost = hostnameOf(input.baseUrl); + const originHost = hostnameOf(input.lastResolvedOrigin); + // A recorded origin that is simply the shared base URL carries no signal + // beyond `baseUrl`, so it must not promote a built-in default into a positive + // user choice. Only a *different* origin — an absolute workspace URL or a + // service-supplied default — outranks the base URL here. + const distinctOriginHost = originHost && originHost !== baseHost ? originHost : undefined; + const host = distinctOriginHost ?? (input.baseUrlIsDefault ? undefined : baseHost); if (!host) { return { site: "domestic", siteReason: "default-fallback" }; } diff --git a/packages/core/src/telemetry/tracker.ts b/packages/core/src/telemetry/tracker.ts index 4353339bc..a12d92148 100644 --- a/packages/core/src/telemetry/tracker.ts +++ b/packages/core/src/telemetry/tracker.ts @@ -231,6 +231,9 @@ export async function trackCommandExecution( bizFrom: normalizeBizFrom(deps.settings.bizFrom), site: siteResolution.site, siteReason: siteResolution.siteReason, + // Read from settings, not flags: `--dry-run` is a global flag, so it + // never reaches `extractParams` (global flags are skipped there). + dryRun: deps.settings.dryRun, }); // The install day is reported when install succeeds, not from this command. diff --git a/packages/core/tests/client-last-resolved-origin.test.ts b/packages/core/tests/client-last-resolved-origin.test.ts index 4906d9b73..763ba13bd 100644 --- a/packages/core/tests/client-last-resolved-origin.test.ts +++ b/packages/core/tests/client-last-resolved-origin.test.ts @@ -1,5 +1,6 @@ -import { expect, test } from "vite-plus/test"; +import { afterEach, expect, test, vi } from "vite-plus/test"; import { Client } from "../src/client/client.ts"; +import { httpTransport } from "../src/client/transport.ts"; import type { Identity, Settings } from "../src/config/schema.ts"; const identity: Identity = { @@ -11,6 +12,8 @@ const identity: Identity = { const settings = { telemetry: true, timeout: 30 } as Settings; +afterEach(() => vi.restoreAllMocks()); + test("url records lastResolvedOrigin for defaultBaseUrl callbacks", () => { const client = new Client({ identity, @@ -81,3 +84,51 @@ test("uploadFile path records origin via url()", async () => { client.url("", () => "https://ws.cn-hongkong.maas.aliyuncs.com"); expect(client.lastResolvedOrigin).toBe("https://ws.cn-hongkong.maas.aliyuncs.com"); }); + +/** + * Issue #349: commands on the workspace gateway pass an absolute URL as `path` + * instead of going through url(), so that origin used to disappear and site + * routing fell back to the shared model base URL. + */ +test("requestJson records the origin of an absolute path", async () => { + const transport = vi.spyOn(httpTransport, "fetch").mockResolvedValue(Response.json({ ok: true })); + const client = new Client({ + identity, + settings, + baseUrl: "https://dashscope-intl.aliyuncs.com", + baseUrlIsDefault: false, + apiCred: { + token: "sk-test", + baseUrl: "https://dashscope-intl.aliyuncs.com", + source: "config", + }, + }); + + await client.requestJson({ + path: "https://ws-review.cn-beijing.maas.aliyuncs.com/api/v1/indices/rag/index/list", + method: "GET", + }); + + expect(transport).toHaveBeenCalledOnce(); + expect(client.lastResolvedOrigin).toBe("https://ws-review.cn-beijing.maas.aliyuncs.com"); +}); + +test("relative paths record the credential origin they are prepended with", async () => { + const transport = vi.spyOn(httpTransport, "fetch").mockResolvedValue(Response.json({ ok: true })); + const client = new Client({ + identity, + settings, + baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: false, + apiCred: { + token: "sk-test", + baseUrl: "https://dashscope.aliyuncs.com", + source: "config", + }, + }); + + await client.requestJson({ path: "/api/v1/tasks/task-one", method: "GET" }); + + expect(transport).toHaveBeenCalledOnce(); + expect(client.lastResolvedOrigin).toBe("https://dashscope.aliyuncs.com"); +}); diff --git a/packages/core/tests/telemetry-service-planes.test.ts b/packages/core/tests/telemetry-service-planes.test.ts new file mode 100644 index 000000000..1dc853760 --- /dev/null +++ b/packages/core/tests/telemetry-service-planes.test.ts @@ -0,0 +1,275 @@ +import { afterEach, expect, test, vi } from "vite-plus/test"; +import { + RAG_PATHS, + SANDBOX_PATHS, + agentStudioHost, + chatPath, + classifyServicePlane, + classifyModelHost, + createRequestSignals, + httpTransport, + knowledgeChatEndpoint, + knowledgeSearchEndpoint, + memoryAddAsyncPath, + memoryEndpoint, + memoryEventPath, + memoryListPath, + memoryNodePath, + memorySearchPath, + memorySkillExportPath, + parsexBaseUrl, + parsexEndpoint, + productSiteOf, + profileSchemaPath, + ragEndpoint, + sandboxEndpoint, + securityOverviewEndpoint, + SERVICE_PLANES, + userProfilePath, + Client, + type Identity, + type ServicePlane, + type Settings, +} from "../src/index.ts"; +// The custom-model import builders are internal to core (only model-import/api.ts +// uses them), so they are not part of the package index. +import { + customModelImportEndpoint, + customModelImportJobEndpoint, +} from "../src/client/endpoints.ts"; +import { resolveTelemetrySite } from "../src/telemetry/site.ts"; + +afterEach(() => vi.restoreAllMocks()); + +const identity: Identity = { + binName: "bl", + version: "0.0.0-test", + clientName: "bailian-cli-test", + npmPackage: "bailian-cli", +}; +const workspaceId = "ws-review"; + +function makeClient(baseUrl: string): Client { + return new Client({ + identity, + settings: { telemetry: true, timeout: 30 } as Settings, + baseUrl, + baseUrlIsDefault: false, + apiCred: { token: "sk-test", baseUrl, source: "config" }, + }); +} + +/** + * Drift guard: every absolute URL the CLI builds for a mainland-only or + * overridable service plane must resolve to a known plane, and a plane + * declared `domestic` must only ever be emitted on a mainland host. A new + * workspace-scoped endpoint missing from the table silently loses its product + * attribution, which is exactly the bug class of issue #349. + */ +test("every RAG admin-plane path maps to the domestic rag-workspace plane", () => { + for (const [name, path] of Object.entries(RAG_PATHS)) { + const plane = classifyServicePlane(ragEndpoint(workspaceId, path)); + expect(plane?.key, `RAG_PATHS.${name} ${path}`).toBe("rag-workspace"); + expect(plane?.site, `RAG_PATHS.${name} ${path}`).toBe("domestic"); + } +}); + +test("knowledge search and chat map to the domestic rag-workspace plane", () => { + expect(classifyServicePlane(knowledgeSearchEndpoint(workspaceId))?.key).toBe("rag-workspace"); + expect(classifyServicePlane(knowledgeChatEndpoint(workspaceId))?.key).toBe("rag-workspace"); +}); + +test("memory endpoints map to the domestic memory plane", () => { + const memoryPaths = [ + memoryAddAsyncPath(), + memoryEventPath("event-one"), + memorySearchPath(), + memoryListPath(), + memoryNodePath("node-one"), + memorySkillExportPath("node-one"), + profileSchemaPath(), + userProfilePath("schema-one"), + ]; + for (const path of memoryPaths) { + const plane = classifyServicePlane(memoryEndpoint(workspaceId, path)); + expect(plane?.key, path).toBe("memory"); + expect(plane?.site, path).toBe("domestic"); + } +}); + +test("overridable planes carry no product verdict", () => { + // A bare origin has no service path, so it carries no verdict at all. + expect(classifyServicePlane(parsexBaseUrl(workspaceId))).toBeUndefined(); + expect( + classifyServicePlane(parsexEndpoint(parsexBaseUrl(workspaceId), "parse", "submit"))?.key, + ).toBe("parsex"); + expect( + classifyServicePlane( + parsexEndpoint("https://ws.cn-beijing.pre-maas.aliyuncs.com", "extract", "result"), + )?.key, + ).toBe("parsex"); + // Prefixes are path-segment bounded, so a sibling namespace stays unmapped. + expect( + classifyServicePlane("https://ws.cn-beijing.maas.aliyuncs.com/api/v2/apps/parse-xfoo"), + ).toBeUndefined(); + expect(classifyServicePlane(sandboxEndpoint(workspaceId, SANDBOX_PATHS.sandboxList))?.key).toBe( + "agentstudio", + ); + expect(classifyServicePlane(securityOverviewEndpoint(agentStudioHost(workspaceId)))?.key).toBe( + "agentstudio", + ); + for (const key of ["parsex", "agentstudio"]) { + expect(SERVICE_PLANES.find((plane) => plane.key === key)?.site).toBe("follow"); + } +}); + +test("custom model import maps to the domestic plane", () => { + expect(classifyServicePlane(customModelImportEndpoint())?.key).toBe("custom-model-import"); + expect(classifyServicePlane(customModelImportJobEndpoint("job-one"))?.site).toBe("domestic"); +}); + +/** + * Pathname-only classification is only sound while a domestic plane is never + * emitted on a non-mainland host. These are the builders behind that invariant. + */ +test("domestic planes are only ever built on mainland hosts", () => { + const mainlandUrls = [ + ragEndpoint(workspaceId, RAG_PATHS.indexList), + knowledgeSearchEndpoint(workspaceId), + knowledgeChatEndpoint(workspaceId), + memoryEndpoint(workspaceId, memoryAddAsyncPath()), + customModelImportEndpoint(), + ]; + for (const requestUrl of mainlandUrls) { + const plane = classifyServicePlane(requestUrl); + expect(plane?.site, requestUrl).toBe("domestic"); + const origin = new URL(requestUrl).origin; + expect(classifyModelHost(origin), `${requestUrl} → ${origin}`).toBe("domestic"); + } +}); + +test("model-domain paths carry no plane, so the host keeps deciding", () => { + expect(classifyServicePlane(`https://dashscope.aliyuncs.com${chatPath()}`)).toBeUndefined(); + expect(classifyServicePlane("not a url")).toBeUndefined(); + expect(classifyServicePlane("")).toBeUndefined(); +}); + +test("productSiteOf ignores follow planes and stays conservative on conflict", () => { + const planes = new Map(SERVICE_PLANES.map((plane) => [plane.key, plane])); + expect(productSiteOf([planes.get("rag-workspace")!, planes.get("parsex")!])).toBe("domestic"); + expect(productSiteOf([planes.get("parsex")!, planes.get("agentstudio")!])).toBeUndefined(); + expect(productSiteOf([])).toBeUndefined(); + // Two disagreeing fixed verdicts fall back to domestic, the same conservative + // default the host classifier uses for unknown hosts. + const syntheticInternationalPlane: ServicePlane = { + key: "test-international", + site: "international", + prefixes: ["/api/test/"], + }; + expect(productSiteOf([syntheticInternationalPlane])).toBe("international"); + expect(productSiteOf([planes.get("memory")!, syntheticInternationalPlane])).toBe("domestic"); +}); + +/** + * `lastOrigin` is the signal site routing reads, so it must follow the most + * recent record. The capped first-seen list is inspection only: A → B → A + * leaves A as the last used origin while the list still ends on B. + */ +test("lastOrigin tracks the most recent record instead of first-seen order", () => { + const signals = createRequestSignals(); + const workspaceUrl = `https://${workspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/indices/rag/index/list`; + const modelUrl = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions"; + + signals.record(workspaceUrl); + signals.record(modelUrl); + signals.record(workspaceUrl); + + expect(signals.lastOrigin()).toBe(`https://${workspaceId}.cn-beijing.maas.aliyuncs.com`); + expect(signals.origins).toEqual([ + `https://${workspaceId}.cn-beijing.maas.aliyuncs.com`, + "https://dashscope-intl.aliyuncs.com", + ]); + // The cap trims the inspection list only; the deciding signals survive. + for (let index = 0; index < 12; index += 1) { + signals.record(`https://proxy-${index}.example.test/api/v1/tasks/task-one`); + } + expect(signals.origins).toHaveLength(8); + expect(signals.lastOrigin()).toBe("https://proxy-11.example.test"); + expect(signals.productSite()).toBe("domestic"); +}); + +test("#349 knowledge list on an international base URL still reports the domestic site", async () => { + const requestedUrls: string[] = []; + const transport = vi.spyOn(httpTransport, "fetch").mockImplementation(async (input) => { + requestedUrls.push( + typeof input === "string" ? input : input instanceof URL ? input.href : input.url, + ); + return Response.json({ data: { rows: [], total_count: 0 } }); + }); + const client = makeClient("https://dashscope-intl.aliyuncs.com"); + + await client.requestJson({ path: ragEndpoint(workspaceId, RAG_PATHS.indexList), method: "GET" }); + + expect(transport).toHaveBeenCalledOnce(); + expect(requestedUrls).toEqual([ + "https://ws-review.cn-beijing.maas.aliyuncs.com/api/v1/indices/rag/index/list", + ]); + // The request origin is now recorded even though it bypassed Client.url(). + expect(client.lastResolvedOrigin).toBe("https://ws-review.cn-beijing.maas.aliyuncs.com"); + expect(client.productSite).toBe("domestic"); + expect( + resolveTelemetrySite({ + auth: "apiKey", + productSite: client.productSite, + lastResolvedOrigin: client.lastResolvedOrigin, + baseUrl: client.baseUrl, + baseUrlIsDefault: client.baseUrlIsDefault, + }), + ).toEqual({ site: "domestic", siteReason: "product-domestic" }); +}); + +test("an overridable plane on an international base URL stays international", async () => { + const transport = vi.spyOn(httpTransport, "fetch").mockResolvedValue(Response.json({ data: {} })); + const client = makeClient("https://dashscope-intl.aliyuncs.com"); + + await client.requestJson({ + path: parsexEndpoint("https://ws.ap-southeast-1.maas.aliyuncs.com", "parse", "submit"), + method: "POST", + body: {}, + }); + + expect(transport).toHaveBeenCalledOnce(); + expect(client.productSite).toBeUndefined(); + expect(client.lastResolvedOrigin).toBe("https://ws.ap-southeast-1.maas.aliyuncs.com"); + expect( + resolveTelemetrySite({ + auth: "apiKey", + productSite: client.productSite, + lastResolvedOrigin: client.lastResolvedOrigin, + baseUrl: client.baseUrl, + baseUrlIsDefault: client.baseUrlIsDefault, + }), + ).toEqual({ site: "international", siteReason: "positive-international" }); +}); + +test("a run-level record is shared with derived Clients", () => { + const signals = createRequestSignals(); + const client = new Client({ + identity, + settings: { telemetry: true, timeout: 30 } as Settings, + baseUrl: "https://dashscope-intl.aliyuncs.com", + baseUrlIsDefault: true, + requestSignals: signals, + }); + + const derived = client.withConsoleSwitchAgent(12345678); + derived.url("/api/v1/indices/rag/index/list", () => ragEndpoint(workspaceId, "")); + + expect(signals.origins).toEqual([`https://${workspaceId}.cn-beijing.maas.aliyuncs.com`]); + expect(signals.planes.map((plane) => plane.key)).toEqual(["rag-workspace"]); + expect(client.productSite).toBe("domestic"); + expect(derived.productSite).toBe("domestic"); + // The outer Client — the one the telemetry stage reads — sees the request the + // derived Client made instead of falling back to the shared base URL. + expect(client.lastResolvedOrigin).toBe(`https://${workspaceId}.cn-beijing.maas.aliyuncs.com`); +}); diff --git a/packages/core/tests/telemetry-site.test.ts b/packages/core/tests/telemetry-site.test.ts index 800ef00df..4be8c72a7 100644 --- a/packages/core/tests/telemetry-site.test.ts +++ b/packages/core/tests/telemetry-site.test.ts @@ -205,6 +205,31 @@ test("mixed profile: console domestic does not force apiKey domestic", () => { ).toEqual({ site: "international", siteReason: "positive-international" }); }); +/** + * Every request now records its own origin, including plain relative paths, so + * an origin that is just the shared default base URL must not be mistaken for a + * user choice. A *different* origin is still a real per-command signal. + */ +test("an origin equal to the default base URL keeps default-fallback", () => { + expect( + resolveTelemetrySite({ + auth: "apiKey", + lastResolvedOrigin: "https://dashscope.aliyuncs.com", + baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: true, + }), + ).toEqual({ site: "domestic", siteReason: "default-fallback" }); + + expect( + resolveTelemetrySite({ + auth: "apiKey", + lastResolvedOrigin: "https://ws-review.cn-beijing.maas.aliyuncs.com", + baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: true, + }), + ).toEqual({ site: "domestic", siteReason: "positive-domestic" }); +}); + test("missing baseUrl defaults domestic", () => { expect(resolveTelemetrySite({ auth: "apiKey" })).toEqual({ site: "domestic", @@ -212,6 +237,63 @@ test("missing baseUrl defaults domestic", () => { }); }); +/** + * The reporting site follows the product, not the domain the user configured: + * a domestic-only service plane reports domestic even when every user-side + * signal points international (issue #349). + */ +test("product verdict outranks every user-side host signal", () => { + expect( + resolveTelemetrySite({ + auth: "apiKey", + productSite: "domestic", + lastResolvedOrigin: "https://ws.ap-southeast-1.maas.aliyuncs.com", + baseUrl: "https://dashscope-intl.aliyuncs.com", + }), + ).toEqual({ site: "domestic", siteReason: "product-domestic" }); + + expect( + resolveTelemetrySite({ + auth: "openapi", + productSite: "international", + baseUrl: "https://dashscope.aliyuncs.com", + }), + ).toEqual({ site: "international", siteReason: "product-international" }); +}); + +test("product verdict outranks consoleSite for auth none", () => { + expect( + resolveTelemetrySite({ + auth: "none", + productSite: "domestic", + consoleSite: "international", + baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: true, + }), + ).toEqual({ site: "domestic", siteReason: "product-domestic" }); +}); + +/** Console commands stay on the account-site axis: there the account site *is* the product site. */ +test("console auth keeps the account-site axis even with a product verdict", () => { + expect( + resolveTelemetrySite({ + auth: "console", + productSite: "domestic", + consoleSite: "international", + }), + ).toEqual({ site: "international", siteReason: "positive-international" }); +}); + +test("without a product verdict host classification is unchanged", () => { + expect( + resolveTelemetrySite({ + auth: "apiKey", + productSite: undefined, + baseUrl: "https://dashscope-intl.aliyuncs.com", + }), + ).toEqual({ site: "international", siteReason: "positive-international" }); +}); + test("telemetryRemoteTarget maps site to endpoint and pid", () => { expect(telemetryRemoteTarget("domestic")).toEqual({ site: "domestic", diff --git a/packages/core/tests/telemetry-tracker.test.ts b/packages/core/tests/telemetry-tracker.test.ts index e2639cd2e..519349b29 100644 --- a/packages/core/tests/telemetry-tracker.test.ts +++ b/packages/core/tests/telemetry-tracker.test.ts @@ -165,6 +165,49 @@ test("resolveSite failure still emits domestic event", async () => { }); }); +/** + * A `--dry-run` preview sends nothing, so no request origin or service plane is + * recorded and its site can only come from the configured base URL. Marking the + * event keeps preview traffic separable from real calls — for domestic-only + * products like knowledge base and memory, a preview from an international base + * URL otherwise looks like international product demand. + */ +test("dry-run runs are marked in the event and in the AEM ext", async () => { + sinkMocks.localSink.mockClear(); + await trackCommandExecution( + { + identity, + settings: { telemetry: true, dryRun: true } as Settings, + caller: unknownCaller, + authMethod: "apiKey", + resolveSite: () => ({ site: "international", siteReason: "positive-international" }), + }, + ["knowledge", "list"], + {}, + async () => {}, + ); + + const event = asCommand(sinkMocks.localSink.mock.calls[0]![0]); + expect(event).toMatchObject({ command: "knowledge list", dryRun: true }); + expect(buildRemoteAemOptions(event).ext).toMatchObject({ dryRun: true }); +}); + +test("normal runs omit the dryRun field", async () => { + sinkMocks.localSink.mockClear(); + await trackCommandExecution( + { + identity, + settings: { telemetry: true, dryRun: false } as Settings, + caller: unknownCaller, + }, + ["config", "show"], + {}, + async () => {}, + ); + + expect(asCommand(sinkMocks.localSink.mock.calls[0]![0])).not.toHaveProperty("dryRun"); +}); + const entryIdentities = [ { label: "bl", diff --git a/packages/runtime/src/create-cli.ts b/packages/runtime/src/create-cli.ts index 4969e9ac8..a3b50d71f 100644 --- a/packages/runtime/src/create-cli.ts +++ b/packages/runtime/src/create-cli.ts @@ -41,6 +41,7 @@ import { reportFirstInstallNow, isFirstInstallReportLaunch, Client, + createRequestSignals, } from "bailian-cli-core"; import { setupProxyFromEnv } from "./proxy.ts"; import { handleError } from "./error-handler.ts"; @@ -339,6 +340,10 @@ export function createCli(commands: Record, opts: CliOptions settings, debug: (diagnostic) => reporter.output.debug(diagnostic), ...resolveModelBaseUrlState(sources), + // `auth: "none"` commands keep this Client, so it needs its own + // per-run record; the other auth domains get a fresh one from + // authStage. + requestSignals: createRequestSignals(), }), }; await runMiddleware(ctx); diff --git a/packages/runtime/src/middleware.ts b/packages/runtime/src/middleware.ts index 8254be2c8..35abfc6c5 100644 --- a/packages/runtime/src/middleware.ts +++ b/packages/runtime/src/middleware.ts @@ -20,6 +20,7 @@ import { CredentialError, formatCommand, Client, + createRequestSignals, DEFAULT_LANGUAGE, isModelConnectionSourceMismatch, resolveApiKey, @@ -193,6 +194,12 @@ export const authStage: Middleware = async (ctx, next) => { const base = { identity: ctx.identity, settings, + // One record per command run. Every Client built from `base` — including + // the derived one from `withConsoleSwitchAgent()` — shares it, so the + // origins and service planes a command touched stay visible to + // `telemetryStage`, which sits outside this stage and reads the Client + // attached to the run context. + requestSignals: createRequestSignals(), // Console credentials do not fall back; keep the selected profile pin. consoleRecoveryHint: consoleRecoveryHint( formatCommand(ctx.identity), @@ -298,6 +305,7 @@ export const telemetryStage: Middleware = (ctx, next) => { resolveTelemetrySite({ auth: ctx.command.auth, consoleSite: ctx.settings.consoleSite, + productSite: ctx.client.productSite, lastResolvedOrigin: ctx.client.lastResolvedOrigin, baseUrl: ctx.client.baseUrl, baseUrlIsDefault: ctx.client.baseUrlIsDefault, diff --git a/packages/runtime/tests/telemetry-stage.test.ts b/packages/runtime/tests/telemetry-stage.test.ts index d7205789b..b23539b61 100644 --- a/packages/runtime/tests/telemetry-stage.test.ts +++ b/packages/runtime/tests/telemetry-stage.test.ts @@ -146,6 +146,35 @@ test("resolveSite treats default baseUrl as fallback", async () => { }); }); +/** + * The stage must forward the Client's product verdict, or a knowledge / memory + * command run against an international base URL would be attributed to the + * international site again (issue #349). + */ +test("resolveSite forwards the client product verdict ahead of host signals", async () => { + const next = vi.fn(async () => {}); + const context = makeContext({ + command: { auth: "apiKey" }, + client: { + baseUrl: "https://dashscope-intl.aliyuncs.com", + baseUrlIsDefault: false, + lastResolvedOrigin: "https://ws-review.cn-beijing.maas.aliyuncs.com", + productSite: "domestic", + }, + settings: { telemetry: true }, + }); + + await telemetryStage(context, next); + + const deps = trackerMocks.trackCommandExecution.mock.calls[0]![0] as { + resolveSite: () => { site: string; siteReason: string }; + }; + expect(deps.resolveSite()).toEqual({ + site: "domestic", + siteReason: "product-domestic", + }); +}); + test("defaults to unknown when caller env is unset", async () => { vi.stubEnv("BAILIAN_CALLER_TYPE", undefined); vi.stubEnv("BAILIAN_CALLER_NAME", undefined); From da8d8e57bc03ff9ac50c1898819edba550b806d8 Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Fri, 27 Nov 2026 11:16:11 +0800 Subject: [PATCH 5/6] docs(telemetry): state that dryRun marks preview mode, not zero requests --- docs/agents/telemetry-change.md | 12 +- packages/core/src/telemetry/event.ts | 17 ++- packages/core/tests/telemetry-tracker.test.ts | 112 +++++++++++++++++- 3 files changed, 129 insertions(+), 12 deletions(-) diff --git a/docs/agents/telemetry-change.md b/docs/agents/telemetry-change.md index 952e2e3f4..e5d12678f 100644 --- a/docs/agents/telemetry-change.md +++ b/docs/agents/telemetry-change.md @@ -173,12 +173,17 @@ mmstat 网关对任何 POST 都返回 `200` + GIF,端点或 pid 写错不会 - 产品归属表在 `packages/core/src/client/service-planes.ts`,按请求 pathname 命名空间识别,且只覆盖 CLI 自己构造的绝对 URL:`domestic` = 出口固定在国内、用户无法覆盖的面(RAG admin 面 / knowledge search+chat / memory / 公共 DashScope 定制模型导入);`follow` = 允许 `--base-url` 或 region 覆盖的面(ParseX / AgentStudio sandbox+security / 模型域),由实际 host 判定。**新增绝对 URL 出口必须同步该表**,漂移守卫见 `packages/core/tests/telemetry-service-planes.test.ts`。 - `siteReason` 新增 `product-domestic` / `product-international`:归属来自产品声明,不是用户配置;`positive-*` 继续只表示用户侧信号。 - 记录对象 `RequestSignals` 每次命令运行创建一份,由 `authStage` 注入 `ClientDeps`;`Client.withConsoleSwitchAgent()` 派生的新 Client 继承同一份,否则内层请求对外层 telemetry 不可见。 -- **dry-run 没有产品归属信号**:`--dry-run` 在拼出 endpoint 后就 `output.result` 返回,不经过 `request` / `requestJson` / `url()`,`RequestSignals` 为空,站点只能由用户配置的 `baseUrl` 决定。所以国际 baseUrl 下 `bl knowledge list --dry-run` 报 `international`,尽管它预览的是北京 workspace 出口。这类事件由 `dryRun=true` 标出:在国内-only 的 family(knowledge / memory / cmodel)里,`dryRun=true`、或 `siteReason` 不是 `product-*`,都说明**这条不是真实调用量**,不能读成「国际站对该产品有需求」。`follow` 面(ParseX / Sandbox / Security / 模型域)的 dry-run 按 baseUrl 判本来就是正确口径,不在此列。 +- **`dryRun` 只标记预览,不标记「零请求」**:`--dry-run` 的含义是本次不创建、不修改资源,**不代表没有网络**。带 `prepare` 的命令在预览阶段照常发只读请求,请求一经发出就记录 origin 与 service plane,所以 `dryRun=true` 与 `siteReason=product-*` **可以共存**:实测 `bl knowledge init --dry-run` → `domestic / product-domestic / dryRun=true`,该命令自己的 help 也写明 dry-run 会读取已有资源。 + - 预览事件的归属口径和真实执行**完全一致**,都由实际触碰的出口决定,不因预览而特殊:`knowledge init` / `knowledge doc sync` 的 prepare 读 workspace 网关 → `product-*`;`deploy router update` 的 prepare 读模型域(`/api/v1/deployments/...`,不在 plane 表里)→ 照样是 `positive-*`(实测国际 baseUrl 下 `bl deploy router update … --dry-run` → `international / positive-international / dryRun=true`,服务端 401 也照样记录出口——失败的请求同样是发出去的请求)。 + - 两个信号各答一个问题,不要互换:**算真实执行调用量** → 按 `dryRun` 把预览剔掉;**判断站点归属来自产品还是用户配置** → 按 `siteReason` 是否 `product-*`。 + - 真正缺产品归属信号的只有「预览且一个请求都没发」:命令拼出 endpoint 后在 dry-run 分支直接 `output.result` 返回(如 `bl knowledge list --dry-run`),`RequestSignals` 为空,站点退到用户配置的 `baseUrl`——国际 baseUrl 下会报 `international`,尽管它预览的是北京 workspace 出口。这类事件在看板上不能读成「国际站对该产品有需求」,判据是 `siteReason` 非 `product-*`,**不是** `dryRun`。 + - `follow` 面(ParseX / Sandbox / Security / 模型域)的 dry-run 按 baseUrl 判本来就是正确口径,不在此列。 + - **执行前提**:`siteReason` 与 `dryRun` 目前只存在于 `ext`(和本地 JSONL),两站都还没给它们建自定义维度(见下方「看板元数据还没跟上」)。维度补齐前,上面的判据只能在 `~/.bailian/telemetry.jsonl` 或 ext 原始导出里用;要在看板上筛预览、筛归属,必须先补这两个维度,否则规则落不了地。 - openapi **禁止**用 ACS `opts.host` 分类。 - `remoteSink` 按 site 使用 keyed `Map` 持有 Tracker;同进程可同时存在国内与国际实例。`uid` / tracker `device_id` **跨站同值**。 - vendored tracker 仅保留本仓对 `send` 的本地改造(登记于此);国际 path 与国内同为 `/aes.1.1`,**不加** `endpointPath` patch。升级 SDK 时必须保留 `send` 改造。 - 看板元数据还没跟上:`site` / `siteReason` 两站都未建自定义维度;`callerType` / `callerName` / `cliVersion` / `cliVersionCode` / `commandPrefix` 国内项目有、国际项目一个都没有。数据已经在 `ext` 里,但国际站要做筛选/聚合(含 Agent 调用率、入口区分)必须先补这些维度。 -- 已知残留:未知/反代 host、残缺配置、登录写盘前首条 `none`、managed-agent 外部拼 host、旧版 CLI、账号站与模型地域混维拆站、`first_install` 固定报国内站(安装阶段没有 auth / Client 上下文)、pipeline 步骤的 Client 未注入 `RequestSignals`(`packages/runtime/src/pipeline/bl-config.ts`,步骤请求不进命令事件)、`mcp --url` 覆盖时记录的是默认 httpUrl 而非实际目标、**国内-only family 的 dry-run 事件按用户 baseUrl 归站**(见上条,用 `dryRun` 字段剔除)。 +- 已知残留:未知/反代 host、残缺配置、登录写盘前首条 `none`、managed-agent 外部拼 host、旧版 CLI、账号站与模型地域混维拆站、`first_install` 固定报国内站(安装阶段没有 auth / Client 上下文)、pipeline 步骤的 Client 未注入 `RequestSignals`(`packages/runtime/src/pipeline/bl-config.ts`,步骤请求不进命令事件)、`mcp --url` 覆盖时记录的是默认 httpUrl 而非实际目标、**国内-only family 中「预览且未发请求」的事件按用户 baseUrl 归站**(见上条;圈出来用 `siteReason` 非 `product-*`,不是用 `dryRun`)。 编译二进制的 `env=prod` 由 `BAILIAN_COMPILED=1` 决定,并且必须先于 `NODE_ENV`。`bun build --compile`(当前 pin 1.3.14)会把点访问 `process.env.NODE_ENV` 内联成构建机的值,未设置时是 `"development"`;`tools/release/lib/binary-compile.mjs` 同时 `--define process.env.NODE_ENV="production"`。这两处读取必须写成 `process.env.*`,包进别的变量后 `--define` 匹配不到。 @@ -281,5 +286,6 @@ vp test packages/core/tests/telemetry-uid.test.ts packages/core/tests/telemetry- - ✗ 把允许 `--base-url` / region 覆盖的面声明成 `domestic`,等于替用户否认他显式选择的海外站点 - ✗ 用 openapi ACS host 或「非 cn- 前缀」推断国际站(`cn-hongkong` 是国际) - ✗ 把 AEM 分流叙事写成「国际数据绝不出境」硬保证;实际是 best-effort 声明口径 -- ✗ 把国内-only family 里 `dryRun=true`(或 `siteReason` 非 `product-*`)的事件算进真实调用量,进而误判国际站产品需求 +- ✗ 用 `dryRun` 反推「有没有发请求」:带 `prepare` 的命令预览时照样读远端,事件同时带 `dryRun=true` 和 `product-*` +- ✗ 把国内-only family 里 `siteReason` 非 `product-*` 的预览事件算进真实调用量,进而误判国际站产品需求 - ✗ 升级 vendored AEM tracker 时丢掉本仓 `send` 改造 diff --git a/packages/core/src/telemetry/event.ts b/packages/core/src/telemetry/event.ts index 6b3f0291c..beedd8c42 100644 --- a/packages/core/src/telemetry/event.ts +++ b/packages/core/src/telemetry/event.ts @@ -34,10 +34,19 @@ export interface TrackingEvent { /** Coarse site resolution reason; never includes raw hosts. */ siteReason?: TelemetrySiteReason; /** - * The run was a `--dry-run` preview, so it sent no business request and - * recorded no request origin or service plane. Sparse — only reported when - * true. This is what separates preview events from real calls: a real call's - * site comes from the product it touched, a preview's can only come from the + * The run was a `--dry-run` preview: it must not create or mutate resources. + * Sparse — only reported when true. + * + * Preview is *not* "no network": commands with `prepare` read existing + * resources even under `--dry-run`, and any request a preview issues records + * its origin and service plane exactly like an executed call does. So this + * field coexists with a `product-*` `siteReason` for workspace-gateway + * previews such as `knowledge init`, while a model-domain preview such as + * `deploy router update` still reports `positive-*`. Being a preview never + * changes how a site is attributed — only the recorded exit decides that. + * + * Use this field to separate preview traffic from executed calls; use + * `siteReason` to tell whether the site came from the product or from the * configured base URL. */ dryRun?: true; diff --git a/packages/core/tests/telemetry-tracker.test.ts b/packages/core/tests/telemetry-tracker.test.ts index 519349b29..86dc99768 100644 --- a/packages/core/tests/telemetry-tracker.test.ts +++ b/packages/core/tests/telemetry-tracker.test.ts @@ -19,6 +19,11 @@ import { FIRST_INSTALL_REPORT_FILE, isFirstInstallReportLaunch, } from "../src/telemetry/first-install.ts"; +import { Client } from "../src/client/client.ts"; +import { httpTransport } from "../src/client/transport.ts"; +import { createRequestSignals } from "../src/client/request-signals.ts"; +import { RAG_PATHS, ragEndpoint } from "../src/client/endpoints.ts"; +import { resolveTelemetrySite } from "../src/telemetry/site.ts"; type ReportedEvent = TrackingEvent | FirstInstallEvent; @@ -166,11 +171,11 @@ test("resolveSite failure still emits domestic event", async () => { }); /** - * A `--dry-run` preview sends nothing, so no request origin or service plane is - * recorded and its site can only come from the configured base URL. Marking the - * event keeps preview traffic separable from real calls — for domestic-only - * products like knowledge base and memory, a preview from an international base - * URL otherwise looks like international product demand. + * `dryRun` marks preview mode, nothing more. A preview that sends no request + * records no origin and no service plane, so its site can only come from the + * configured base URL — for domestic-only products like knowledge base and + * memory that would otherwise read as international product demand. Reporting + * the flag keeps preview traffic separable from executed calls. */ test("dry-run runs are marked in the event and in the AEM ext", async () => { sinkMocks.localSink.mockClear(); @@ -208,6 +213,103 @@ test("normal runs omit the dryRun field", async () => { expect(asCommand(sinkMocks.localSink.mock.calls[0]![0])).not.toHaveProperty("dryRun"); }); +/** + * The two signals are orthogonal, and this is the case that must not be + * "corrected" into treating `dryRun` as proof of zero network traffic: commands + * with `prepare` read existing resources even under `--dry-run`, so the run + * records a real service plane and still earns a product verdict. + */ +test("dryRun coexists with a product site verdict for previews that read resources", () => { + const event = createTrackingEvent({ + command: "knowledge init", + durationMs: 12, + success: true, + identity, + authMethod: "apiKey", + caller: unknownCaller, + site: "domestic", + siteReason: "product-domestic", + dryRun: true, + }); + + expect(event).toMatchObject({ + command: "knowledge init", + dryRun: true, + site: "domestic", + siteReason: "product-domestic", + }); + expect(buildRemoteAemOptions(event).ext).toMatchObject({ + dryRun: true, + siteReason: "product-domestic", + }); +}); + +/** + * End-to-end for the narrowed claim. The pure-field test above only proves the + * two keys can coexist; this drives the real path — a `--dry-run` run whose + * prepare phase reads the mainland workspace gateway while the configured model + * base URL is international — and asserts the event carries both the preview + * mark and the product verdict. If request recording ever stops happening for + * absolute `path` requests, this goes red instead of the docs quietly lying. + */ +test("a preview that read the workspace gateway reports dryRun with a product site", async () => { + sinkMocks.localSink.mockClear(); + const transport = vi + .spyOn(httpTransport, "fetch") + .mockResolvedValue(Response.json({ data: { rows: [], total_count: 0 } })); + const client = new Client({ + identity, + settings: { telemetry: true, dryRun: true, timeout: 30 } as Settings, + baseUrl: "https://dashscope-intl.aliyuncs.com", + baseUrlIsDefault: false, + requestSignals: createRequestSignals(), + apiCred: { + token: "sk-test", + baseUrl: "https://dashscope-intl.aliyuncs.com", + source: "config", + }, + }); + + try { + await trackCommandExecution( + { + identity, + settings: { telemetry: true, dryRun: true } as Settings, + caller: unknownCaller, + authMethod: "apiKey", + resolveSite: () => + resolveTelemetrySite({ + auth: "apiKey", + productSite: client.productSite, + lastResolvedOrigin: client.lastResolvedOrigin, + baseUrl: client.baseUrl, + baseUrlIsDefault: client.baseUrlIsDefault, + }), + }, + ["knowledge", "init"], + {}, + async () => { + // The read-only request a `knowledge init` preview actually issues. + await client.requestJson({ + path: ragEndpoint("ws-review", RAG_PATHS.indexList), + method: "GET", + }); + }, + ); + } finally { + vi.restoreAllMocks(); + } + + expect(transport).toHaveBeenCalledOnce(); + expect(asCommand(sinkMocks.localSink.mock.calls[0]![0])).toMatchObject({ + command: "knowledge init", + success: true, + dryRun: true, + site: "domestic", + siteReason: "product-domestic", + }); +}); + const entryIdentities = [ { label: "bl", From 63857e1c952b2b81f67419b2593cbd21e5cf4df1 Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Fri, 27 Nov 2026 15:14:27 +0800 Subject: [PATCH 6/6] docs(telemetry): drop stale remoteSendEvent references PR #349 replaced the single global remoteSendEvent with a per-site Tracker map (entry.sendEvent), but two lines in the checklist and the first-install call chain still named the removed symbol. They described a symbol that no longer exists, so a reader following the "no await before enqueue" rule could not locate it. --- docs/agents/telemetry-change.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/agents/telemetry-change.md b/docs/agents/telemetry-change.md index 7ffbaac9f..8a79e0762 100644 --- a/docs/agents/telemetry-change.md +++ b/docs/agents/telemetry-change.md @@ -116,7 +116,7 @@ postinstall.js launchFirstInstallReport setupProxyFromEnv()(失败则直连,不让安装失败) tracker.ts reportFirstInstallNow event.ts createFirstInstallEvent - sink.ts remoteSink → remoteSendEvent("first_install", ...) + sink.ts remoteSink → 国内站 Tracker 的 sendEvent("first_install", ...) first-install.ts noteFirstInstallReportQueued ``` @@ -254,7 +254,7 @@ AEM 映射: - [ ] 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` 从调用到对应站点 Tracker 的 `sendEvent` 入队之间不得出现 `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` 强制退出仍落盘」