@aronnaxlin/bgm-cli 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -15,8 +15,8 @@
15
15
  npm / npx:
16
16
 
17
17
  ```bash
18
- npx @aronnax/bgm-cli --help
19
- npm install -g @aronnax/bgm-cli
18
+ npx @aronnaxlin/bgm-cli --help
19
+ npm install -g @aronnaxlin/bgm-cli
20
20
  ```
21
21
 
22
22
  macOS / Linux:
@@ -52,6 +52,19 @@ bgm auth set-token YOUR_ACCESS_TOKEN
52
52
  bgm auth token-status
53
53
  ```
54
54
 
55
+ ### Multiple accounts
56
+
57
+ Snapshot the current credentials as a named profile and switch between accounts quickly:
58
+
59
+ ```bash
60
+ bgm auth profile save main
61
+ bgm auth profile list
62
+ bgm auth profile use another
63
+ bgm --profile another user me
64
+ ```
65
+
66
+ `bgm --profile <name> <command>` runs a single command as that account without switching; it is a read-only override and never writes to disk.
67
+
55
68
  ### Proxy
56
69
 
57
70
  If your network needs a proxy to reach the Bangumi API reliably, configure an HTTP/HTTPS proxy for all CLI requests:
@@ -80,13 +93,34 @@ bgm character search "Asuka" --limit 3
80
93
  bgm person search "Anno" --limit 3
81
94
  bgm collection get 348335
82
95
  bgm collection indexes --user sai --limit 5
96
+ bgm book get 3510
97
+ bgm book ep 3510 10
83
98
  bgm group list --sort members --limit 10
84
99
  bgm group user sai --limit 5
85
100
  bgm index user sai --limit 5
101
+ bgm search subject "One Piece" --limit 5
86
102
  bgm trending subjects --type anime --limit 5
87
103
  bgm --json user me
88
104
  ```
89
105
 
106
+ ### Paste A Link
107
+
108
+ Hand a Bangumi web link straight to `bgm` and it resolves to the matching command:
109
+
110
+ ```bash
111
+ bgm "https://bangumi.tv/group/topic/469977#post_4029724" # that single reply -> bgm group post 4029724
112
+ bgm url https://bgm.tv/subject/253/characters # -> bgm subject characters 253
113
+ bgm --url https://bgm.tv/anime/list/sai/collect --dry-run # resolve only, no request
114
+ ```
115
+
116
+ - Three equivalent forms: `bgm <url>`, `bgm url <url>`, `bgm --url <url>` (`-url` also works).
117
+ - Hosts: `bgm.tv`, `bangumi.tv`, `chii.in`, `next.bgm.tv`, `api.bgm.tv`; the `https://` and `www.` prefixes are optional.
118
+ - Resolution is read-only, so a link never triggers a write. `--dry-run` prints the resolution and stops.
119
+ - A `#post_<id>` anchor resolves to that single reply; `?page=n` becomes `--offset`.
120
+ - Extra flags are forwarded to the resolved command, and `--json` output carries a `resolvedFrom` field.
121
+ - Quote links containing `#` so the shell does not truncate them.
122
+ - Run `bgm url --help` for the full list of supported link shapes.
123
+
90
124
  ## Documentation Index
91
125
 
92
126
  - This project also ships installable Skills for AI or agent workflows around `bgm-cli`.
@@ -114,8 +148,9 @@ Detailed split documentation is currently maintained in Simplified Chinese under
114
148
  - Thanks to [`bgm.tv`](https://bgm.tv/) for the main Bangumi site and community ecosystem.
115
149
  - Thanks to [`bangumi/server-private`](https://github.com/bangumi/server-private) for private API implementation references.
116
150
  - Thanks to [`bangumi/api`](https://github.com/bangumi/api) for public API implementation and documentation foundations.
117
- - Thanks to [`bgm-status.ry.mk`](https://bgm-status.ry.mk/) for the community-run Bangumi availability status service used by this feature; the service author is [`wataame`](https://bangumi.tv/user/wataame).
118
- - This repository tries to reflect currently verifiable Bangumi behavior, but it does not promise full website feature coverage or long-term stability of third-party behaviors.
151
+ - Thanks to [`SearchEncore`](https://bgmdb.ry.mk/v1/docs) (`bgmdb.ry.mk`) for the community-maintained Bangumi enhanced search capability; the service author is [`wataame`](https://bangumi.tv/user/wataame). SearchEncore is a community-run search service that complements the official bangumi.tv API.
152
+ - Thanks to [`bgm-status.ry.mk`](https://bgm-status.ry.mk/) for the community-run Bangumi availability status service; the service author is also [`wataame`](https://bangumi.tv/user/wataame).
153
+ - This repository tries to reflect currently verifiable Bangumi behavior, but it does not promise full website feature coverage.
119
154
 
120
155
  ## License
121
156
 
package/README.md CHANGED
@@ -15,8 +15,8 @@
15
15
  npm / npx:
16
16
 
17
17
  ```bash
18
- npx @aronnax/bgm-cli --help
19
- npm install -g @aronnax/bgm-cli
18
+ npx @aronnaxlin/bgm-cli --help
19
+ npm install -g @aronnaxlin/bgm-cli
20
20
  ```
21
21
 
22
22
  macOS / Linux:
@@ -52,6 +52,19 @@ bgm auth set-token YOUR_ACCESS_TOKEN
52
52
  bgm auth token-status
53
53
  ```
54
54
 
55
+ ### 多账户
56
+
57
+ 可以把当前凭据存成命名 profile,在多个账户之间快捷切换:
58
+
59
+ ```bash
60
+ bgm auth profile save main
61
+ bgm auth profile list
62
+ bgm auth profile use another
63
+ bgm --profile another user me
64
+ ```
65
+
66
+ `bgm --profile <name> <command>` 只在单条命令内临时使用该账户,不切换、不写盘。
67
+
55
68
  ### 代理
56
69
 
57
70
  如果你所在网络访问 Bangumi API 不稳定,可以为所有 CLI 请求设置 HTTP/HTTPS 代理:
@@ -84,16 +97,37 @@ bgm collection indexes --limit 5
84
97
  bgm episode list 348335 --type main --limit 10
85
98
  bgm episode comments 348335 1
86
99
  bgm episode watch 348335 1
100
+ bgm book get 3510
101
+ bgm book ep 3510 10
87
102
  bgm blog --help
88
103
  bgm group list --sort members --limit 10
89
104
  bgm user friends --limit 5
90
105
  bgm group user --limit 5
91
106
  bgm index user --limit 5
107
+ bgm search subject "海贼王" --limit 5
92
108
  bgm trending subjects --type anime --limit 5
93
109
  bgm status --site bgm.tv
94
110
  bgm --json user me
95
111
  ```
96
112
 
113
+ ### 粘贴链接直接查询
114
+
115
+ 把 Bangumi 网页链接直接交给 `bgm`,它会解析成对应命令并输出同样的结果:
116
+
117
+ ```bash
118
+ bgm "https://bangumi.tv/group/topic/469977#post_4029724" # 定位到该楼 -> bgm group post 4029724
119
+ bgm url https://bgm.tv/subject/253/characters # -> bgm subject characters 253
120
+ bgm --url https://bgm.tv/anime/list/sai/collect --dry-run # 只看解析结果,不发请求
121
+ ```
122
+
123
+ - 三种写法等价:`bgm <url>`、`bgm url <url>`、`bgm --url <url>`(`-url` 亦可)。
124
+ - 支持 `bgm.tv`、`bangumi.tv`、`chii.in`、`next.bgm.tv`、`api.bgm.tv`,可省略 `https://` 与 `www.`。
125
+ - 解析是只读的,链接永远不会触发写操作;`--dry-run` 只打印解析结果。
126
+ - `#post_<id>` 锚点会精确定位到该楼回复;`?page=n` 会换算成 `--offset`。
127
+ - 多余的参数会透传给解析出的命令,`--json` 输出会附带 `resolvedFrom` 溯源字段。
128
+ - 链接含 `#` 时请加引号,否则会被 shell 截断。
129
+ - 完整支持列表见 `bgm url --help`。
130
+
97
131
  ## 文档索引
98
132
 
99
133
  - 本项目同时提供可安装的 Skills,适合让 AI / Agent 直接安装并操作 `bgm-cli`。
@@ -119,8 +153,9 @@ bgm --json user me
119
153
  - 感谢 [`bgm.tv`](https://bgm.tv/) 提供 Bangumi 主站与社区生态。
120
154
  - 感谢 [`bangumi/server-private`](https://github.com/bangumi/server-private) 提供 private API 相关实现参考。
121
155
  - 感谢 [`bangumi/api`](https://github.com/bangumi/api) 提供公开 API 相关实现与文档基础。
122
- - 感谢 [`bgm-status.ry.mk`](https://bgm-status.ry.mk/) 提供社区维护的 Bangumi 可用性状态观测能力;该服务作者为 [`wataame`](https://bangumi.tv/user/wataame)。
123
- - 本仓库会尽量反映当前可验证的 Bangumi 行为约束,但不承诺覆盖网站上的全部功能,也不承诺第三方站点行为长期稳定不变。
156
+ - 感谢 [`SearchEncore`](https://bgmdb.ry.mk/v1/docs)(`bgmdb.ry.mk`)提供社区维护的 Bangumi 增强搜索能力;该服务作者为 [`wataame`](https://bangumi.tv/user/wataame)。SearchEncore 是社区成员自发维护的搜索服务,数据来自社区聚合,与 bangumi.tv 官方接口互补。
157
+ - 感谢 [`bgm-status.ry.mk`](https://bgm-status.ry.mk/) 提供社区维护的 Bangumi 可用性状态观测能力;该服务作者同样为 [`wataame`](https://bangumi.tv/user/wataame)。
158
+ - 本仓库会尽量反映当前可验证的 Bangumi 行为约束,但不承诺覆盖网站上的全部功能。
124
159
 
125
160
  ## 许可证
126
161
 
package/README.zh-TW.md CHANGED
@@ -15,8 +15,8 @@
15
15
  npm / npx:
16
16
 
17
17
  ```bash
18
- npx @aronnax/bgm-cli --help
19
- npm install -g @aronnax/bgm-cli
18
+ npx @aronnaxlin/bgm-cli --help
19
+ npm install -g @aronnaxlin/bgm-cli
20
20
  ```
21
21
 
22
22
  macOS / Linux:
@@ -52,6 +52,19 @@ bgm auth set-token YOUR_ACCESS_TOKEN
52
52
  bgm auth token-status
53
53
  ```
54
54
 
55
+ ### 多帳戶
56
+
57
+ 可以把當前憑據存成命名 profile,在多個帳戶之間快捷切換:
58
+
59
+ ```bash
60
+ bgm auth profile save main
61
+ bgm auth profile list
62
+ bgm auth profile use another
63
+ bgm --profile another user me
64
+ ```
65
+
66
+ `bgm --profile <name> <command>` 只在單條命令內臨時使用該帳戶,不切換、不寫盤。
67
+
55
68
  ### 代理
56
69
 
57
70
  如果你所在網路存取 Bangumi API 不穩定,可以為所有 CLI 請求設定 HTTP/HTTPS 代理:
@@ -80,13 +93,34 @@ bgm character search "明日香" --limit 3
80
93
  bgm person search "庵野" --limit 3
81
94
  bgm collection get 348335
82
95
  bgm collection indexes --user sai --limit 5
96
+ bgm book get 3510
97
+ bgm book ep 3510 10
83
98
  bgm group list --sort members --limit 10
84
99
  bgm group user sai --limit 5
85
100
  bgm index user sai --limit 5
101
+ bgm search subject "海賊王" --limit 5
86
102
  bgm trending subjects --type anime --limit 5
87
103
  bgm --json user me
88
104
  ```
89
105
 
106
+ ### 貼上連結直接查詢
107
+
108
+ 把 Bangumi 網頁連結直接交給 `bgm`,它會解析成對應命令並輸出同樣的結果:
109
+
110
+ ```bash
111
+ bgm "https://bangumi.tv/group/topic/469977#post_4029724" # 定位到該樓 -> bgm group post 4029724
112
+ bgm url https://bgm.tv/subject/253/characters # -> bgm subject characters 253
113
+ bgm --url https://bgm.tv/anime/list/sai/collect --dry-run # 只看解析結果,不發請求
114
+ ```
115
+
116
+ - 三種寫法等價:`bgm <url>`、`bgm url <url>`、`bgm --url <url>`(`-url` 亦可)。
117
+ - 支援 `bgm.tv`、`bangumi.tv`、`chii.in`、`next.bgm.tv`、`api.bgm.tv`,可省略 `https://` 與 `www.`。
118
+ - 解析是唯讀的,連結永遠不會觸發寫入操作;`--dry-run` 只印出解析結果。
119
+ - `#post_<id>` 錨點會精確定位到該樓回覆;`?page=n` 會換算成 `--offset`。
120
+ - 多餘的參數會透傳給解析出的命令,`--json` 輸出會附帶 `resolvedFrom` 溯源欄位。
121
+ - 連結含 `#` 時請加引號,否則會被 shell 截斷。
122
+ - 完整支援列表見 `bgm url --help`。
123
+
90
124
  ## 文件索引
91
125
 
92
126
  - 本專案同時提供可安裝的 Skills,適合讓 AI / Agent 直接安裝並操作 `bgm-cli`。
@@ -114,8 +148,9 @@ bgm --json user me
114
148
  - 感謝 [`bgm.tv`](https://bgm.tv/) 提供 Bangumi 主站與社群生態。
115
149
  - 感謝 [`bangumi/server-private`](https://github.com/bangumi/server-private) 提供 private API 相關實作參考。
116
150
  - 感謝 [`bangumi/api`](https://github.com/bangumi/api) 提供公開 API 相關實作與文件基礎。
117
- - 感謝 [`bgm-status.ry.mk`](https://bgm-status.ry.mk/) 提供社群維護的 Bangumi 可用性狀態觀測能力;該服務作者為 [`wataame`](https://bangumi.tv/user/wataame)。
118
- - 本倉庫會盡量反映目前可驗證的 Bangumi 行為限制,但不承諾覆蓋網站上的全部功能,也不承諾第三方站點行為會長期穩定不變。
151
+ - 感謝 [`SearchEncore`](https://bgmdb.ry.mk/v1/docs)(`bgmdb.ry.mk`)提供社群維護的 Bangumi 增強搜尋能力;該服務作者為 [`wataame`](https://bangumi.tv/user/wataame)。SearchEncore 是社群成員自發維護的搜尋服務,資料來自社群聚合,與 bangumi.tv 官方介面互補。
152
+ - 感謝 [`bgm-status.ry.mk`](https://bgm-status.ry.mk/) 提供社群維護的 Bangumi 可用性狀態觀測能力;該服務作者同樣為 [`wataame`](https://bangumi.tv/user/wataame)。
153
+ - 本倉庫會盡量反映目前可驗證的 Bangumi 行為限制,但不承諾覆蓋網站上的全部功能。
119
154
 
120
155
  ## 授權
121
156
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aronnaxlin/bgm-cli",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Command-line client for Bangumi.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "author": "aronnaxlin",
package/src/cli.js CHANGED
@@ -13,6 +13,7 @@ import { BangumiClient, BangumiOAuthClient } from "./core/client.js";
13
13
  import { getInstalledProxy, installProxyFromConfig, resolveProxyUrl } from "./core/proxy.js";
14
14
  import { DEFAULT_TURNSTILE_TIMEOUT_MS, startTurnstileFlow } from "./core/turnstile.js";
15
15
  import {
16
+ AUTH_CONFIG_KEYS,
16
17
  ConfigError,
17
18
  clearConfigValue,
18
19
  clearConfigValues,
@@ -20,8 +21,12 @@ import {
20
21
  getConfig,
21
22
  getConfigFilePath,
22
23
  getConfigSourceFilePath,
24
+ getProfileOverride,
23
25
  normalizeConfigValue,
26
+ readConfig,
27
+ replaceConfigValues,
24
28
  setConfigValues,
29
+ setProfileOverride,
25
30
  } from "./core/config.js";
26
31
  import { CommandError, formatDisplayResult, printResult, printUsage } from "./core/output.js";
27
32
  import {
@@ -66,6 +71,13 @@ import {
66
71
  fallbackUserAgent,
67
72
  getPrivateLoginUrl,
68
73
  } from "./utils/auth.js";
74
+ import {
75
+ buildProfileListPayload,
76
+ computeProfileDelete,
77
+ computeProfileSave,
78
+ computeProfileSwitch,
79
+ listAuthEnvOverrides,
80
+ } from "./utils/profiles.js";
69
81
  import {
70
82
  getManagedInstallDir,
71
83
  getShellReloadHint,
@@ -106,21 +118,15 @@ import { runCharacterCommand } from "./commands/character.js";
106
118
  import { runPersonCommand } from "./commands/person.js";
107
119
  import { runTrendingCommand } from "./commands/trending.js";
108
120
  import { runNotifyCommand } from "./commands/notify.js";
121
+ import { runBookCommand } from "./commands/book.js";
122
+ import { runSearchCommand } from "./commands/search.js";
123
+ import { runUrlCommand } from "./commands/url.js";
124
+ import { looksLikeBangumiUrl } from "./utils/bangumi-url.js";
109
125
 
110
126
  const CLI_DIR = path.dirname(fileURLToPath(import.meta.url));
111
127
  const REPO_ROOT = path.resolve(CLI_DIR, "..");
112
128
 
113
129
  const REMOTE_INSTALL_SCRIPT_BASE_URL = "https://raw.githubusercontent.com/aronnaxlin/bgm-cli/main/scripts";
114
- const AUTH_CONFIG_KEYS = [
115
- "accessToken",
116
- "refreshToken",
117
- "tokenType",
118
- "privateSessionId",
119
- "privateSessionUpdatedAt",
120
- "clientId",
121
- "clientSecret",
122
- "redirectUri",
123
- ];
124
130
 
125
131
  async function main(argv) {
126
132
  const parsed = parseGlobalArgs(argv);
@@ -140,25 +146,43 @@ async function main(argv) {
140
146
  return;
141
147
  }
142
148
 
149
+ if (hasHelpFlag(parsed.args)) {
150
+ printUsage(resolveHelpTarget(parsed.args));
151
+ return;
152
+ }
153
+
154
+ if (parsed.profile !== undefined) {
155
+ setProfileOverride(parsed.profile);
156
+ getConfig();
157
+ warnAuthEnvOverrides();
158
+ }
159
+
143
160
  if (parsed.init) {
161
+ ensureNoProfileOverride("bgm --init");
144
162
  await runInitWizard(context);
145
163
  return;
146
164
  }
147
165
 
148
- if (parsed.args.length === 0) {
149
- printUsage();
166
+ if (parsed.url !== undefined) {
167
+ await runUrlCommand([parsed.url, ...parsed.args], context);
150
168
  return;
151
169
  }
152
170
 
153
- if (hasHelpFlag(parsed.args)) {
154
- printUsage(resolveHelpTarget(parsed.args));
171
+ if (parsed.args.length === 0) {
172
+ printUsage();
155
173
  return;
156
174
  }
157
175
 
158
176
  const [group, command, ...rest] = parsed.args;
159
177
 
178
+ if (looksLikeBangumiUrl(group)) {
179
+ await runUrlCommand(parsed.args, context);
180
+ return;
181
+ }
182
+
160
183
  switch (group) {
161
184
  case "tui":
185
+ ensureNoProfileOverride("bgm tui");
162
186
  await runTui(context, { runConfigCommand, runSetupCommand });
163
187
  return;
164
188
  case "config":
@@ -204,18 +228,27 @@ async function main(argv) {
204
228
  case "collection":
205
229
  await runCollectionCommand(command, rest, context);
206
230
  return;
231
+ case "book":
232
+ await runBookCommand(command, rest, context);
233
+ return;
207
234
  case "status":
208
235
  await runStatusCommand(command, rest, context);
209
236
  return;
210
237
  case "user":
211
238
  await runUserCommand(command, rest, context);
212
239
  return;
240
+ case "search":
241
+ await runSearchCommand(command, rest, context);
242
+ return;
213
243
  case "notify":
214
244
  await runNotifyCommand(command, rest, context);
215
245
  return;
216
246
  case "calendar":
217
247
  await runCalendarCommand(command, rest, context);
218
248
  return;
249
+ case "url":
250
+ await runUrlCommand([command, ...rest], context);
251
+ return;
219
252
  default:
220
253
  throw new CommandError(`Unknown command group: ${group}`);
221
254
  }
@@ -406,6 +439,9 @@ async function runConfigCommand(command, args, context) {
406
439
  }
407
440
 
408
441
  const normalizedKey = normalizeConfigKey(key);
442
+ if (AUTH_CONFIG_KEYS.includes(normalizedKey)) {
443
+ ensureNoProfileOverride(`bgm config set ${normalizedKey}`);
444
+ }
409
445
  const normalizedValue = normalizeConfigValue(normalizedKey, value);
410
446
  await setConfigValues({ [normalizedKey]: normalizedValue });
411
447
  printResult(
@@ -425,6 +461,9 @@ async function runConfigCommand(command, args, context) {
425
461
  }
426
462
 
427
463
  const normalizedKey = normalizeConfigKey(key);
464
+ if (AUTH_CONFIG_KEYS.includes(normalizedKey)) {
465
+ ensureNoProfileOverride(`bgm config unset ${normalizedKey}`);
466
+ }
428
467
  await clearConfigValue(normalizedKey);
429
468
  printResult(
430
469
  {
@@ -513,6 +552,7 @@ async function runAuthCommand(command, args, context) {
513
552
 
514
553
  switch (command) {
515
554
  case "login": {
555
+ ensureNoProfileOverride("bgm auth login");
516
556
  const savedSessionId = getSavedPrivateSessionId(config);
517
557
  if (savedSessionId && !toBoolean(options.force, false)) {
518
558
  throw new CommandError("Private session is already saved. Run `bgm auth status` to inspect it, `bgm auth logout` to end it, or `bgm auth login --force` to replace it.");
@@ -554,6 +594,7 @@ async function runAuthCommand(command, args, context) {
554
594
  return;
555
595
  }
556
596
  case "logout": {
597
+ ensureNoProfileOverride("bgm auth logout");
557
598
  const sessionId = typeof config.privateSessionId === "string" ? config.privateSessionId.trim() : "";
558
599
  if (!sessionId) {
559
600
  throw new CommandError("No saved private API session. Run `bgm auth login` first, or use `bgm auth clear` to clear local auth state.");
@@ -594,6 +635,7 @@ async function runAuthCommand(command, args, context) {
594
635
  });
595
636
 
596
637
  if (toBoolean(options.save, false)) {
638
+ ensureNoProfileOverride("bgm auth token --save");
597
639
  await setConfigValues({
598
640
  clientId: options.clientId ?? config.clientId,
599
641
  clientSecret: options.clientSecret ?? config.clientSecret,
@@ -616,6 +658,7 @@ async function runAuthCommand(command, args, context) {
616
658
  });
617
659
 
618
660
  if (toBoolean(options.save, false)) {
661
+ ensureNoProfileOverride("bgm auth refresh --save");
619
662
  await setConfigValues({
620
663
  clientId: options.clientId ?? config.clientId,
621
664
  clientSecret: options.clientSecret ?? config.clientSecret,
@@ -662,11 +705,13 @@ async function runAuthCommand(command, args, context) {
662
705
  return;
663
706
  }
664
707
  case "session-login": {
708
+ ensureNoProfileOverride("bgm auth session-login");
665
709
  const result = await runPrivateSessionLogin(options, context);
666
710
  printResult(result, context);
667
711
  return;
668
712
  }
669
713
  case "set-token": {
714
+ ensureNoProfileOverride("bgm auth set-token");
670
715
  const accessToken = options.accessToken ?? firstPositional(options);
671
716
  if (!accessToken) {
672
717
  throw new CommandError("Usage: bgm auth set-token <access_token>");
@@ -688,6 +733,7 @@ async function runAuthCommand(command, args, context) {
688
733
  return;
689
734
  }
690
735
  case "set-session": {
736
+ ensureNoProfileOverride("bgm auth set-session");
691
737
  const rawSession = options.session ?? firstPositional(options);
692
738
  if (!rawSession) {
693
739
  throw new CommandError("Usage: bgm auth set-session <chiiNextSessionID|cookie_string>");
@@ -730,20 +776,135 @@ async function runAuthCommand(command, args, context) {
730
776
  return;
731
777
  }
732
778
  case "clear": {
779
+ ensureNoProfileOverride("bgm auth clear");
733
780
  const clearKeys = resolveAuthClearKeys(options);
734
- await clearConfigValues(clearKeys);
781
+ const rawConfig = await readConfig();
782
+ const isFullClear = AUTH_CONFIG_KEYS.every((key) => clearKeys.includes(key));
783
+ const keys = isFullClear && rawConfig.activeProfile !== undefined
784
+ ? [...clearKeys, "activeProfile"]
785
+ : clearKeys;
786
+ await clearConfigValues(keys);
735
787
  printResult(
736
788
  {
737
789
  resource: "auth-clear",
738
- cleared: clearKeys,
790
+ cleared: keys,
739
791
  configFile: getConfigFilePath(),
740
792
  },
741
793
  context,
742
794
  );
743
795
  return;
744
796
  }
797
+ case "profile": {
798
+ await runAuthProfileCommand(options, context);
799
+ return;
800
+ }
745
801
  default:
746
- throw new CommandError("Usage: bgm auth <login|logout|status|token-status|login-url|token|refresh|turnstile|session-login|set-token|set-session|session-status|clear> ...");
802
+ throw new CommandError("Usage: bgm auth <login|logout|status|token-status|login-url|token|refresh|turnstile|session-login|set-token|set-session|session-status|clear|profile> ...");
803
+ }
804
+ }
805
+
806
+ async function runAuthProfileCommand(options, context) {
807
+ const subcommand = getPositional(options, 0);
808
+ const name = getPositional(options, 1);
809
+
810
+ switch (subcommand) {
811
+ case "list": {
812
+ const rawConfig = await readConfig();
813
+ printResult(
814
+ buildProfileListPayload(rawConfig, {
815
+ configFile: getConfigFilePath(),
816
+ envOverrides: listAuthEnvOverrides(),
817
+ profileOverride: getProfileOverride(),
818
+ }),
819
+ context,
820
+ );
821
+ return;
822
+ }
823
+ case "save": {
824
+ ensureNoProfileOverride("bgm auth profile save");
825
+ if (!name) {
826
+ throw new CommandError("Usage: bgm auth profile save <name> [--force]");
827
+ }
828
+ const rawConfig = await readConfig();
829
+ const change = computeProfileSave(rawConfig, name, { force: toBoolean(options.force, false) });
830
+ await replaceConfigValues(change);
831
+ printResult(
832
+ {
833
+ resource: "auth-profile-mutation",
834
+ action: "save",
835
+ profile: change.profile,
836
+ activeProfile: change.profile,
837
+ configFile: getConfigFilePath(),
838
+ envOverrides: listAuthEnvOverrides(),
839
+ },
840
+ context,
841
+ );
842
+ return;
843
+ }
844
+ case "use": {
845
+ ensureNoProfileOverride("bgm auth profile use");
846
+ if (!name) {
847
+ throw new CommandError("Usage: bgm auth profile use <name> [--force]");
848
+ }
849
+ const rawConfig = await readConfig();
850
+ const change = computeProfileSwitch(rawConfig, name, { force: toBoolean(options.force, false) });
851
+ await replaceConfigValues(change);
852
+ printResult(
853
+ {
854
+ resource: "auth-profile-mutation",
855
+ action: "use",
856
+ profile: change.profile,
857
+ activeProfile: change.profile,
858
+ previousProfile: change.previousProfile,
859
+ syncedPrevious: change.syncedPrevious,
860
+ configFile: getConfigFilePath(),
861
+ envOverrides: listAuthEnvOverrides(),
862
+ },
863
+ context,
864
+ );
865
+ return;
866
+ }
867
+ case "delete": {
868
+ ensureNoProfileOverride("bgm auth profile delete");
869
+ if (!name) {
870
+ throw new CommandError("Usage: bgm auth profile delete <name>");
871
+ }
872
+ const rawConfig = await readConfig();
873
+ const change = computeProfileDelete(rawConfig, name);
874
+ await replaceConfigValues(change);
875
+ printResult(
876
+ {
877
+ resource: "auth-profile-mutation",
878
+ action: "delete",
879
+ profile: change.profile,
880
+ activeProfile: change.wasActive ? null : (typeof rawConfig.activeProfile === "string" ? rawConfig.activeProfile : null),
881
+ ...(change.wasActive ? { credentialsRetained: true } : {}),
882
+ configFile: getConfigFilePath(),
883
+ envOverrides: listAuthEnvOverrides(),
884
+ },
885
+ context,
886
+ );
887
+ return;
888
+ }
889
+ default:
890
+ throw new CommandError("Usage: bgm auth profile <list|save|use|delete> ...");
891
+ }
892
+ }
893
+
894
+ function warnAuthEnvOverrides() {
895
+ const envOverrides = listAuthEnvOverrides();
896
+ if (envOverrides.length > 0) {
897
+ process.stderr.write(
898
+ `Warning: environment variables override the --profile credentials: ${envOverrides.join(", ")}\n`,
899
+ );
900
+ }
901
+ }
902
+
903
+ function ensureNoProfileOverride(actionLabel) {
904
+ if (getProfileOverride()) {
905
+ throw new CommandError(
906
+ `--profile is a read-only account override; \`${actionLabel}\` would modify saved credentials. Run \`bgm auth profile use <name>\` to switch accounts instead.`,
907
+ );
747
908
  }
748
909
  }
749
910
 
@@ -779,10 +940,18 @@ function buildAuthStatusPayload(config) {
779
940
  const accessToken = typeof config.accessToken === "string" ? config.accessToken.trim() : "";
780
941
  const refreshToken = typeof config.refreshToken === "string" ? config.refreshToken.trim() : "";
781
942
  const privateSession = getSavedPrivateSessionId(config);
943
+ const activeProfile = typeof config.activeProfile === "string" && config.activeProfile.trim() !== ""
944
+ ? config.activeProfile.trim()
945
+ : null;
946
+ const profileOverride = getProfileOverride();
947
+ const envOverrides = profileOverride ? listAuthEnvOverrides() : [];
782
948
 
783
949
  return {
784
950
  resource: "auth-status",
785
951
  configFile: getConfigFilePath(),
952
+ ...(activeProfile ? { activeProfile } : {}),
953
+ ...(profileOverride ? { profileOverride } : {}),
954
+ ...(envOverrides.length > 0 ? { envOverrides } : {}),
786
955
  policy: "p1 requests use the private session cookie when saved; Access Token is not sent together with it.",
787
956
  channels: {
788
957
  accessToken: {