@eddyskywalker/dsh-chatgpt-subscription 0.88.2 → 0.89.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.
Files changed (31) hide show
  1. package/README.md +1 -1
  2. package/lib/client.js +67 -10
  3. package/lib/client.js.map +1 -1
  4. package/lib/index.js +306 -61
  5. package/lib/types/client/locales-ru/hub.d.ts.map +1 -1
  6. package/lib/types/client/providers/codex-chatgpt/CodexSubscriptionSection.d.ts +1 -1
  7. package/lib/types/client/providers/codex-chatgpt/CodexSubscriptionSection.d.ts.map +1 -1
  8. package/lib/types/client/providers/codex-chatgpt/api.d.ts +3 -1
  9. package/lib/types/client/providers/codex-chatgpt/api.d.ts.map +1 -1
  10. package/lib/types/client/providers/codex-chatgpt/locales.d.ts +9 -1
  11. package/lib/types/client/providers/codex-chatgpt/locales.d.ts.map +1 -1
  12. package/lib/types/client/providers/codex-chatgpt/styles.d.ts.map +1 -1
  13. package/lib/types/compat.d.ts +1 -1
  14. package/lib/types/host/common/account-pool.d.ts +3 -0
  15. package/lib/types/host/common/account-pool.d.ts.map +1 -1
  16. package/lib/types/host/providers/antigravity-acp/adapter.d.ts.map +1 -1
  17. package/lib/types/host/providers/antigravity-acp/binary.d.ts +1 -1
  18. package/lib/types/host/providers/antigravity-acp/binary.d.ts.map +1 -1
  19. package/lib/types/host/providers/antigravity-acp/errors.d.ts +4 -2
  20. package/lib/types/host/providers/antigravity-acp/errors.d.ts.map +1 -1
  21. package/lib/types/host/providers/codex-chatgpt/codex-account-pool.d.ts +2 -0
  22. package/lib/types/host/providers/codex-chatgpt/codex-account-pool.d.ts.map +1 -1
  23. package/lib/types/host/providers/codex-chatgpt/codex-file-import.d.ts +12 -0
  24. package/lib/types/host/providers/codex-chatgpt/codex-file-import.d.ts.map +1 -0
  25. package/lib/types/host/providers/codex-chatgpt/codex-identity.d.ts +1 -0
  26. package/lib/types/host/providers/codex-chatgpt/codex-identity.d.ts.map +1 -1
  27. package/lib/types/host/providers/codex-chatgpt/routes.d.ts.map +1 -1
  28. package/lib/types/host/providers/opendesign/mapper.d.ts.map +1 -1
  29. package/lib/types/shared/contracts.d.ts +6 -0
  30. package/lib/types/shared/contracts.d.ts.map +1 -1
  31. package/package.json +1 -1
package/lib/index.js CHANGED
@@ -27,9 +27,9 @@ import { Agent, ProxyAgent, WebSocket, fetch as fetch$1 } from "undici";
27
27
  import * as SettingsModule from "@deepseek-ai/dsh-settings";
28
28
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
29
29
  import { URL as URL$1, URLSearchParams as URLSearchParams$1, fileURLToPath } from "node:url";
30
+ import { crc32, gzipSync, inflateRawSync } from "node:zlib";
30
31
  import { StringDecoder } from "node:string_decoder";
31
32
  import { EventStreamCodec } from "@smithy/eventstream-codec";
32
- import { gzipSync } from "node:zlib";
33
33
  //#region src/shared/i18n-contracts.ts
34
34
  /**
35
35
  * Language ids this plugin speaks, and the one parser that decides which one a
@@ -840,7 +840,7 @@ const ROUTE_PREFIX$5 = "/api/dsh-chatgpt-subscription";
840
840
  * `test/responses-client.test.ts` asserts the two agree, so a release that
841
841
  * forgets this constant fails the suite instead of shipping quietly.
842
842
  */
843
- const PLUGIN_VERSION = "0.88.2";
843
+ const PLUGIN_VERSION = "0.89.0";
844
844
  const CODEX_CHATGPT_PROVIDER_ID = "codex-chatgpt";
845
845
  const CODEX_API_BASE = "https://chatgpt.com/backend-api/codex";
846
846
  const CODEX_RESPONSES_URL = `${CODEX_API_BASE}/responses`;
@@ -3134,6 +3134,8 @@ function describePoolStoragePath(platform, poolFile, storage, keychainService, a
3134
3134
  }
3135
3135
  /** Shortest cooldown a 429 may impose; a provider asking for less is clamped. */
3136
3136
  const MIN_COOLDOWN_MS = 1e4;
3137
+ /** A new account would exceed the configured pool capacity. */
3138
+ var AccountPoolCapacityError = class extends Error {};
3137
3139
  /** Accept a stored rotation strategy, or fall back to sequential. */
3138
3140
  function normalizeRotationStrategy(value) {
3139
3141
  return value === "round-robin" || value === "sticky" ? value : "sequential";
@@ -3452,7 +3454,7 @@ var AccountPoolCore = class {
3452
3454
  const key = this.hooks.dedupeKey?.(credentials);
3453
3455
  const existingIndex = key === void 0 ? -1 : data.accounts.findIndex((account) => this.hooks.dedupeKey?.(account.credentials) === key);
3454
3456
  const maxAccounts = this.hooks.maxAccounts ?? 20;
3455
- if (existingIndex < 0 && data.accounts.length >= maxAccounts) throw new Error(t("pool.maxAccounts", {
3457
+ if (existingIndex < 0 && data.accounts.length >= maxAccounts) throw new AccountPoolCapacityError(t("pool.maxAccounts", {
3456
3458
  provider: this.hooks.displayName,
3457
3459
  max: maxAccounts
3458
3460
  }));
@@ -4622,7 +4624,7 @@ var OAuthService = class {
4622
4624
  throw new OAuthServiceError("oauth-token-exchange-failed", `The ChatGPT device code could not be issued (${response.status}${detail === null ? "" : `, ${detail}`}).`, response.status);
4623
4625
  }
4624
4626
  const payload = await response.json().catch(() => null);
4625
- const record = isRecord$93(payload) ? payload : {};
4627
+ const record = isRecord$94(payload) ? payload : {};
4626
4628
  const authId = nonEmptyString$12(record.device_auth_id);
4627
4629
  const userCode = nonEmptyString$12(record.user_code) ?? nonEmptyString$12(record.usercode);
4628
4630
  if (authId === void 0 || userCode === void 0) throw new OAuthServiceError("oauth-token-exchange-failed", "ChatGPT returned no device code.");
@@ -4689,7 +4691,7 @@ var OAuthService = class {
4689
4691
  const detail = deviceErrorIdentifier(payload);
4690
4692
  throw new OAuthServiceError("oauth-token-exchange-failed", `The ChatGPT device confirmation was refused (${response.status}${detail === void 0 ? "" : `, ${detail}`}).`, response.status);
4691
4693
  }
4692
- const record = isRecord$93(payload) ? payload : {};
4694
+ const record = isRecord$94(payload) ? payload : {};
4693
4695
  const authorizationCode = nonEmptyString$12(record.authorization_code);
4694
4696
  const codeVerifier = nonEmptyString$12(record.code_verifier);
4695
4697
  if (authorizationCode === void 0 || codeVerifier === void 0) throw new OAuthServiceError("oauth-token-exchange-failed", "ChatGPT confirmed the device code but returned no authorization code.");
@@ -5022,11 +5024,11 @@ const DEVICE_PENDING_STATUSES = /* @__PURE__ */ new Set([
5022
5024
  function isPendingDeviceAnswer(response, payload) {
5023
5025
  if (response.status === 403 || response.status === 404) return true;
5024
5026
  if (!response.ok && response.status !== 400) return false;
5025
- if (!isRecord$93(payload)) return false;
5027
+ if (!isRecord$94(payload)) return false;
5026
5028
  const status = payload.status;
5027
5029
  if (typeof status === "string" && DEVICE_PENDING_STATUSES.has(status.toLowerCase())) return true;
5028
5030
  const error = payload.error;
5029
- if (isRecord$93(error)) {
5031
+ if (isRecord$94(error)) {
5030
5032
  const code = error.code;
5031
5033
  if (typeof code === "string" && DEVICE_PENDING_STATUSES.has(code.toLowerCase())) return true;
5032
5034
  }
@@ -5040,18 +5042,18 @@ function isPendingDeviceAnswer(response, payload) {
5040
5042
  * wrong.
5041
5043
  */
5042
5044
  function deviceErrorIdentifier(payload) {
5043
- if (!isRecord$93(payload)) return void 0;
5045
+ if (!isRecord$94(payload)) return void 0;
5044
5046
  const candidates = [payload.code];
5045
5047
  const error = payload.error;
5046
5048
  if (typeof error === "string") candidates.push(error);
5047
- else if (isRecord$93(error)) candidates.push(error.code, error.type);
5049
+ else if (isRecord$94(error)) candidates.push(error.code, error.type);
5048
5050
  candidates.push(payload.status);
5049
5051
  for (const candidate of candidates) if (typeof candidate === "string" && /^[a-z0-9_.-]{1,64}$/i.test(candidate)) return candidate;
5050
5052
  }
5051
5053
  function nonEmptyString$12(value) {
5052
5054
  return typeof value === "string" && value !== "" ? value : void 0;
5053
5055
  }
5054
- function isRecord$93(value) {
5056
+ function isRecord$94(value) {
5055
5057
  return typeof value === "object" && value !== null && !Array.isArray(value);
5056
5058
  }
5057
5059
  async function oauthErrorIdentifier(response) {
@@ -5139,7 +5141,7 @@ const CODEX_CLI_CREDENTIAL_SOURCE = "codex";
5139
5141
  * here, and the import has to be repeated afterwards.
5140
5142
  */
5141
5143
  const ADOPTED_CODEX_CREDENTIAL_EXPIRED_HINT = "The sign-in imported from the Codex CLI has expired. Sign in again in the Codex CLI, then import it again from this settings card.";
5142
- function isRecord$92(value) {
5144
+ function isRecord$93(value) {
5143
5145
  return typeof value === "object" && value !== null && !Array.isArray(value);
5144
5146
  }
5145
5147
  /** A trimmed, non-empty string, or nothing. */
@@ -5241,7 +5243,7 @@ function decodeJwtClaims$1(token) {
5241
5243
  if (parts.length !== 3) return void 0;
5242
5244
  try {
5243
5245
  const value = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
5244
- return isRecord$92(value) ? value : void 0;
5246
+ return isRecord$93(value) ? value : void 0;
5245
5247
  } catch {
5246
5248
  return;
5247
5249
  }
@@ -5286,10 +5288,10 @@ function expiryFromAccessToken(accessToken) {
5286
5288
  * the file carries cannot reach the result.
5287
5289
  */
5288
5290
  function parseAdoptedCodexCredential(value, sourcePath) {
5289
- if (!isRecord$92(value)) return void 0;
5291
+ if (!isRecord$93(value)) return void 0;
5290
5292
  if (value.auth_mode !== "chatgpt") return void 0;
5291
5293
  const tokens = value[CODEX_CLI_TOKENS_KEY];
5292
- if (!isRecord$92(tokens)) return void 0;
5294
+ if (!isRecord$93(tokens)) return void 0;
5293
5295
  const accessToken = nonEmptyString$11(tokens.access_token);
5294
5296
  if (accessToken === void 0) return void 0;
5295
5297
  const refreshToken = nonEmptyString$11(tokens.refresh_token);
@@ -5308,7 +5310,7 @@ function parseAdoptedCodexCredential(value, sourcePath) {
5308
5310
  const email = claims === void 0 ? void 0 : nonEmptyString$11(claims.email);
5309
5311
  if (email !== void 0) credentials.email = email;
5310
5312
  const authClaims = claims === void 0 ? void 0 : claims[CODEX_AUTH_CLAIMS_KEY];
5311
- const planType = isRecord$92(authClaims) ? nonEmptyString$11(authClaims.chatgpt_plan_type) : void 0;
5313
+ const planType = isRecord$93(authClaims) ? nonEmptyString$11(authClaims.chatgpt_plan_type) : void 0;
5312
5314
  if (planType !== void 0) credentials.planType = planType;
5313
5315
  }
5314
5316
  const accountId = nonEmptyString$11(tokens.account_id);
@@ -5618,6 +5620,12 @@ var CodexAccountPool = class extends AccountPoolCore {
5618
5620
  const blockedUntil = this.quotaBlockedUntil?.(account, now);
5619
5621
  return blockedUntil === void 0 || blockedUntil <= now;
5620
5622
  }
5623
+ /** Add or update a file's accounts in one storage transaction. */
5624
+ async importAccounts(credentials) {
5625
+ await this.updatePool((data) => {
5626
+ for (const credential of credentials) this.addAccountToPool(data, credential);
5627
+ });
5628
+ }
5621
5629
  /**
5622
5630
  * Force one account's token refresh and persist the rotated pair.
5623
5631
  *
@@ -7959,11 +7967,11 @@ function createControlledModelFetch(baseFetch, options) {
7959
7967
  * text and may opt into a hard handoff threshold; coordination tools are exempt
7960
7968
  * because they are expected to recur while real work continues.
7961
7969
  */
7962
- function isRecord$91(value) {
7970
+ function isRecord$92(value) {
7963
7971
  return typeof value === "object" && value !== null;
7964
7972
  }
7965
7973
  function isPlainRecord$2(value) {
7966
- if (!isRecord$91(value) || Array.isArray(value)) return false;
7974
+ if (!isRecord$92(value) || Array.isArray(value)) return false;
7967
7975
  const prototype = Object.getPrototypeOf(value);
7968
7976
  return prototype === Object.prototype || prototype === null;
7969
7977
  }
@@ -8110,15 +8118,15 @@ function nonEmptyString$10(value) {
8110
8118
  }
8111
8119
  /** 判断一次工具执行结果是否失败。 */
8112
8120
  function isToolErrorResult(result) {
8113
- return isRecord$91(result) && result["isError"] === true;
8121
+ return isRecord$92(result) && result["isError"] === true;
8114
8122
  }
8115
8123
  /** 读一次工具执行结果里的结构化错误码。 */
8116
8124
  function toolErrorCodeOf(result) {
8117
- if (!isRecord$91(result)) return void 0;
8125
+ if (!isRecord$92(result)) return void 0;
8118
8126
  const error = result["error"];
8119
- if (!isRecord$91(error)) return void 0;
8127
+ if (!isRecord$92(error)) return void 0;
8120
8128
  const info = error["info"];
8121
- if (isRecord$91(info)) {
8129
+ if (isRecord$92(info)) {
8122
8130
  const infoCode = nonEmptyString$10(info["code"]);
8123
8131
  if (infoCode !== void 0) return infoCode;
8124
8132
  }
@@ -8126,18 +8134,18 @@ function toolErrorCodeOf(result) {
8126
8134
  }
8127
8135
  /** 读一次工具执行结果里的全部文本块。 */
8128
8136
  function toolResultTextOf(result) {
8129
- if (!isRecord$91(result)) return "";
8137
+ if (!isRecord$92(result)) return "";
8130
8138
  const content = result["content"];
8131
8139
  if (!Array.isArray(content)) return "";
8132
8140
  const parts = [];
8133
- for (const block of content) if (isRecord$91(block) && block["type"] === "text") parts.push(nonEmptyString$10(block["text"]) ?? "");
8141
+ for (const block of content) if (isRecord$92(block) && block["type"] === "text") parts.push(nonEmptyString$10(block["text"]) ?? "");
8134
8142
  return parts.join("\n");
8135
8143
  }
8136
8144
  /** 读一次工具执行结果里的失败文本(无 `error.message` 且为错误结果时回退读取文本内容)。 */
8137
8145
  function toolErrorTextOf(result) {
8138
- if (isRecord$91(result)) {
8146
+ if (isRecord$92(result)) {
8139
8147
  const error = result["error"];
8140
- if (isRecord$91(error)) {
8148
+ if (isRecord$92(error)) {
8141
8149
  const msg = nonEmptyString$10(error["message"]);
8142
8150
  if (msg !== void 0) return msg;
8143
8151
  }
@@ -8532,12 +8540,12 @@ const BOOLEAN_KEYS = [
8532
8540
  "hint",
8533
8541
  "waitJobs"
8534
8542
  ];
8535
- function isRecord$90(value) {
8543
+ function isRecord$91(value) {
8536
8544
  return typeof value === "object" && value !== null && !Array.isArray(value);
8537
8545
  }
8538
8546
  /** Validate one provider override without silently dropping unknown keys. */
8539
8547
  function parsePromptCacheOverride(provider, value) {
8540
- if (!isRecord$90(value)) throw new Error(`prompt cache policy for "${provider}" must be an object`);
8548
+ if (!isRecord$91(value)) throw new Error(`prompt cache policy for "${provider}" must be an object`);
8541
8549
  const out = {};
8542
8550
  for (const [key, entry] of Object.entries(value)) {
8543
8551
  if (!OVERRIDE_KEYS.has(key)) throw new Error(`prompt cache policy for "${provider}" has unknown field "${key}"`);
@@ -8558,7 +8566,7 @@ function parsePromptCacheOverride(provider, value) {
8558
8566
  /** Validate a whole config-owned map. Undefined means no overrides. */
8559
8567
  function parsePromptCacheOverrides(value) {
8560
8568
  if (value === void 0) return {};
8561
- if (!isRecord$90(value)) throw new Error("promptCacheOverrides must be an object keyed by provider id");
8569
+ if (!isRecord$91(value)) throw new Error("promptCacheOverrides must be an object keyed by provider id");
8562
8570
  const out = {};
8563
8571
  for (const [provider, override] of Object.entries(value)) {
8564
8572
  if (!/^[a-z0-9][a-z0-9-]*$/.test(provider)) throw new Error(`invalid prompt cache provider id "${provider}"`);
@@ -10595,14 +10603,14 @@ async function fetchWithPrefixCoordination(fetchFn, coordinator, groupKey, warmT
10595
10603
  * Dynamic mid-conversation updates stay at their original history position;
10596
10604
  * only the initial harness bootstrap run is normalised ahead of the user task.
10597
10605
  */
10598
- function isRecord$89(value) {
10606
+ function isRecord$90(value) {
10599
10607
  return typeof value === "object" && value !== null && !Array.isArray(value);
10600
10608
  }
10601
10609
  function firstTextOf$1(content) {
10602
10610
  if (typeof content === "string") return content.trim() === "" ? void 0 : content;
10603
10611
  if (!Array.isArray(content)) return void 0;
10604
10612
  for (const block of content) {
10605
- if (!isRecord$89(block)) continue;
10613
+ if (!isRecord$90(block)) continue;
10606
10614
  if (block.type === "text" && typeof block.text === "string" && block.text !== "") return block.text;
10607
10615
  if (block.type === "tool-result") {
10608
10616
  const nested = firstTextOf$1(block.content);
@@ -10616,7 +10624,7 @@ function isToolResultMessage$9(message) {
10616
10624
  /** Stability tier for an initial bootstrap reminder; null means dynamic/history-bound. */
10617
10625
  function classifyBootstrapUserMessage$1(message) {
10618
10626
  if (message.role !== "user" || isToolResultMessage$9(message)) return null;
10619
- const source = isRecord$89(message.source) ? message.source : void 0;
10627
+ const source = isRecord$90(message.source) ? message.source : void 0;
10620
10628
  const kind = source !== void 0 && typeof source.kind === "string" ? source.kind : void 0;
10621
10629
  const text = firstTextOf$1(message.content)?.trimStart() ?? "";
10622
10630
  if (kind === "progress-updates-language" || text.startsWith("Progress update output language override:")) return 1;
@@ -10627,7 +10635,7 @@ function classifyBootstrapUserMessage$1(message) {
10627
10635
  }
10628
10636
  function isCompactCheckpointMessage(message) {
10629
10637
  if (message === void 0 || message.role !== "user" || isToolResultMessage$9(message)) return false;
10630
- const source = isRecord$89(message.source) ? message.source : void 0;
10638
+ const source = isRecord$90(message.source) ? message.source : void 0;
10631
10639
  if (source !== void 0 && source.kind === "compact-checkpoint") return true;
10632
10640
  return firstTextOf$1(message.content)?.trimStart().startsWith("This is an automatically generated checkpoint condensing") === true;
10633
10641
  }
@@ -10635,7 +10643,7 @@ function isCompactCheckpointMessage(message) {
10635
10643
  function normalizeAgentInstructionsMessage(message) {
10636
10644
  if (!Array.isArray(message.content) || message.content.length !== 1) return message;
10637
10645
  const first = message.content[0];
10638
- if (!isRecord$89(first) || first.type !== "text" || typeof first.text !== "string") return message;
10646
+ if (!isRecord$90(first) || first.type !== "text" || typeof first.text !== "string") return message;
10639
10647
  const raw = first.text;
10640
10648
  const firstIdx = raw.indexOf("\n\nInstructions from: ");
10641
10649
  if (firstIdx < 0) return message;
@@ -10748,7 +10756,7 @@ function allTextOf(content) {
10748
10756
  if (typeof content === "string") return content;
10749
10757
  if (!Array.isArray(content)) return "";
10750
10758
  return content.map((block) => {
10751
- if (!isRecord$89(block)) return "";
10759
+ if (!isRecord$90(block)) return "";
10752
10760
  if (block.type === "text" && typeof block.text === "string") return block.text;
10753
10761
  if (block.type === "tool-result") return allTextOf(block.content);
10754
10762
  return "";
@@ -12704,8 +12712,8 @@ function parseCodexUsage(value) {
12704
12712
  for (const [index, value] of additional.entries()) {
12705
12713
  const limit = record$5(value);
12706
12714
  if (limit === null) continue;
12707
- const idSource = text$7(limit.limit_name) ?? text$7(limit.metered_feature) ?? `additional-${index + 1}`;
12708
- addBucket(buckets, usedIds, uniqueId(slug(idSource), usedIds), readableLimitName(text$7(limit.limit_name) ?? text$7(limit.metered_feature) ?? idSource), planType, limit.rate_limit);
12715
+ const idSource = text$8(limit.limit_name) ?? text$8(limit.metered_feature) ?? `additional-${index + 1}`;
12716
+ addBucket(buckets, usedIds, uniqueId(slug(idSource), usedIds), readableLimitName(text$8(limit.limit_name) ?? text$8(limit.metered_feature) ?? idSource), planType, limit.rate_limit);
12709
12717
  }
12710
12718
  return {
12711
12719
  buckets,
@@ -12790,7 +12798,7 @@ function parseResetCredits(value) {
12790
12798
  availableCreditIds: []
12791
12799
  };
12792
12800
  const available = (Array.isArray(data.credits) ? data.credits : []).map(record$5).filter((credit) => credit !== null && credit.status === "available").map((credit) => ({
12793
- id: text$7(credit.id),
12801
+ id: text$8(credit.id),
12794
12802
  expiresAt: timestamp(credit.expires_at)
12795
12803
  })).filter((credit) => credit.id !== null).sort((left, right) => (left.expiresAt ?? Number.MAX_SAFE_INTEGER) - (right.expiresAt ?? Number.MAX_SAFE_INTEGER));
12796
12804
  const reported = numeric(data.available_count);
@@ -12824,7 +12832,7 @@ function decimalText(value) {
12824
12832
  const trimmed = value.trim();
12825
12833
  return trimmed !== "" ? trimmed : null;
12826
12834
  }
12827
- function text$7(value) {
12835
+ function text$8(value) {
12828
12836
  return typeof value === "string" && value.trim() !== "" ? value.trim() : null;
12829
12837
  }
12830
12838
  function slug(value) {
@@ -12858,6 +12866,166 @@ function identityKey(credentials) {
12858
12866
  return codexAccountIdentity(credentials) ?? credentials.planType ?? "signed-in";
12859
12867
  }
12860
12868
  //#endregion
12869
+ //#region src/host/providers/codex-chatgpt/codex-file-import.ts
12870
+ const MAX_CREDENTIAL_IMPORT_BYTES = 16 * 1024 * 1024;
12871
+ const MAX_JSON_ACCOUNTS = 1e3;
12872
+ const MAX_ZIP_ENTRIES = 1e3;
12873
+ const MAX_ZIP_ENTRY_BYTES = 2 * 1024 * 1024;
12874
+ const MAX_ZIP_TOTAL_BYTES = 32 * 1024 * 1024;
12875
+ var CodexCredentialImportError = class extends Error {
12876
+ constructor(message) {
12877
+ super(message);
12878
+ this.name = "CodexCredentialImportError";
12879
+ }
12880
+ };
12881
+ function isRecord$89(value) {
12882
+ return typeof value === "object" && value !== null && !Array.isArray(value);
12883
+ }
12884
+ function text$7(value) {
12885
+ if (typeof value !== "string") return void 0;
12886
+ const trimmed = value.trim();
12887
+ return trimmed === "" ? void 0 : trimmed;
12888
+ }
12889
+ function expiry(accessToken, record) {
12890
+ const exp = parseJwtClaims(accessToken)?.exp;
12891
+ const milliseconds = typeof exp === "number" ? Math.round(exp * 1e3) : NaN;
12892
+ if (Number.isSafeInteger(milliseconds) && milliseconds >= 0) return milliseconds;
12893
+ for (const candidate of [
12894
+ record.expires_at,
12895
+ record.expiresAt,
12896
+ record.expired
12897
+ ]) {
12898
+ if (typeof candidate !== "string") continue;
12899
+ const parsed = Date.parse(candidate);
12900
+ if (Number.isFinite(parsed) && parsed >= 0) return parsed;
12901
+ }
12902
+ }
12903
+ function parseCredential(record) {
12904
+ if (record.disabled === true) return void 0;
12905
+ const accessToken = text$7(record.access_token);
12906
+ const refreshToken = text$7(record.refresh_token);
12907
+ if (accessToken === void 0 || refreshToken === void 0) return void 0;
12908
+ const expiresAt = expiry(accessToken, record);
12909
+ if (expiresAt === void 0) return void 0;
12910
+ const idToken = text$7(record.id_token);
12911
+ const identity = extractIdentity({
12912
+ accessToken,
12913
+ ...idToken === void 0 ? {} : { idToken }
12914
+ });
12915
+ const live = isRecord$89(record.live_identity) ? record.live_identity : {};
12916
+ const credentials = {
12917
+ accessToken,
12918
+ refreshToken,
12919
+ expiresAt,
12920
+ accountId: text$7(record.account_id) ?? text$7(record.chatgpt_account_id) ?? text$7(live.account_id) ?? identity.accountId,
12921
+ userId: text$7(record.chatgpt_user_id) ?? text$7(live.user_id) ?? identity.userId,
12922
+ email: text$7(record.email) ?? text$7(live.email) ?? identity.email,
12923
+ planType: text$7(record.plan_type) ?? text$7(record.chatgpt_plan_type) ?? text$7(live.plan) ?? text$7(live.official_plan) ?? identity.planType
12924
+ };
12925
+ if (idToken !== void 0) credentials.idToken = idToken;
12926
+ return credentials;
12927
+ }
12928
+ function parseSub2Api(value) {
12929
+ if (!isRecord$89(value) || !Array.isArray(value.accounts)) throw new CodexCredentialImportError("The file is not a sub2api account export.");
12930
+ if (!(value.type === void 0 && text$7(value.exported_at) !== void 0 && Array.isArray(value.proxies)) && value.type !== "sub2api-data" && value.type !== "sub2api-bundle") throw new CodexCredentialImportError("The file is not a sub2api account export.");
12931
+ if (value.accounts.length > MAX_JSON_ACCOUNTS) throw new CodexCredentialImportError(`The export exceeds the ${MAX_JSON_ACCOUNTS}-account import limit.`);
12932
+ const credentials = [];
12933
+ let skipped = 0;
12934
+ for (const account of value.accounts) {
12935
+ const parsed = isRecord$89(account) && account.platform === "openai" && account.type === "oauth" && account.disabled !== true && isRecord$89(account.credentials) && (account.credentials.type === void 0 || account.credentials.type === "codex") ? parseCredential(account.credentials) : void 0;
12936
+ if (parsed === void 0) skipped += 1;
12937
+ else credentials.push(parsed);
12938
+ }
12939
+ return {
12940
+ format: "sub2api",
12941
+ credentials,
12942
+ skipped
12943
+ };
12944
+ }
12945
+ function assertRange(buffer, offset, length) {
12946
+ if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0 || offset + length > buffer.length) throw new CodexCredentialImportError("The CPA ZIP directory is malformed.");
12947
+ }
12948
+ function zipEntries(buffer) {
12949
+ if (buffer.length < 22) throw new CodexCredentialImportError("The CPA ZIP file is malformed.");
12950
+ let end = -1;
12951
+ for (let offset = buffer.length - 22; offset >= Math.max(0, buffer.length - 65557); offset -= 1) if (buffer.readUInt32LE(offset) === 101010256 && offset + 22 + buffer.readUInt16LE(offset + 20) === buffer.length) {
12952
+ end = offset;
12953
+ break;
12954
+ }
12955
+ if (end < 0) throw new CodexCredentialImportError("The CPA ZIP directory is missing.");
12956
+ const count = buffer.readUInt16LE(end + 10);
12957
+ const directorySize = buffer.readUInt32LE(end + 12);
12958
+ const directoryOffset = buffer.readUInt32LE(end + 16);
12959
+ if (buffer.readUInt16LE(end + 4) !== 0 || buffer.readUInt16LE(end + 6) !== 0 || buffer.readUInt16LE(end + 8) !== count || count > MAX_ZIP_ENTRIES || directoryOffset + directorySize !== end) throw new CodexCredentialImportError("The CPA ZIP file is too large or uses an unsupported directory.");
12960
+ const directory = buffer.subarray(directoryOffset, end);
12961
+ const fileData = buffer.subarray(0, directoryOffset);
12962
+ const entries = [];
12963
+ let cursor = 0;
12964
+ let totalBytes = 0;
12965
+ for (let index = 0; index < count; index += 1) {
12966
+ assertRange(directory, cursor, 46);
12967
+ if (directory.readUInt32LE(cursor) !== 33639248) throw new CodexCredentialImportError("The CPA ZIP directory is malformed.");
12968
+ const flags = directory.readUInt16LE(cursor + 8);
12969
+ const method = directory.readUInt16LE(cursor + 10);
12970
+ const expectedCrc = directory.readUInt32LE(cursor + 16);
12971
+ const compressedSize = directory.readUInt32LE(cursor + 20);
12972
+ const uncompressedSize = directory.readUInt32LE(cursor + 24);
12973
+ const nameLength = directory.readUInt16LE(cursor + 28);
12974
+ const extraLength = directory.readUInt16LE(cursor + 30);
12975
+ const commentLength = directory.readUInt16LE(cursor + 32);
12976
+ const localOffset = directory.readUInt32LE(cursor + 42);
12977
+ assertRange(directory, cursor + 46, nameLength + extraLength + commentLength);
12978
+ const name = directory.toString("utf8", cursor + 46, cursor + 46 + nameLength);
12979
+ cursor += 46 + nameLength + extraLength + commentLength;
12980
+ if (!name.toLowerCase().endsWith(".json")) continue;
12981
+ if ((flags & 1) !== 0 || method !== 0 && method !== 8 || compressedSize === 4294967295 || uncompressedSize > MAX_ZIP_ENTRY_BYTES || totalBytes + uncompressedSize > MAX_ZIP_TOTAL_BYTES) throw new CodexCredentialImportError("The CPA ZIP contains an encrypted, oversized, or unsupported JSON entry.");
12982
+ assertRange(fileData, localOffset, 30);
12983
+ if (fileData.readUInt32LE(localOffset) !== 67324752) throw new CodexCredentialImportError("The CPA ZIP entry is malformed.");
12984
+ const dataOffset = localOffset + 30 + fileData.readUInt16LE(localOffset + 26) + fileData.readUInt16LE(localOffset + 28);
12985
+ assertRange(fileData, dataOffset, compressedSize);
12986
+ const compressed = fileData.subarray(dataOffset, dataOffset + compressedSize);
12987
+ let data;
12988
+ try {
12989
+ data = method === 0 ? compressed : inflateRawSync(compressed, { maxOutputLength: Math.max(1, uncompressedSize) });
12990
+ } catch {
12991
+ throw new CodexCredentialImportError("A CPA ZIP JSON entry cannot be decompressed.");
12992
+ }
12993
+ if (data.length !== uncompressedSize || crc32(data) !== expectedCrc) throw new CodexCredentialImportError("A CPA ZIP JSON entry failed its integrity check.");
12994
+ totalBytes += data.length;
12995
+ entries.push(data);
12996
+ }
12997
+ if (cursor !== directory.length) throw new CodexCredentialImportError("The CPA ZIP directory is malformed.");
12998
+ return entries;
12999
+ }
13000
+ function parseCpa(buffer) {
13001
+ const entries = zipEntries(buffer);
13002
+ const credentials = [];
13003
+ let skipped = 0;
13004
+ for (const entry of entries) try {
13005
+ const value = JSON.parse(entry.toString("utf8"));
13006
+ const parsed = isRecord$89(value) && value.type === "codex" ? parseCredential(value) : void 0;
13007
+ if (parsed === void 0) skipped += 1;
13008
+ else credentials.push(parsed);
13009
+ } catch {
13010
+ skipped += 1;
13011
+ }
13012
+ return {
13013
+ format: "cpa",
13014
+ credentials,
13015
+ skipped
13016
+ };
13017
+ }
13018
+ function parseCodexCredentialFile(buffer) {
13019
+ if (buffer.length === 0 || buffer.length > 16777216) throw new CodexCredentialImportError("The import file is empty or exceeds the 16 MB limit.");
13020
+ if (buffer.length >= 4 && buffer.readUInt32LE(0) === 67324752) return parseCpa(buffer);
13021
+ try {
13022
+ return parseSub2Api(JSON.parse(buffer.toString("utf8")));
13023
+ } catch (error) {
13024
+ if (error instanceof CodexCredentialImportError) throw error;
13025
+ throw new CodexCredentialImportError("The file is neither a sub2api JSON export nor a CPA ZIP archive.");
13026
+ }
13027
+ }
13028
+ //#endregion
12861
13029
  //#region src/host/providers/codex-chatgpt/routes.ts
12862
13030
  const MAX_BODY_BYTES$15 = 64 * 1024;
12863
13031
  function registerRoutes(ctx, oauth, usage, preferences, proxyManager, searchSwitcher, routeAudit, accountPool, fetchConfiguration, adopt) {
@@ -12956,6 +13124,73 @@ function registerRoutes(ctx, oauth, usage, preferences, proxyManager, searchSwit
12956
13124
  });
12957
13125
  return;
12958
13126
  }
13127
+ const refreshedStatus = async () => {
13128
+ const afterAction = await oauth.status();
13129
+ return {
13130
+ ...afterAction,
13131
+ quota: await usage.status(afterAction.authenticated),
13132
+ preferences: preferences.status()
13133
+ };
13134
+ };
13135
+ if (url.pathname === `/api/dsh-chatgpt-subscription/accounts/import`) {
13136
+ if (request.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase() !== "application/octet-stream") {
13137
+ jsonError(response, 415, {
13138
+ code: "bad-request",
13139
+ message: "The credential file must be sent as an octet stream."
13140
+ });
13141
+ return;
13142
+ }
13143
+ if (accountPool === void 0) {
13144
+ jsonError(response, 400, {
13145
+ code: "bad-request",
13146
+ message: "The ChatGPT account pool is not installed."
13147
+ });
13148
+ return;
13149
+ }
13150
+ try {
13151
+ const data = await readBinary(request, MAX_CREDENTIAL_IMPORT_BYTES);
13152
+ if (data === null) {
13153
+ response.setHeader("connection", "close");
13154
+ jsonError(response, 413, {
13155
+ code: "bad-request",
13156
+ message: "The import file exceeds the 16 MB limit."
13157
+ });
13158
+ return;
13159
+ }
13160
+ const parsed = parseCodexCredentialFile(data);
13161
+ if (parsed.credentials.length === 0) {
13162
+ jsonError(response, 400, {
13163
+ code: "bad-request",
13164
+ message: "The file contains no usable ChatGPT OAuth accounts."
13165
+ });
13166
+ return;
13167
+ }
13168
+ await accountPool.importAccounts(parsed.credentials);
13169
+ json$1(response, {
13170
+ ok: true,
13171
+ value: {
13172
+ status: await refreshedStatus(),
13173
+ format: parsed.format,
13174
+ imported: parsed.credentials.length,
13175
+ skipped: parsed.skipped
13176
+ }
13177
+ });
13178
+ } catch (error) {
13179
+ if (error instanceof CodexCredentialImportError) jsonError(response, 400, {
13180
+ code: "bad-request",
13181
+ message: error.message
13182
+ });
13183
+ else if (error instanceof AccountPoolCapacityError) jsonError(response, 409, {
13184
+ code: "bad-request",
13185
+ message: error.message
13186
+ });
13187
+ else {
13188
+ const mapped = publicError(error, "internal");
13189
+ jsonError(response, statusFor(mapped), mapped);
13190
+ }
13191
+ }
13192
+ return;
13193
+ }
12959
13194
  const contentType = request.headers["content-type"];
12960
13195
  if (typeof contentType !== "string" || !contentType.toLowerCase().startsWith("application/json")) {
12961
13196
  jsonError(response, 415, {
@@ -12972,14 +13207,6 @@ function registerRoutes(ctx, oauth, usage, preferences, proxyManager, searchSwit
12972
13207
  });
12973
13208
  return;
12974
13209
  }
12975
- const refreshedStatus = async () => {
12976
- const afterAction = await oauth.status();
12977
- return {
12978
- ...afterAction,
12979
- quota: await usage.status(afterAction.authenticated),
12980
- preferences: preferences.status()
12981
- };
12982
- };
12983
13210
  try {
12984
13211
  switch (url.pathname) {
12985
13212
  case `${ROUTE_PREFIX$5}/i18n/locale`: {
@@ -13233,17 +13460,22 @@ function registerRoutes(ctx, oauth, usage, preferences, proxyManager, searchSwit
13233
13460
  for (const dispose of disposers) dispose();
13234
13461
  };
13235
13462
  }
13236
- async function readJson$6(request) {
13463
+ async function readBinary(request, limit) {
13237
13464
  const chunks = [];
13238
13465
  let total = 0;
13239
- for await (const chunk of request) {
13466
+ for await (const chunk of request.iterator({ destroyOnReturn: false })) {
13240
13467
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
13241
13468
  total += buffer.length;
13242
- if (total > MAX_BODY_BYTES$15) return null;
13469
+ if (total > limit) return null;
13243
13470
  chunks.push(buffer);
13244
13471
  }
13472
+ return Buffer.concat(chunks, total);
13473
+ }
13474
+ async function readJson$6(request) {
13475
+ const data = await readBinary(request, MAX_BODY_BYTES$15);
13476
+ if (data === null) return null;
13245
13477
  try {
13246
- const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
13478
+ const value = JSON.parse(data.toString("utf8"));
13247
13479
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
13248
13480
  } catch {
13249
13481
  return null;
@@ -26160,8 +26392,10 @@ const ACP_ERROR_CODES = {
26160
26392
  ACP_AUTH_REQUIRED: "The Antigravity CLI is not signed in. Run `agy acp --login` or use the sign-in button in this card.",
26161
26393
  /** The executable is missing or cannot be started. */
26162
26394
  ACP_BINARY_UNAVAILABLE: "No usable Antigravity CLI (agy) was found. Install it, or let this line download the official ACP server.",
26163
- /** The agent process exited mid-turn. */
26164
- ACP_DISCONNECTED: "The Antigravity agent process ended mid-turn. Retry to reconnect.",
26395
+ /** The agent process exited before a prompt was sent. */
26396
+ ACP_DISCONNECTED: "The Antigravity agent process ended before the prompt was sent. Retry to reconnect.",
26397
+ /** A dispatched prompt may already have run tools; never replay it automatically. */
26398
+ ACP_PROMPT_INTERRUPTED: "The Antigravity connection ended after the prompt was sent. The turn was not retried automatically because that could repeat completed actions. Review the workspace and retry manually.",
26165
26399
  /** A JSON-RPC error the line has no specific handling for. */
26166
26400
  ACP_RPC_ERROR: "The Antigravity ACP server returned a JSON-RPC error.",
26167
26401
  /**
@@ -27155,7 +27389,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
27155
27389
  const type = typeof update.sessionUpdate === "string" ? update.sessionUpdate : "";
27156
27390
  if (type === "process_exit") {
27157
27391
  const detail = asRecord$19(update.detail);
27158
- throw acpError("ACP_DISCONNECTED", `(code ${String(detail?.code ?? "null")}, signal ${String(detail?.signal ?? "none")}).`);
27392
+ throw acpError("ACP_PROMPT_INTERRUPTED", `(code ${String(detail?.code ?? "null")}, signal ${String(detail?.signal ?? "none")}).`);
27159
27393
  }
27160
27394
  if (type === "usage_update") {
27161
27395
  const occupancy = readOccupancy(update);
@@ -27295,7 +27529,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
27295
27529
  }
27296
27530
  yield* closeBlocks();
27297
27531
  const reason = settleReason(settled.stopReason);
27298
- if (reason.kind === "error") throw new LlmError(reason.failure.message, "SERVER");
27532
+ if (reason.kind === "error") throw new LlmError(reason.failure.message, reason.failure.code);
27299
27533
  yield {
27300
27534
  type: "finish",
27301
27535
  reason: reason.kind === "aborted" ? {
@@ -27463,7 +27697,8 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
27463
27697
  durationMs: this.now() - startedAt
27464
27698
  };
27465
27699
  } catch (error) {
27466
- turn.settled = { error: asError(error) };
27700
+ const failure = asLlmError(error);
27701
+ turn.settled = { error: failure.code === "ACP_DISCONNECTED" ? acpError("ACP_PROMPT_INTERRUPTED", failure.message) : failure };
27467
27702
  } finally {
27468
27703
  turn.queue.push({ sessionUpdate: "prompt_settled" });
27469
27704
  }
@@ -28014,6 +28249,7 @@ function asLlmError(error) {
28014
28249
  if (error instanceof Error && error.name === "AbortError") return new LlmError("The Antigravity ACP turn was cancelled.", "ABORTED");
28015
28250
  if (error instanceof AcpError) {
28016
28251
  if (error.code === -32e3 || /authentication required/i.test(error.message)) return acpError("ACP_AUTH_REQUIRED");
28252
+ if (error.code === void 0) return acpError("ACP_DISCONNECTED", error.message);
28017
28253
  if (error.code === -32602) return acpError("ACP_INVALID_PARAMS");
28018
28254
  if (error.code === -32601) return acpError("ACP_METHOD_UNSUPPORTED");
28019
28255
  if (UPSTREAM_DECLINED.test(error.message)) return acpError("ACP_UPSTREAM_BLOCKED", error.message);
@@ -28023,9 +28259,6 @@ function asLlmError(error) {
28023
28259
  if (/ENOENT|not found|cannot find/i.test(message)) return acpError("ACP_BINARY_UNAVAILABLE", message);
28024
28260
  return acpError("ACP_DISCONNECTED", message);
28025
28261
  }
28026
- function asError(error) {
28027
- return error instanceof Error ? error : new Error(String(error));
28028
- }
28029
28262
  function abortError$1() {
28030
28263
  const error = /* @__PURE__ */ new Error("Antigravity ACP turn was cancelled");
28031
28264
  error.name = "AbortError";
@@ -28437,9 +28670,10 @@ const ACP_BINARY_RELEASES = {
28437
28670
  * The registry's standalone server already speaks ACP on stdio and rejects the
28438
28671
  * full CLI's acp and disable-telemetry flags. Detect configured paths too.
28439
28672
  */
28440
- function acpLaunchArgs(binary) {
28673
+ function acpLaunchArgs(binary, platform = process.platform) {
28441
28674
  const executable = path.basename(binary.path).toLowerCase();
28442
- return binary.kind === "downloaded" || executable === "agy_acp_server.exe" || executable === "agy_acp_server.par" ? [] : ["acp", "--disable-telemetry"];
28675
+ if (!(binary.kind === "downloaded" || executable === "agy_acp_server.exe" || executable === "agy_acp_server.par")) return ["acp", "--disable-telemetry"];
28676
+ return platform === "linux" ? ["--uid="] : [];
28443
28677
  }
28444
28678
  /** How long a resolved executable is reused before the disk is read again. */
28445
28679
  const BINARY_CACHE_TTL_MS = 5 * 6e4;
@@ -91573,6 +91807,17 @@ function withCompletionTokens(body) {
91573
91807
  };
91574
91808
  }
91575
91809
  /**
91810
+ * OpenDesign requires an object root even when every `oneOf` branch already
91811
+ * says so. Add it only on the wire copy; mixed-type unions keep their semantics.
91812
+ */
91813
+ function openDesignToolParameters(parameters) {
91814
+ if (parameters.type !== void 0 || !Array.isArray(parameters.oneOf) || parameters.oneOf.length === 0) return parameters;
91815
+ return parameters.oneOf.every((branch) => isRecord$34(branch) && branch.type === "object") ? {
91816
+ ...parameters,
91817
+ type: "object"
91818
+ } : parameters;
91819
+ }
91820
+ /**
91576
91821
  * Build the wire request for one harness call.
91577
91822
  * @param options - the harness request (model, system, history, tools, sampling).
91578
91823
  * @param connection - resolved connection facts (default output budget).
@@ -91590,7 +91835,7 @@ function buildOpenDesignBody(options, connection, images) {
91590
91835
  function: {
91591
91836
  name: tool.name,
91592
91837
  description: tool.description,
91593
- parameters: tool.parameters
91838
+ parameters: openDesignToolParameters(tool.parameters)
91594
91839
  }
91595
91840
  }));
91596
91841
  const maxTokens = options.maxTokens ?? connection.maxTokens;