Skip to content
Open
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
4 changes: 4 additions & 0 deletions docs/agents/auth-change.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ defineCommand({ auth }) → runtime/authStage → ctx.client → command.run(ctx

命令不要直接解析 token、env 或 config。业务请求统一走 `ctx.client`;登录/配置命令通过 `ctx.authStore` / `ctx.configStore` 的窄接口操作落盘。

### 例外:agent 命令的 SDK 凭证桥接

`bl agent *` 命令声明 `auth: "none"`,凭证由 `@openagentpack/sdk` 自主从 env 解析(agents.yaml 的 `${DASHSCOPE_API_KEY}` / `${BAILIAN_WORKSPACE_ID}` 插值)。为让 bl 登录态复用,`packages/commands/src/commands/agent/_engine/credentials.ts` 的 `bridgeBailianCredentials()` 会**直接 `readConfigFile()`**,把 config 的 `api_key` / `workspace_id` 作为最低优先级兜底填入对应 env,仅填空值,不覆盖已有。这是唯一允许命令层直接读 config 的场景(SDK 只认 env,不走 `ctx.client`);优先级链:`~/.agents/config.json` > shell env > `.env` > `~/.bailian/config.json`。

## 必查清单

### A. core 层(类型 + 解析)
Expand Down
5 changes: 4 additions & 1 deletion packages/cli/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@ node_modules
dist
*.log
.DS_Store
outputs/
outputs/
# agents
agents.state.json
.env
32 changes: 32 additions & 0 deletions packages/cli/src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,22 @@ import {
pluginLink,
pluginList,
pluginRemove,
agentInit,
agentValidate,
agentPlan,
agentApply,
agentDestroy,
agentStateList,
agentStateShow,
agentStateRm,
agentStateImport,
agentSessionCreate,
agentSessionList,
agentSessionGet,
agentSessionDelete,
agentSessionRun,
agentSessionSend,
agentSessionEvents,
} from "bailian-cli-commands";

// Full bailian-cli product: every command, exposed under the `bl` binary.
Expand Down Expand Up @@ -186,4 +202,20 @@ export const commands: Record<string, AnyCommand> = {
"plugin link": pluginLink,
"plugin list": pluginList,
"plugin remove": pluginRemove,
"agent init": agentInit,
"agent validate": agentValidate,
"agent plan": agentPlan,
"agent apply": agentApply,
"agent destroy": agentDestroy,
"agent state list": agentStateList,
"agent state show": agentStateShow,
"agent state rm": agentStateRm,
"agent state import": agentStateImport,
"agent session create": agentSessionCreate,
"agent session list": agentSessionList,
"agent session get": agentSessionGet,
"agent session delete": agentSessionDelete,
"agent session run": agentSessionRun,
"agent session send": agentSessionSend,
"agent session events": agentSessionEvents,
};
1 change: 1 addition & 0 deletions packages/commands/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"check": "vp check"
},
"dependencies": {
"@openagentpack/sdk": "0.3.0-beta-8d9edcd-20260722",
"bailian-cli-core": "workspace:*",
"bailian-cli-runtime": "workspace:*",
"boxen": "catalog:",
Expand Down
11 changes: 11 additions & 0 deletions packages/commands/src/commands/agent/_engine/address-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { ResourceAddress } from "@openagentpack/sdk";

/** Full state address: provider.type.name */
export function formatResourceAddress(address: ResourceAddress): string {
return `${address.provider}.${address.type}.${address.name}`;
}

/** CLI display short label: type.name (provider) */
export function formatResourceLabel(address: ResourceAddress): string {
return `${address.type}.${address.name} (${address.provider})`;
}
54 changes: 54 additions & 0 deletions packages/commands/src/commands/agent/_engine/config-loader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import {
createProjectRuntime,
type ProjectRuntimeContext,
resolveProjectConfig,
UserError,
} from "@openagentpack/sdk";
import { ensureCredentials } from "./credentials.ts";
import { loadFileState } from "./file-state-manager.ts";
import { type HostContext, installSdkTransport } from "./transport.ts";

export { CREDENTIALS_NOTE } from "./credentials.ts";

/**
* Build a full ProjectRuntimeContext from a config file path — the standard
* entry point for agent commands that need the SDK engine. Mirrors OpenAgentPack
* CLI's buildCliRuntime: resolve config → load local state → assemble runtime.
* Takes the host context first so every SDK-engine command wires the
* instrumented transport (UA / tracking headers / verbose) by construction.
*/
export async function buildAgentRuntime(
host: HostContext,
filePath: string,
options: {
resolveEnv?: boolean;
projectName?: string;
statePath?: string;
} = {},
): Promise<ProjectRuntimeContext & { configPath: string }> {
installSdkTransport(host);
ensureCredentials();
const { config, configPath, projectName } = await resolveProjectConfig(filePath, options);
const state = await loadFileState(configPath, options.statePath, projectName);
const ctx = createProjectRuntime({
projectName,
config,
state,
configPath,
providers: config.providers,
});
return { ...ctx, configPath };
}

/** Ensure a user-supplied --provider value is actually configured in agents.yaml. */
export function assertProviderConfigured(
ctx: ProjectRuntimeContext,
provider: string | undefined,
): void {
if (!provider || provider === "all") return;
if (ctx.providers.has(provider)) return;
const available = Array.from(ctx.providers.keys()).join(", ") || "none";
throw new UserError(
`Provider '${provider}' is not configured. Available providers: ${available}.`,
);
}
23 changes: 23 additions & 0 deletions packages/commands/src/commands/agent/_engine/console-capture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* Redirect `console.log` / `console.info` to stderr while `fn` runs.
*
* The OpenAgentPack SDK's provider adapters emit progress/debug logging via
* `console.log` (e.g. `[skill-upload]`), which would corrupt bl's stdout data
* channel in `--output json` mode. Wrapping SDK calls that may log keeps stdout
* a clean data channel. Restores the originals on completion.
*/
export async function withStdoutProtected<T>(fn: () => Promise<T>): Promise<T> {
const originalLog = console.log;
const originalInfo = console.info;
const toStderr = (...args: unknown[]): void => {
process.stderr.write(`${args.map((arg) => String(arg)).join(" ")}\n`);
};
console.log = toStderr;
console.info = toStderr;
try {
return await fn();
} finally {
console.log = originalLog;
console.info = originalInfo;
}
}
63 changes: 63 additions & 0 deletions packages/commands/src/commands/agent/_engine/credentials.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { bootstrapRuntimeCredentialsSync } from "@openagentpack/sdk";
import { readConfigFile } from "bailian-cli-core";

let bootstrapped = false;

/**
* Shared `--help` note documenting where agent commands get provider
* credentials. Mirrors the credential-source hint bl's native commands surface
* (knowledge / usage / token-plan), adapted for the SDK's env-based resolution
* and the {@link bridgeBailianCredentials} fallback. Attach to every command
* that loads agents.yaml. `bl` prefix is safe: agent commands ship on `bl` only.
*/
export const CREDENTIALS_NOTE = [
"Credentials come from the env vars referenced in agents.yaml (e.g. ${DASHSCOPE_API_KEY}, ${BAILIAN_BASE_URL}).",
"For the bailian provider, bl fills these from your login as a fallback: `bl auth login --api-key <key> --agentstudio-base-url <url>`.",
];

/**
* Bridge bl's own login state into the env vars the OpenAgentPack SDK reads for
* the bailian provider. bl persists `api_key` / `agentstudio_base_url` in
* `~/.bailian/config.json` (via `bl auth login`); mirror them onto
* `DASHSCOPE_API_KEY` / `BAILIAN_BASE_URL` so users don't have to re-declare the
* same credentials for `bl agent *`. `workspace_id` is still bridged for configs
* that predate the base_url flow (the SDK accepts either).
*
* Lowest priority: only fills a var that is still unset, so anything already in
* the environment (shell export, `.env`, or `~/.agents/config.json` — which the
* SDK bootstrap has already applied) wins. Missing values are left alone; the
* SDK surfaces its own error when interpolation can't resolve, and non-bailian
* providers (claude/qoder/ark) don't need DashScope credentials at all.
*/
export function bridgeBailianCredentials(): void {
const file = readConfigFile();
if (!process.env.DASHSCOPE_API_KEY?.trim() && file.api_key) {
process.env.DASHSCOPE_API_KEY = file.api_key;
}
if (!process.env.BAILIAN_BASE_URL?.trim() && file.agentstudio_base_url) {
process.env.BAILIAN_BASE_URL = file.agentstudio_base_url;
}
if (!process.env.BAILIAN_WORKSPACE_ID?.trim() && file.workspace_id) {
process.env.BAILIAN_WORKSPACE_ID = file.workspace_id;
}
}

/**
* Lazily load `.env` and `~/.agents/config.json` into `process.env` so the
* OpenAgentPack SDK can resolve provider credentials (e.g. DASHSCOPE_API_KEY,
* BAILIAN_WORKSPACE_ID), then bridge bl's own config as a fallback. Safe to call
* repeatedly — only the first call does I/O.
*
* Effective precedence for bailian provider fields:
* ~/.agents/config.json > shell env > .env > ~/.bailian/config.json
*
* NOTE: agent commands declare `auth: "none"` and let the SDK own credential
* resolution. The bl-config bridge is a best-effort fallback; it never overrides
* a value the SDK bootstrap already resolved.
*/
export function ensureCredentials(): void {
if (bootstrapped) return;
bootstrapped = true;
bootstrapRuntimeCredentialsSync();
bridgeBailianCredentials();
}
57 changes: 57 additions & 0 deletions packages/commands/src/commands/agent/_engine/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { UserError } from "@openagentpack/sdk";
import { type ApiErrorBody, BailianError, ExitCode, mapApiError } from "bailian-cli-core";

/**
* Structural shape of the SDK's `ApiError` (thrown by provider clients on HTTP
* 4xx/5xx). Matched on fields instead of `instanceof` because the installed SDK
* version does not export the class yet, and structural matching keeps this
* check stable across SDK versions either way.
*/
interface SdkApiErrorLike extends Error {
statusCode: number;
responseBody: string;
}

function isSdkApiError(error: Error): error is SdkApiErrorLike {
const candidate = error as Partial<SdkApiErrorLike>;
return typeof candidate.statusCode === "number" && typeof candidate.responseBody === "string";
}

/**
* The SDK embeds the raw response body in its error message; recover the
* structured fields (message / code / request_id) when the body is JSON so
* `mapApiError` surfaces a clean server message plus api metadata. Non-JSON
* bodies pass through verbatim as the message.
*/
function parseSdkResponseBody(raw: string): ApiErrorBody {
try {
const parsed: unknown = JSON.parse(raw);
if (parsed && typeof parsed === "object") return parsed as ApiErrorBody;
} catch {
/* non-JSON body */
}
return { message: raw.trim() || undefined };
}

/**
* Run an SDK-backed operation, translating SDK error types into BailianError so
* bl's error handler produces the right exit code and hint formatting.
* SDK `UserError` → USAGE; SDK `ApiError` (server HTTP error) → GENERAL via
* `mapApiError` (server message passed through verbatim, with
* httpStatus/apiCode/requestId metadata for --output json); any other Error →
* GENERAL (message passed through, per bl's "don't translate server errors"
* boundary).
*/
export async function withAgentErrors<T>(fn: () => Promise<T>): Promise<T> {
try {
return await fn();
} catch (error) {
if (error instanceof BailianError) throw error;
if (error instanceof UserError) throw new BailianError(error.message, ExitCode.USAGE);
if (error instanceof Error && isSdkApiError(error)) {
throw mapApiError(error.statusCode, parseSdkResponseBody(error.responseBody));
}
if (error instanceof Error) throw new BailianError(error.message, ExitCode.GENERAL);
throw error;
}
}
10 changes: 10 additions & 0 deletions packages/commands/src/commands/agent/_engine/feedback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type { RuntimeFeedbackEvent } from "@openagentpack/sdk";

/**
* Render SDK runtime feedback to stderr, keeping stdout a clean data channel.
* Used as the `onFeedback` sink for plan/apply so progress messages don't mix
* with structured output.
*/
export function renderAgentFeedback(event: RuntimeFeedbackEvent): void {
process.stderr.write(`${event.message}\n`);
}
24 changes: 24 additions & 0 deletions packages/commands/src/commands/agent/_engine/file-state-manager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { basename, dirname, resolve } from "node:path";
import {
type IStateManager,
LocalFileStateBackend,
StateManager,
type StateScope,
} from "@openagentpack/sdk";

function createStateScope(configPath: string, projectName?: string): StateScope {
const resolved = resolve(configPath);
return { projectId: projectName ?? basename(dirname(resolved)) };
}

/** Load or initialize a file-based StateManager (mirrors OpenAgentPack CLI). */
export async function loadFileState(
configPath: string,
statePath?: string,
projectName?: string,
): Promise<IStateManager> {
const resolved = resolve(configPath);
const backend = new LocalFileStateBackend({ configPath: resolved, statePath });
const path = backend.getStatePath(createStateScope(resolved, projectName));
return StateManager.load(path);
}
25 changes: 25 additions & 0 deletions packages/commands/src/commands/agent/_engine/pagination.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export interface PagedResult<T> {
items: T[];
hasMore: boolean;
nextPage?: string;
}

/** Fetch the first page, then follow cursors while `all` is true. */
export async function fetchAllPages<T>(
fetchPage: (page?: string) => Promise<PagedResult<T>>,
all?: boolean,
): Promise<PagedResult<T>> {
const first = await fetchPage();
const items = [...first.items];
let hasMore = first.hasMore;
let nextPage = first.nextPage;

while (all && nextPage) {
const next = await fetchPage(nextPage);
items.push(...next.items);
hasMore = next.hasMore;
nextPage = next.nextPage;
}

return { items, hasMore, nextPage };
}
Loading