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
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,11 +228,15 @@ Get an ordinary key from the [DashScope Console](https://bailian.console.aliyun.

### Alibaba Cloud OpenAPI AK/SK

Token Plan seat and member management requires an Alibaba Cloud AccessKey. Get yours from the [RAM Console](https://ram.console.aliyun.com/manage/ak).
Token Plan seat/member management and console token refresh need an Alibaba Cloud AccessKey. Run the setup guide, or get keys from the [RAM Console](https://ram.console.aliyun.com/manage/ak) and paste them.

> Recommended: create a RAM sub-account with minimum privileges instead of using the root account's AK/SK.

```bash
# Open the setup guide (when finished, paste your AccessKey back in the terminal)
bl auth login --open-api

# If you already have an AccessKey, configure it directly
bl auth login --open-api --access-key-id LTAI5t... --access-key-secret ...
```

Expand Down
6 changes: 5 additions & 1 deletion README.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,11 +227,15 @@ bl auth login --api-key <API_KEY>

### 阿里云 OpenAPI AK/SK

Token Plan 的席位与成员管理需要阿里云 AccessKey。前往 [RAM 控制台](https://ram.console.aliyun.com/manage/ak) 获取。
Token Plan 的席位与成员管理、以及控制台会话换票需要阿里云 AccessKey。可先运行引导获取,或前往 [RAM 控制台](https://ram.console.aliyun.com/manage/ak) 获取后粘贴。

> 建议:创建 RAM 子账号并授予最小权限,避免使用主账号 AK/SK。

```bash
# 打开引导页(按照引导完成操作后,回到命令行粘贴 AccessKey)
bl auth login --open-api

# 若已有 AccessKey,直接配置
bl auth login --open-api --access-key-id LTAI5t... --access-key-secret ...
```

Expand Down
6 changes: 5 additions & 1 deletion docs/agents/auth-change.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,11 @@ defineCommand({ auth }) → runtime/authStage → ctx.client → command.run(ctx
- `bl auth login --api-key ...` 先通过只读 `GET /models` 校验 Key,校验成功后才原子写入 `api_key` 与实际匹配的 `base_url`。公共 DashScope 站点使用 `/api/v1/models?page_no=1&page_size=1`,`*.maas.aliyuncs.com`(Workspace 与 Token Plan)使用 `/compatible-mode/v1/models`。显式 `--base-url` 只校验该站点,不自动改写;未显式指定时,普通 `sk-*` / `sk-ws-*` 按“当前 Profile 已保存的同类站点 → 基于 `workspace_id` 构造的各地域 Workspace 专属站点 → 公共地域”顺序选择首个成功结果,`sk-sp-*` 并行探测国内站与新加坡 Token Plan,其他格式同时尝试两类候选。所有候选失败时选择最有诊断价值的原始错误透传:无 HTTP status 的网络、超时或响应解析错误优先,其次为 HTTP 429/5xx,最后为其他 HTTP 错误;同级保持候选顺序。HTTP status、API code、request ID 与服务端 message 保持不变,不重新分类为 `AUTH`。任一失败都不落盘、不激活 Profile
- 未显式传 `--config` 时,`sk-sp-*` 自动写入并激活 `token-plan`;普通 `sk-*` / `sk-ws-*` 仅在当前为 `token-plan` 时改写并激活 `default`,否则保留当前 Profile;其他格式不自动切换。显式 `--config` 始终优先。`sk-sp-*` 无论写入哪个 Profile 都会携带 Token Plan 的预设默认模型,并在保留已有项的基础上补齐 `api_key_capabilities`,不自动删除任何已有能力。登录仍不得删除其他鉴权域的凭证
- `bl auth login --console` 更新 `access_token` 以及回调携带的 console 作用域字段;若所选 Profile 没有模型 API Key,会要求控制台页面创建并回传一个普通 API Key 与 Base URL 一并保存。该回调结果不重复执行 `/models` 校验,且不会创建或配置 Token Plan
- `bl auth login --open-api ...` 调用 OpenAPI 生成 CLI `access_token`,通过目标 Console 网关的只读 `loginInfo` 校验后,才一并写入 `access_key_id` / `access_key_secret` / `access_token` 和实际 `console_region` / `console_site`;失败不覆盖原凭证、不激活 Profile。一次成功登录同时产生 `openapi` 与 `console` 域凭证
- `bl auth login --open-api` **不带** AK/SK:打开控制台 `/aksk-guide` 浏览器引导(不等浏览器回传、不启本地 callback;SecretKey 不会经页面回传)。URL 与粘贴命令必须在等待打开器之前打印(顺序规则与 `login-console.ts`「先注册回调再打开」一致),并且这条等待**由引导自己选择上限**:`openInBrowser(url, { timeoutMs: 5000 })`——Linux `xdg-open` 在部分桌面会挂到浏览器退出,不设上限就会占住终端、用户无法粘贴后续命令。被上限杀掉归类为「未确认」(`isOpenPathTimeout`),文案不得说成失败,也不得宣称「已打开」;结果文案不得与警告重复同一句「请手动打开上方地址」;exit 仍为 0。支持 `--no-browser` 只打印 URL,以及 `--console-site` 选择国内/国际站。粘贴命令**无条件回显**引导页实际使用的 `--console-site`(含显式 `domestic`)与按 `recoveryConfigName` 解析出的 `--config`,使粘贴回来等价于「引导页站点 + 目标 Profile」
- `shared/local-server.ts` 的 `openPath` / `openInBrowser`:**等待上限是 opt-in,默认不设 `timeout`**。这条是硬约束,不要改成全局默认——`config/ui.ts` 的 `/api/agent/open`、`/api/asset/open` 把 reject 映射成 HTTP 400,`config ui` 启动与 `login-console.ts` 把 reject 说成「无法打开默认浏览器」;给它们加默认上限会把「已经打开但慢」误报成失败。要上限的调用方显式传 `timeoutMs`,并**必须**用 `isOpenPathTimeout(error)` 分支出「未确认」。上限生效靠的是到点 `SIGTERM` 杀掉子进程:`child.unref()` 单独不够,`execFile` 的 stdout/stderr 管道句柄仍会 ref 住事件循环(实测仍等满)
- `bl auth login --open-api --access-key-id … --access-key-secret …`:调用 OpenAPI 生成 CLI `access_token`,通过目标 Console 网关的只读 `loginInfo` 校验后,才一并写入 `access_key_id` / `access_key_secret` / `access_token` 和实际 `console_region` / `console_site`;失败不覆盖原凭证、不激活 Profile。一次成功登录同时产生 `openapi` 与 `console` 域凭证。`--console-site` 在 guide 与带 AK/SK 落盘路径均可用,且落盘路径必须尊重它:`resolveCLIAccessTokenTarget` / `generateCLIAccessToken` / `validateConsoleAccessToken` 三跳都要用同一个由 `flags.consoleSite || settings.consoleSite || "domestic"` 解析出的站点(`generateCLIAccessToken` 内部会重算 target,漏一跳就回到旧值)。`region × site` 在 `console/gateway.ts` 是二维合法表,无需联动改 region
- **命令自有 flag 与 `settings` 的同名字段**:`create-cli.ts` 只把全局 flag 与凭证域 flag(`GLOBAL_FLAGS` + `credentialFlagDefs(cmd)`)放进 `sources`,命令 `flags` map 里声明的键只进 `ctx.flags`。因此 `auth: "none"` 这类命令里,`settings.<field>` **读不到用户传的 flag**,而 `validate()` 收到的是 `ctx.flags`——于是出现「校验放行、执行时静默忽略」的窗口。凡是 run 里要用到命令自有 flag,必须显式 `flags.X || settings.X`,不得只读 `settings.X`;新增这类 flag 时补一条「flag 与 Profile 默认值不一致时以 flag 为准」的用例(`tests/auth-login-openapi-site.test.ts` 是模板)。`--dry-run` 提前 return 的分支不会覆盖这类缺陷,不能作为「flag 生效」的证据
- `auth status` 未配置 OpenAPI 时提示:先 `auth login --open-api` 按引导获取 AccessKey;若已有则用 `--access-key-id` / `--access-key-secret` 直接配置。缺凭证的 AUTH hint 同样指向 `auth login --open-api`,并保留成对 flag / env 说明
- `bl auth logout --console` 只清 `access_token`
- `bl auth logout --open-api` 只清 `access_key_id` / `access_key_secret` / `security_token`
- `bl auth logout` 清 `api_key` + `base_url` + `access_token` + `access_key_*`
Expand Down
6 changes: 5 additions & 1 deletion packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,11 +228,15 @@ Get an ordinary key from the [DashScope Console](https://bailian.console.aliyun.

### Alibaba Cloud OpenAPI AK/SK

Token Plan seat and member management requires an Alibaba Cloud AccessKey. Get yours from the [RAM Console](https://ram.console.aliyun.com/manage/ak).
Token Plan seat/member management and console token refresh need an Alibaba Cloud AccessKey. Run the setup guide, or get keys from the [RAM Console](https://ram.console.aliyun.com/manage/ak) and paste them.

> Recommended: create a RAM sub-account with minimum privileges instead of using the root account's AK/SK.

```bash
# Open the setup guide (when finished, paste your AccessKey back in the terminal)
bl auth login --open-api

# If you already have an AccessKey, configure it directly
bl auth login --open-api --access-key-id LTAI5t... --access-key-secret ...
```

Expand Down
6 changes: 5 additions & 1 deletion packages/cli/README.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,11 +227,15 @@ bl auth login --api-key <API_KEY>

### 阿里云 OpenAPI AK/SK

Token Plan 的席位与成员管理需要阿里云 AccessKey。前往 [RAM 控制台](https://ram.console.aliyun.com/manage/ak) 获取。
Token Plan 的席位与成员管理、以及控制台会话换票需要阿里云 AccessKey。可先运行引导获取,或前往 [RAM 控制台](https://ram.console.aliyun.com/manage/ak) 获取后粘贴。

> 建议:创建 RAM 子账号并授予最小权限,避免使用主账号 AK/SK。

```bash
# 打开引导页(按照引导完成操作后,回到命令行粘贴 AccessKey)
bl auth login --open-api

# 若已有 AccessKey,直接配置
bl auth login --open-api --access-key-id LTAI5t... --access-key-secret ...
```

Expand Down
115 changes: 115 additions & 0 deletions packages/commands/src/commands/auth/login-openapi-guide.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { formatCommand, type Identity, type LocalizedText } from "bailian-cli-core";
import { akskGuidePage } from "bailian-cli-runtime";
import { isOpenPathTimeout, openInBrowser } from "../shared/local-server.ts";
import { resolveConsoleOrigin, type LoginDeps } from "./login-console.ts";

/**
* How long this guide may wait on the OS opener before calling the outcome
* unconfirmed. The command prints a paste-ready follow-up command and must hand the
* prompt back for it, so it opts into a cap that other `openPath` callers do not pay.
*/
const OPEN_WAIT_CAP_MS = 5_000;

export interface OpenApiGuideOptions {
site?: string;
/** Profile name to echo as `--config` in the paste-ready command. */
config?: string;
noBrowser?: boolean;
}

export interface OpenApiPasteOptions {
site?: string;
config?: string;
}

function localizeGuide(deps: LoginDeps, text: LocalizedText): string {
if (typeof text === "string") return text;
return deps.localize ? deps.localize(text) : text["en-US"];
}

/** Console URL for the OpenAPI AK/SK browser guide. */
export function resolveAkskGuideUrl(site?: string): string {
return akskGuidePage(resolveConsoleOrigin(site));
}

/** Paste-ready command after the browser guide completes. */
export function openApiPasteCommand(identity: Identity, options: OpenApiPasteOptions = {}): string {
const parts = ["auth login --open-api --access-key-id <id> --access-key-secret <secret>"];
// Always echo the resolved site. It is exactly the site the guide page targeted,
// so pinning it can never be wrong; omitting it lets a Profile default override an
// explicit choice (e.g. file `console_site: international` + `--console-site domestic`
// would otherwise save the credential to the international gateway).
if (options.site) {
parts.push(`--console-site ${options.site}`);
}
if (options.config?.trim()) {
parts.push(`--config ${options.config.trim()}`);
}
return formatCommand(identity, parts.join(" "));
}

/**
* Open (or print) the AK/SK guide page. Does not wait for a callback — SecretKey
* never returns through the browser. The URL and the paste-ready command are printed
* before awaiting the opener, so a slow or hanging `open` / `xdg-open` never withholds
* what the user needs to act on — the same ordering rule `login-console.ts` follows by
* registering the callback before opening the browser.
*
* The wait is capped via `openInBrowser(url, { timeoutMs })`: on desktops where
* `xdg-open` stays attached to the browser, an uncapped await would keep the prompt
* away and the user could not paste the follow-up command. An opener killed at that
* cap is an unconfirmed outcome — never reported as a failure, never as a success.
*/
export async function runOpenApiGuide(
deps: LoginDeps,
options: OpenApiGuideOptions = {},
): Promise<{ url: string; browserOpened: boolean }> {
const url = resolveAkskGuideUrl(options.site);
const paste = openApiPasteCommand(deps.identity, {
site: options.site,
config: options.config,
});

deps.output.info(
`${localizeGuide(deps, {
"en-US": "Open the following URL in your browser:",
"zh-CN": "请在浏览器中打开以下地址:",
})}\n${url}`,
);

deps.output.info(
localizeGuide(deps, {
"en-US": `After finishing the guide, return here and paste your AccessKey:\n ${paste}`,
"zh-CN": `按照引导完成操作后,回到当前命令行粘贴AccessKey:\n ${paste}`,
}),
);

let browserOpened = false;
if (!options.noBrowser) {
try {
await openInBrowser(url, { timeoutMs: OPEN_WAIT_CAP_MS });
browserOpened = true;
} catch (error: unknown) {
if (isOpenPathTimeout(error)) {
deps.output.warning(
localizeGuide(deps, {
"en-US":
"Could not confirm the browser opened: the system open command did not return in time. Open the URL above manually if no tab appeared.",
"zh-CN":
"未能确认浏览器是否打开:系统打开命令超时未返回。若没有新标签页,请手动打开上方地址。",
}),
);
} else {
const reason = error instanceof Error ? error.message : String(error);
deps.output.warning(
localizeGuide(deps, {
"en-US": `Could not open a browser automatically (${reason}). Open the URL above manually.`,
"zh-CN": `无法自动打开浏览器(${reason})。请手动打开上方地址。`,
}),
);
}
}
}

return { url, browserOpened };
}
Loading