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
9 changes: 9 additions & 0 deletions packages/sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@
// ./internal and are deliberately not exported — do not add internal-only symbols here.

export { UserError } from "./internal/errors.ts";
// Server-side HTTP errors thrown by provider clients. Exported so hosts (CLIs,
// servers) can branch on them and surface statusCode/responseBody structurally
// instead of parsing the message string.
export { ApiError, ConflictError } from "./internal/providers/base-client.ts";

// Transport seam: hosts install a fetch-compatible implementation to add
// cross-cutting request concerns (tracking headers, logging) without touching
// globalThis.fetch. Unset → provider clients use the global fetch as before.
export { setDefaultFetch, type FetchLike } from "./internal/transport.ts";

export type {
BackendRuntimeInput,
Expand Down
3 changes: 2 additions & 1 deletion packages/sdk/src/internal/executor/skill-resolver.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { readFileSync, statSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { resolveFetch } from "../transport.ts";
import type { SkillDecl } from "../types/config.ts";
import type { SkillFile } from "../types/skill-file.ts";
import { collectFiles } from "../utils/collect-files.ts";
Expand All @@ -10,7 +11,7 @@ import type { ExecContext } from "./context.ts";
// is read relative to configPath (zip, directory, or a single SKILL.md).
export async function resolveSkillFiles(decl: SkillDecl, ctx: ExecContext): Promise<SkillFile[]> {
if (/^https?:\/\//i.test(decl.source)) {
const res = await fetch(decl.source);
const res = await resolveFetch()(decl.source);
if (!res.ok) throw new Error(`skill source 下载失败:${res.status} ${decl.source}`);
return extractSkillZipFiles(Buffer.from(await res.arrayBuffer()));
}
Expand Down
9 changes: 8 additions & 1 deletion packages/sdk/src/internal/provider-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,14 @@ export function resolveActiveProvider(): ProviderConfigProvider {
/** Whether the current process env has all required fields for the active provider. */
export function areRuntimeCredentialsReady(): boolean {
const provider = resolveActiveProvider();
return AGENTS_PROVIDER_FIELDS[provider].every((field) => process.env[field.key]?.trim());
return AGENTS_PROVIDER_FIELDS[provider].every((field) => {
if (process.env[field.key]?.trim()) return true;
// bailian derives its endpoint from either workspace_id or base_url, so a
// configured BAILIAN_BASE_URL satisfies the workspace_id slot (mirrors the
// provider config schema's "at least one" rule).
if (field.key === "BAILIAN_WORKSPACE_ID") return Boolean(process.env.BAILIAN_BASE_URL?.trim());
return false;
});
}

function isProvider(value: string): value is ProviderConfigProvider {
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk/src/internal/providers/bailian/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export class BailianAdapter implements ProviderAdapter {
private client: BailianClient;
private projectName: string;

constructor(apiKey: string, workspaceId: string, baseUrl?: string, projectName?: string) {
constructor(apiKey: string, workspaceId?: string, baseUrl?: string, projectName?: string) {
this.client = new BailianClient({ apiKey, workspaceId, baseUrl });
this.projectName = projectName ?? "";
}
Expand Down
11 changes: 9 additions & 2 deletions packages/sdk/src/internal/providers/bailian/client.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { UserError } from "../../errors.ts";
import { BaseApiClient } from "../base-client.ts";

export interface BailianClientConfig {
apiKey: string;
workspaceId: string;
workspaceId?: string;
baseUrl?: string;
}

Expand All @@ -15,7 +16,13 @@ export class BailianClient extends BaseApiClient {
constructor(config: BailianClientConfig) {
super();
this.apiKey = config.apiKey;
this.baseUrl = config.baseUrl ?? `https://${config.workspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/agentstudio`;
if (config.baseUrl) {
this.baseUrl = config.baseUrl;
} else if (config.workspaceId) {
this.baseUrl = `https://${config.workspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/agentstudio`;
} else {
throw new UserError("bailian provider requires either base_url or workspace_id");
}
}

protected headers(): Record<string, string> {
Expand Down
18 changes: 13 additions & 5 deletions packages/sdk/src/internal/providers/bailian/config.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import { z } from "zod";

export const bailianConfigSchema = z.object({
api_key: z.string(),
workspace_id: z.string(),
base_url: z.string().optional(),
});
// workspace_id and base_url are both optional but at least one is required: the
// client derives the AgentStudio base URL from workspace_id, or takes base_url
// verbatim. Hosts that only know the full endpoint (e.g. bl's --agentstudio-base-url)
// can supply base_url and skip workspace_id entirely.
export const bailianConfigSchema = z
.object({
api_key: z.string(),
workspace_id: z.string().optional(),
base_url: z.string().optional(),
})
.refine((config) => Boolean(config.workspace_id || config.base_url), {
message: "either workspace_id or base_url is required",
});

export type BailianConfig = z.infer<typeof bailianConfigSchema>;
15 changes: 8 additions & 7 deletions packages/sdk/src/internal/providers/base-client.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { resolveFetch } from "../transport.ts";
import type { RemoteResource } from "./interface.ts";

export class ApiError extends Error {
Expand Down Expand Up @@ -34,7 +35,7 @@ export abstract class BaseApiClient {
}

async post(path: string, body: unknown): Promise<unknown> {
const res = await fetch(`${this.baseUrl}${path}`, {
const res = await resolveFetch()(`${this.baseUrl}${path}`, {
method: "POST",
headers: this.headers(),
body: JSON.stringify(body),
Expand All @@ -44,7 +45,7 @@ export abstract class BaseApiClient {
}

async put(path: string, body: unknown): Promise<unknown> {
const res = await fetch(`${this.baseUrl}${path}`, {
const res = await resolveFetch()(`${this.baseUrl}${path}`, {
method: "PUT",
headers: this.headers(),
body: JSON.stringify(body),
Expand All @@ -54,15 +55,15 @@ export abstract class BaseApiClient {
}

async delete(path: string): Promise<void> {
const res = await fetch(`${this.baseUrl}${path}`, {
const res = await resolveFetch()(`${this.baseUrl}${path}`, {
method: "DELETE",
headers: this.headers(),
});
await this.throwIfError(res);
}

async get(path: string): Promise<unknown> {
const res = await fetch(`${this.baseUrl}${path}`, {
const res = await resolveFetch()(`${this.baseUrl}${path}`, {
method: "GET",
headers: this.headers(),
});
Expand All @@ -71,7 +72,7 @@ export abstract class BaseApiClient {
}

async getBuffer(path: string): Promise<Buffer> {
const res = await fetch(`${this.baseUrl}${path}`, {
const res = await resolveFetch()(`${this.baseUrl}${path}`, {
method: "GET",
headers: this.headers(),
});
Expand All @@ -81,7 +82,7 @@ export abstract class BaseApiClient {

async *sse(path: string, options?: { headers?: Record<string, string> }): AsyncGenerator<Record<string, unknown>> {
const controller = new AbortController();
const res = await fetch(`${this.baseUrl}${path}`, {
const res = await resolveFetch()(`${this.baseUrl}${path}`, {
method: "GET",
headers: { ...this.headers(), Accept: "text/event-stream", ...options?.headers },
signal: controller.signal,
Expand Down Expand Up @@ -140,7 +141,7 @@ export abstract class BaseApiClient {
// boundary itself. Every provider's multipart headers are exactly its JSON
// headers minus Content-Type, so derive them here.
const { "Content-Type": _contentType, ...headers } = this.headers();
const res = await fetch(`${this.baseUrl}${path}`, {
const res = await resolveFetch()(`${this.baseUrl}${path}`, {
method: "POST",
headers,
body: formData,
Expand Down
39 changes: 30 additions & 9 deletions packages/sdk/src/internal/providers/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,22 @@ export function allProviders(): ProviderDefinition[] {
return Array.from(registry.values());
}

/**
* Validate a raw provider config against its schema, mapping zod issues to a
* readable UserError. Providers call `.parse()`-style validation through here so
* config mistakes surface as `provider 'x' config invalid: field: message` lines
* instead of a raw ZodError JSON dump leaking to the host's stderr.
*/
function parseProviderConfig(def: ProviderDefinition, rawConfig: unknown): unknown {
const result = def.configSchema.safeParse(rawConfig);
if (result.success) return result.data;
const details = result.error.issues.map((issue) => {
const path = issue.path.join(".");
return path ? `${path}: ${issue.message}` : issue.message;
});
throw new UserError(`Provider '${def.name}' config invalid:\n${details.join("\n")}`);
}

export function buildProviders(
providersConfig: Record<string, unknown>,
projectName?: string,
Expand All @@ -62,7 +78,7 @@ export function buildProviders(
if (!def) {
throw new UserError(`Unknown provider '${name}'. Registered: ${Array.from(registry.keys()).join(", ")}`);
}
const parsed = def.configSchema.parse(rawConfig);
const parsed = parseProviderConfig(def, rawConfig);
const adapter = def.createAdapter(parsed, projectName);
validateProviderFacets(def, adapter);
adapters.set(name, adapter);
Expand All @@ -75,11 +91,14 @@ export function buildProviders(
* Environment variable mappings for each provider.
* Used to construct a provider adapter without a agents.yaml config file.
*/
const PROVIDER_ENV_VARS: Record<string, Record<string, { env: string[]; required: boolean }>> = {
const PROVIDER_ENV_VARS: Record<string, Record<string, { env: string[]; required: boolean; placeholder?: boolean }>> = {
bailian: {
api_key: { env: ["DASHSCOPE_API_KEY", "BAILIAN_API_KEY"], required: true },
workspace_id: { env: ["BAILIAN_WORKSPACE_ID"], required: true },
base_url: { env: ["BAILIAN_BASE_URL"], required: false },
// Neither workspace_id nor base_url is required on its own; the config schema
// enforces "at least one" so a host can supply just base_url (BAILIAN_BASE_URL).
// base_url is the preferred placeholder emitted by `agents sync`.
workspace_id: { env: ["BAILIAN_WORKSPACE_ID"], required: false },
base_url: { env: ["BAILIAN_BASE_URL"], required: false, placeholder: true },
},
qoder: {
api_key: { env: ["QODER_PAT", "QODER_API_KEY"], required: true },
Expand All @@ -97,15 +116,17 @@ const PROVIDER_ENV_VARS: Record<string, Record<string, { env: string[]; required

/**
* Build a `providers` config block for a single provider using `${ENV}`
* placeholders for its required fields. Used by `agents sync` to emit a providers
* block without leaking resolved secrets when the original file is unavailable.
* placeholders. Emits fields that are either required for env resolution or
* explicitly marked as the provider's preferred placeholder (e.g. bailian's
* base_url). Used by `agents sync` to emit a providers block without leaking
* resolved secrets when the original file is unavailable.
*/
export function placeholderProviderConfig(providerName: string): Record<string, string> {
const envMap = PROVIDER_ENV_VARS[providerName];
if (!envMap) return {};
const out: Record<string, string> = {};
for (const [field, { env, required }] of Object.entries(envMap)) {
if (required && env[0]) out[field] = `\${${env[0]}}`;
for (const [field, { env, required, placeholder }] of Object.entries(envMap)) {
if ((required || placeholder) && env[0]) out[field] = `\${${env[0]}}`;
}
return out;
}
Expand Down Expand Up @@ -160,7 +181,7 @@ export function buildProviderFromEnv(providerName: string, projectName?: string)
}

const config = resolveProviderConfigFromEnv(providerName);
const parsed = def.configSchema.parse(config);
const parsed = parseProviderConfig(def, config);
const adapter = def.createAdapter(parsed, projectName);
validateProviderFacets(def, adapter);
return adapter;
Expand Down
22 changes: 22 additions & 0 deletions packages/sdk/src/internal/transport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Host-injectable transport seam. A host embedding the SDK (a CLI, a server)
// can install a fetch-compatible implementation — e.g. to add tracking headers
// or request logging — without monkey-patching globalThis.fetch. Response
// semantics (ApiError classification, SSE parsing, pagination) stay in the
// provider clients regardless of the installed implementation.

export type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;

let defaultFetch: FetchLike | undefined;

/** Install the fetch implementation used by all provider clients; pass undefined to reset. */
export function setDefaultFetch(fetchImpl: FetchLike | undefined): void {
defaultFetch = fetchImpl;
}

/**
* Resolve the active fetch implementation. Falls back to the *current*
* globalThis.fetch (resolved per call, so test-time fetch mocks keep working).
*/
export function resolveFetch(): FetchLike {
return defaultFetch ?? ((input, init) => fetch(input, init));
}
20 changes: 17 additions & 3 deletions packages/sdk/tests/unit/bailian.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,19 @@ describe("bailianConfigSchema", () => {
expect(() => bailianConfigSchema.parse({ workspace_id: "ws-123" })).toThrow();
});

test("rejects config missing workspace_id", () => {
expect(() => bailianConfigSchema.parse({ api_key: "sk-abc" })).toThrow();
test("accepts base_url without workspace_id", () => {
const result = bailianConfigSchema.parse({
api_key: "sk-abc",
base_url: "https://custom.example.com/api/v1/agentstudio",
});
expect(result.workspace_id).toBeUndefined();
expect(result.base_url).toBe("https://custom.example.com/api/v1/agentstudio");
});

test("rejects config with neither workspace_id nor base_url", () => {
expect(() => bailianConfigSchema.parse({ api_key: "sk-abc" })).toThrow(
/either workspace_id or base_url is required/,
);
});
});

Expand Down Expand Up @@ -328,7 +339,10 @@ describe("Bailian mapEnvironment", () => {

test("rejects 'limited' networking instead of silently widening it", () => {
const decl: EnvironmentDecl = {
config: { type: "cloud", networking: { type: "limited", allowed_hosts: ["api.github.com"] } },
config: {
type: "cloud",
networking: { type: "limited", allowed_hosts: ["api.github.com"] },
},
};
// The real API rejects non-unrestricted networking; silently dropping the
// restriction would widen a declared egress boundary, so we must throw.
Expand Down
23 changes: 23 additions & 0 deletions packages/sdk/tests/unit/provider-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,29 @@ describe("provider-config bootstrap", () => {
}
});

test("areRuntimeCredentialsReady accepts BAILIAN_BASE_URL in place of workspace_id", () => {
const prevProvider = process.env.AGENTS_PROVIDER;
const prevKey = process.env.DASHSCOPE_API_KEY;
const prevWs = process.env.BAILIAN_WORKSPACE_ID;
const prevBaseUrl = process.env.BAILIAN_BASE_URL;
process.env.AGENTS_PROVIDER = "bailian";
process.env.DASHSCOPE_API_KEY = "sk-x";
delete process.env.BAILIAN_WORKSPACE_ID;
process.env.BAILIAN_BASE_URL = "https://ws.cn-beijing.maas.aliyuncs.com/api/v1/agentstudio";
try {
expect(areRuntimeCredentialsReady()).toBe(true);
} finally {
if (prevProvider === undefined) delete process.env.AGENTS_PROVIDER;
else process.env.AGENTS_PROVIDER = prevProvider;
if (prevKey === undefined) delete process.env.DASHSCOPE_API_KEY;
else process.env.DASHSCOPE_API_KEY = prevKey;
if (prevWs === undefined) delete process.env.BAILIAN_WORKSPACE_ID;
else process.env.BAILIAN_WORKSPACE_ID = prevWs;
if (prevBaseUrl === undefined) delete process.env.BAILIAN_BASE_URL;
else process.env.BAILIAN_BASE_URL = prevBaseUrl;
}
});

test("applyProviderConfigToEnv respects force flag", () => {
const prevProvider = process.env.AGENTS_PROVIDER;
const prevKey = process.env.ARK_API_KEY;
Expand Down
28 changes: 28 additions & 0 deletions packages/sdk/tests/unit/provider-registry.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { expect, test } from "bun:test";
import { placeholderProviderConfig } from "../../src/internal/providers/registry.ts";

// Placeholder values are literal "${ENV_VAR}" tokens; assert their shape with a
// regex instead of literal strings so biome's noTemplateCurlyInString rule (which
// guards against accidental template placeholders) stays happy.
const PLACEHOLDER_RE = /^\$\{[A-Z_]+\}$/;

// `agents sync` falls back to these placeholders when the source providers block
// is unavailable. bailian must emit base_url (its preferred field) so the emitted
// config is valid without a workspace_id.
test("placeholderProviderConfig emits api_key + base_url for bailian, not workspace_id", () => {
const block = placeholderProviderConfig("bailian");
expect(Object.keys(block).sort()).toEqual(["api_key", "base_url"]);
expect(block.workspace_id).toBeUndefined();
for (const value of Object.values(block)) {
expect(value).toMatch(PLACEHOLDER_RE);
}
});

test("placeholderProviderConfig emits only required fields for other providers", () => {
expect(Object.keys(placeholderProviderConfig("claude"))).toEqual(["api_key"]);
expect(Object.keys(placeholderProviderConfig("ark"))).toEqual(["api_key"]);
});

test("placeholderProviderConfig returns empty for an unknown provider", () => {
expect(placeholderProviderConfig("nope")).toEqual({});
});
Loading
Loading