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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,6 @@ packages/cli/scene/**/outputs/

# Local scratch / plan drafts (never commit)
.scratch/

# pnpm pack output
*.tgz
10 changes: 10 additions & 0 deletions packages/cli/src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ import {
memoryDelete,
memoryProfileCreate,
memoryProfileGet,
memoryProfileList,
memoryProfileDetail,
memoryProfileUpdate,
memoryProfileDelete,
knowledgeRetrieve,
knowledgeSearch,
knowledgeChat,
Expand Down Expand Up @@ -98,6 +102,7 @@ import {
managedAgentValidate,
managedAgentPlan,
managedAgentApply,
managedAgentRun,
managedAgentDestroy,
managedAgentStateList,
managedAgentStateShow,
Expand Down Expand Up @@ -149,6 +154,10 @@ export const commands: Record<string, AnyCommand> = {
"memory delete": memoryDelete,
"memory profile create": memoryProfileCreate,
"memory profile get": memoryProfileGet,
"memory profile list": memoryProfileList,
"memory profile detail": memoryProfileDetail,
"memory profile update": memoryProfileUpdate,
"memory profile delete": memoryProfileDelete,
"knowledge retrieve": knowledgeRetrieve,
"knowledge search": knowledgeSearch,
"knowledge chat": knowledgeChat,
Expand Down Expand Up @@ -217,6 +226,7 @@ export const commands: Record<string, AnyCommand> = {
"managed-agent validate": managedAgentValidate,
"managed-agent plan": managedAgentPlan,
"managed-agent apply": managedAgentApply,
"managed-agent run": managedAgentRun,
"managed-agent destroy": managedAgentDestroy,
"managed-agent state list": managedAgentStateList,
"managed-agent state show": managedAgentStateShow,
Expand Down
50 changes: 34 additions & 16 deletions packages/commands/src/commands/managed-agent/_engine/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export interface CredentialHost {
*/
export const CREDENTIALS_NOTE = [
"Bailian credentials come from bl's auth chain: --api-key > DASHSCOPE_API_KEY > `bl auth login` (active config profile).",
"The agentstudio endpoint is workspace-scoped: the base URL is composed from the workspace id (agents.yaml workspace_id > $BAILIAN_WORKSPACE_ID > bl's configured workspace_id) as https://{workspace}.cn-beijing.maas.aliyuncs.com/api/v1/agentstudio, and the key must belong to that workspace.",
"Other providers read the env vars referenced in agents.yaml (e.g. ${ANTHROPIC_API_KEY}), including .env and ~/.agents/config.json.",
"Resolved credentials are injected into the SDK in-memory and cleared from the environment; they never persist in process env.",
];
Expand Down Expand Up @@ -85,13 +86,19 @@ export function prepareProviderEnv(): void {
* the block references them and the interpolated value is empty (a literal in
* agents.yaml is respected).
*
* `base_url` carries {@link AGENTSTUDIO_API_PATH} because the SDK appends resource
* paths onto it verbatim; a value already ending in the suffix is left as-is.
* It is filled even without a credential — `client.baseUrl` is readable
* credential-less (defaults to the CLI's model-domain base URL) — so offline
* commands (which skip the credential assert) still satisfy the SDK's
* "workspace_id or base_url" schema. With no credential the `api_key` is left
* untouched: online commands reject it via {@link assertProviderCredentials}.
* `base_url` is composed from the workspace when one is known — block
* `workspace_id` (agents.yaml literal or interpolated `${BAILIAN_WORKSPACE_ID}`)
* first, then bl's configured `workspace_id` — because agentstudio is served
* only on the workspace-scoped host; the bare model-domain origin 404s it
* (managed-agents API overview: `https://{workspace_id}.cn-beijing.maas.
* aliyuncs.com/api/v1/agentstudio`, region cn-beijing only). Only with no
* workspace at all does the model-domain origin get {@link AGENTSTUDIO_API_PATH}
* suffixed. A value already ending in the suffix is left as-is. base_url is
* filled even without a credential — `client.baseUrl` is readable
* credential-less — so offline commands (which skip the credential assert)
* still satisfy the SDK's "workspace_id or base_url" schema. With no
* credential the `api_key` is left untouched: online commands reject it via
* {@link assertProviderCredentials}.
*/
export function injectProviderCredentials(
providers: Record<string, unknown>,
Expand All @@ -103,16 +110,27 @@ export function injectProviderCredentials(

const cred = host.client.exportApiCredential();
if (cred) block.api_key = cred.token;
if ("base_url" in block && !block.base_url) {
// Defensive normalization: the auth chain already normalizes base_url to
// an origin, but never let a trailing slash produce "//api/v1/agentstudio".
const origin = host.client.baseUrl.replace(/\/+$/, "");
block.base_url = origin.endsWith(AGENTSTUDIO_API_PATH)
? origin
: `${origin}${AGENTSTUDIO_API_PATH}`;
if ("workspace_id" in block && !block.workspace_id) {
// agents.yaml interpolation already replaced `${BAILIAN_WORKSPACE_ID}` in
// file-based flows; the inline runtime passes an object config that never
// interpolates, so read the env var here too (prepareProviderEnv
// placeholders it to "" when unset). bl's configured workspace_id is the
// last resort.
block.workspace_id =
process.env.BAILIAN_WORKSPACE_ID?.trim() || host.settings.workspaceId || "";
}
if ("workspace_id" in block && !block.workspace_id && host.settings.workspaceId) {
block.workspace_id = host.settings.workspaceId;
if ("base_url" in block && !block.base_url) {
const workspaceId = typeof block.workspace_id === "string" ? block.workspace_id.trim() : "";
if (workspaceId) {
block.base_url = `https://${workspaceId}.cn-beijing.maas.aliyuncs.com${AGENTSTUDIO_API_PATH}`;
} else {
// Defensive normalization: the auth chain already normalizes base_url to
// an origin, but never let a trailing slash produce "//api/v1/agentstudio".
const origin = host.client.baseUrl.replace(/\/+$/, "");
block.base_url = origin.endsWith(AGENTSTUDIO_API_PATH)
? origin
: `${origin}${AGENTSTUDIO_API_PATH}`;
}
}
}

Expand Down
124 changes: 124 additions & 0 deletions packages/commands/src/commands/managed-agent/_engine/inline-runtime.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
import {
type BackendRuntimeInput,
LocalFileStateBackend,
resolveProjectConfigFromObject,
} from "@openagentpack/sdk";
import { getConfigDir } from "bailian-cli-core";
import {
assertProviderCredentials,
type CredentialHost,
injectProviderCredentials,
normalizeInterpolatedProviderBlocks,
prepareProviderEnv,
scrubCredentialEnv,
} from "./credentials.ts";
import { type HostContext, installSdkTransport } from "./transport.ts";

/** Default agent identity `bl managed-agent run` materializes and reuses. */
export const DEFAULT_INLINE_AGENT = "dsh-remote-runner";

/** Default model for the materialized agent. */
export const DEFAULT_INLINE_MODEL = "qwen3.8-max";

/** Default role when the caller supplies no `--instructions`. */
export const DEFAULT_INLINE_INSTRUCTIONS = "You are a helpful assistant. Complete the task.";

/** Environment name declared in the inline config; one cloud env per agent. */
const INLINE_ENVIRONMENT = "cloud";

export interface InlineAgentOptions {
agentName: string;
instructions: string;
model: string;
/** Override the persisted state location (defaults under the bl config dir). */
statePath?: string;
}

/**
* Slugify an agent name into a filesystem- and project-id-safe token. The state
* for each distinct agent lives in its own directory so repeat runs reuse the
* same materialized remote agent.
*/
function slugify(agentName: string): string {
const slug = agentName
.toLowerCase()
.replace(/[^a-z0-9._-]+/g, "-")
.replace(/^-+|-+$/g, "");
return slug.length > 0 ? slug : "agent";
}

/** Where a materialized agent's state is persisted (not the user's cwd). */
export function inlineStatePath(agentName: string): string {
return join(getConfigDir(), "managed-agent", slugify(agentName), "state.json");
}

/**
* The minimal in-memory project config that materializes into one cloud agent.
* `providers.bailian` carries empty `api_key`/`base_url`/`workspace_id`
* placeholders so {@link injectProviderCredentials} fills them from bl's auth
* chain and workspace sources (it only writes fields the block already
* declares). `workspace_id` lets injection compose the workspace-scoped
* agentstudio host instead of the model-domain origin.
*/
export function buildInlineConfig(opts: InlineAgentOptions): Record<string, unknown> {
return {
version: "1",
providers: {
bailian: { api_key: "", base_url: "", workspace_id: "" },
},
defaults: { provider: "bailian" },
environments: {
[INLINE_ENVIRONMENT]: {
description: "Bailian CLI cloud environment",
config: { type: "cloud", networking: { type: "unrestricted" } },
},
},
agents: {
[opts.agentName]: {
description: opts.agentName,
model: opts.model,
instructions: opts.instructions,
environment: INLINE_ENVIRONMENT,
provider: "bailian",
},
},
};
}

/**
* Build the `BackendRuntimeInput` shared by ensure (`syncAgentResourcesWith
* StateBackend`) and run (`readProjectRuntime` + `startSessionRun`). Mirrors the
* credential spine of {@link buildAgentRuntime} but sources config from an
* in-memory object instead of a file, so no `agents.yaml` or `apply` is required.
*/
export async function buildInlineBackendInput(
host: HostContext & CredentialHost,
opts: InlineAgentOptions,
): Promise<BackendRuntimeInput> {
installSdkTransport(host);
prepareProviderEnv();

const rawConfig = buildInlineConfig(opts);
const { config, projectName } = await resolveProjectConfigFromObject(rawConfig, {
projectName: slugify(opts.agentName),
});

normalizeInterpolatedProviderBlocks(config.providers);
injectProviderCredentials(config.providers, host);
scrubCredentialEnv();
assertProviderCredentials(config.providers);

const statePath = opts.statePath ?? inlineStatePath(opts.agentName);
mkdirSync(dirname(statePath), { recursive: true });
const stateBackend = new LocalFileStateBackend({ statePath });

return {
projectName,
config,
stateBackend,
stateScope: { projectId: slugify(opts.agentName) },
providers: config.providers,
};
}
137 changes: 137 additions & 0 deletions packages/commands/src/commands/managed-agent/run.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import {
BailianError,
defineCommand,
detectOutputFormat,
ExitCode,
type FlagsDef,
} from "bailian-cli-core";
import { emitResult } from "bailian-cli-runtime";
import {
readProjectRuntime,
startSessionRun,
startSessionRunPolling,
syncAgentResourcesWithStateBackend,
} from "@openagentpack/sdk";
import { CREDENTIALS_NOTE } from "./_engine/config-loader.ts";
import { withStdoutProtected } from "./_engine/console-capture.ts";
import { withAgentErrors } from "./_engine/errors.ts";
import {
buildInlineBackendInput,
DEFAULT_INLINE_AGENT,
DEFAULT_INLINE_INSTRUCTIONS,
DEFAULT_INLINE_MODEL,
} from "./_engine/inline-runtime.ts";
import { renderCollectedEvents, streamAndRenderEvents } from "./_engine/session-render.ts";

const RUN_FLAGS = {
prompt: {
type: "string",
valueHint: "<text>",
description: "Task to run (required)",
required: true,
},
instructions: {
type: "string",
valueHint: "<text>",
description: "Role/system instructions for the remote agent (default: generic assistant)",
},
model: {
type: "string",
valueHint: "<id>",
description: `Model for the remote agent (default: ${DEFAULT_INLINE_MODEL})`,
},
agent: {
type: "string",
valueHint: "<name>",
description: `Agent identity to create/reuse (default: ${DEFAULT_INLINE_AGENT})`,
},
noStream: {
type: "switch",
description: "Use polling instead of SSE streaming",
},
} satisfies FlagsDef;

export default defineCommand({
description: "Provision (if needed) a cloud agent and run a task in one step",
auth: "apiKey",
usageArgs: "--prompt <text> [--instructions <text>] [--model <id>] [--agent <name>]",
flags: RUN_FLAGS,
exampleArgs: [
'--prompt "Summarize the latest AI news"',
'--prompt "Audit this dependency tree" --instructions "You are a security expert" --model qwen3.8-max',
],
notes: [
...CREDENTIALS_NOTE,
"Unlike `apply`, this creates/updates the cloud agent + environment on demand without --yes. The first run provisions cloud resources (may incur cost and take longer to start); later runs with the same --agent reuse them.",
],
async run(ctx) {
const { settings, flags } = ctx;
const format = detectOutputFormat(settings.output);
const asJson = format === "json";

const agentName = flags.agent ?? DEFAULT_INLINE_AGENT;
const model = flags.model ?? DEFAULT_INLINE_MODEL;
const instructions = flags.instructions ?? DEFAULT_INLINE_INSTRUCTIONS;

if (settings.dryRun) {
emitResult(
{
would_run: {
prompt: flags.prompt,
agent: agentName,
model,
instructions,
mode: flags.noStream ? "polling" : "streaming",
},
},
format,
);
return;
}

await withAgentErrors(() =>
withStdoutProtected(async () => {
const input = await buildInlineBackendInput(ctx, { agentName, instructions, model });

// Ensure the remote agent + its cloud environment exist. Idempotent:
// a repeat run with the same agent name reuses the materialized state.
if (!asJson) process.stderr.write(`Ensuring cloud agent "${agentName}"…\n`);
const sync = await syncAgentResourcesWithStateBackend(input, agentName, {
policy: "force",
quiet: true,
});
if (sync.status !== "completed") {
const detail =
sync.error ??
sync.diagnostics.find((diag) => diag.severity === "error")?.message ??
`provisioning ended with status "${sync.status}"`;
throw new BailianError(
`Failed to provision cloud agent "${agentName}": ${detail}`,
ExitCode.GENERAL,
);
}

// Run the task inside a runtime bound to the just-materialized state.
await readProjectRuntime(input, async (runtime) => {
if (flags.noStream) {
const run = await startSessionRunPolling(runtime, flags.prompt, { agent: agentName });
if (!asJson) process.stderr.write(`Session created: ${run.session.id}\n`);
renderCollectedEvents(run, asJson, {
session_id: run.session.id,
provider: run.provider,
agent: run.agentName,
});
} else {
const run = await startSessionRun(runtime, flags.prompt, { agent: agentName });
if (!asJson) process.stderr.write(`Session created: ${run.session.id}\n`);
await streamAndRenderEvents(run.events, asJson, {
session_id: run.session.id,
provider: run.provider,
agent: run.agentName,
});
}
});
}),
);
},
});
Loading