dsh-agent-sdk-bridge 1.2.2 → 1.2.3

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/lib/index.js CHANGED
@@ -3725,6 +3725,23 @@ function planContinuation(previous, current) {
3725
3725
  * @module dsh-agent-sdk-bridge/codebuddy-state
3726
3726
  */
3727
3727
  /**
3728
+ * A stored account reading with its credential removed.
3729
+ *
3730
+ * The CLI's `accountInfo()` answer carries a bearer token, and older versions
3731
+ * persisted that object whole — a second copy of the credential in a file that
3732
+ * gets backed up and pasted into bug reports, one the plugin never read. A
3733
+ * region holds exactly one credential, in `token`.
3734
+ */
3735
+ function withoutCredential(account) {
3736
+ if (account === void 0) return void 0;
3737
+ const clean = {};
3738
+ for (const [key, value] of Object.entries(account)) {
3739
+ if (/token|secret|credential|password|cookie/i.test(key)) continue;
3740
+ clean[key] = value;
3741
+ }
3742
+ return clean;
3743
+ }
3744
+ /**
3728
3745
  * The default file path.
3729
3746
  *
3730
3747
  * `DSH_HOME` is honoured so a desktop profile and a web profile keep separate
@@ -3769,13 +3786,46 @@ var CodeBuddyStateStore = class {
3769
3786
  this.loaded = true;
3770
3787
  try {
3771
3788
  const parsed = JSON.parse(readFileSync(this.file, "utf8"));
3772
- if (parsed.version === 1 && parsed.regions !== null && typeof parsed.regions === "object") this.state = {
3773
- version: 1,
3774
- regions: parsed.regions
3775
- };
3789
+ if (parsed.version === 1 && parsed.regions !== null && typeof parsed.regions === "object") {
3790
+ this.state = {
3791
+ version: 1,
3792
+ regions: parsed.regions
3793
+ };
3794
+ this.recoverLostTokens();
3795
+ }
3776
3796
  } catch {}
3777
3797
  return this.state;
3778
3798
  }
3799
+ /**
3800
+ * Lift a credential the old layout hid inside the account object.
3801
+ *
3802
+ * The CLI's `accountInfo()` answer carries a bearer token of its own, and an
3803
+ * earlier version persisted that whole object here. When the top-level
3804
+ * `token` was later dropped — which any quota failure used to do, because
3805
+ * expiry was *guessed* from the error text — the region read as signed out
3806
+ * even though a working credential still sat in the file, and nothing could
3807
+ * recover it without a fresh browser login. This picks the copy back up.
3808
+ *
3809
+ * {@link persist} no longer stores a token inside the account, so this runs
3810
+ * only over files written by those older versions.
3811
+ */
3812
+ recoverLostTokens() {
3813
+ let recovered = false;
3814
+ for (const [key, saved] of Object.entries(this.state.regions)) {
3815
+ const region = key;
3816
+ const hidden = (saved?.account)?.token;
3817
+ if (saved === void 0 || saved.token !== void 0) continue;
3818
+ if (typeof hidden !== "string" || hidden.length === 0) continue;
3819
+ this.state.regions[region] = {
3820
+ ...saved,
3821
+ token: hidden,
3822
+ signedIn: true,
3823
+ account: withoutCredential(saved.account)
3824
+ };
3825
+ recovered = true;
3826
+ }
3827
+ if (recovered) this.persist();
3828
+ }
3779
3829
  region(region) {
3780
3830
  return this.ensureLoaded().regions[region];
3781
3831
  }
@@ -3807,6 +3857,7 @@ var CodeBuddyStateStore = class {
3807
3857
  const next = { ...state.regions[region] };
3808
3858
  for (const [key, value] of Object.entries(patch)) if (value === void 0) delete next[key];
3809
3859
  else next[key] = value;
3860
+ if (next.account !== void 0) next.account = withoutCredential(next.account);
3810
3861
  state.regions[region] = next;
3811
3862
  this.persist();
3812
3863
  }
@@ -3964,11 +4015,24 @@ function tokenFor(region) {
3964
4015
  * pins the environment, so a fresh process always reads the right catalog.
3965
4016
  */
3966
4017
  function cliEnv(region) {
3967
- const env = { CODEBUDDY_CONFIG_DIR: codeBuddyCliDir(region) };
4018
+ const env = cliDirEnv(region);
3968
4019
  const token = tokenFor(region);
3969
4020
  if (token !== void 0) env.CODEBUDDY_AUTH_TOKEN = token;
3970
4021
  return { env };
3971
4022
  }
4023
+ /**
4024
+ * The region's own CLI directory, with no credential attached.
4025
+ *
4026
+ * The login, logout and silent-token calls need this and nothing else: they
4027
+ * must not carry a bearer token (login starts fresh, logout clears), but they
4028
+ * absolutely must be scoped to one region. Without it they acted on the CLI's
4029
+ * default `~/.codebuddy`, which both regions share — so signing in for one
4030
+ * region overwrote the other's login, and `logout` for the region the page was
4031
+ * showing left the credential of the other one standing.
4032
+ */
4033
+ function cliDirEnv(region) {
4034
+ return { CODEBUDDY_CONFIG_DIR: codeBuddyCliDir(region) };
4035
+ }
3972
4036
  /** Remember a bearer token in memory and on disk. */
3973
4037
  function rememberBearerToken(region, token, user) {
3974
4038
  if (token.length === 0) return;
@@ -4165,10 +4229,6 @@ var CodeBuddyAccountReader = class {
4165
4229
  }
4166
4230
  async fetch(region) {
4167
4231
  const at = Date.now();
4168
- if (tokenFor(region) === void 0) return {
4169
- at,
4170
- error: `${region === "cn" ? "CodeBuddy 国内版" : "CodeBuddy 国际版"}尚未登录,请在页面顶部选择该区域并登录。`
4171
- };
4172
4232
  try {
4173
4233
  const account = await readAccount(region, readLive(this.timeoutMs, CODEBUDDY_FETCH_TIMEOUT_MS));
4174
4234
  if (isUnauthenticatedAccount(account)) {
@@ -4204,7 +4264,7 @@ var CodeBuddyAccountReader = class {
4204
4264
  };
4205
4265
  } catch (quotaError) {
4206
4266
  const message = quotaError instanceof Error ? quotaError.message : String(quotaError);
4207
- if (isExpiredToken(message)) forgetToken(region);
4267
+ if (isCredentialRejected(quotaError)) forgetToken(region);
4208
4268
  else codeBuddyState.patch(region, {
4209
4269
  quota: void 0,
4210
4270
  quotaError: message
@@ -4242,7 +4302,7 @@ async function readAccount(region, timeoutMs) {
4242
4302
  });
4243
4303
  try {
4244
4304
  await withTimeout$1(q.connect(), timeoutMs);
4245
- return await withTimeout$1(q.accountInfo(), timeoutMs);
4305
+ return withoutCredential(await withTimeout$1(q.accountInfo(), timeoutMs)) ?? {};
4246
4306
  } finally {
4247
4307
  await q.return().catch(() => void 0);
4248
4308
  }
@@ -4329,15 +4389,21 @@ function formatLocalTime(date) {
4329
4389
  /**
4330
4390
  * A bearer token for the region, from a recent login or a silent SDK read.
4331
4391
  *
4332
- * `authenticate` returns the CLI's existing account token without opening a
4333
- * browser when the region is already signed in, so this stays a read. When it
4334
- * is not signed in the call times out; callers treat that as "log in first".
4392
+ * The silent read is the documented behaviour of `authenticate` — return the
4393
+ * CLI's existing token instead of opening a browser when the region is signed
4394
+ * in — but it did not work as measured: on a machine with a live CodeBuddy
4395
+ * login it timed out for both regions, each in the shared default directory and
4396
+ * in both per-region directories. So treat it as best effort, and never as a
4397
+ * place to recover from: the copy this plugin saved is the only credential a
4398
+ * session can count on, which is why dropping it used to read as "not signed
4399
+ * in" even while the account still worked.
4335
4400
  */
4336
4401
  async function readBearerToken(region) {
4337
4402
  const cached = tokenFor(region);
4338
4403
  if (cached !== void 0) return cached;
4339
4404
  const result = await withTimeout$1((await loadCodeBuddySdk()).unstable_v2_authenticate({
4340
4405
  environment: codeBuddyEnvironment(region),
4406
+ env: cliDirEnv(region),
4341
4407
  timeout: 3e3,
4342
4408
  onAuthUrl: () => {}
4343
4409
  }), 6e3);
@@ -4393,7 +4459,7 @@ async function fetchCodeBuddyQuota(region, token, fetchImpl = fetch) {
4393
4459
  });
4394
4460
  const text = await response.text();
4395
4461
  if (!response.ok) {
4396
- if (response.status === 401 || response.status === 403) throw new Error("CodeBuddy 登录已过期,请重新登录");
4462
+ if (response.status === 401 || response.status === 403) throw new CredentialRejectedError("CodeBuddy 登录已过期,请重新登录");
4397
4463
  const detail = text.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim().slice(0, 160);
4398
4464
  throw new Error(`CodeBuddy 额度接口返回 HTTP ${response.status}${detail === "" ? "" : `:${detail}`}`);
4399
4465
  }
@@ -4405,9 +4471,31 @@ async function fetchCodeBuddyQuota(region, token, fetchImpl = fetch) {
4405
4471
  }
4406
4472
  return parseCodeBuddyQuota(payload);
4407
4473
  }
4408
- /** Whether a quota failure means the stored credential is no longer usable. */
4409
- function isExpiredToken(message) {
4410
- return /401|403|登录已过期|unauthor|token/i.test(message);
4474
+ /**
4475
+ * The credential this region holds was rejected by the endpoint.
4476
+ *
4477
+ * Thrown where the rejection is *known* — an explicit HTTP 401/403 — rather
4478
+ * than inferred from the error text. Inferring it was the bug: the loose
4479
+ * matcher below used to treat any failure whose message happened to contain
4480
+ * "token", "401" inside a number, or an HTML body mentioning a token, as an
4481
+ * expired login. It then dropped a working credential, and because a missing
4482
+ * local token reads as "signed out", the page showed an account as not signed
4483
+ * in while the CLI still had a usable login.
4484
+ */
4485
+ var CredentialRejectedError = class extends Error {};
4486
+ /**
4487
+ * Whether a quota failure genuinely means the credential no longer works.
4488
+ *
4489
+ * The typed error carries the CLI's own expiry sentence, which is also matched
4490
+ * here because the message is ours, fixed, and not derived from server text.
4491
+ * Everything else — a 5xx, a bad payload, a timeout, an unreachable endpoint —
4492
+ * leaves the credential alone.
4493
+ *
4494
+ * @param error - whatever quota reading threw.
4495
+ */
4496
+ function isCredentialRejected(error) {
4497
+ if (error instanceof CredentialRejectedError) return true;
4498
+ return (error instanceof Error ? error.message : String(error)) === "CodeBuddy 登录已过期,请重新登录";
4411
4499
  }
4412
4500
  /** Read quota, retrying once with a fresh token after an auth failure. */
4413
4501
  async function readQuotaWithToken(region) {
@@ -4417,7 +4505,7 @@ async function readQuotaWithToken(region) {
4417
4505
  try {
4418
4506
  return await fetchCodeBuddyQuota(region, token);
4419
4507
  } catch (error) {
4420
- if (!isExpiredToken(error instanceof Error ? error.message : String(error))) throw error;
4508
+ if (!isCredentialRejected(error)) throw error;
4421
4509
  forgetToken(region);
4422
4510
  return await fetchCodeBuddyQuota(region, await readBearerToken(region).catch((renewError) => {
4423
4511
  throw new Error(authErrorText(region, renewError));
@@ -4466,7 +4554,10 @@ var CodeBuddyAuth = class {
4466
4554
  async logout(region) {
4467
4555
  let failure;
4468
4556
  try {
4469
- await withTimeout$1((await loadCodeBuddySdk()).unstable_v2_logout({ environment: codeBuddyEnvironment(region) }), CODEBUDDY_FETCH_TIMEOUT_MS);
4557
+ await withTimeout$1((await loadCodeBuddySdk()).unstable_v2_logout({
4558
+ environment: codeBuddyEnvironment(region),
4559
+ env: cliDirEnv(region)
4560
+ }), CODEBUDDY_FETCH_TIMEOUT_MS);
4470
4561
  } catch (error) {
4471
4562
  failure = error instanceof Error ? error.message : String(error);
4472
4563
  }
@@ -4487,11 +4578,15 @@ var CodeBuddyAuth = class {
4487
4578
  const { region } = status;
4488
4579
  try {
4489
4580
  const sdk = await loadCodeBuddySdk();
4490
- await withTimeout$1(sdk.unstable_v2_logout({ environment: codeBuddyEnvironment(region) }), LOGOUT_TIMEOUT_MS).catch(() => void 0);
4581
+ await withTimeout$1(sdk.unstable_v2_logout({
4582
+ environment: codeBuddyEnvironment(region),
4583
+ env: cliDirEnv(region)
4584
+ }), LOGOUT_TIMEOUT_MS).catch(() => void 0);
4491
4585
  if (!this.current(run)) return;
4492
4586
  bearerTokens.delete(region);
4493
4587
  const result = await sdk.unstable_v2_authenticate({
4494
4588
  environment: codeBuddyEnvironment(region),
4589
+ env: cliDirEnv(region),
4495
4590
  timeout: LOGIN_TIMEOUT_MS,
4496
4591
  onAuthUrl: (state) => {
4497
4592
  status.url = state.authUrl;
@@ -4632,12 +4727,14 @@ var CodeBuddySession = class {
4632
4727
  * compacts (and the gateway rejects) anything past 276K — while the host,
4633
4728
  * told 1M, keeps showing and feeding a larger history. Replaying that history
4634
4729
  * then collapses to a summary. Applying the same number the host divides by
4635
- * keeps the two in step; models that expose no choice reject it and keep
4636
- * their default.
4730
+ * keeps the two in step; the adapter therefore sends a window for every model
4731
+ * it knows about, not only the ones that advertise a choice — the mainland
4732
+ * catalog declares no lengths anywhere and its physical `maxInputTokens` is a
4733
+ * provider number the CLI is free to ignore when left to itself.
4637
4734
  *
4638
- * The CLI refuses to clear the override (`contextWindow must be a positive
4639
- * safe integer`), so the adapter sends the model's default instead when the
4640
- * page returns to "default".
4735
+ * A rejected value keeps the CLI on its own default, which is the one case
4736
+ * where the two denominators can still disagree; it is reported nowhere, so
4737
+ * the host's figure stays the visible contract.
4641
4738
  */
4642
4739
  async applyContextWindow(session) {
4643
4740
  const window = this.contextWindow;
@@ -20,6 +20,15 @@ export interface CodeBuddySavedUser {
20
20
  userName: string;
21
21
  userNickname: string;
22
22
  }
23
+ /**
24
+ * A stored account reading with its credential removed.
25
+ *
26
+ * The CLI's `accountInfo()` answer carries a bearer token, and older versions
27
+ * persisted that object whole — a second copy of the credential in a file that
28
+ * gets backed up and pasted into bug reports, one the plugin never read. A
29
+ * region holds exactly one credential, in `token`.
30
+ */
31
+ export declare function withoutCredential(account: CodeBuddyAccount | undefined): CodeBuddyAccount | undefined;
23
32
  /** Everything remembered for one login region. */
24
33
  export interface CodeBuddySavedRegion {
25
34
  /** Bearer credential from the SDK login, used to restore the login. */
@@ -50,6 +59,20 @@ export declare class CodeBuddyStateStore {
50
59
  private state;
51
60
  constructor(file?: string);
52
61
  private ensureLoaded;
62
+ /**
63
+ * Lift a credential the old layout hid inside the account object.
64
+ *
65
+ * The CLI's `accountInfo()` answer carries a bearer token of its own, and an
66
+ * earlier version persisted that whole object here. When the top-level
67
+ * `token` was later dropped — which any quota failure used to do, because
68
+ * expiry was *guessed* from the error text — the region read as signed out
69
+ * even though a working credential still sat in the file, and nothing could
70
+ * recover it without a fresh browser login. This picks the copy back up.
71
+ *
72
+ * {@link persist} no longer stores a token inside the account, so this runs
73
+ * only over files written by those older versions.
74
+ */
75
+ private recoverLostTokens;
53
76
  region(region: CodeBuddyRegion): CodeBuddySavedRegion | undefined;
54
77
  /** The stored bearer token, or undefined when the region is signed out. */
55
78
  token(region: CodeBuddyRegion): string | undefined;
@@ -282,12 +282,14 @@ export declare class CodeBuddySession {
282
282
  * compacts (and the gateway rejects) anything past 276K — while the host,
283
283
  * told 1M, keeps showing and feeding a larger history. Replaying that history
284
284
  * then collapses to a summary. Applying the same number the host divides by
285
- * keeps the two in step; models that expose no choice reject it and keep
286
- * their default.
285
+ * keeps the two in step; the adapter therefore sends a window for every model
286
+ * it knows about, not only the ones that advertise a choice — the mainland
287
+ * catalog declares no lengths anywhere and its physical `maxInputTokens` is a
288
+ * provider number the CLI is free to ignore when left to itself.
287
289
  *
288
- * The CLI refuses to clear the override (`contextWindow must be a positive
289
- * safe integer`), so the adapter sends the model's default instead when the
290
- * page returns to "default".
290
+ * A rejected value keeps the CLI on its own default, which is the one case
291
+ * where the two denominators can still disagree; it is reported nowhere, so
292
+ * the host's figure stays the visible contract.
291
293
  */
292
294
  private applyContextWindow;
293
295
  /**
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "dsh-agent-sdk-bridge",
3
3
  "displayName": "Agent SDK Bridge",
4
4
  "description": "DeepSeek Harness LLM adapter bridge for Qoder CN, Qoder International, Tencent CodeBuddy and MiniMax Code subscriptions. It reuses each provider's own SDK or official ACP server and CLI login, shows available quota, and exposes per-provider settings pages with independent international and mainland login regions.",
5
- "version": "1.2.2",
5
+ "version": "1.2.3",
6
6
  "type": "module",
7
7
  "license": "MIT",
8
8
  "author": "k1-h2",
@@ -28,6 +28,24 @@ export interface CodeBuddySavedUser {
28
28
  userNickname: string
29
29
  }
30
30
 
31
+ /**
32
+ * A stored account reading with its credential removed.
33
+ *
34
+ * The CLI's `accountInfo()` answer carries a bearer token, and older versions
35
+ * persisted that object whole — a second copy of the credential in a file that
36
+ * gets backed up and pasted into bug reports, one the plugin never read. A
37
+ * region holds exactly one credential, in `token`.
38
+ */
39
+ export function withoutCredential(account: CodeBuddyAccount | undefined): CodeBuddyAccount | undefined {
40
+ if (account === undefined) return undefined
41
+ const clean: Record<string, unknown> = {}
42
+ for (const [key, value] of Object.entries(account as Record<string, unknown>)) {
43
+ if (/token|secret|credential|password|cookie/i.test(key)) continue
44
+ clean[key] = value
45
+ }
46
+ return clean as CodeBuddyAccount
47
+ }
48
+
31
49
  /** Everything remembered for one login region. */
32
50
  export interface CodeBuddySavedRegion {
33
51
  /** Bearer credential from the SDK login, used to restore the login. */
@@ -93,6 +111,7 @@ export class CodeBuddyStateStore {
93
111
  const parsed = JSON.parse(readFileSync(this.file, 'utf8')) as Partial<SavedFile>
94
112
  if (parsed.version === 1 && parsed.regions !== null && typeof parsed.regions === 'object') {
95
113
  this.state = { version: 1, regions: parsed.regions }
114
+ this.recoverLostTokens()
96
115
  }
97
116
  } catch {
98
117
  // A missing or unreadable file is the normal first-run state.
@@ -100,6 +119,37 @@ export class CodeBuddyStateStore {
100
119
  return this.state
101
120
  }
102
121
 
122
+ /**
123
+ * Lift a credential the old layout hid inside the account object.
124
+ *
125
+ * The CLI's `accountInfo()` answer carries a bearer token of its own, and an
126
+ * earlier version persisted that whole object here. When the top-level
127
+ * `token` was later dropped — which any quota failure used to do, because
128
+ * expiry was *guessed* from the error text — the region read as signed out
129
+ * even though a working credential still sat in the file, and nothing could
130
+ * recover it without a fresh browser login. This picks the copy back up.
131
+ *
132
+ * {@link persist} no longer stores a token inside the account, so this runs
133
+ * only over files written by those older versions.
134
+ */
135
+ private recoverLostTokens(): void {
136
+ let recovered = false
137
+ for (const [key, saved] of Object.entries(this.state.regions)) {
138
+ const region = key as CodeBuddyRegion
139
+ const hidden = (saved?.account as { token?: unknown } | undefined)?.token
140
+ if (saved === undefined || saved.token !== undefined) continue
141
+ if (typeof hidden !== 'string' || hidden.length === 0) continue
142
+ this.state.regions[region] = {
143
+ ...saved,
144
+ token: hidden,
145
+ signedIn: true,
146
+ account: withoutCredential(saved.account),
147
+ }
148
+ recovered = true
149
+ }
150
+ if (recovered) this.persist()
151
+ }
152
+
103
153
  region(region: CodeBuddyRegion): CodeBuddySavedRegion | undefined {
104
154
  return this.ensureLoaded().regions[region]
105
155
  }
@@ -138,6 +188,9 @@ export class CodeBuddyStateStore {
138
188
  if (value === undefined) delete next[key as keyof CodeBuddySavedRegion]
139
189
  else (next as Record<string, unknown>)[key] = value
140
190
  }
191
+ // The account object arrives from the CLI carrying a bearer token of its
192
+ // own; keep exactly one credential per region on disk.
193
+ if (next.account !== undefined) next.account = withoutCredential(next.account)
141
194
  state.regions[region] = next
142
195
  this.persist()
143
196
  }
package/src/codebuddy.ts CHANGED
@@ -21,7 +21,7 @@ import type {
21
21
  CanUseTool, Message, RawLanguageModel, UserMessage,
22
22
  } from '@tencent-ai/agent-sdk'
23
23
  import type { CodeBuddyRegion } from './brand.ts'
24
- import { CodeBuddyStateStore, codeBuddyCliDir } from './codebuddy-state.ts'
24
+ import { CodeBuddyStateStore, codeBuddyCliDir, withoutCredential } from './codebuddy-state.ts'
25
25
  import type { CodeBuddySavedUser } from './codebuddy-state.ts'
26
26
  import { jsonSchemaToShape } from './jsonschema.ts'
27
27
  import type { Live } from './live.ts'
@@ -218,12 +218,26 @@ function tokenFor(region: CodeBuddyRegion): string | undefined {
218
218
  * pins the environment, so a fresh process always reads the right catalog.
219
219
  */
220
220
  function cliEnv(region: CodeBuddyRegion): { env: Record<string, string> } {
221
- const env: Record<string, string> = { CODEBUDDY_CONFIG_DIR: codeBuddyCliDir(region) }
221
+ const env = cliDirEnv(region)
222
222
  const token = tokenFor(region)
223
223
  if (token !== undefined) env.CODEBUDDY_AUTH_TOKEN = token
224
224
  return { env }
225
225
  }
226
226
 
227
+ /**
228
+ * The region's own CLI directory, with no credential attached.
229
+ *
230
+ * The login, logout and silent-token calls need this and nothing else: they
231
+ * must not carry a bearer token (login starts fresh, logout clears), but they
232
+ * absolutely must be scoped to one region. Without it they acted on the CLI's
233
+ * default `~/.codebuddy`, which both regions share — so signing in for one
234
+ * region overwrote the other's login, and `logout` for the region the page was
235
+ * showing left the credential of the other one standing.
236
+ */
237
+ function cliDirEnv(region: CodeBuddyRegion): Record<string, string> {
238
+ return { CODEBUDDY_CONFIG_DIR: codeBuddyCliDir(region) }
239
+ }
240
+
227
241
  /** Remember a bearer token in memory and on disk. */
228
242
  function rememberBearerToken(region: CodeBuddyRegion, token: string, user?: CodeBuddySavedUser): void {
229
243
  if (token.length === 0) return
@@ -448,12 +462,15 @@ export class CodeBuddyAccountReader {
448
462
 
449
463
  private async fetch(region: CodeBuddyRegion): Promise<CodeBuddyUsageSnapshot> {
450
464
  const at = Date.now()
451
- // No saved credential means this region was explicitly signed out. Never
452
- // probe the CLI here: it may hold the *other* region's single cached
453
- // login, and adopting that account would misattribute it to this region.
454
- if (tokenFor(region) === undefined) {
455
- return { at, error: `${region === 'cn' ? 'CodeBuddy 国内版' : 'CodeBuddy 国际版'}尚未登录,请在页面顶部选择该区域并登录。` }
456
- }
465
+ // Ask the CLI even when this region holds no credential of ours.
466
+ //
467
+ // Refusing here used to be the guard against adopting the *other* region's
468
+ // login: the CLI's default directory is shared, so a probe could answer with
469
+ // whichever account logged in last. Every call now runs inside this region's
470
+ // own directory, so the answer can only be this region's — and the refusal
471
+ // had become pure damage: any accident that dropped the local copy of a
472
+ // working token left the card saying "not signed in" for an account the CLI
473
+ // still had, with no path back short of a fresh browser login.
457
474
  try {
458
475
  const account = await readAccount(region, readLive(this.timeoutMs, CODEBUDDY_FETCH_TIMEOUT_MS))
459
476
  // An unauthenticated CLI answers with an empty object or an anonymous
@@ -470,7 +487,7 @@ export class CodeBuddyAccountReader {
470
487
  return { at, account, quota }
471
488
  } catch (quotaError) {
472
489
  const message = quotaError instanceof Error ? quotaError.message : String(quotaError)
473
- if (isExpiredToken(message)) forgetToken(region)
490
+ if (isCredentialRejected(quotaError)) forgetToken(region)
474
491
  else codeBuddyState.patch(region, { quota: undefined, quotaError: message })
475
492
  return { at, account, quotaError: message }
476
493
  }
@@ -500,7 +517,9 @@ async function readAccount(region: CodeBuddyRegion, timeoutMs: number): Promise<
500
517
  })
501
518
  try {
502
519
  await withTimeout(q.connect(), timeoutMs)
503
- return await withTimeout(q.accountInfo(), timeoutMs)
520
+ // The CLI's answer carries a bearer token beside the identity; it goes on
521
+ // to the settings page through `/usage`, so the credential comes off here.
522
+ return withoutCredential(await withTimeout(q.accountInfo(), timeoutMs)) ?? {}
504
523
  } finally {
505
524
  await q.return().catch(() => undefined)
506
525
  }
@@ -609,9 +628,14 @@ function formatLocalTime(date: Date): string {
609
628
  /**
610
629
  * A bearer token for the region, from a recent login or a silent SDK read.
611
630
  *
612
- * `authenticate` returns the CLI's existing account token without opening a
613
- * browser when the region is already signed in, so this stays a read. When it
614
- * is not signed in the call times out; callers treat that as "log in first".
631
+ * The silent read is the documented behaviour of `authenticate` — return the
632
+ * CLI's existing token instead of opening a browser when the region is signed
633
+ * in — but it did not work as measured: on a machine with a live CodeBuddy
634
+ * login it timed out for both regions, each in the shared default directory and
635
+ * in both per-region directories. So treat it as best effort, and never as a
636
+ * place to recover from: the copy this plugin saved is the only credential a
637
+ * session can count on, which is why dropping it used to read as "not signed
638
+ * in" even while the account still worked.
615
639
  */
616
640
  async function readBearerToken(region: CodeBuddyRegion): Promise<string> {
617
641
  const cached = tokenFor(region)
@@ -619,6 +643,10 @@ async function readBearerToken(region: CodeBuddyRegion): Promise<string> {
619
643
  const sdk = await loadCodeBuddySdk()
620
644
  const result = await withTimeout(sdk.unstable_v2_authenticate({
621
645
  environment: codeBuddyEnvironment(region),
646
+ // Scoped to this region's directory. Left out, the CLI answered from its
647
+ // shared default directory — whichever region had signed in last — and
648
+ // `rememberBearerToken` below then recorded *that* account as this region's.
649
+ env: cliDirEnv(region),
622
650
  timeout: 3000,
623
651
  onAuthUrl: () => {
624
652
  // A quota read must never pop a browser; the page owns login.
@@ -682,7 +710,7 @@ export async function fetchCodeBuddyQuota(
682
710
  const text = await response.text()
683
711
  if (!response.ok) {
684
712
  if (response.status === 401 || response.status === 403) {
685
- throw new Error('CodeBuddy 登录已过期,请重新登录')
713
+ throw new CredentialRejectedError('CodeBuddy 登录已过期,请重新登录')
686
714
  }
687
715
  const detail = text.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 160)
688
716
  throw new Error(`CodeBuddy 额度接口返回 HTTP ${response.status}${detail === '' ? '' : `:${detail}`}`)
@@ -696,9 +724,33 @@ export async function fetchCodeBuddyQuota(
696
724
  return parseCodeBuddyQuota(payload)
697
725
  }
698
726
 
699
- /** Whether a quota failure means the stored credential is no longer usable. */
700
- function isExpiredToken(message: string): boolean {
701
- return /401|403|登录已过期|unauthor|token/i.test(message)
727
+ /**
728
+ * The credential this region holds was rejected by the endpoint.
729
+ *
730
+ * Thrown where the rejection is *known* — an explicit HTTP 401/403 — rather
731
+ * than inferred from the error text. Inferring it was the bug: the loose
732
+ * matcher below used to treat any failure whose message happened to contain
733
+ * "token", "401" inside a number, or an HTML body mentioning a token, as an
734
+ * expired login. It then dropped a working credential, and because a missing
735
+ * local token reads as "signed out", the page showed an account as not signed
736
+ * in while the CLI still had a usable login.
737
+ */
738
+ class CredentialRejectedError extends Error {}
739
+
740
+ /**
741
+ * Whether a quota failure genuinely means the credential no longer works.
742
+ *
743
+ * The typed error carries the CLI's own expiry sentence, which is also matched
744
+ * here because the message is ours, fixed, and not derived from server text.
745
+ * Everything else — a 5xx, a bad payload, a timeout, an unreachable endpoint —
746
+ * leaves the credential alone.
747
+ *
748
+ * @param error - whatever quota reading threw.
749
+ */
750
+ function isCredentialRejected(error: unknown): boolean {
751
+ if (error instanceof CredentialRejectedError) return true
752
+ const message = error instanceof Error ? error.message : String(error)
753
+ return message === 'CodeBuddy 登录已过期,请重新登录'
702
754
  }
703
755
 
704
756
  /** Read quota, retrying once with a fresh token after an auth failure. */
@@ -709,8 +761,7 @@ async function readQuotaWithToken(region: CodeBuddyRegion): Promise<CodeBuddyQuo
709
761
  try {
710
762
  return await fetchCodeBuddyQuota(region, token)
711
763
  } catch (error) {
712
- const detail = error instanceof Error ? error.message : String(error)
713
- if (!isExpiredToken(detail)) throw error
764
+ if (!isCredentialRejected(error)) throw error
714
765
  forgetToken(region)
715
766
  const renewed = await readBearerToken(region).catch((renewError: unknown) => {
716
767
  throw new Error(authErrorText(region, renewError))
@@ -768,7 +819,7 @@ export class CodeBuddyAuth {
768
819
  try {
769
820
  const sdk = await loadCodeBuddySdk()
770
821
  await withTimeout(
771
- sdk.unstable_v2_logout({ environment: codeBuddyEnvironment(region) }),
822
+ sdk.unstable_v2_logout({ environment: codeBuddyEnvironment(region), env: cliDirEnv(region) }),
772
823
  CODEBUDDY_FETCH_TIMEOUT_MS,
773
824
  )
774
825
  } catch (error) {
@@ -796,14 +847,18 @@ export class CodeBuddyAuth {
796
847
  // it returns that token without ever calling `onAuthUrl`, so the click
797
848
  // looks dead and an expired credential survives forever. A login click
798
849
  // always means "open the browser", so drop the stored credential first.
850
+ // Both calls are scoped to this region's directory: the CLI's default
851
+ // directory is shared, so an unscoped logout here signed the *other*
852
+ // region out as a side effect of logging this one in.
799
853
  await withTimeout(
800
- sdk.unstable_v2_logout({ environment: codeBuddyEnvironment(region) }),
854
+ sdk.unstable_v2_logout({ environment: codeBuddyEnvironment(region), env: cliDirEnv(region) }),
801
855
  LOGOUT_TIMEOUT_MS,
802
856
  ).catch(() => undefined)
803
857
  if (!this.current(run)) return
804
858
  bearerTokens.delete(region)
805
859
  const result = await sdk.unstable_v2_authenticate({
806
860
  environment: codeBuddyEnvironment(region),
861
+ env: cliDirEnv(region),
807
862
  timeout: LOGIN_TIMEOUT_MS,
808
863
  onAuthUrl: (state) => {
809
864
  // The bundled CLI opens the browser itself as part of the login
@@ -976,12 +1031,14 @@ export class CodeBuddySession {
976
1031
  * compacts (and the gateway rejects) anything past 276K — while the host,
977
1032
  * told 1M, keeps showing and feeding a larger history. Replaying that history
978
1033
  * then collapses to a summary. Applying the same number the host divides by
979
- * keeps the two in step; models that expose no choice reject it and keep
980
- * their default.
1034
+ * keeps the two in step; the adapter therefore sends a window for every model
1035
+ * it knows about, not only the ones that advertise a choice — the mainland
1036
+ * catalog declares no lengths anywhere and its physical `maxInputTokens` is a
1037
+ * provider number the CLI is free to ignore when left to itself.
981
1038
  *
982
- * The CLI refuses to clear the override (`contextWindow must be a positive
983
- * safe integer`), so the adapter sends the model's default instead when the
984
- * page returns to "default".
1039
+ * A rejected value keeps the CLI on its own default, which is the one case
1040
+ * where the two denominators can still disagree; it is reported nowhere, so
1041
+ * the host's figure stays the visible contract.
985
1042
  */
986
1043
  private async applyContextWindow(session: SessionImpl): Promise<void> {
987
1044
  const window = this.contextWindow
@@ -992,7 +1049,8 @@ export class CodeBuddySession {
992
1049
  try {
993
1050
  await session.setConfig({ contextWindow: window })
994
1051
  } catch {
995
- // `Allowed: <none>` models have one fixed window; their default stands.
1052
+ // Nothing selectable here, or the value was refused: the model's own
1053
+ // default stands rather than failing the turn over a budget hint.
996
1054
  }
997
1055
  }
998
1056