import { httpTransport } from "./transport.ts"; import type { Identity, Settings } from "../config/schema.ts"; import type { ApiKeyCredential, ConsoleCredential, OpenApiCredential } from "../auth/types.ts"; import { BailianError } from "../errors/base.ts"; import { ExitCode } from "../errors/codes.ts"; import { request, requestJson, type HttpDeps, type RequestOpts } from "./http.ts"; import { buildAcsCanonicalQuery, signAcsRequest, type AcsQueryParams } from "./acs.ts"; import { imageFileToDataUri, isLocalFile, resolveFileUrl } from "../files/upload.ts"; import { bailianMcpPath, bailianMcpSsePath, connectBailianMcpWithFallback, type McpConnectedClient, } from "./mcp.ts"; import { SdkMcpAdapter } from "./mcp-sdk.ts"; import { ConsoleSession } from "./console-session.ts"; import { debugRequest, debugResponse } from "./diagnostics.ts"; import { getApiKeyLoginKind } from "../config/profile-presets.ts"; import { trackingHeaders } from "./headers.ts"; /** Client 的结构化依赖:身份 + 有效配置 + 各域凭证(按命令的 auth 注入)。 */ export interface ClientDeps { identity: Identity; settings: Settings; debug?: HttpDeps["debug"]; /** Model 域 base URL(凭证无关链解析,resolveModelBaseUrl;有 apiCred 时两者一致)。 */ baseUrl: string; /** True only when the shared URL chain used its default; explicit origins win over service defaults. */ baseUrlIsDefault?: boolean; apiCred?: ApiKeyCredential; consoleCred?: ConsoleCredential; /** Lazily resolve AK/SK only when the Console token is missing or expired. */ resolveConsoleOpenApiCredential?: () => OpenApiCredential; /** Optional host-provided recovery text; core does not construct CLI instructions. */ consoleRecoveryHint?: string; openApiCred?: OpenApiCredential; } /** Like {@link RequestOpts} but with a `path` (credential baseUrl prepended) or an absolute URL. */ export interface ClientRequestOpts extends Omit { path: string; } export interface ClientOpenApiQueryOpts { host: string; path: string; action: string; version: string; method: "GET" | "POST"; queryParams: AcsQueryParams; } export interface ClientOpenApiJsonOpts { host: string; path: string; action: string; version: string; method: "GET" | "POST"; /** JSON request body; omit for query-only calls (signed as an empty body). */ body?: unknown; queryParams?: AcsQueryParams; } export interface OpenApiResponse { Success?: boolean; Code?: string; Message?: string; } /** * A command's network surface: call its methods to reach the API — the * credential and base URL are already baked in, so commands never handle tokens * or baseUrl. Model methods (`request`/`requestJson`/`mcp`) need an api key; * `uploadFile` only needs one for local files, and passes URLs through without * credentials. `console` uses a Console token, obtaining one lazily from * resolved AK/SK when needed. Concurrent calls share the exchange, not results. */ export class Client { private consoleSession: ConsoleSession; constructor(private readonly deps: ClientDeps) { this.consoleSession = new ConsoleSession(deps); } private get http(): HttpDeps { return { identity: this.deps.identity, settings: this.deps.settings, debug: this.deps.debug }; } private requireApi(): ApiKeyCredential { if (!this.deps.apiCred) { throw new BailianError("This command needs a model-domain API key.", ExitCode.AUTH); } return this.deps.apiCred; } private requireOpenApi(): OpenApiCredential { if (!this.deps.openApiCred) { throw new BailianError( "This command needs Alibaba Cloud OpenAPI AK/SK credentials.", ExitCode.AUTH, ); } return this.deps.openApiCred; } /** Model-domain base URL. Readable without a key (e.g. dry-run preview); real requests still need one. */ get baseUrl(): string { return this.deps.apiCred?.baseUrl ?? this.deps.baseUrl; } /** * Export the model-domain credential for delegation to an embedded SDK that * owns its own transport (e.g. @openagentpack/sdk). Deliberate escape hatch: * regular commands keep calling {@link request}/{@link requestJson} and never * handle tokens; only trusted internal adapters such as managed-agent/_engine * and the Command Pack host use this export. Undefined when no credential * resolved (authStage tolerates that only under dry-run). */ exportApiCredential(): ApiKeyCredential | undefined { return this.deps.apiCred; } /** * Headers for registering a Bailian MCP endpoint in an external Agent. * Credential resolution and channel attribution remain owned by the client. */ bailianMcpRegistrationHeaders(): Record { const credential = this.requireApi(); return { Authorization: `Bearer ${credential.token}`, ...trackingHeaders(this.deps.identity), }; } /** * Full URL for a model-domain path. Services may supply a lazy default origin, * evaluated only when no flag/env/profile base URL was configured. */ url(path: string, defaultBaseUrl?: () => string): string { const baseUrl = this.deps.baseUrlIsDefault && defaultBaseUrl ? defaultBaseUrl() : this.baseUrl; return baseUrl + path; } private toOpts({ path, ...rest }: ClientRequestOpts): RequestOpts { const cred = this.requireApi(); return { ...rest, url: /^https?:\/\//.test(path) ? path : cred.baseUrl + path, headers: { ...rest.headers, Authorization: `Bearer ${cred.token}` }, }; } request(opts: ClientRequestOpts): Promise { return request(this.http, this.toOpts(opts)); } requestJson(opts: ClientRequestOpts): Promise { return requestJson(this.http, this.toOpts(opts)); } /** Resolve a file arg, honoring a lazy service default origin just like {@link url}. */ uploadFile( source: string, model: string, opts: { signal?: AbortSignal; defaultBaseUrl?: () => string } = {}, ): Promise { if (!isLocalFile(source)) return Promise.resolve(source); const credential = this.requireApi(); return resolveFileUrl(source, credential.token, model, { signal: opts.signal, baseUrl: this.url("", opts.defaultBaseUrl), identity: this.deps.identity, timeout: this.deps.settings.timeout, }); } /** * Resolve an image input while keeping Token Plan's upload limitation isolated. * Token Plan local images are sent as Data URIs; every other connection keeps * the established temporary OSS upload flow. URLs and existing Data URIs pass through. */ resolveImageInput( source: string, model: string, opts: { signal?: AbortSignal; defaultBaseUrl?: () => string } = {}, ): Promise { if (!isLocalFile(source)) return Promise.resolve(source); if (this.usesTokenPlanEndpoint()) { return Promise.resolve(imageFileToDataUri(source)); } return this.uploadFile(source, model, opts); } usesTokenPlanEndpoint(): boolean { try { return /^token-plan\.[a-z0-9-]+\.maas\.aliyuncs\.com$/i.test(new URL(this.baseUrl).hostname); } catch { return false; } } /** * True when the effective model-domain connection is a Token Plan one: either * the token-plan endpoint or a plan key (`sk-sp-`). Both shapes are verified * unable to reach Bailian MCP (the plan gateway has no `/api/v1/mcps` route — * bare 404 — and plan keys get 401 InvalidApiKey on the standard MCP path), * so callers routing through MCP (AIGC `auto` mode) reject up front. */ usesTokenPlanConnection(): boolean { return ( this.usesTokenPlanEndpoint() || getApiKeyLoginKind(this.deps.apiCred?.token ?? "") === "token-plan" ); } /** Open an MCP client. Accepts a path (prepended with the model baseUrl) or an absolute URL. */ mcp(pathOrUrl: string): McpConnectedClient { const url = /^https?:\/\//.test(pathOrUrl) ? pathOrUrl : this.requireApi().baseUrl + pathOrUrl; return new SdkMcpAdapter({ deps: this.http, url, authToken: this.deps.apiCred?.token, transport: "streamable", }); } /** * Connect to a Bailian MCP: try Streamable HTTP, then SSE on 405 (except WebSearch). * `urlOverride` maps to `--url`: Streamable first, then classic SSE on the same URL (405/404). * `serviceSource` overrides the `X-Dashscope-Service` attribution value (default * `bailian-cli`); AIGC "auto"-mode MCP calls pass `bailian-cli-call`. */ connectBailianMcp( serverCode: string, urlOverride?: string, serviceSource?: string, ): Promise<{ client: McpConnectedClient; url: string }> { this.requireApi(); return connectBailianMcpWithFallback({ deps: this.http, authToken: this.deps.apiCred?.token, httpUrl: this.url(bailianMcpPath(serverCode)), sseUrl: this.url(bailianMcpSsePath(serverCode)), serverCode, urlOverride, serviceSource, }); } /** 创建仅本次调用链使用的 Console 身份;不修改原 Client、Settings 或持久化配置。 */ withConsoleSwitchAgent(switchAgent: number): Client { const client = new Client({ ...this.deps, settings: { ...this.deps.settings, consoleSwitchAgent: switchAgent }, }); client.consoleSession = this.consoleSession.withSwitchAgent(switchAgent); return client; } console(api: string, data: Record): Promise { return this.consoleSession.request(api, data); } openApiQueryJson(opts: ClientOpenApiQueryOpts): Promise { return this.openApiJson(opts); } async openApiJson(opts: ClientOpenApiJsonOpts): Promise { const cred = this.requireOpenApi(); const bodyStr = opts.body === undefined ? "" : JSON.stringify(opts.body); const queryString = opts.queryParams ? buildAcsCanonicalQuery(opts.queryParams) : ""; const endpoint = `https://${opts.host}${opts.path}${queryString ? `?${queryString}` : ""}`; const headers = signAcsRequest({ accessKeyId: cred.accessKeyId, accessKeySecret: cred.accessKeySecret, securityToken: cred.securityToken, action: opts.action, version: opts.version, body: bodyStr, host: opts.host, pathname: opts.path, method: opts.method, queryString, }); debugRequest(this.http, opts.method, endpoint, { action: opts.action, version: opts.version }); const timeoutMs = this.deps.settings.timeout * 1000; const res = await httpTransport.fetch(endpoint, { method: opts.method, headers: { ...headers, ...trackingHeaders(this.deps.identity) }, body: bodyStr || undefined, signal: AbortSignal.timeout(timeoutMs), }); const rawText = await res.text(); debugResponse(this.http, res); let data: T; try { data = JSON.parse(rawText) as T; } catch { throw new BailianError( `${res.status} ${res.statusText} - ${rawText.slice(0, 500)}`, ExitCode.GENERAL, ); } if (!res.ok || data.Success === false) { throw new BailianError( `${data.Code || res.status} - ${data.Message || res.statusText}`, ExitCode.GENERAL, ); } return data; } }