dsh-agent-sdk-bridge 1.2.1 → 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
@@ -4,16 +4,15 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSyn
4
4
  import { homedir, tmpdir } from "node:os";
5
5
  import * as path from "node:path";
6
6
  import { delimiter, dirname, join } from "node:path";
7
- import * as cnSdk from "@qodercn-ai/qodercn-agent-sdk";
8
- import { createSdkMcpServer, qodercliAuth } from "@qodercn-ai/qodercn-agent-sdk";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
8
  import { createHash, randomBytes, randomUUID } from "node:crypto";
9
+ import { createSdkMcpServer } from "@qodercn-ai/qodercn-agent-sdk";
10
10
  import { z } from "zod";
11
11
  import { spawn } from "node:child_process";
12
12
  import { createServer } from "node:http";
13
13
  import { Readable, Writable } from "node:stream";
14
14
  import { ClientSideConnection, PROTOCOL_VERSION, ndJsonStream } from "@agentclientprotocol/sdk";
15
15
  import { TextDecoder } from "node:util";
16
- import { fileURLToPath } from "node:url";
17
16
  import { isVolatile } from "@deepseek-ai/cosmokit";
18
17
  import z$1 from "@deepseek-ai/schemastery";
19
18
  //#region src/brand.ts
@@ -465,6 +464,7 @@ function cliConflictMessage(brand) {
465
464
  * @returns the original detail, prefixed with the actionable explanation.
466
465
  */
467
466
  function cliFailureText(detail, brand) {
467
+ if (/DaemonConfigurationConflict|Global daemon is already initialized with different options/i.test(detail)) return `本机 ${brandProfile(brand).cliCommands[0]} 的运行配置在本次会话期间发生了变化,SDK 的本地守护进程仍按旧配置运行。插件已重置这部分运行时,请重试一次;若仍失败,重启 DSH Web。原始信息:${detail}`;
468
468
  if (!/exit(?:ed)?(?: with)? code 42|sdk_worker_removed/i.test(detail)) return detail;
469
469
  const profile = brandProfile(brand);
470
470
  const pkg = profile.cliPackages[0];
@@ -645,53 +645,187 @@ function isWorkerRuntime(entry) {
645
645
  *
646
646
  * The Qoder editions publish the same API under different scopes, so the rest
647
647
  * of the plugin imports this module instead of a package name. The CN SDK is a
648
- * real dependency and is loaded statically; the international one is optional
649
- * at runtime — a deployment that only has a CN account may not have it
650
- * installed — so it is imported on demand and its absence is reported to the
651
- * settings page as a plain error instead of failing the plugin's mount.
648
+ * real dependency and is loaded eagerly; the international one is optional at
649
+ * runtime — a deployment that only has a CN account may not have it installed —
650
+ * so it is imported on demand and its absence is reported to the settings page
651
+ * as a plain error instead of failing the plugin's mount.
652
652
  *
653
653
  * CodeBuddy has its own, unrelated API and is loaded dynamically for the same
654
654
  * reason: an account may never use it, and its package carries a large CLI.
655
655
  *
656
- * The Qoder module is typed against the CN package because the two are
657
- * API-compatible: every Qoder call site is shared, and the only thing that
658
- * changes is which process the protocol is spoken to.
656
+ * ## Why modules are reloaded
657
+ *
658
+ * Every Qoder SDK routes all queries through one **process-wide daemon** that
659
+ * is initialized with the first query's launch configuration (CLI path,
660
+ * interpreter, environment, proxy) and then refuses any different one for the
661
+ * life of the process:
662
+ *
663
+ * DaemonConfigurationConflictError:
664
+ * Global daemon is already initialized with different options
665
+ *
666
+ * The host is long-lived, so its configuration is not: a CLI can be
667
+ * reinstalled, an edition can appear, an installer can change the machine
668
+ * environment. When that happens the ready daemon no longer matches and every
669
+ * later query fails until the process restarts — a state the settings page
670
+ * cannot recover from on its own.
671
+ *
672
+ * So the module tracks the configuration signature it loaded under and takes a
673
+ * fresh instance whenever the signature changes; {@link resetSdk} does the same
674
+ * after a conflict is observed. A new instance has an empty daemon registry, so
675
+ * it initializes against the current configuration instead of arguing with the
676
+ * old one.
659
677
  *
660
678
  * @module dsh-agent-sdk-bridge/sdk
661
679
  */
662
- let globalSdk;
680
+ const generations = /* @__PURE__ */ new Map();
681
+ /** Brands whose next load must take a fresh instance even if the signature matches. */
682
+ const forced = /* @__PURE__ */ new Set();
683
+ let counter = 0;
663
684
  let codeBuddySdk;
685
+ const require = createRequire(import.meta.url);
664
686
  /**
665
- * Load the SDK for one Qoder edition.
687
+ * The launch configuration a Qoder query would use, as a comparable string.
666
688
  *
667
- * @param brand - which edition's SDK to load.
668
- * @returns the SDK module.
689
+ * Mirrors the fields the SDK's own daemon compares before reusing itself. The
690
+ * environment is included because the SDK hands it to the CLI verbatim, and a
691
+ * difference there is enough to make the daemon reject a query.
692
+ *
693
+ * @param brand - which edition's configuration to describe.
694
+ * @returns a stable string that changes exactly when the configuration does.
669
695
  */
670
- function loadSdk(brand) {
671
- if (brand === "cn") return Promise.resolve(cnSdk);
672
- globalSdk ??= importGlobalSdk();
673
- return globalSdk;
696
+ function configurationSignature(brand) {
697
+ const options = qoderCliOptions(brand);
698
+ const env = Object.entries(options.env ?? {}).filter(([, value]) => value !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
699
+ return JSON.stringify({
700
+ path: options.pathToQoderCLIExecutable ?? null,
701
+ executable: options.executable ?? null,
702
+ env
703
+ });
674
704
  }
675
705
  /**
676
- * Import the international SDK by a variable specifier.
706
+ * Import one edition's SDK.
677
707
  *
678
- * A literal specifier would make TypeScript and the bundler require the package
679
- * at build time, which is exactly what an optional edition must not do.
708
+ * A fresh instance is the same file imported under a unique URL: the module's
709
+ * top-level daemon state is per instance, while the implementation is shared by
710
+ * the module loader as usual.
711
+ *
712
+ * @param brand - which edition to load.
713
+ * @param fresh - ignore the already-loaded instance and take a new one.
680
714
  */
681
- async function importGlobalSdk() {
682
- const specifier = brandProfile("global").sdkPackage;
715
+ async function importSdk(brand, fresh) {
716
+ const specifier = brandProfile(brand).sdkPackage;
683
717
  try {
684
- return await import(
718
+ if (!fresh) return await import(
685
719
  /* @vite-ignore */
686
720
  specifier
721
+ );
722
+ const entry = pathToFileURL(require.resolve(specifier)).href;
723
+ counter += 1;
724
+ return await import(
725
+ /* @vite-ignore */
726
+ `${entry}?generation=${counter}`
687
727
  );
688
728
  } catch (error) {
689
- globalSdk = void 0;
729
+ generations.delete(brand);
730
+ forced.delete(brand);
731
+ if (brand === "cn") throw error;
690
732
  const detail = error instanceof Error ? error.message : String(error);
691
733
  throw new Error(`未安装国际版 SDK(${specifier}):${detail}`);
692
734
  }
693
735
  }
694
736
  /**
737
+ * Load the SDK for one Qoder edition, under its current configuration.
738
+ *
739
+ * @param brand - which edition's SDK to load.
740
+ * @returns the SDK module.
741
+ */
742
+ function loadSdk(brand) {
743
+ const signature = configurationSignature(brand);
744
+ const current = generations.get(brand);
745
+ if (current !== void 0 && current.signature === signature && !forced.has(brand)) return current.module;
746
+ const module = importSdk(brand, current !== void 0 || forced.delete(brand));
747
+ const generation = {
748
+ signature,
749
+ module
750
+ };
751
+ generations.set(brand, generation);
752
+ module.catch(() => {
753
+ if (generations.get(brand) === generation) generations.delete(brand);
754
+ });
755
+ return module;
756
+ }
757
+ /**
758
+ * Drop the loaded instance so the next {@link loadSdk} starts a new daemon.
759
+ *
760
+ * @param brand - which edition to reset.
761
+ */
762
+ function resetSdk(brand) {
763
+ generations.delete(brand);
764
+ forced.add(brand);
765
+ }
766
+ /**
767
+ * Whether an error is the SDK's daemon refusing a different configuration.
768
+ *
769
+ * @param error - whatever a query threw.
770
+ */
771
+ function isDaemonConflict(error) {
772
+ const text = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
773
+ return text.includes("DaemonConfigurationConflictError") || text.includes("Global daemon is already initialized with different options");
774
+ }
775
+ /**
776
+ * Run one idempotent SDK operation, recovering from a daemon conflict once.
777
+ *
778
+ * A conflict means the daemon was initialized under a configuration that no
779
+ * longer applies. A fresh module instance starts an empty daemon with the
780
+ * current one, so the retry succeeds without a restart. Only use this for
781
+ * operations that can be repeated without side effects (reads), never for a
782
+ * turn that may already have emitted output.
783
+ *
784
+ * @param brand - which edition to query.
785
+ * @param run - the operation, given the module to use.
786
+ */
787
+ async function withSdk(brand, run) {
788
+ try {
789
+ return await run(await loadSdk(brand));
790
+ } catch (error) {
791
+ if (!isDaemonConflict(error)) throw error;
792
+ resetSdk(brand);
793
+ return await run(await loadSdk(brand));
794
+ }
795
+ }
796
+ /**
797
+ * Open one cheap control query so a stale daemon is discovered before a turn
798
+ * starts streaming.
799
+ *
800
+ * A turn cannot be retried once it has emitted output, so the session path has
801
+ * to find out about a configuration conflict first. `getUsageInfo` is a
802
+ * control request: it initializes the daemon and reads the account without
803
+ * running a model turn.
804
+ *
805
+ * @param brand - which edition to probe.
806
+ */
807
+ async function probeDaemon(brand) {
808
+ const sdk = await loadSdk(brand);
809
+ const q = sdk.query({
810
+ prompt: (async function* () {
811
+ await new Promise(() => {});
812
+ })(),
813
+ options: {
814
+ ...qoderCliOptions(brand),
815
+ auth: sdk.qodercliAuth(),
816
+ tools: [],
817
+ allowedTools: [],
818
+ settingSources: [],
819
+ maxTurns: 1
820
+ }
821
+ });
822
+ try {
823
+ await q.getUsageInfo();
824
+ } finally {
825
+ await q.close().catch(() => void 0);
826
+ }
827
+ }
828
+ /**
695
829
  * Load the CodeBuddy Agent SDK.
696
830
  *
697
831
  * Kept lazy because the package ships its own ~200 MB CLI and is useless to a
@@ -832,7 +966,10 @@ var QoderModelCatalog = class {
832
966
  }
833
967
  async fetch() {
834
968
  if (foreignCliOverride(this.brand) !== void 0) throw new Error(cliConflictMessage(this.brand));
835
- const sdk = await loadSdk(this.brand);
969
+ if (resolveQoderCli(this.brand) === void 0) throw new Error(cliConflictMessage(this.brand));
970
+ return withSdk(this.brand, (sdk) => this.read(sdk));
971
+ }
972
+ async read(sdk) {
836
973
  const q = sdk.query({
837
974
  prompt: inertInput$2(),
838
975
  options: {
@@ -2057,11 +2194,18 @@ var QoderSession = class {
2057
2194
  async ensureStarted() {
2058
2195
  if (this.q !== null) return this.q;
2059
2196
  if (foreignCliOverride(this.brand) !== void 0) throw new Error(cliConflictMessage(this.brand));
2060
- const q = (await loadSdk(this.brand)).query({
2197
+ if (resolveQoderCli(this.brand) === void 0) throw new Error(cliConflictMessage(this.brand));
2198
+ try {
2199
+ await probeDaemon(this.brand);
2200
+ } catch (error) {
2201
+ if (isDaemonConflict(error)) resetSdk(this.brand);
2202
+ }
2203
+ const sdk = await loadSdk(this.brand);
2204
+ const q = sdk.query({
2061
2205
  prompt: this.channel,
2062
2206
  options: {
2063
2207
  ...qoderCliOptions(this.brand),
2064
- auth: qodercliAuth(),
2208
+ auth: sdk.qodercliAuth(),
2065
2209
  tools: [],
2066
2210
  allowedTools: [],
2067
2211
  canUseTool: this.canUseTool,
@@ -2419,6 +2563,11 @@ var QoderSession = class {
2419
2563
  }
2420
2564
  });
2421
2565
  } catch (error) {
2566
+ if (isDaemonConflict(error)) {
2567
+ resetSdk(this.brand);
2568
+ this.q = null;
2569
+ q.close().catch(() => void 0);
2570
+ }
2422
2571
  this.endTurn({
2423
2572
  kind: "error",
2424
2573
  failure: {
@@ -2738,11 +2887,13 @@ var QoderSessionManager = class {
2738
2887
  const systemPrompt = options.system;
2739
2888
  const brand = this.runtime.brand ?? "cn";
2740
2889
  if (foreignCliOverride(brand) !== void 0) throw new Error(cliConflictMessage(brand));
2741
- const q = (await loadSdk(brand)).query({
2890
+ if (resolveQoderCli(brand) === void 0) throw new Error(cliConflictMessage(brand));
2891
+ const sdk = await loadSdk(brand);
2892
+ const q = sdk.query({
2742
2893
  prompt,
2743
2894
  options: {
2744
2895
  ...qoderCliOptions(brand),
2745
- auth: qodercliAuth(),
2896
+ auth: sdk.qodercliAuth(),
2746
2897
  tools: [],
2747
2898
  allowedTools: [],
2748
2899
  canUseTool: gateTools,
@@ -2775,7 +2926,10 @@ var QoderSessionManager = class {
2775
2926
  }
2776
2927
  }
2777
2928
  } catch (error) {
2778
- if (signal?.aborted !== true) throw error;
2929
+ if (signal?.aborted !== true) {
2930
+ if (isDaemonConflict(error)) resetSdk(brand);
2931
+ throw error;
2932
+ }
2779
2933
  }
2780
2934
  if (signal?.aborted === true) {
2781
2935
  yield {
@@ -2916,30 +3070,7 @@ var QoderUsage = class {
2916
3070
  cliMissing: true,
2917
3071
  error: cliConflictMessage(this.brand)
2918
3072
  };
2919
- const sdk = await loadSdk(this.brand);
2920
- const timeoutMs = readLive(this.timeoutMs, DEFAULT_USAGE_TIMEOUT_MS);
2921
- const q = sdk.query({
2922
- prompt: inertInput$1(),
2923
- options: {
2924
- ...qoderCliOptions(this.brand),
2925
- auth: sdk.qodercliAuth(),
2926
- tools: [],
2927
- allowedTools: [],
2928
- settingSources: [],
2929
- maxTurns: 1
2930
- }
2931
- });
2932
- try {
2933
- const usage = await withTimeout$2(q.getUsageInfo(), timeoutMs);
2934
- const account = await withTimeout$2(q.accountInfo(), timeoutMs).catch(() => void 0);
2935
- return {
2936
- at,
2937
- ...usage === null || usage === void 0 ? { error: "CLI 未返回额度信息" } : { usage },
2938
- ...account === void 0 ? {} : { account }
2939
- };
2940
- } finally {
2941
- await q.close().catch(() => void 0);
2942
- }
3073
+ return await withSdk(this.brand, (sdk) => this.readSnapshot(sdk, at));
2943
3074
  } catch (error) {
2944
3075
  const detail = error instanceof Error ? error.message : String(error);
2945
3076
  const command = brandProfile(this.brand).cliCommands[0];
@@ -2949,6 +3080,31 @@ var QoderUsage = class {
2949
3080
  };
2950
3081
  }
2951
3082
  }
3083
+ async readSnapshot(sdk, at) {
3084
+ const timeoutMs = readLive(this.timeoutMs, DEFAULT_USAGE_TIMEOUT_MS);
3085
+ const q = sdk.query({
3086
+ prompt: inertInput$1(),
3087
+ options: {
3088
+ ...qoderCliOptions(this.brand),
3089
+ auth: sdk.qodercliAuth(),
3090
+ tools: [],
3091
+ allowedTools: [],
3092
+ settingSources: [],
3093
+ maxTurns: 1
3094
+ }
3095
+ });
3096
+ try {
3097
+ const usage = await withTimeout$2(q.getUsageInfo(), timeoutMs);
3098
+ const account = await withTimeout$2(q.accountInfo(), timeoutMs).catch(() => void 0);
3099
+ return {
3100
+ at,
3101
+ ...usage === null || usage === void 0 ? { error: "CLI 未返回额度信息" } : { usage },
3102
+ ...account === void 0 ? {} : { account }
3103
+ };
3104
+ } finally {
3105
+ await q.close().catch(() => void 0);
3106
+ }
3107
+ }
2952
3108
  };
2953
3109
  //#endregion
2954
3110
  //#region src/adapter.ts
@@ -3569,6 +3725,23 @@ function planContinuation(previous, current) {
3569
3725
  * @module dsh-agent-sdk-bridge/codebuddy-state
3570
3726
  */
3571
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
+ /**
3572
3745
  * The default file path.
3573
3746
  *
3574
3747
  * `DSH_HOME` is honoured so a desktop profile and a web profile keep separate
@@ -3613,13 +3786,46 @@ var CodeBuddyStateStore = class {
3613
3786
  this.loaded = true;
3614
3787
  try {
3615
3788
  const parsed = JSON.parse(readFileSync(this.file, "utf8"));
3616
- if (parsed.version === 1 && parsed.regions !== null && typeof parsed.regions === "object") this.state = {
3617
- version: 1,
3618
- regions: parsed.regions
3619
- };
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
+ }
3620
3796
  } catch {}
3621
3797
  return this.state;
3622
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
+ }
3623
3829
  region(region) {
3624
3830
  return this.ensureLoaded().regions[region];
3625
3831
  }
@@ -3651,6 +3857,7 @@ var CodeBuddyStateStore = class {
3651
3857
  const next = { ...state.regions[region] };
3652
3858
  for (const [key, value] of Object.entries(patch)) if (value === void 0) delete next[key];
3653
3859
  else next[key] = value;
3860
+ if (next.account !== void 0) next.account = withoutCredential(next.account);
3654
3861
  state.regions[region] = next;
3655
3862
  this.persist();
3656
3863
  }
@@ -3808,11 +4015,24 @@ function tokenFor(region) {
3808
4015
  * pins the environment, so a fresh process always reads the right catalog.
3809
4016
  */
3810
4017
  function cliEnv(region) {
3811
- const env = { CODEBUDDY_CONFIG_DIR: codeBuddyCliDir(region) };
4018
+ const env = cliDirEnv(region);
3812
4019
  const token = tokenFor(region);
3813
4020
  if (token !== void 0) env.CODEBUDDY_AUTH_TOKEN = token;
3814
4021
  return { env };
3815
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
+ }
3816
4036
  /** Remember a bearer token in memory and on disk. */
3817
4037
  function rememberBearerToken(region, token, user) {
3818
4038
  if (token.length === 0) return;
@@ -4009,10 +4229,6 @@ var CodeBuddyAccountReader = class {
4009
4229
  }
4010
4230
  async fetch(region) {
4011
4231
  const at = Date.now();
4012
- if (tokenFor(region) === void 0) return {
4013
- at,
4014
- error: `${region === "cn" ? "CodeBuddy 国内版" : "CodeBuddy 国际版"}尚未登录,请在页面顶部选择该区域并登录。`
4015
- };
4016
4232
  try {
4017
4233
  const account = await readAccount(region, readLive(this.timeoutMs, CODEBUDDY_FETCH_TIMEOUT_MS));
4018
4234
  if (isUnauthenticatedAccount(account)) {
@@ -4048,7 +4264,7 @@ var CodeBuddyAccountReader = class {
4048
4264
  };
4049
4265
  } catch (quotaError) {
4050
4266
  const message = quotaError instanceof Error ? quotaError.message : String(quotaError);
4051
- if (isExpiredToken(message)) forgetToken(region);
4267
+ if (isCredentialRejected(quotaError)) forgetToken(region);
4052
4268
  else codeBuddyState.patch(region, {
4053
4269
  quota: void 0,
4054
4270
  quotaError: message
@@ -4086,7 +4302,7 @@ async function readAccount(region, timeoutMs) {
4086
4302
  });
4087
4303
  try {
4088
4304
  await withTimeout$1(q.connect(), timeoutMs);
4089
- return await withTimeout$1(q.accountInfo(), timeoutMs);
4305
+ return withoutCredential(await withTimeout$1(q.accountInfo(), timeoutMs)) ?? {};
4090
4306
  } finally {
4091
4307
  await q.return().catch(() => void 0);
4092
4308
  }
@@ -4173,15 +4389,21 @@ function formatLocalTime(date) {
4173
4389
  /**
4174
4390
  * A bearer token for the region, from a recent login or a silent SDK read.
4175
4391
  *
4176
- * `authenticate` returns the CLI's existing account token without opening a
4177
- * browser when the region is already signed in, so this stays a read. When it
4178
- * 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.
4179
4400
  */
4180
4401
  async function readBearerToken(region) {
4181
4402
  const cached = tokenFor(region);
4182
4403
  if (cached !== void 0) return cached;
4183
4404
  const result = await withTimeout$1((await loadCodeBuddySdk()).unstable_v2_authenticate({
4184
4405
  environment: codeBuddyEnvironment(region),
4406
+ env: cliDirEnv(region),
4185
4407
  timeout: 3e3,
4186
4408
  onAuthUrl: () => {}
4187
4409
  }), 6e3);
@@ -4237,7 +4459,7 @@ async function fetchCodeBuddyQuota(region, token, fetchImpl = fetch) {
4237
4459
  });
4238
4460
  const text = await response.text();
4239
4461
  if (!response.ok) {
4240
- if (response.status === 401 || response.status === 403) throw new Error("CodeBuddy 登录已过期,请重新登录");
4462
+ if (response.status === 401 || response.status === 403) throw new CredentialRejectedError("CodeBuddy 登录已过期,请重新登录");
4241
4463
  const detail = text.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim().slice(0, 160);
4242
4464
  throw new Error(`CodeBuddy 额度接口返回 HTTP ${response.status}${detail === "" ? "" : `:${detail}`}`);
4243
4465
  }
@@ -4249,9 +4471,31 @@ async function fetchCodeBuddyQuota(region, token, fetchImpl = fetch) {
4249
4471
  }
4250
4472
  return parseCodeBuddyQuota(payload);
4251
4473
  }
4252
- /** Whether a quota failure means the stored credential is no longer usable. */
4253
- function isExpiredToken(message) {
4254
- 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 登录已过期,请重新登录";
4255
4499
  }
4256
4500
  /** Read quota, retrying once with a fresh token after an auth failure. */
4257
4501
  async function readQuotaWithToken(region) {
@@ -4261,7 +4505,7 @@ async function readQuotaWithToken(region) {
4261
4505
  try {
4262
4506
  return await fetchCodeBuddyQuota(region, token);
4263
4507
  } catch (error) {
4264
- if (!isExpiredToken(error instanceof Error ? error.message : String(error))) throw error;
4508
+ if (!isCredentialRejected(error)) throw error;
4265
4509
  forgetToken(region);
4266
4510
  return await fetchCodeBuddyQuota(region, await readBearerToken(region).catch((renewError) => {
4267
4511
  throw new Error(authErrorText(region, renewError));
@@ -4310,7 +4554,10 @@ var CodeBuddyAuth = class {
4310
4554
  async logout(region) {
4311
4555
  let failure;
4312
4556
  try {
4313
- 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);
4314
4561
  } catch (error) {
4315
4562
  failure = error instanceof Error ? error.message : String(error);
4316
4563
  }
@@ -4331,11 +4578,15 @@ var CodeBuddyAuth = class {
4331
4578
  const { region } = status;
4332
4579
  try {
4333
4580
  const sdk = await loadCodeBuddySdk();
4334
- 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);
4335
4585
  if (!this.current(run)) return;
4336
4586
  bearerTokens.delete(region);
4337
4587
  const result = await sdk.unstable_v2_authenticate({
4338
4588
  environment: codeBuddyEnvironment(region),
4589
+ env: cliDirEnv(region),
4339
4590
  timeout: LOGIN_TIMEOUT_MS,
4340
4591
  onAuthUrl: (state) => {
4341
4592
  status.url = state.authUrl;
@@ -4476,12 +4727,14 @@ var CodeBuddySession = class {
4476
4727
  * compacts (and the gateway rejects) anything past 276K — while the host,
4477
4728
  * told 1M, keeps showing and feeding a larger history. Replaying that history
4478
4729
  * then collapses to a summary. Applying the same number the host divides by
4479
- * keeps the two in step; models that expose no choice reject it and keep
4480
- * 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.
4481
4734
  *
4482
- * The CLI refuses to clear the override (`contextWindow must be a positive
4483
- * safe integer`), so the adapter sends the model's default instead when the
4484
- * 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.
4485
4738
  */
4486
4739
  async applyContextWindow(session) {
4487
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;