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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 81 additions & 27 deletions docs/agents/telemetry-change.md

Large diffs are not rendered by default.

26 changes: 3 additions & 23 deletions packages/commands/src/commands/auth/login-api-key.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import {
BailianError,
getApiKeyLoginKind,
KNOWN_MODEL_BASE_URLS,
normalizeModelBaseUrl,
ORDINARY_WORKSPACE_REGIONS,
requestJson,
type ApiKeyLoginKind,
type AuthPersistPatch,
Expand Down Expand Up @@ -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<Record<ApiKeyEndpointKind, readonly string[]>> = {
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");
Expand Down Expand Up @@ -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);
}
}
Expand Down
62 changes: 60 additions & 2 deletions packages/core/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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. */
Expand Down Expand Up @@ -77,9 +85,14 @@ export interface OpenApiResponse {
*/
export class Client {
private consoleSession: ConsoleSession;
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 {
Expand Down Expand Up @@ -108,6 +121,40 @@ 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 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.requestSignals.lastOrigin();
}

/**
* 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);
}

/**
* Export the model-domain credential for delegation to an embedded SDK that
* owns its own transport (e.g. @openagentpack/sdk). Deliberate escape hatch:
Expand Down Expand Up @@ -138,14 +185,21 @@ export class Client {
*/
url(path: string, defaultBaseUrl?: () => string): string {
const baseUrl = this.deps.baseUrlIsDefault && defaultBaseUrl ? defaultBaseUrl() : this.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}` },
};
}
Expand Down Expand Up @@ -251,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);
Expand Down
9 changes: 9 additions & 0 deletions packages/core/src/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
74 changes: 74 additions & 0 deletions packages/core/src/client/request-signals.ts
Original file line number Diff line number Diff line change
@@ -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<string>();
const planes = new Set<ServicePlane>();
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);
},
};
}
116 changes: 116 additions & 0 deletions packages/core/src/client/service-planes.ts
Original file line number Diff line number Diff line change
@@ -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<PlaneSite, "follow">;

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
// <workspace>.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<ServicePlane>): ProductSite | undefined {
const verdicts = new Set<ProductSite>();
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;
}
12 changes: 12 additions & 0 deletions packages/core/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Loading