@eddyskywalker/dsh-chatgpt-subscription 0.75.1 → 0.76.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 (56) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +1 -1
  3. package/lib/client.js +1014 -812
  4. package/lib/client.js.map +1 -1
  5. package/lib/index.js +953 -386
  6. package/lib/types/client/CodexSubscriptionSection.d.ts.map +1 -1
  7. package/lib/types/client/antigravity-acp/AntigravityAcpSection.d.ts.map +1 -1
  8. package/lib/types/client/antigravity-acp/locales.d.ts +12 -12
  9. package/lib/types/client/claude/ClaudeSection.d.ts.map +1 -1
  10. package/lib/types/client/cline-pass/ClinePassSection.d.ts.map +1 -1
  11. package/lib/types/client/command-code/CommandCodeSection.d.ts.map +1 -1
  12. package/lib/types/client/common/LineProxySection.d.ts +78 -0
  13. package/lib/types/client/common/LineProxySection.d.ts.map +1 -0
  14. package/lib/types/client/glm-coding-plan/GlmCodingPlanSection.d.ts.map +1 -1
  15. package/lib/types/client/kimi-code/KimiCodeSection.d.ts.map +1 -1
  16. package/lib/types/client/locales-ru/hub.d.ts.map +1 -1
  17. package/lib/types/client/locales.d.ts +15 -3
  18. package/lib/types/client/locales.d.ts.map +1 -1
  19. package/lib/types/client/minimax-code/MinimaxCodeSection.d.ts.map +1 -1
  20. package/lib/types/client/ollama/OllamaSection.d.ts.map +1 -1
  21. package/lib/types/client/opendesign/OpenDesignSection.d.ts.map +1 -1
  22. package/lib/types/client/qoder/QoderSection.d.ts.map +1 -1
  23. package/lib/types/client/step-code/StepCodeSection.d.ts.map +1 -1
  24. package/lib/types/client/workbuddy/WorkBuddySection.d.ts.map +1 -1
  25. package/lib/types/compat.d.ts +1 -1
  26. package/lib/types/host/antigravity-acp/adapter.d.ts +17 -0
  27. package/lib/types/host/antigravity-acp/adapter.d.ts.map +1 -1
  28. package/lib/types/host/antigravity-acp/auth-cache.d.ts +11 -2
  29. package/lib/types/host/antigravity-acp/auth-cache.d.ts.map +1 -1
  30. package/lib/types/host/antigravity-acp/binary.d.ts +68 -0
  31. package/lib/types/host/antigravity-acp/binary.d.ts.map +1 -1
  32. package/lib/types/host/antigravity-acp/catalog.d.ts.map +1 -1
  33. package/lib/types/host/antigravity-acp/errors.d.ts +10 -0
  34. package/lib/types/host/antigravity-acp/errors.d.ts.map +1 -1
  35. package/lib/types/host/antigravity-acp/login.d.ts +22 -6
  36. package/lib/types/host/antigravity-acp/login.d.ts.map +1 -1
  37. package/lib/types/host/antigravity-acp/mcp-bridge.d.ts +9 -2
  38. package/lib/types/host/antigravity-acp/mcp-bridge.d.ts.map +1 -1
  39. package/lib/types/host/antigravity-acp/routes.d.ts +23 -4
  40. package/lib/types/host/antigravity-acp/routes.d.ts.map +1 -1
  41. package/lib/types/host/antigravity-acp/subagent.d.ts +32 -0
  42. package/lib/types/host/antigravity-acp/subagent.d.ts.map +1 -1
  43. package/lib/types/host/antigravity-acp/types.d.ts +15 -0
  44. package/lib/types/host/antigravity-acp/types.d.ts.map +1 -1
  45. package/lib/types/host/preferences.d.ts.map +1 -1
  46. package/lib/types/host/proxy-manager.d.ts +37 -3
  47. package/lib/types/host/proxy-manager.d.ts.map +1 -1
  48. package/lib/types/host/routes.d.ts.map +1 -1
  49. package/lib/types/host/workbuddy/model-catalog.d.ts +20 -10
  50. package/lib/types/host/workbuddy/model-catalog.d.ts.map +1 -1
  51. package/lib/types/index.d.ts.map +1 -1
  52. package/lib/types/shared/contracts.d.ts +53 -0
  53. package/lib/types/shared/contracts.d.ts.map +1 -1
  54. package/lib/types/shared/preferences.d.ts +51 -1
  55. package/lib/types/shared/preferences.d.ts.map +1 -1
  56. package/package.json +1 -1
package/lib/index.js CHANGED
@@ -817,7 +817,7 @@ const ROUTE_PREFIX$5 = "/api/dsh-chatgpt-subscription";
817
817
  * `test/responses-client.test.ts` asserts the two agree, so a release that
818
818
  * forgets this constant fails the suite instead of shipping quietly.
819
819
  */
820
- const PLUGIN_VERSION = "0.75.1";
820
+ const PLUGIN_VERSION = "0.76.0";
821
821
  const CODEX_CHATGPT_PROVIDER_ID = "codex-chatgpt";
822
822
  const CODEX_API_BASE = "https://chatgpt.com/backend-api/codex";
823
823
  const CODEX_RESPONSES_URL = `${CODEX_API_BASE}/responses`;
@@ -6692,6 +6692,337 @@ function isSource(value) {
6692
6692
  return value !== null;
6693
6693
  }
6694
6694
  //#endregion
6695
+ //#region src/shared/contracts.ts
6696
+ /**
6697
+ * Every provider line a proxy choice can be stored for.
6698
+ *
6699
+ * The ids are the LLM route ids this plugin registers, not the shorthand some
6700
+ * host tables use: model request control spells the Claude line `claude` while
6701
+ * its route id is `claude-subscription`, and it never lists `opendesign` or
6702
+ * `workbuddy-subscription` under those names. Keeping one list here means the
6703
+ * card, the store and the fetch wiring cannot drift apart.
6704
+ */
6705
+ const LINE_PROXY_PROVIDER_IDS = [
6706
+ "codex-chatgpt",
6707
+ "claude-subscription",
6708
+ "kimi-code",
6709
+ "minimax-code",
6710
+ "command-code",
6711
+ "ollama",
6712
+ "glm-coding-plan",
6713
+ "step-code",
6714
+ "cline-pass",
6715
+ "qoder",
6716
+ "opendesign",
6717
+ "workbuddy-subscription",
6718
+ "antigravity-acp"
6719
+ ];
6720
+ //#endregion
6721
+ //#region src/shared/compaction-route.ts
6722
+ /** Runtime membership test for one stored target. */
6723
+ function isCompactionRouteTarget(value) {
6724
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
6725
+ const record = value;
6726
+ return isNonEmptyString(record.provider) && isNonEmptyString(record.model);
6727
+ }
6728
+ function isNonEmptyString(value) {
6729
+ return typeof value === "string" && value.trim().length > 0;
6730
+ }
6731
+ /**
6732
+ * Decide whether the payload is admissible on the target.
6733
+ *
6734
+ * An undisclosed modality list is unknown, not negative: the harness documents
6735
+ * absence as "not disclosed", so refusing on it would disable the feature on
6736
+ * every route that simply does not advertise. The request still runs, and a
6737
+ * real rejection falls back the same way an error does.
6738
+ *
6739
+ * @param facts - what the directory says about the target.
6740
+ * @param needs - what the payload contains.
6741
+ * @returns the refusal reason, or `undefined` when the target may take it.
6742
+ */
6743
+ function compactionSkipReason(facts, needs) {
6744
+ const modalities = facts.modalities;
6745
+ if (modalities === void 0) return void 0;
6746
+ const accepts = new Set(modalities);
6747
+ if (needs.video && !accepts.has("video")) return "target-accepts-no-video";
6748
+ }
6749
+ /**
6750
+ * Whether the target can carry images inline.
6751
+ *
6752
+ * Used for the recorded outcome only: an image the target cannot take is
6753
+ * replaced by a placeholder during projection, so the summary is still produced
6754
+ * but may describe a screenshot it never saw.
6755
+ *
6756
+ * @param facts - what the directory says about the target.
6757
+ * @returns false only when the target discloses image support and omits it.
6758
+ */
6759
+ function compactionRoutesImages(facts) {
6760
+ const modalities = facts.modalities;
6761
+ if (modalities === void 0) return true;
6762
+ return modalities.includes("image");
6763
+ }
6764
+ //#endregion
6765
+ //#region src/shared/preferences.ts
6766
+ const PREFERENCES_NAMESPACE = "dsh-chatgpt-subscription";
6767
+ const DEFAULT_PREFERENCES = {
6768
+ enabled: true,
6769
+ quickQuotaVisible: false,
6770
+ fastMode: false,
6771
+ outputVerbosity: null,
6772
+ reasoningSummary: null,
6773
+ visibleModelIds: [...DEFAULT_VISIBLE_CODEX_MODEL_IDS],
6774
+ searchProvider: "dsh",
6775
+ contextWindowOverrides: {},
6776
+ proxyMode: "auto",
6777
+ customProxyUrl: null,
6778
+ noProxy: null,
6779
+ lineProxies: {},
6780
+ compactionRoute: null,
6781
+ subagentDefaultModels: [],
6782
+ subagentModelsByMainModel: {},
6783
+ subagentDefaultAllowParentFork: false,
6784
+ subagentAllowParentForkByMainModel: {}
6785
+ };
6786
+ const SEARCH_PROVIDER_CODEX = "codex";
6787
+ function isSearchProviderPreference(value) {
6788
+ return value === "dsh" || value === "codex";
6789
+ }
6790
+ function isCodexOutputVerbosity(value) {
6791
+ return value === "low" || value === "medium" || value === "high";
6792
+ }
6793
+ function isCodexReasoningSummary(value) {
6794
+ return value === "auto" || value === "concise" || value === "detailed" || value === "none";
6795
+ }
6796
+ function isProxyMode(value) {
6797
+ return value === "auto" || value === "custom" || value === "direct";
6798
+ }
6799
+ /** The shipped per-line proxy: system proxy, exactly like the old shared setting. */
6800
+ const DEFAULT_LINE_PROXY = {
6801
+ mode: "auto",
6802
+ customProxyUrl: null
6803
+ };
6804
+ /**
6805
+ * One custom proxy URL in the shape the transport accepts.
6806
+ *
6807
+ * Mirrors the shared preference store's own normalization: a bare `host:port`
6808
+ * gains `http://`, and a blank URL is `null` (which makes a `custom` line fall
6809
+ * back to a direct connection, the same reading the global setting had).
6810
+ * @param value - Raw URL from a card or a stored document.
6811
+ * @returns the normalized URL, or null when there is none.
6812
+ */
6813
+ function normalizeLineProxyUrl(value) {
6814
+ if (typeof value !== "string") return null;
6815
+ const trimmed = value.trim();
6816
+ if (trimmed.length === 0) return null;
6817
+ if (/^https?:\/\//i.test(trimmed) || /^socks5?:\/\//i.test(trimmed)) return trimmed;
6818
+ return `http://${trimmed}`;
6819
+ }
6820
+ /**
6821
+ * Normalize one line's proxy entry.
6822
+ * @param value - Candidate entry from a card or a stored document.
6823
+ * @returns the normalized entry, or null when the value is not a usable one.
6824
+ */
6825
+ function normalizeLineProxyConfig(value) {
6826
+ const record = asRecord$24(value);
6827
+ if (record === void 0) return null;
6828
+ const mode = record["mode"];
6829
+ if (!isProxyMode(mode)) return null;
6830
+ const customProxyUrl = normalizeLineProxyUrl(record["customProxyUrl"]);
6831
+ return {
6832
+ mode,
6833
+ customProxyUrl: mode === "custom" ? customProxyUrl : null
6834
+ };
6835
+ }
6836
+ /**
6837
+ * Merge a per-line proxy patch into the stored map.
6838
+ *
6839
+ * A merge, not a replace: saving one card must not rewrite the other twelve,
6840
+ * and `null` is how one line returns to the shipped `auto` default. Unknown
6841
+ * provider ids are refused rather than stored, because a typo would otherwise
6842
+ * look like a saved setting that never takes effect.
6843
+ * @param current - Map already stored in the preferences document.
6844
+ * @param patch - Incoming patch from a settings card or a route body.
6845
+ * @returns the merged map, or null when any key or value is malformed.
6846
+ */
6847
+ function mergeLineProxies(current, patch) {
6848
+ const record = asRecord$24(patch);
6849
+ if (record === void 0) return null;
6850
+ const merged = { ...current };
6851
+ for (const [rawKey, rawValue] of Object.entries(record)) {
6852
+ const key = rawKey.trim();
6853
+ if (!isLineProxyProviderId(key)) return null;
6854
+ if (rawValue === null) {
6855
+ delete merged[key];
6856
+ continue;
6857
+ }
6858
+ const normalized = normalizeLineProxyConfig(rawValue);
6859
+ if (normalized === null) return null;
6860
+ merged[key] = normalized;
6861
+ }
6862
+ return merged;
6863
+ }
6864
+ /**
6865
+ * Whether one id names a provider line a proxy can be stored for.
6866
+ * @param value - Candidate provider id.
6867
+ * @returns whether the id is in {@link LINE_PROXY_PROVIDER_IDS}.
6868
+ */
6869
+ function isLineProxyProviderId(value) {
6870
+ return typeof value === "string" && LINE_PROXY_PROVIDER_IDS.includes(value);
6871
+ }
6872
+ /**
6873
+ * Canonical form of one `NO_PROXY`-style bypass list.
6874
+ *
6875
+ * Entries may be separated by commas or whitespace, because a list pasted from
6876
+ * a README or a shell export is usually one or the other. Each entry is trimmed
6877
+ * and the list is deduplicated case-insensitively on first spelling and order:
6878
+ * the card shows the user's own arrangement back to them, while a host named
6879
+ * twice can never produce two matcher entries.
6880
+ * @param value - Raw list from the card, the environment, or a document.
6881
+ * @returns the canonical comma-separated list; an empty string when none.
6882
+ */
6883
+ function normalizeNoProxyList(value) {
6884
+ const entries = [];
6885
+ const seen = /* @__PURE__ */ new Set();
6886
+ for (const raw of value.split(/[,\s]+/)) {
6887
+ const entry = raw.trim();
6888
+ if (entry.length === 0) continue;
6889
+ const key = entry.toLowerCase();
6890
+ if (seen.has(key)) continue;
6891
+ seen.add(key);
6892
+ entries.push(entry);
6893
+ }
6894
+ return entries.join(", ");
6895
+ }
6896
+ function asRecord$24(value) {
6897
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
6898
+ }
6899
+ /**
6900
+ * Read one non-empty trimmed string field.
6901
+ * @param value - Candidate field value from stored JSON.
6902
+ * @returns the trimmed string, or undefined when it is not a non-empty string.
6903
+ */
6904
+ function trimmedString(value) {
6905
+ if (typeof value !== "string") return void 0;
6906
+ const trimmed = value.trim();
6907
+ return trimmed.length === 0 ? void 0 : trimmed;
6908
+ }
6909
+ /**
6910
+ * Whether one value is a complete `{ provider, model }` route.
6911
+ *
6912
+ * Both halves are trimmed and must be non-empty: a route with a blank provider
6913
+ * names no adapter, and a blank model names no model, so neither can ever be
6914
+ * authorized. Stored documents are untrusted JSON, which is why this narrows
6915
+ * rather than asserts.
6916
+ * @param value - Candidate route.
6917
+ * @returns whether the value is a usable route.
6918
+ */
6919
+ function isSubagentModelRoute(value) {
6920
+ const record = asRecord$24(value);
6921
+ if (record === void 0) return false;
6922
+ return trimmedString(record["provider"]) !== void 0 && trimmedString(record["model"]) !== void 0;
6923
+ }
6924
+ /**
6925
+ * Normalize one route list, deduplicating it without reordering.
6926
+ *
6927
+ * Order is preserved because it is the order the settings card shows and the
6928
+ * order `list_subagent_models` prints: a set would silently reshuffle the list
6929
+ * a user arranged.
6930
+ * @param value - Candidate route list from stored JSON.
6931
+ * @returns the trimmed, deduplicated routes, or null when the value is not an
6932
+ * array of well-formed routes.
6933
+ */
6934
+ function normalizeSubagentModelRoutes(value) {
6935
+ if (!Array.isArray(value)) return null;
6936
+ const routes = [];
6937
+ const seen = /* @__PURE__ */ new Set();
6938
+ for (const entry of value) {
6939
+ if (!isSubagentModelRoute(entry)) return null;
6940
+ const provider = entry.provider.trim();
6941
+ const model = entry.model.trim();
6942
+ const key = `${provider}/${model}`;
6943
+ if (seen.has(key)) continue;
6944
+ seen.add(key);
6945
+ routes.push({
6946
+ provider,
6947
+ model
6948
+ });
6949
+ }
6950
+ return routes;
6951
+ }
6952
+ /**
6953
+ * Whether one key names a main agent route as `provider/model`.
6954
+ *
6955
+ * The split is at the FIRST slash, so a model id that legally contains a slash
6956
+ * (`command-code` + `deepseek/deepseek-v4.1-flash`) still round-trips: the
6957
+ * provider half ends at the first separator and the model half keeps the rest.
6958
+ * @param key - Candidate map key.
6959
+ * @returns whether the key carries a non-empty provider and a non-empty model.
6960
+ */
6961
+ function isValidMainModelKey(key) {
6962
+ if (typeof key !== "string") return false;
6963
+ const trimmed = key.trim();
6964
+ const separator = trimmed.indexOf("/");
6965
+ if (separator <= 0) return false;
6966
+ return trimmed.slice(separator + 1).length > 0;
6967
+ }
6968
+ /**
6969
+ * Merge one `subagentModelsByMainModel` patch into the stored map.
6970
+ *
6971
+ * A merge rather than a replace, so the card can clear or set one main model
6972
+ * without resending every other entry — and `null` (or `[]`) is how one entry
6973
+ * is cleared, since a stored map has no other way to say "no override".
6974
+ * @param current - Map already stored in the preferences document.
6975
+ * @param patch - Incoming patch from a settings card or a route body.
6976
+ * @returns the merged map, or null when any key or value is malformed.
6977
+ */
6978
+ function mergeSubagentModelsByMainModel(current, patch) {
6979
+ const patchRecord = asRecord$24(patch);
6980
+ if (patchRecord === void 0) return null;
6981
+ const merged = { ...current };
6982
+ for (const [rawKey, rawRoutes] of Object.entries(patchRecord)) {
6983
+ const key = rawKey.trim();
6984
+ if (!isValidMainModelKey(key)) return null;
6985
+ if (rawRoutes === null || Array.isArray(rawRoutes) && rawRoutes.length === 0) {
6986
+ delete merged[key];
6987
+ continue;
6988
+ }
6989
+ const routes = normalizeSubagentModelRoutes(rawRoutes);
6990
+ if (routes === null) return null;
6991
+ merged[key] = routes;
6992
+ }
6993
+ return merged;
6994
+ }
6995
+ /**
6996
+ * Merge one `subagentAllowParentForkByMainModel` patch into the stored map.
6997
+ *
6998
+ * `null` clears one key so that main model falls back to
6999
+ * `subagentDefaultAllowParentFork`; a boolean sets an explicit per-main-model
7000
+ * override (`true` OR `false`, since overriding a `true` global default back to
7001
+ * `false` for one main model is legitimate).
7002
+ * @param current - Map already stored in the preferences document.
7003
+ * @param patch - Incoming patch from a settings card or a route body.
7004
+ * @returns the merged map, or null when any key or value is malformed.
7005
+ */
7006
+ function mergeSubagentAllowParentForkByMainModel(current, patch) {
7007
+ const patchRecord = asRecord$24(patch);
7008
+ if (patchRecord === void 0) return null;
7009
+ const merged = {};
7010
+ if (current !== void 0) {
7011
+ for (const [k, v] of Object.entries(current)) if (typeof v === "boolean" && isValidMainModelKey(k)) merged[k.trim()] = v;
7012
+ }
7013
+ for (const [rawKey, rawValue] of Object.entries(patchRecord)) {
7014
+ const key = rawKey.trim();
7015
+ if (!isValidMainModelKey(key)) return null;
7016
+ if (rawValue === null) {
7017
+ delete merged[key];
7018
+ continue;
7019
+ }
7020
+ if (typeof rawValue !== "boolean") return null;
7021
+ merged[key] = rawValue;
7022
+ }
7023
+ return merged;
7024
+ }
7025
+ //#endregion
6695
7026
  //#region src/host/proxy-manager.ts
6696
7027
  const SYSTEM_PROXY_CACHE_TTL_MS = 5e3;
6697
7028
  /**
@@ -6727,8 +7058,8 @@ function proxyAgentOptions(uri, allowH2, headersTimeoutMs) {
6727
7058
  };
6728
7059
  }
6729
7060
  /** One pool per (proxy, protocol policy, credential): neither policy nor identity may be shared. */
6730
- function agentCacheKey(proxyUrl, allowH2, poolKey, headersTimeoutMs) {
6731
- return `${poolKey ?? "shared"}:${allowH2 === false ? "h1" : "auto"}:${headersTimeoutMs ?? "default"}:${proxyUrl}`;
7061
+ function agentCacheKey(proxyUrl, allowH2, poolKey, headersTimeoutMs, line) {
7062
+ return `${line ?? "shared"}:${poolKey ?? "shared"}:${allowH2 === false ? "h1" : "auto"}:${headersTimeoutMs ?? "default"}:${proxyUrl}`;
6732
7063
  }
6733
7064
  /** The key of the dispatcher that serves one credential's unproxied traffic. */
6734
7065
  function directAgentKey(poolKey, allowH2, omitAlpn, headersTimeoutMs) {
@@ -7169,21 +7500,34 @@ var ProxyManager = class {
7169
7500
  /**
7170
7501
  * The active `NO_PROXY` list, re-read at most once per TTL.
7171
7502
  *
7503
+ * Two sources, one answer: the deployment list from {@link ProxyFetchOptions.noProxyReader}
7504
+ * and the list the settings card stores in `getPreferences().noProxy`. Neither
7505
+ * replaces the other, because the card is the discoverable place and the
7506
+ * environment file is the deployment-level place.
7507
+ *
7172
7508
  * A reader that throws (an unreadable `$DSH_HOME/.env`) reads as "no bypass
7173
7509
  * list", never as "bypass everything": the wrong guess in that direction would
7174
- * take an active proxy away from every line at once.
7510
+ * take an active proxy away from every line at once. The same applies to one
7511
+ * source failing: the other source still answers.
7175
7512
  */
7176
7513
  getNoProxyList(force = false) {
7177
7514
  const now = Date.now();
7178
7515
  if (!force && now - this.lastNoProxyCheck < SYSTEM_PROXY_CACHE_TTL_MS) return this.cachedNoProxy;
7179
7516
  this.lastNoProxyCheck = now;
7180
- try {
7181
- this.cachedNoProxy = this.noProxyReader().trim();
7182
- } catch {
7183
- this.cachedNoProxy = "";
7184
- }
7517
+ this.cachedNoProxy = this.readNoProxyList();
7185
7518
  return this.cachedNoProxy;
7186
7519
  }
7520
+ /** Both bypass sources, canonicalized and concatenated; each failure reads as empty. */
7521
+ readNoProxyList() {
7522
+ const parts = [];
7523
+ try {
7524
+ parts.push(this.noProxyReader());
7525
+ } catch {}
7526
+ try {
7527
+ parts.push(this.getPreferences().noProxy ?? "");
7528
+ } catch {}
7529
+ return normalizeNoProxyList(parts.join(","));
7530
+ }
7187
7531
  /**
7188
7532
  * Observe the system proxy becoming known.
7189
7533
  *
@@ -7200,15 +7544,30 @@ var ProxyManager = class {
7200
7544
  this.proxyListeners.delete(listener);
7201
7545
  };
7202
7546
  }
7203
- resolveActiveProxyUrl() {
7547
+ /**
7548
+ * The proxy one provider line actually uses.
7549
+ *
7550
+ * With a `line`, that line's own entry decides: an absent entry is the
7551
+ * shipped `auto` default, so a fresh install keeps following the machine and
7552
+ * a line a user never opened is not silently forced direct. Without a
7553
+ * `line`, the retired shared pair answers — kept only so an older caller (or
7554
+ * a deployment pinning the old field) still resolves to what it always did.
7555
+ *
7556
+ * @param line - Provider id whose entry should decide, or undefined for the
7557
+ * legacy shared setting.
7558
+ * @returns the proxy URL in force, or null for a direct connection.
7559
+ */
7560
+ resolveActiveProxyUrl(line) {
7204
7561
  const prefs = this.getPreferences();
7205
- const mode = prefs.proxyMode ?? "auto";
7562
+ const entry = line === void 0 ? void 0 : (prefs.lineProxies ?? {})[line];
7563
+ const mode = entry?.mode ?? (line === void 0 ? prefs.proxyMode ?? "auto" : DEFAULT_LINE_PROXY.mode);
7564
+ const customUrl = line === void 0 ? prefs.customProxyUrl : entry?.customProxyUrl ?? null;
7206
7565
  if (mode === "direct") return null;
7207
- if (mode === "custom") return prefs.customProxyUrl ? normalizeProxyUrl(prefs.customProxyUrl) : null;
7566
+ if (mode === "custom") return customUrl ? normalizeProxyUrl(customUrl) : null;
7208
7567
  return this.getSystemProxy();
7209
7568
  }
7210
- getOrCreateAgent(proxyUrl, allowH2, poolKey, headersTimeoutMs) {
7211
- const key = agentCacheKey(proxyUrl, allowH2, poolKey, headersTimeoutMs);
7569
+ getOrCreateAgent(proxyUrl, allowH2, poolKey, headersTimeoutMs, line) {
7570
+ const key = agentCacheKey(proxyUrl, allowH2, poolKey, headersTimeoutMs, line);
7212
7571
  const existing = this.agents.get(key);
7213
7572
  if (existing instanceof ProxyAgent) return existing;
7214
7573
  const agent = new ProxyAgent(proxyAgentOptions(proxyUrl, allowH2, headersTimeoutMs));
@@ -7280,15 +7639,15 @@ var ProxyManager = class {
7280
7639
  };
7281
7640
  return async (input, init) => {
7282
7641
  const poolKey = overrides?.credentialPools === true ? credentialPoolKey(init) : void 0;
7283
- const activeProxy = this.resolveActiveProxyUrl();
7642
+ const activeProxy = this.resolveActiveProxyUrl(overrides?.line);
7284
7643
  if (!activeProxy) return poolKey === void 0 && overrides?.headersTimeoutMs === void 0 ? this.baseFetch(input, init) : this.dispatchWith(input, init, shape(this.getOrCreateDirectAgent(poolKey ?? "shared", overrides)));
7285
7644
  if (shouldBypassProxy(requestTarget(input), this.getNoProxyList())) return poolKey === void 0 && overrides?.headersTimeoutMs === void 0 ? this.baseFetch(input, init) : this.dispatchWith(input, init, shape(this.getOrCreateDirectAgent(poolKey ?? "shared", overrides)));
7286
7645
  for (let attempt = 0;; attempt += 1) try {
7287
- const agent = shape(this.getOrCreateAgent(activeProxy, overrides?.allowH2, poolKey, overrides?.headersTimeoutMs));
7646
+ const agent = shape(this.getOrCreateAgent(activeProxy, overrides?.allowH2, poolKey, overrides?.headersTimeoutMs, overrides?.line));
7288
7647
  return await this.dispatchWith(input, init, agent);
7289
7648
  } catch (error) {
7290
7649
  if (attempt === 0 && isDestroyedClientError(error)) {
7291
- this.agents.delete(agentCacheKey(activeProxy, overrides?.allowH2, poolKey, overrides?.headersTimeoutMs));
7650
+ this.agents.delete(agentCacheKey(activeProxy, overrides?.allowH2, poolKey, overrides?.headersTimeoutMs, overrides?.line));
7292
7651
  continue;
7293
7652
  }
7294
7653
  throw error;
@@ -8693,212 +9052,6 @@ var FilePreferencesStore = class {
8693
9052
  }
8694
9053
  };
8695
9054
  //#endregion
8696
- //#region src/shared/compaction-route.ts
8697
- /** Runtime membership test for one stored target. */
8698
- function isCompactionRouteTarget(value) {
8699
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
8700
- const record = value;
8701
- return isNonEmptyString(record.provider) && isNonEmptyString(record.model);
8702
- }
8703
- function isNonEmptyString(value) {
8704
- return typeof value === "string" && value.trim().length > 0;
8705
- }
8706
- /**
8707
- * Decide whether the payload is admissible on the target.
8708
- *
8709
- * An undisclosed modality list is unknown, not negative: the harness documents
8710
- * absence as "not disclosed", so refusing on it would disable the feature on
8711
- * every route that simply does not advertise. The request still runs, and a
8712
- * real rejection falls back the same way an error does.
8713
- *
8714
- * @param facts - what the directory says about the target.
8715
- * @param needs - what the payload contains.
8716
- * @returns the refusal reason, or `undefined` when the target may take it.
8717
- */
8718
- function compactionSkipReason(facts, needs) {
8719
- const modalities = facts.modalities;
8720
- if (modalities === void 0) return void 0;
8721
- const accepts = new Set(modalities);
8722
- if (needs.video && !accepts.has("video")) return "target-accepts-no-video";
8723
- }
8724
- /**
8725
- * Whether the target can carry images inline.
8726
- *
8727
- * Used for the recorded outcome only: an image the target cannot take is
8728
- * replaced by a placeholder during projection, so the summary is still produced
8729
- * but may describe a screenshot it never saw.
8730
- *
8731
- * @param facts - what the directory says about the target.
8732
- * @returns false only when the target discloses image support and omits it.
8733
- */
8734
- function compactionRoutesImages(facts) {
8735
- const modalities = facts.modalities;
8736
- if (modalities === void 0) return true;
8737
- return modalities.includes("image");
8738
- }
8739
- //#endregion
8740
- //#region src/shared/preferences.ts
8741
- const PREFERENCES_NAMESPACE = "dsh-chatgpt-subscription";
8742
- const DEFAULT_PREFERENCES = {
8743
- enabled: true,
8744
- quickQuotaVisible: false,
8745
- fastMode: false,
8746
- outputVerbosity: null,
8747
- reasoningSummary: null,
8748
- visibleModelIds: [...DEFAULT_VISIBLE_CODEX_MODEL_IDS],
8749
- searchProvider: "dsh",
8750
- contextWindowOverrides: {},
8751
- proxyMode: "auto",
8752
- customProxyUrl: null,
8753
- compactionRoute: null,
8754
- subagentDefaultModels: [],
8755
- subagentModelsByMainModel: {},
8756
- subagentDefaultAllowParentFork: false,
8757
- subagentAllowParentForkByMainModel: {}
8758
- };
8759
- const SEARCH_PROVIDER_CODEX = "codex";
8760
- function isSearchProviderPreference(value) {
8761
- return value === "dsh" || value === "codex";
8762
- }
8763
- function isCodexOutputVerbosity(value) {
8764
- return value === "low" || value === "medium" || value === "high";
8765
- }
8766
- function isCodexReasoningSummary(value) {
8767
- return value === "auto" || value === "concise" || value === "detailed" || value === "none";
8768
- }
8769
- function isProxyMode(value) {
8770
- return value === "auto" || value === "custom" || value === "direct";
8771
- }
8772
- function asRecord$24(value) {
8773
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
8774
- }
8775
- /**
8776
- * Read one non-empty trimmed string field.
8777
- * @param value - Candidate field value from stored JSON.
8778
- * @returns the trimmed string, or undefined when it is not a non-empty string.
8779
- */
8780
- function trimmedString(value) {
8781
- if (typeof value !== "string") return void 0;
8782
- const trimmed = value.trim();
8783
- return trimmed.length === 0 ? void 0 : trimmed;
8784
- }
8785
- /**
8786
- * Whether one value is a complete `{ provider, model }` route.
8787
- *
8788
- * Both halves are trimmed and must be non-empty: a route with a blank provider
8789
- * names no adapter, and a blank model names no model, so neither can ever be
8790
- * authorized. Stored documents are untrusted JSON, which is why this narrows
8791
- * rather than asserts.
8792
- * @param value - Candidate route.
8793
- * @returns whether the value is a usable route.
8794
- */
8795
- function isSubagentModelRoute(value) {
8796
- const record = asRecord$24(value);
8797
- if (record === void 0) return false;
8798
- return trimmedString(record["provider"]) !== void 0 && trimmedString(record["model"]) !== void 0;
8799
- }
8800
- /**
8801
- * Normalize one route list, deduplicating it without reordering.
8802
- *
8803
- * Order is preserved because it is the order the settings card shows and the
8804
- * order `list_subagent_models` prints: a set would silently reshuffle the list
8805
- * a user arranged.
8806
- * @param value - Candidate route list from stored JSON.
8807
- * @returns the trimmed, deduplicated routes, or null when the value is not an
8808
- * array of well-formed routes.
8809
- */
8810
- function normalizeSubagentModelRoutes(value) {
8811
- if (!Array.isArray(value)) return null;
8812
- const routes = [];
8813
- const seen = /* @__PURE__ */ new Set();
8814
- for (const entry of value) {
8815
- if (!isSubagentModelRoute(entry)) return null;
8816
- const provider = entry.provider.trim();
8817
- const model = entry.model.trim();
8818
- const key = `${provider}/${model}`;
8819
- if (seen.has(key)) continue;
8820
- seen.add(key);
8821
- routes.push({
8822
- provider,
8823
- model
8824
- });
8825
- }
8826
- return routes;
8827
- }
8828
- /**
8829
- * Whether one key names a main agent route as `provider/model`.
8830
- *
8831
- * The split is at the FIRST slash, so a model id that legally contains a slash
8832
- * (`command-code` + `deepseek/deepseek-v4.1-flash`) still round-trips: the
8833
- * provider half ends at the first separator and the model half keeps the rest.
8834
- * @param key - Candidate map key.
8835
- * @returns whether the key carries a non-empty provider and a non-empty model.
8836
- */
8837
- function isValidMainModelKey(key) {
8838
- if (typeof key !== "string") return false;
8839
- const trimmed = key.trim();
8840
- const separator = trimmed.indexOf("/");
8841
- if (separator <= 0) return false;
8842
- return trimmed.slice(separator + 1).length > 0;
8843
- }
8844
- /**
8845
- * Merge one `subagentModelsByMainModel` patch into the stored map.
8846
- *
8847
- * A merge rather than a replace, so the card can clear or set one main model
8848
- * without resending every other entry — and `null` (or `[]`) is how one entry
8849
- * is cleared, since a stored map has no other way to say "no override".
8850
- * @param current - Map already stored in the preferences document.
8851
- * @param patch - Incoming patch from a settings card or a route body.
8852
- * @returns the merged map, or null when any key or value is malformed.
8853
- */
8854
- function mergeSubagentModelsByMainModel(current, patch) {
8855
- const patchRecord = asRecord$24(patch);
8856
- if (patchRecord === void 0) return null;
8857
- const merged = { ...current };
8858
- for (const [rawKey, rawRoutes] of Object.entries(patchRecord)) {
8859
- const key = rawKey.trim();
8860
- if (!isValidMainModelKey(key)) return null;
8861
- if (rawRoutes === null || Array.isArray(rawRoutes) && rawRoutes.length === 0) {
8862
- delete merged[key];
8863
- continue;
8864
- }
8865
- const routes = normalizeSubagentModelRoutes(rawRoutes);
8866
- if (routes === null) return null;
8867
- merged[key] = routes;
8868
- }
8869
- return merged;
8870
- }
8871
- /**
8872
- * Merge one `subagentAllowParentForkByMainModel` patch into the stored map.
8873
- *
8874
- * `null` clears one key so that main model falls back to
8875
- * `subagentDefaultAllowParentFork`; a boolean sets an explicit per-main-model
8876
- * override (`true` OR `false`, since overriding a `true` global default back to
8877
- * `false` for one main model is legitimate).
8878
- * @param current - Map already stored in the preferences document.
8879
- * @param patch - Incoming patch from a settings card or a route body.
8880
- * @returns the merged map, or null when any key or value is malformed.
8881
- */
8882
- function mergeSubagentAllowParentForkByMainModel(current, patch) {
8883
- const patchRecord = asRecord$24(patch);
8884
- if (patchRecord === void 0) return null;
8885
- const merged = {};
8886
- if (current !== void 0) {
8887
- for (const [k, v] of Object.entries(current)) if (typeof v === "boolean" && isValidMainModelKey(k)) merged[k.trim()] = v;
8888
- }
8889
- for (const [rawKey, rawValue] of Object.entries(patchRecord)) {
8890
- const key = rawKey.trim();
8891
- if (!isValidMainModelKey(key)) return null;
8892
- if (rawValue === null) {
8893
- delete merged[key];
8894
- continue;
8895
- }
8896
- if (typeof rawValue !== "boolean") return null;
8897
- merged[key] = rawValue;
8898
- }
8899
- return merged;
8900
- }
8901
- //#endregion
8902
9055
  //#region src/host/common/legacy-preferences.ts
8903
9056
  /**
8904
9057
  * One-time import of the preferences earlier releases kept in the harness's own
@@ -9143,6 +9296,15 @@ function registerPreferenceStore(settings) {
9143
9296
  z$1.const("direct")
9144
9297
  ]).default(DEFAULT_PREFERENCES.proxyMode),
9145
9298
  customProxyUrl: z$1.union([z$1.string(), z$1.const(null)]).default(DEFAULT_PREFERENCES.customProxyUrl),
9299
+ noProxy: z$1.union([z$1.string(), z$1.const(null)]).default(DEFAULT_PREFERENCES.noProxy ?? null),
9300
+ lineProxies: z$1.dict(z$1.object({
9301
+ mode: z$1.union([
9302
+ z$1.const("auto"),
9303
+ z$1.const("custom"),
9304
+ z$1.const("direct")
9305
+ ]),
9306
+ customProxyUrl: z$1.union([z$1.string(), z$1.const(null)])
9307
+ })).default(DEFAULT_PREFERENCES.lineProxies ?? {}),
9146
9308
  compactionRoute: z$1.union([z$1.object({
9147
9309
  provider: z$1.string(),
9148
9310
  model: z$1.string()
@@ -9161,6 +9323,17 @@ function registerPreferenceStore(settings) {
9161
9323
  var SettingsPreferenceStore = class {
9162
9324
  scope;
9163
9325
  load;
9326
+ /** One-shot load plus the one-time per-line proxy migration it triggers. */
9327
+ hydrated;
9328
+ /**
9329
+ * True while the one-time migration writes.
9330
+ *
9331
+ * That write is bookkeeping, not a user change: waking the preference
9332
+ * watchers with it would restart the web provider selection during the
9333
+ * profile composition window, which is exactly the startup race those
9334
+ * watchers' deferral exists to avoid.
9335
+ */
9336
+ migrating = false;
9164
9337
  /**
9165
9338
  * @param scope - Namespace scope, or the plugin-owned file store standing in for one.
9166
9339
  * @param load - One-shot load of that file store; absent for a settings scope.
@@ -9170,7 +9343,39 @@ var SettingsPreferenceStore = class {
9170
9343
  this.load = load;
9171
9344
  }
9172
9345
  hydrate() {
9173
- return this.load();
9346
+ this.hydrated ??= this.load().then(() => this.migrateLineProxies());
9347
+ return this.hydrated;
9348
+ }
9349
+ /**
9350
+ * Copy the retired shared proxy setting onto every provider line, once.
9351
+ *
9352
+ * Before per-line proxies there was one `proxyMode`/`customProxyUrl` pair that
9353
+ * every line shared. Leaving those values where they are would be a silent
9354
+ * behaviour change at upgrade: the fields stay for export compatibility, but
9355
+ * nothing reads them any more, so every line would quietly fall back to
9356
+ * `auto`. The migration makes each line state the value it was already using.
9357
+ *
9358
+ * Idempotent by construction: a document that carries ANY per-line entry has
9359
+ * already been migrated (or has been edited since), and is never touched —
9360
+ * re-running this on a user's own choices would silently undo them.
9361
+ */
9362
+ async migrateLineProxies() {
9363
+ const current = this.scope.get();
9364
+ if (Object.keys(current.lineProxies ?? {}).length > 0) return;
9365
+ const legacy = {
9366
+ mode: current.proxyMode ?? DEFAULT_LINE_PROXY.mode,
9367
+ customProxyUrl: normalizeLineProxyUrl(current.customProxyUrl)
9368
+ };
9369
+ const lineProxies = Object.fromEntries(LINE_PROXY_PROVIDER_IDS.map((line) => [line, {
9370
+ mode: legacy.mode,
9371
+ customProxyUrl: legacy.mode === "custom" ? legacy.customProxyUrl : null
9372
+ }]));
9373
+ this.migrating = true;
9374
+ try {
9375
+ await this.scope.update({ lineProxies });
9376
+ } catch {} finally {
9377
+ this.migrating = false;
9378
+ }
9174
9379
  }
9175
9380
  status() {
9176
9381
  return withWritable(this.scope.get());
@@ -9227,6 +9432,16 @@ var SettingsPreferenceStore = class {
9227
9432
  if (merged === null) throw new PreferenceError("Unsupported subagentAllowParentForkByMainModel preference.");
9228
9433
  normalized.subagentAllowParentForkByMainModel = merged;
9229
9434
  }
9435
+ if (patch.lineProxies !== void 0) {
9436
+ const merged = mergeLineProxies(this.scope.get().lineProxies, patch.lineProxies);
9437
+ if (merged === null) throw new PreferenceError("Unsupported lineProxies preference.");
9438
+ normalized.lineProxies = merged;
9439
+ }
9440
+ if (patch.noProxy !== void 0) {
9441
+ if (patch.noProxy !== null && typeof patch.noProxy !== "string") throw new PreferenceError("Unsupported noProxy preference.");
9442
+ const normalizedList = patch.noProxy === null ? "" : normalizeNoProxyList(patch.noProxy);
9443
+ normalized.noProxy = normalizedList.length === 0 ? null : normalizedList;
9444
+ }
9230
9445
  if (patch.customProxyUrl !== void 0) if (patch.customProxyUrl !== null) {
9231
9446
  const trimmed = patch.customProxyUrl.trim();
9232
9447
  if (trimmed.length > 0 && !/^https?:\/\//i.test(trimmed) && !/^socks5?:\/\//i.test(trimmed)) normalized.customProxyUrl = `http://${trimmed}`;
@@ -9236,7 +9451,10 @@ var SettingsPreferenceStore = class {
9236
9451
  return this.status();
9237
9452
  }
9238
9453
  watch(callback) {
9239
- return this.scope.watch((next, prev) => callback(withWritable(next), withWritable(prev)));
9454
+ return this.scope.watch((next, prev) => {
9455
+ if (this.migrating) return void 0;
9456
+ return callback(withWritable(next), withWritable(prev));
9457
+ });
9240
9458
  }
9241
9459
  };
9242
9460
  var PreferenceError = class extends Error {
@@ -12372,12 +12590,26 @@ function registerRoutes(ctx, oauth, usage, preferences, proxyManager, searchSwit
12372
12590
  codexCliSignInPath,
12373
12591
  detectedProxy: proxyManager?.getSystemProxy() ?? null,
12374
12592
  activeProxy: proxyManager?.resolveActiveProxyUrl() ?? null,
12593
+ activeProxies: proxyManager === void 0 ? void 0 : Object.fromEntries(LINE_PROXY_PROVIDER_IDS.map((line) => [line, maskProxyUrl(proxyManager.resolveActiveProxyUrl(line))])),
12375
12594
  switcher: searchSwitcher?.status() ?? null,
12376
12595
  fetchConfiguration
12377
12596
  }
12378
12597
  });
12379
12598
  return;
12380
12599
  }
12600
+ if (request.method === "GET" && url.pathname === `/api/dsh-chatgpt-subscription/proxy`) {
12601
+ const prefs = preferences.status();
12602
+ json(response, {
12603
+ ok: true,
12604
+ value: {
12605
+ lineProxies: prefs.lineProxies ?? {},
12606
+ noProxy: prefs.noProxy ?? null,
12607
+ detectedProxy: proxyManager?.getSystemProxy() ?? null,
12608
+ activeProxies: proxyManager === void 0 ? {} : Object.fromEntries(LINE_PROXY_PROVIDER_IDS.map((line) => [line, maskProxyUrl(proxyManager.resolveActiveProxyUrl(line))]))
12609
+ }
12610
+ });
12611
+ return;
12612
+ }
12381
12613
  if (request.method === "GET" && url.pathname === `/api/dsh-chatgpt-subscription/subagent-route-audit`) {
12382
12614
  const sessionId = url.searchParams.get("sessionId");
12383
12615
  if (sessionId === null || sessionId.length === 0) {
@@ -12746,6 +12978,28 @@ async function compactionCandidates(ctx) {
12746
12978
  };
12747
12979
  }))).filter((provider) => provider.models.length > 0) };
12748
12980
  }
12981
+ /**
12982
+ * A proxy URL with any credential half removed.
12983
+ *
12984
+ * The status route reports which proxy a line uses, and a custom proxy may carry
12985
+ * `user:pass@`. The card only needs to say WHICH proxy answered, so the user
12986
+ * half never travels: a settings page is not a place to re-display a secret
12987
+ * that was typed once.
12988
+ * @param value - Resolved proxy URL, or null for a direct connection.
12989
+ * @returns the URL without credentials, or null.
12990
+ */
12991
+ function maskProxyUrl(value) {
12992
+ if (value === null) return null;
12993
+ try {
12994
+ const url = new URL(value);
12995
+ if (url.username === "" && url.password === "") return value;
12996
+ url.username = "";
12997
+ url.password = "";
12998
+ return url.toString();
12999
+ } catch {
13000
+ return null;
13001
+ }
13002
+ }
12749
13003
  function isRecord$64(value) {
12750
13004
  return typeof value === "object" && value !== null && !Array.isArray(value);
12751
13005
  }
@@ -12821,6 +13075,15 @@ function readPreferencesUpdate(value, current) {
12821
13075
  if (value.proxyMode !== "auto" && value.proxyMode !== "custom" && value.proxyMode !== "direct") throw new PreferenceError("proxyMode must be auto, custom, or direct.");
12822
13076
  patch.proxyMode = value.proxyMode;
12823
13077
  }
13078
+ if ("lineProxies" in value) {
13079
+ if (mergeLineProxies(current.lineProxies, value.lineProxies) === null) throw new PreferenceError("lineProxies must map known provider ids to { mode, customProxyUrl }, or null to clear one.");
13080
+ patch.lineProxies = value.lineProxies;
13081
+ }
13082
+ if ("noProxy" in value) {
13083
+ if (value.noProxy !== null && typeof value.noProxy !== "string") throw new PreferenceError("noProxy must be a string or null.");
13084
+ patch.noProxy = value.noProxy === null ? null : normalizeNoProxyList(value.noProxy);
13085
+ if (patch.noProxy === "") patch.noProxy = null;
13086
+ }
12824
13087
  if ("customProxyUrl" in value) {
12825
13088
  if (value.customProxyUrl !== null && typeof value.customProxyUrl !== "string") throw new PreferenceError("customProxyUrl must be a string or null.");
12826
13089
  patch.customProxyUrl = value.customProxyUrl;
@@ -24903,7 +25166,6 @@ var McpBridge = class {
24903
25166
  descriptor;
24904
25167
  token = randomBytes(32).toString("base64url");
24905
25168
  exposed;
24906
- withdrawn = /* @__PURE__ */ new Map();
24907
25169
  parked = /* @__PURE__ */ new Map();
24908
25170
  waiters = /* @__PURE__ */ new Set();
24909
25171
  closed = false;
@@ -24946,7 +25208,15 @@ var McpBridge = class {
24946
25208
  this.parked.clear();
24947
25209
  return calls;
24948
25210
  }
24949
- /** How many calls are currently waiting for an answer. */
25211
+ /**
25212
+ * How many calls the harness has not picked up yet.
25213
+ *
25214
+ * Deliberately the *parked* set - calls the agent has made that the harness has
25215
+ * not taken yet - and not the responses still held open. The cap exists to stop
25216
+ * a runaway agent from piling up calls nobody has picked up; a call the harness
25217
+ * already took is one it answers by the next generation, and counting those as
25218
+ * well would fire the cap during a legitimate multi-step round.
25219
+ */
24950
25220
  get pendingCount() {
24951
25221
  return this.parked.size;
24952
25222
  }
@@ -25095,7 +25365,7 @@ var McpBridge = class {
25095
25365
  async handleToolCall(id, params, response) {
25096
25366
  const record = typeof params === "object" && params !== null && !Array.isArray(params) ? params : {};
25097
25367
  const exposedName = typeof record.name === "string" ? record.name : "";
25098
- const tool = this.exposed.find((entry) => entry.exposedName === exposedName) ?? this.withdrawn.get(exposedName);
25368
+ const tool = this.exposed.find((entry) => entry.exposedName === exposedName);
25099
25369
  if (tool === void 0) {
25100
25370
  respond(response, 200, jsonRpcResult(id, {
25101
25371
  content: [{
@@ -25253,6 +25523,16 @@ const ACP_ERROR_CODES = {
25253
25523
  ACP_DISCONNECTED: "The Antigravity agent process ended mid-turn. Retry to reconnect.",
25254
25524
  /** A JSON-RPC error the line has no specific handling for. */
25255
25525
  ACP_RPC_ERROR: "The Antigravity ACP server returned a JSON-RPC error.",
25526
+ /**
25527
+ * The service declined the account or the request itself - a quota wall, a
25528
+ * policy block, a verification challenge, a rate limit.
25529
+ *
25530
+ * Kept apart from {@link ACP_RPC_ERROR} because the two want opposite
25531
+ * treatment: a transport fault is worth another attempt, while putting the same
25532
+ * account in front of the same wall two more times is how a strict policy turns
25533
+ * one failure into a pattern.
25534
+ */
25535
+ ACP_UPSTREAM_BLOCKED: "The Antigravity service declined this account or request (quota, policy or verification). Retrying here will not change the answer - resolve it in the official client first.",
25256
25536
  /** The server rejected the request parameters or the model id. */
25257
25537
  ACP_INVALID_PARAMS: "The Antigravity ACP server rejected the request parameters or the model id.",
25258
25538
  /** The server does not implement the method this client called. */
@@ -25746,6 +26026,30 @@ function isEffort(value) {
25746
26026
  return EFFORT_ORDER$2.includes(value);
25747
26027
  }
25748
26028
  /**
26029
+ * Which sign-in method to hand the agent when it asks for one.
26030
+ *
26031
+ * The server publishes whatever method list the installed CLI supports, and the
26032
+ * order below is the line's preference: the personal OAuth flow first, then the
26033
+ * terminal flow, then a business account, then the API-key forms. This lives
26034
+ * here - not beside one call site - because two call sites ask the same question:
26035
+ * a main-model session (`adapter.openSession`) and the catalogue read
26036
+ * (`catalog.readCatalogFrom`). They used to disagree, one of them hard-coding
26037
+ * `oauth-personal` and getting a method the server never offered.
26038
+ *
26039
+ * @param authMethods - The ids the server announced in `initialize`.
26040
+ * @returns The method id to request.
26041
+ */
26042
+ function preferAuthMethod(authMethods) {
26043
+ for (const candidate of [
26044
+ "oauth-personal",
26045
+ "terminal-login",
26046
+ "oauth-business",
26047
+ "gemini-api-key",
26048
+ "agent-platform"
26049
+ ]) if (authMethods.includes(candidate)) return candidate;
26050
+ return authMethods[0] ?? "oauth-personal";
26051
+ }
26052
+ /**
25749
26053
  * Collapse the server's tier-suffixed model ids into one selectable model each.
25750
26054
  *
25751
26055
  * The server publishes two different lists that describe the same catalog:
@@ -26019,6 +26323,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26019
26323
  for (const entry of [...this.dormant.values()]) await this.closeDormant(entry);
26020
26324
  for (const turn of [...this.live.values()]) {
26021
26325
  if (this.live.get(turn.dshSessionId) === turn) this.live.delete(turn.dshSessionId);
26326
+ turn.closed = true;
26022
26327
  this.activeTurns = Math.max(0, this.activeTurns - 1);
26023
26328
  turn.queue.close();
26024
26329
  this.cancelTurn(turn);
@@ -26048,10 +26353,12 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26048
26353
  const settings = await this.options.settings.read();
26049
26354
  const images = await resolveRequestImages$1(options, this.options.attachments, signal).catch(() => NO_RESOLVED_IMAGES$3);
26050
26355
  const effort = options.reasoningEffort === void 0 ? settings.defaultReasoningEffort ?? void 0 : String(options.reasoningEffort);
26051
- const live = this.live.get(dshSessionId);
26052
- if (live !== void 0 && live.model === options.model && live.effort === effort && canContinue(options.messages, live.covered, live.fingerprint)) return this.continueTurn(live, options, images, signal, activity);
26053
- if (live !== void 0) await this.closeTurn(live);
26054
26356
  const auxiliary = options.purpose !== void 0;
26357
+ if (!auxiliary) {
26358
+ const live = this.live.get(dshSessionId);
26359
+ if (live !== void 0 && live.model === options.model && live.effort === effort && canContinue(options.messages, live.covered, live.fingerprint)) return this.continueTurn(live, options, images, signal, activity);
26360
+ if (live !== void 0) await this.closeTurn(live);
26361
+ }
26055
26362
  const dormant = auxiliary ? void 0 : this.dormant.get(dshSessionId);
26056
26363
  if (dormant !== void 0) if (this.usableDormant(dormant, options)) {
26057
26364
  const resumed = await this.resumeDormant(dormant, options, settings, effort, images, signal, activity);
@@ -26066,6 +26373,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26066
26373
  this.activeTurns += 1;
26067
26374
  const queue = new UpdateQueue();
26068
26375
  const bridge = new McpBridge(options.tools ?? []);
26376
+ const binding = {};
26069
26377
  let client;
26070
26378
  let reusedSessions = 0;
26071
26379
  try {
@@ -26074,10 +26382,11 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26074
26382
  if (warm !== void 0) {
26075
26383
  client = warm.client;
26076
26384
  reusedSessions = warm.sessions;
26077
- this.attachHandlers(client, queue, activity);
26078
- } else client = this.spawn(launch, queue, activity);
26385
+ this.attachHandlers(client, queue, activity, binding);
26386
+ } else client = this.spawn(launch, queue, activity, binding);
26079
26387
  const descriptor = await bridge.start();
26080
26388
  const sessionId = await this.openSession(client, options, [descriptor], settings);
26389
+ binding.acpSessionId = sessionId;
26081
26390
  await this.applyModelAndEffort(client, sessionId, options.model, effort);
26082
26391
  const prompt = buildPrompt(options, images, 0);
26083
26392
  if ((options.tools ?? []).length > 0) prompt.blocks.unshift({
@@ -26102,9 +26411,10 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26102
26411
  awaitingHarness: false,
26103
26412
  sessionsUsed: reusedSessions + 1,
26104
26413
  tools: fingerprintTools(options.tools),
26105
- parkable
26414
+ parkable,
26415
+ closed: false
26106
26416
  };
26107
- this.live.set(dshSessionId, turn);
26417
+ if (parkable) this.live.set(dshSessionId, turn);
26108
26418
  this.sendPrompt(turn, prompt.blocks);
26109
26419
  return this.pump(turn, signal, activity);
26110
26420
  } catch (error) {
@@ -26328,12 +26638,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26328
26638
  }
26329
26639
  } finally {
26330
26640
  if (!finished) await this.closeTurn(turn);
26331
- else if (!turn.awaitingHarness && this.live.get(turn.dshSessionId) === turn) {
26332
- this.live.delete(turn.dshSessionId);
26333
- this.activeTurns = Math.max(0, this.activeTurns - 1);
26334
- if (turn.parkable) await this.park(turn);
26335
- else await this.release(turn);
26336
- }
26641
+ else if (!turn.awaitingHarness) await this.finishTurn(turn, true);
26337
26642
  }
26338
26643
  }
26339
26644
  /**
@@ -26356,9 +26661,10 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26356
26661
  if ((typeof toolCall?.name === "string" ? toolCall.name : "").startsWith(`mcp_dsh-bridge_`)) return answer();
26357
26662
  return (await this.options.settings.read()).permissionPolicy === "allow" ? answer() : void 0;
26358
26663
  }
26359
- spawn(launch, queue, activity) {
26664
+ spawn(launch, queue, activity, binding) {
26360
26665
  const handlers = {
26361
- onSessionUpdate: (_sessionId, update) => {
26666
+ onSessionUpdate: (sessionId, update) => {
26667
+ if (!ownsSession(binding, sessionId)) return;
26362
26668
  queue.push(update);
26363
26669
  activity.pulse();
26364
26670
  },
@@ -26469,19 +26775,17 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26469
26775
  sessionId: turn.acpSessionId,
26470
26776
  prompt: blocks
26471
26777
  }));
26472
- const usage = asRecord$19(result?.usage);
26778
+ const rawUsage = asRecord$19(result?.usage);
26779
+ const usage = rawUsage === void 0 ? void 0 : readUsage(rawUsage);
26473
26780
  turn.settled = {
26474
26781
  stopReason: typeof result?.stopReason === "string" ? result.stopReason : "end_turn",
26475
- ...usage === void 0 ? {} : { usage: readUsage(usage) }
26782
+ ...usage === void 0 ? {} : { usage }
26783
+ };
26784
+ if (usage !== void 0) this.lastUsage = {
26785
+ ...usage,
26786
+ at: this.now(),
26787
+ durationMs: this.now() - startedAt
26476
26788
  };
26477
- if (usage !== void 0) {
26478
- const read = readUsage(usage);
26479
- if (read !== void 0) this.lastUsage = {
26480
- ...read,
26481
- at: this.now(),
26482
- durationMs: this.now() - startedAt
26483
- };
26484
- }
26485
26789
  } catch (error) {
26486
26790
  turn.settled = { error: asError(error) };
26487
26791
  } finally {
@@ -26497,11 +26801,36 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26497
26801
  * agent's own start-up wait on the next message.
26498
26802
  */
26499
26803
  async closeTurn(turn) {
26500
- if (this.live.get(turn.dshSessionId) === turn) this.live.delete(turn.dshSessionId);
26501
- this.activeTurns = Math.max(0, this.activeTurns - 1);
26804
+ if (turn.closed) return;
26502
26805
  turn.queue.close();
26503
26806
  this.cancelTurn(turn);
26504
- await this.release(turn);
26807
+ await this.finishTurn(turn, false);
26808
+ }
26809
+ /**
26810
+ * Account for one turn exactly once, then hand its process back.
26811
+ *
26812
+ * Every ending goes through here: a completed stream parks the conversation, an
26813
+ * abandoned one releases the process, and a turn whose live entry was replaced
26814
+ * releases it too - it no longer owns this session's conversation, so parking it
26815
+ * would replace the parked one with a transcript nobody is talking to.
26816
+ *
26817
+ * The `closed` flag is what makes this safe to call from a second path: the pump
26818
+ * finishing after a cancellation, and a cancellation arriving after the pump
26819
+ * finished, both used to be able to decrement `activeTurns` or release a process
26820
+ * twice.
26821
+ *
26822
+ * @param turn - The turn being ended.
26823
+ * @param parkAllowed - Whether a conversation may be left parked behind it.
26824
+ */
26825
+ async finishTurn(turn, parkAllowed) {
26826
+ if (turn.closed) return;
26827
+ turn.closed = true;
26828
+ const owned = this.live.get(turn.dshSessionId) === turn;
26829
+ if (owned) this.live.delete(turn.dshSessionId);
26830
+ this.activeTurns = Math.max(0, this.activeTurns - 1);
26831
+ turn.queue.close();
26832
+ if (parkAllowed && turn.parkable && owned) await this.park(turn);
26833
+ else await this.release(turn);
26505
26834
  }
26506
26835
  /**
26507
26836
  * Ask the agent to stop the prompt this turn left running.
@@ -26552,7 +26881,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26552
26881
  const queue = new UpdateQueue();
26553
26882
  try {
26554
26883
  if (entry.model !== options.model || entry.effort !== effort) await this.applyModelAndEffort(entry.client, entry.acpSessionId, options.model, effort);
26555
- this.attachHandlers(entry.client, queue, activity);
26884
+ this.attachHandlers(entry.client, queue, activity, { acpSessionId: entry.acpSessionId });
26556
26885
  const prompt = buildPrompt(options, images, entry.covered);
26557
26886
  const turn = {
26558
26887
  dshSessionId: entry.dshSessionId,
@@ -26572,7 +26901,8 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26572
26901
  awaitingHarness: false,
26573
26902
  sessionsUsed: entry.sessionsUsed,
26574
26903
  tools: entry.tools,
26575
- parkable: true
26904
+ parkable: true,
26905
+ closed: false
26576
26906
  };
26577
26907
  this.live.set(turn.dshSessionId, turn);
26578
26908
  this.activeTurns += 1;
@@ -26673,9 +27003,10 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26673
27003
  }
26674
27004
  }
26675
27005
  /** Re-install per-turn handlers on a reused client. */
26676
- attachHandlers(client, queue, activity) {
27006
+ attachHandlers(client, queue, activity, binding) {
26677
27007
  client.rebind({
26678
- onSessionUpdate: (_sessionId, update) => {
27008
+ onSessionUpdate: (sessionId, update) => {
27009
+ if (!ownsSession(binding, sessionId)) return;
26679
27010
  queue.push(update);
26680
27011
  activity.pulse();
26681
27012
  },
@@ -26914,16 +27245,6 @@ function needsAuth(error, authMethods) {
26914
27245
  const message = error instanceof Error ? error.message : String(error);
26915
27246
  return /authentication required/i.test(message) && authMethods.length > 0;
26916
27247
  }
26917
- function preferAuthMethod(authMethods) {
26918
- for (const candidate of [
26919
- "oauth-personal",
26920
- "terminal-login",
26921
- "oauth-business",
26922
- "gemini-api-key",
26923
- "agent-platform"
26924
- ]) if (authMethods.includes(candidate)) return candidate;
26925
- return authMethods[0] ?? "oauth-personal";
26926
- }
26927
27248
  function readUsage(raw) {
26928
27249
  const input = numberField(raw.inputTokens);
26929
27250
  const output = numberField(raw.outputTokens);
@@ -26938,6 +27259,15 @@ function readUsage(raw) {
26938
27259
  ...numberField(raw.totalTokens) === void 0 ? {} : { totalTokens: numberField(raw.totalTokens) }
26939
27260
  };
26940
27261
  }
27262
+ /**
27263
+ * Text that means the *service* declined the account rather than the agent failing.
27264
+ *
27265
+ * ACP carries upstream failures inside a JSON-RPC error message, so the sentence
27266
+ * is the only place that distinction survives. The list is deliberately about
27267
+ * what a user can act on - a quota, a policy or verification block, a rate limit -
27268
+ * and a match is reported as {@link ACP_UPSTREAM_BLOCKED}, which is not retried.
27269
+ */
27270
+ const UPSTREAM_DECLINED = /\b(?:429|403)\b|rate.?limit|too many requests|quota|resource[_ ]exhausted|terms of service|\btos\b|violat|valid(?:ation)?[_ ]required|permission[_ ]denied|account[_ ](?:disabled|suspended)|policy[_ ]violation|verification|verify your|unusual activity|risk|suspended|forbidden/i;
26941
27271
  function numberField(value) {
26942
27272
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
26943
27273
  }
@@ -26976,12 +27306,43 @@ function settleReason(stopReason) {
26976
27306
  };
26977
27307
  }
26978
27308
  }
27309
+ /**
27310
+ * Whether one `session/update` frame belongs to the turn reading right now.
27311
+ *
27312
+ * A reused process can still be flushing the conversation it ran before: the
27313
+ * `session/cancel` that ended it is a notification, not a barrier, and the process
27314
+ * is handed back to the pool without waiting for its prompt to settle. Those late
27315
+ * frames carry the old session id, and appending them would put another
27316
+ * conversation's text into this answer.
27317
+ *
27318
+ * The id decides whenever it is present. Two cases look similar and are not:
27319
+ *
27320
+ * - A frame that carries *no* id keeps the previous behaviour, because a server
27321
+ * that never repeats the id in a notification must still work - the id has
27322
+ * always been part of the ACP envelope rather than something this line added.
27323
+ * - A frame that names a session while this turn has not created one yet is a
27324
+ * leftover by construction: a warm process is checked out and rewired *before*
27325
+ * `session/new` answers, so anything addressed in that window can only belong
27326
+ * to the conversation it was running before. Keeping it "because we have no id
27327
+ * yet" was the hole in the first version of this filter.
27328
+ *
27329
+ * @param binding - The session this turn owns, once it exists.
27330
+ * @param sessionId - The id the frame carries, empty when it carried none.
27331
+ * @returns whether the frame belongs to this turn.
27332
+ */
27333
+ function ownsSession(binding, sessionId) {
27334
+ if (sessionId === "") return true;
27335
+ if (binding.acpSessionId === void 0) return false;
27336
+ return sessionId === binding.acpSessionId;
27337
+ }
26979
27338
  function asLlmError(error) {
26980
27339
  if (error instanceof LlmError) return error;
27340
+ if (error instanceof Error && error.name === "AbortError") return new LlmError("The Antigravity ACP turn was cancelled.", "ABORTED");
26981
27341
  if (error instanceof AcpError) {
26982
- if (error.code === -32e3) return acpError("ACP_AUTH_REQUIRED");
27342
+ if (error.code === -32e3 || /authentication required/i.test(error.message)) return acpError("ACP_AUTH_REQUIRED");
26983
27343
  if (error.code === -32602) return acpError("ACP_INVALID_PARAMS");
26984
27344
  if (error.code === -32601) return acpError("ACP_METHOD_UNSUPPORTED");
27345
+ if (UPSTREAM_DECLINED.test(error.message)) return acpError("ACP_UPSTREAM_BLOCKED", error.message);
26985
27346
  return acpError("ACP_RPC_ERROR", error.message);
26986
27347
  }
26987
27348
  const message = error instanceof Error ? error.message : String(error);
@@ -27230,7 +27591,7 @@ async function readCatalogFrom(client, signal) {
27230
27591
  version: "1.0.0"
27231
27592
  }
27232
27593
  }, signal));
27233
- const authMethods = Array.isArray(init?.authMethods) ? init.authMethods : [];
27594
+ const authMethods = Array.isArray(init?.authMethods) ? init.authMethods.map((entry) => String(entry.id ?? "")).filter((id) => id !== "") : [];
27234
27595
  const create = async () => {
27235
27596
  const value = asRecord$18(await client.request("session/new", {
27236
27597
  cwd: process.cwd(),
@@ -27245,7 +27606,7 @@ async function readCatalogFrom(client, signal) {
27245
27606
  } catch (error) {
27246
27607
  const message = error instanceof Error ? error.message : String(error);
27247
27608
  if (!/authentication required/i.test(message) || authMethods.length === 0) throw error;
27248
- await client.request("authenticate", { methodId: "oauth-personal" }, signal);
27609
+ await client.request("authenticate", { methodId: preferAuthMethod(authMethods) }, signal);
27249
27610
  session = await create();
27250
27611
  }
27251
27612
  const availableModels = readAvailableModels(asRecord$18(session.models)?.availableModels ?? session.availableModels);
@@ -27400,6 +27761,8 @@ const ACP_BINARY_RELEASES = {
27400
27761
  executable: "agy_acp_server.par"
27401
27762
  }
27402
27763
  };
27764
+ /** How long a resolved executable is reused before the disk is read again. */
27765
+ const BINARY_CACHE_TTL_MS = 5 * 6e4;
27403
27766
  /** Candidate paths the local CLI may live at, most specific first. */
27404
27767
  function localCliCandidates(home, platform) {
27405
27768
  return (platform === "win32" ? [
@@ -27475,6 +27838,11 @@ async function resolveAcpBinary(configured, options = {}) {
27475
27838
  },
27476
27839
  diagnostics: { tried }
27477
27840
  };
27841
+ if (options.download === false) return { diagnostics: {
27842
+ tried,
27843
+ deferred: true,
27844
+ error: "No Antigravity CLI (agy) is installed yet. This line downloads the official ACP server the first time you start a turn, run the self-check, or press refresh."
27845
+ } };
27478
27846
  try {
27479
27847
  return {
27480
27848
  binary: {
@@ -27492,6 +27860,78 @@ async function resolveAcpBinary(configured, options = {}) {
27492
27860
  }
27493
27861
  }
27494
27862
  /**
27863
+ * A cached answer to "which executable may this line run?".
27864
+ *
27865
+ * Resolution touches the disk once per candidate and spawns `agy --version` to
27866
+ * prove the file answers, which is not something a page render should do. The
27867
+ * answer is therefore reused for a few minutes; a change of `binaryPath` and the
27868
+ * refresh click invalidate or force it.
27869
+ *
27870
+ * A cached *passive* answer is never served to an active caller: if the reading
27871
+ * was taken without permission to download and found nothing, a turn asking the
27872
+ * same question must still be allowed to fetch the release.
27873
+ */
27874
+ var AcpBinaryCache = class {
27875
+ resolve;
27876
+ now;
27877
+ ttlMs;
27878
+ value;
27879
+ fetchedAt = 0;
27880
+ withDownload = false;
27881
+ inflight;
27882
+ /** Whether the in-flight read is allowed to install. */
27883
+ inflightDownload = false;
27884
+ /**
27885
+ * @param resolve - Reads the real answer; called at most once per window.
27886
+ * @param now - Clock seam.
27887
+ * @param ttlMs - How long one answer stays valid.
27888
+ */
27889
+ constructor(resolve, now = Date.now, ttlMs = BINARY_CACHE_TTL_MS) {
27890
+ this.resolve = resolve;
27891
+ this.now = now;
27892
+ this.ttlMs = ttlMs;
27893
+ }
27894
+ /** The cached answer, when one is still valid. */
27895
+ peek() {
27896
+ if (this.value === void 0) return void 0;
27897
+ return this.now() - this.fetchedAt < this.ttlMs ? this.value : void 0;
27898
+ }
27899
+ /**
27900
+ * Read the resolution, reusing a valid answer or one in-flight read.
27901
+ *
27902
+ * @param options - `force` re-reads the disk; `download` allows fetching a release.
27903
+ * @returns The executable (when one was found) and what was tried.
27904
+ */
27905
+ async read(options = {}) {
27906
+ if (options.force !== true) {
27907
+ const cached = this.peek();
27908
+ if (cached !== void 0 && (options.download !== true || this.withDownload || cached.binary !== void 0)) return cached;
27909
+ }
27910
+ const download = options.download !== false;
27911
+ if (this.inflight !== void 0) {
27912
+ if (!(download && !this.inflightDownload)) return this.inflight;
27913
+ await this.inflight.catch(() => void 0);
27914
+ }
27915
+ const promise = this.resolve({ download }).then((value) => {
27916
+ this.value = value;
27917
+ this.fetchedAt = this.now();
27918
+ this.withDownload = download;
27919
+ return value;
27920
+ }).finally(() => {
27921
+ if (this.inflight === promise) this.inflight = void 0;
27922
+ });
27923
+ this.inflight = promise;
27924
+ this.inflightDownload = download;
27925
+ return promise;
27926
+ }
27927
+ /** Forget the answer, e.g. because the configured path just changed. */
27928
+ invalidate() {
27929
+ this.value = void 0;
27930
+ this.fetchedAt = 0;
27931
+ this.withDownload = false;
27932
+ }
27933
+ };
27934
+ /**
27495
27935
  * Download and extract one release.
27496
27936
  *
27497
27937
  * The archive is fetched whole (bounded), hashed, and only then extracted; an
@@ -27622,24 +28062,41 @@ function findEndOfCentralDirectory(bytes) {
27622
28062
  *
27623
28063
  * @module dsh-chatgpt-subscription/host/antigravity-acp/login
27624
28064
  */
28065
+ /** How long the login launcher may run before it is considered detached. */
28066
+ const LOGIN_LAUNCH_BUDGET_MS = 1e4;
28067
+ /**
28068
+ * How long a launcher is watched for a start-up failure before it is left alone.
28069
+ *
28070
+ * A successful sign-in keeps the process alive until the browser callback lands,
28071
+ * so this may not wait for the exit: it only has to catch the failures that
28072
+ * happen before the CLI ever gets going - an executable that cannot be spawned,
28073
+ * or a command line the CLI rejects.
28074
+ */
28075
+ const LOGIN_FAILURE_WINDOW_MS = 1e3;
28076
+ /** Most stderr kept for that failure sentence; a login banner is not a diagnostic. */
28077
+ const LOGIN_STDERR_CAP = 2e3;
27625
28078
  /**
27626
28079
  * Start the official sign-in.
27627
28080
  *
27628
- * The process is spawned detached and its stdout/stderr are drained: on a desktop
27629
- * it opens the browser and exits once the callback lands, on a headless host it
27630
- * prints the URL it would have opened. Either way this call returns as soon as
27631
- * the process exists - it never waits for the user.
28081
+ * The process is spawned detached: on a desktop it opens the browser and exits
28082
+ * once the callback lands, on a headless host it prints the URL it would have
28083
+ * opened. Either way this call never waits for the user.
28084
+ *
28085
+ * What it *does* wait for is the failure that happens before the CLI gets going.
28086
+ * The command line is `agy acp --login`, and a rejected command line, a
28087
+ * misconfigured path or a binary that cannot be spawned all exit (or error)
28088
+ * within milliseconds - and the previous version reported "sign-in started" for
28089
+ * every one of them while discarding the only sentence that explained it. The
28090
+ * launcher is therefore watched for {@link LOGIN_FAILURE_WINDOW_MS}: a spawn
28091
+ * error, or a non-zero exit that left stderr behind, is returned as the reason.
27632
28092
  *
27633
28093
  * @param launch - The resolved executable.
27634
- * @returns whether a process was started.
28094
+ * @returns whether a process was started, and why it was not.
27635
28095
  */
27636
28096
  function startLogin(launch) {
28097
+ let child;
27637
28098
  try {
27638
- const child = spawn(launch.command, [
27639
- ...launch.args.slice(0, -1),
27640
- "acp",
27641
- "--login"
27642
- ], {
28099
+ child = spawn(launch.command, [...launch.args, "--login"], {
27643
28100
  detached: true,
27644
28101
  stdio: [
27645
28102
  "ignore",
@@ -27648,15 +28105,57 @@ function startLogin(launch) {
27648
28105
  ],
27649
28106
  windowsHide: true
27650
28107
  });
27651
- child.stderr?.resume();
27652
- child.unref();
27653
- return { started: true };
27654
28108
  } catch (error) {
27655
- return {
28109
+ return Promise.resolve({
27656
28110
  started: false,
27657
28111
  error: error instanceof Error ? error.message : String(error)
27658
- };
28112
+ });
27659
28113
  }
28114
+ return watchLauncher(child);
28115
+ }
28116
+ /**
28117
+ * Watch one launcher through its start-up window.
28118
+ *
28119
+ * @param child - The detached sign-in process.
28120
+ * @returns whether it started, and the CLI's own explanation when it did not.
28121
+ */
28122
+ function watchLauncher(child) {
28123
+ let stderr = "";
28124
+ child.stderr?.setEncoding("utf8");
28125
+ child.stderr?.on("data", (chunk) => {
28126
+ if (stderr.length < LOGIN_STDERR_CAP) stderr += chunk.slice(0, LOGIN_STDERR_CAP - stderr.length);
28127
+ });
28128
+ child.unref();
28129
+ return new Promise((resolve) => {
28130
+ let settled = false;
28131
+ const settle = (result) => {
28132
+ if (settled) return;
28133
+ settled = true;
28134
+ clearTimeout(windowTimer);
28135
+ clearTimeout(detachTimer);
28136
+ resolve(result);
28137
+ };
28138
+ const detail = () => stderr.trim().split(/\r?\n/u).filter((line) => line !== "").slice(-3).join(" ");
28139
+ const failed = (reason) => ({
28140
+ started: false,
28141
+ error: detail() === "" ? reason : reason + ": " + detail()
28142
+ });
28143
+ const windowTimer = setTimeout(() => settle({ started: true }), LOGIN_FAILURE_WINDOW_MS);
28144
+ windowTimer.unref?.();
28145
+ const detachTimer = setTimeout(() => {
28146
+ child.stderr?.removeAllListeners("data");
28147
+ child.removeAllListeners();
28148
+ }, LOGIN_LAUNCH_BUDGET_MS);
28149
+ detachTimer.unref?.();
28150
+ child.once("error", (error) => settle(failed(error.message)));
28151
+ child.once("exit", (code, signal) => {
28152
+ if (code === 0 || signal !== null) {
28153
+ settle({ started: true });
28154
+ return;
28155
+ }
28156
+ settle(failed(`The Antigravity CLI exited with code ${String(code ?? "null")} before sign-in began.`));
28157
+ });
28158
+ });
27660
28159
  }
27661
28160
  /**
27662
28161
  * Ask the agent whether it currently holds usable credentials.
@@ -27749,20 +28248,27 @@ const MAX_BODY_BYTES$8 = 64 * 1024;
27749
28248
  * host restarted twice in an afternoon still shows a current list.
27750
28249
  */
27751
28250
  const CATALOG_FRESHNESS_MS = 1440 * 60 * 1e3;
27752
- /** Build the status payload the card renders. */
27753
- async function readStatus(options) {
28251
+ /**
28252
+ * Build the status payload the card renders.
28253
+ *
28254
+ * @param options - The line's live state and actions.
28255
+ * @param read - `fresh` when this read is a user action rather than a poll.
28256
+ * @returns The status the card renders.
28257
+ */
28258
+ async function readStatus(options, read = {}) {
28259
+ const fresh = read.fresh === true;
27754
28260
  const settings = await options.settings.read();
27755
28261
  if (!settings.enabled) return disabledStatus(settings);
27756
- const resolved = await options.resolveBinary().catch(() => ({ error: "The executable could not be resolved." }));
28262
+ const resolved = await options.resolveBinary({ fresh }).catch(() => ({ error: "The executable could not be resolved." }));
27757
28263
  const catalog = await options.catalog.rehydrate();
27758
- const auth = resolved.binary === void 0 ? { authenticated: false } : await options.auth().catch(() => ({ authenticated: false }));
28264
+ const auth = resolved.binary === void 0 ? { authenticated: false } : await options.auth({ force: fresh }).catch(() => ({ authenticated: false }));
27759
28265
  const models = catalog?.models ?? [];
27760
28266
  const conflict = options.conflict();
27761
28267
  return {
27762
28268
  enabled: settings.enabled,
27763
28269
  binary: resolved.binary === void 0 ? {
27764
28270
  kind: "missing",
27765
- ...resolved.error === void 0 ? {} : { error: missingBinaryMessage(resolved.error) }
28271
+ ...resolved.error === void 0 ? {} : { error: resolved.deferred === true ? resolved.error : missingBinaryMessage(resolved.error) }
27766
28272
  } : {
27767
28273
  kind: resolved.binary.kind,
27768
28274
  path: resolved.binary.path,
@@ -27846,11 +28352,12 @@ function registerAntigravityAcpRoutes(ctx, options) {
27846
28352
  if (!sameSettings(await options.settings.read(), await options.settings.update(update))) ctx.emit?.("llm/adapters-updated");
27847
28353
  if (update.binaryPath !== void 0) {
27848
28354
  options.catalog.invalidate();
28355
+ options.invalidateBinary?.();
27849
28356
  await options.catalog.read({ force: true }).catch(() => void 0);
27850
28357
  }
27851
28358
  return sendJson$10(response, 200, {
27852
28359
  ok: true,
27853
- value: await readStatus(options)
28360
+ value: await readStatus(options, { fresh: true })
27854
28361
  });
27855
28362
  }
27856
28363
  if (path === "login/start") {
@@ -27873,7 +28380,7 @@ function registerAntigravityAcpRoutes(ctx, options) {
27873
28380
  if (method !== "GET") return sendMethodNotAllowed$9(response);
27874
28381
  return sendJson$10(response, 200, {
27875
28382
  ok: true,
27876
- value: await options.auth()
28383
+ value: await options.auth({ force: true })
27877
28384
  });
27878
28385
  }
27879
28386
  if (path === "logout") {
@@ -27919,6 +28426,7 @@ function registerAntigravityAcpRoutes(ctx, options) {
27919
28426
  ok: false,
27920
28427
  error: "Cross-origin request rejected."
27921
28428
  });
28429
+ options.invalidateBinary?.();
27922
28430
  const refreshed = await options.catalog.read({ force: true }).catch(() => void 0);
27923
28431
  await options.auth({ force: true }).catch(() => void 0);
27924
28432
  if (refreshed === void 0) return sendJson$10(response, 502, {
@@ -27927,7 +28435,7 @@ function registerAntigravityAcpRoutes(ctx, options) {
27927
28435
  });
27928
28436
  return sendJson$10(response, 200, {
27929
28437
  ok: true,
27930
- value: await readStatus(options)
28438
+ value: await readStatus(options, { fresh: true })
27931
28439
  });
27932
28440
  }
27933
28441
  return sendJson$10(response, 404, {
@@ -28015,8 +28523,17 @@ async function readRequestJson$10(request) {
28015
28523
  }
28016
28524
  //#endregion
28017
28525
  //#region src/host/antigravity-acp/auth-cache.ts
28018
- /** How long one probe answers for. */
28019
- const AUTH_CACHE_TTL_MS = 6e4;
28526
+ /**
28527
+ * How long one probe answers for.
28528
+ *
28529
+ * Ten minutes, not one. A probe is a whole `agy` process plus a `session/new`
28530
+ * against Google, and the card, the hub overview and the composer badge each poll
28531
+ * this route - at a one-minute window that was a process launch per minute for a
28532
+ * question whose answer changes only when the user signs in or out. Those two
28533
+ * events are exactly what invalidates the cache (`login/start`, `login/status`,
28534
+ * the refresh click), so the window does not delay a real state change.
28535
+ */
28536
+ const AUTH_CACHE_TTL_MS = 10 * 6e4;
28020
28537
  /** The cache itself. */
28021
28538
  var AcpAuthCache = class {
28022
28539
  probe;
@@ -28196,10 +28713,12 @@ function registerAntigravityAcpSubagent(ctx, options) {
28196
28713
  * working directory, and that is all.
28197
28714
  */
28198
28715
  function createProvider(options) {
28716
+ const cap = options.maxActiveRuns ?? 4;
28717
+ let active = 0;
28199
28718
  return {
28200
28719
  name: SUBAGENT_PROVIDER_NAME,
28201
28720
  capabilities: {
28202
- agentOptions: false,
28721
+ agentOptions: true,
28203
28722
  agentPreset: false,
28204
28723
  outputSchema: false,
28205
28724
  depthLimit: false
@@ -28208,27 +28727,44 @@ function createProvider(options) {
28208
28727
  async start(request) {
28209
28728
  const settings = await options.settings.read();
28210
28729
  if (!settings.enabled) throw new LlmError$1("The Antigravity (ACP) line is switched off. Enable it in the subscription overview before delegating to it.", "ACP_DISABLED");
28211
- const launch = await options.resolveLaunch();
28212
- const task = promptText(request.prompt);
28213
- let settled = false;
28214
- const running = startRun(launch, request.cwd, task, settings.permissionPolicy, options, request.signal);
28215
- return {
28216
- id: SUBAGENT_PROVIDER_NAME,
28217
- result: running.result,
28218
- dispose: async () => {
28219
- if (settled) return;
28220
- settled = true;
28221
- running.settle({
28222
- output: running.output(),
28223
- stopReason: "aborted"
28224
- });
28225
- await running.client.dispose().catch(() => void 0);
28226
- }
28730
+ if (active >= cap) throw acpError("ACP_SESSION_LIMIT", `${active} delegated runs are already in flight (limit ${cap}).`);
28731
+ active += 1;
28732
+ let released = false;
28733
+ const release = () => {
28734
+ if (released) return;
28735
+ released = true;
28736
+ active = Math.max(0, active - 1);
28227
28737
  };
28738
+ try {
28739
+ const launch = await options.resolveLaunch();
28740
+ const task = promptText(request.prompt);
28741
+ let settled = false;
28742
+ const running = startRun(launch, request.cwd, task, settings.permissionPolicy, options, request);
28743
+ running.result.then(release, release);
28744
+ return {
28745
+ id: SUBAGENT_PROVIDER_NAME,
28746
+ result: running.result,
28747
+ dispose: async () => {
28748
+ if (settled) return;
28749
+ settled = true;
28750
+ running.settle({
28751
+ output: running.output(),
28752
+ stopReason: "aborted"
28753
+ });
28754
+ await running.client.dispose().catch(() => void 0);
28755
+ }
28756
+ };
28757
+ } catch (error) {
28758
+ release();
28759
+ throw error;
28760
+ }
28228
28761
  }
28229
28762
  };
28230
28763
  }
28231
- function startRun(launch, cwd, task, permissionPolicy, options, signal) {
28764
+ function startRun(launch, cwd, task, permissionPolicy, options, request) {
28765
+ const signal = request.signal;
28766
+ const model = textField(request.agentOptions?.model);
28767
+ const effort = textField(request.agentOptions?.reasoningEffort);
28232
28768
  let settle = () => void 0;
28233
28769
  const result = new Promise((resolve) => {
28234
28770
  settle = resolve;
@@ -28296,6 +28832,16 @@ function startRun(launch, cwd, task, permissionPolicy, options, signal) {
28296
28832
  }));
28297
28833
  const sessionId = typeof session?.sessionId === "string" ? session.sessionId : void 0;
28298
28834
  if (sessionId === void 0) throw new Error("Antigravity ACP did not return a session id.");
28835
+ if (model !== void 0) await client.request("session/set_config_option", {
28836
+ sessionId,
28837
+ configId: "model",
28838
+ value: model
28839
+ });
28840
+ if (effort !== void 0) await client.request("session/set_config_option", {
28841
+ sessionId,
28842
+ configId: "thought_level",
28843
+ value: effort
28844
+ }).catch(() => void 0);
28299
28845
  const answer = asRecord$16(await withTimeout$11(client.request("session/prompt", {
28300
28846
  sessionId,
28301
28847
  prompt: [{
@@ -28333,6 +28879,10 @@ function startRun(launch, cwd, task, permissionPolicy, options, signal) {
28333
28879
  output
28334
28880
  };
28335
28881
  }
28882
+ /** A non-empty string, or undefined; the host's own values are untrusted input here. */
28883
+ function textField(value) {
28884
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
28885
+ }
28336
28886
  /** Flatten the prompt blocks a caller supplied into the one text the agent gets. */
28337
28887
  function promptText(prompt) {
28338
28888
  const parts = [];
@@ -97599,7 +98149,7 @@ function refreshSourceForDomain(domain) {
97599
98149
  * with that list — so a row living only in the fallback would drop out of the
97600
98150
  * picker the moment the catalog loaded.
97601
98151
  *
97602
- * The list is empty as of the 2026-11-04 read: all three ids are published now,
98152
+ * The list is empty as of the 2026-11-16 read: all three ids are published now,
97603
98153
  * with figures measured on the wire, and their rows therefore live in
97604
98154
  * {@link FALLBACK_MODELS} like any other. The seam stays rather than being
97605
98155
  * deleted because the gap it covers belongs to the gateway, not to those three
@@ -97610,7 +98160,7 @@ const UNPUBLISHED_MODELS = [];
97610
98160
  /**
97611
98161
  * Offline fallback catalog, transcribed from a live `/v3/config` read.
97612
98162
  *
97613
- * Last transcribed 2026-11-04 from both backends. Used when the gateway cannot
98163
+ * Last transcribed 2026-11-16 from both backends. Used when the gateway cannot
97614
98164
  * be reached (first run before sign-in, or a network failure); a reachable
97615
98165
  * gateway always wins.
97616
98166
  */
@@ -97701,7 +98251,7 @@ const FALLBACK_MODELS$1 = [
97701
98251
  ],
97702
98252
  defaultReasoningEffort: "high",
97703
98253
  canDisableThinking: false,
97704
- description: "DeepSeek 旗舰模型,支持 1M 上下文窗口,原生多模态"
98254
+ description: "DeepSeek · 修订版 1017 · 原生多模态模型,支持 1M 上下文"
97705
98255
  },
97706
98256
  {
97707
98257
  id: "deepseek-v4.1-flash-sg",
@@ -97740,7 +98290,7 @@ const FALLBACK_MODELS$1 = [
97740
98290
  ],
97741
98291
  defaultReasoningEffort: "high",
97742
98292
  canDisableThinking: false,
97743
- description: "原生多模态模型,擅长视觉理解与专业任务"
98293
+ description: "Z.ai · 原生多模态模型,擅长视觉理解与专业任务"
97744
98294
  },
97745
98295
  {
97746
98296
  id: "gpt-6-astra",
@@ -97782,11 +98332,8 @@ const FALLBACK_MODELS$1 = [
97782
98332
  contextWindow: 192e3,
97783
98333
  maxContextWindow: 192e3,
97784
98334
  maxTokens: 64e3,
97785
- regions: ["intl", "cn"],
97786
- credits: {
97787
- cn: "0.00",
97788
- intl: "0.00"
97789
- },
98335
+ regions: ["intl"],
98336
+ credits: { intl: "0.00" },
97790
98337
  supportsImage: true,
97791
98338
  reasoningEfforts: ["low", "high"],
97792
98339
  defaultReasoningEffort: "high",
@@ -97910,7 +98457,7 @@ const FALLBACK_MODELS$1 = [
97910
98457
  ],
97911
98458
  defaultReasoningEffort: "high",
97912
98459
  canDisableThinking: false,
97913
- description: "能力均衡,适合日常使用"
98460
+ description: "Z.ai · 旗舰模型,擅长复杂软件工程与长程智能体任务"
97914
98461
  },
97915
98462
  {
97916
98463
  id: "glm-5.2",
@@ -97927,7 +98474,7 @@ const FALLBACK_MODELS$1 = [
97927
98474
  reasoningEfforts: ["high"],
97928
98475
  defaultReasoningEffort: "high",
97929
98476
  canDisableThinking: false,
97930
- description: "1M 上下文,擅长长程任务"
98477
+ description: "Z.ai · 支持 1M 上下文,擅长长程任务"
97931
98478
  },
97932
98479
  {
97933
98480
  id: "minimax-m3.1-flash",
@@ -97950,7 +98497,7 @@ const FALLBACK_MODELS$1 = [
97950
98497
  ],
97951
98498
  defaultReasoningEffort: "max",
97952
98499
  canDisableThinking: false,
97953
- description: "原生多模态,擅长office、agentic、编程任务,推理速度优异"
98500
+ description: "MiniMax · 原生多模态,擅长办公、智能体与编程任务,推理速度优异"
97954
98501
  },
97955
98502
  {
97956
98503
  id: "kimi-k3.1-pro",
@@ -97971,7 +98518,7 @@ const FALLBACK_MODELS$1 = [
97971
98518
  ],
97972
98519
  defaultReasoningEffort: "high",
97973
98520
  canDisableThinking: false,
97974
- description: "Kimi 全新旗舰模型,3万亿级参数。办公、代码、3D 创作与长程 Agent 能力全面升级。"
98521
+ description: "Moonshot AI · 新一代旗舰,办公、编程、3D 创作、金融研究与建模及长程智能体任务"
97975
98522
  },
97976
98523
  {
97977
98524
  id: "kimi-k3.1-pro-highspeed",
@@ -98133,7 +98680,7 @@ const FALLBACK_MODELS$1 = [
98133
98680
  ],
98134
98681
  defaultReasoningEffort: "high",
98135
98682
  canDisableThinking: false,
98136
- description: ""
98683
+ description: "DeepSeek · 旗舰模型,支持 1M 上下文"
98137
98684
  },
98138
98685
  {
98139
98686
  id: "deepseek-v4-flash",
@@ -98205,7 +98752,7 @@ const FALLBACK_MODELS$1 = [
98205
98752
  ],
98206
98753
  defaultReasoningEffort: "high",
98207
98754
  canDisableThinking: false,
98208
- description: ""
98755
+ description: "MiniMax · 软件工程与办公工作流,涵盖调试与重构"
98209
98756
  },
98210
98757
  {
98211
98758
  id: "glm-5.0",
@@ -98301,7 +98848,7 @@ const FALLBACK_MODELS$1 = [
98301
98848
  ],
98302
98849
  defaultReasoningEffort: "high",
98303
98850
  canDisableThinking: false,
98304
- description: "擅长处理复杂的长程自主任务,前端开发能力突出,同时在知识工作与科研推理上表现出色。"
98851
+ description: "Moonshot AI · 擅长大型代码库开发与复杂长程自主任务,前端开发、知识工作与科研推理突出(前代模型)"
98305
98852
  },
98306
98853
  {
98307
98854
  id: "kimi-k2.8-preview",
@@ -98357,24 +98904,6 @@ const FALLBACK_MODELS$1 = [
98357
98904
  canDisableThinking: false,
98358
98905
  description: ""
98359
98906
  },
98360
- {
98361
- id: "hy3-x",
98362
- name: "Hy3",
98363
- contextWindow: 192e3,
98364
- maxContextWindow: 192e3,
98365
- maxTokens: 64e3,
98366
- regions: ["cn"],
98367
- credits: { cn: "0.05" },
98368
- supportsImage: true,
98369
- reasoningEfforts: [
98370
- "low",
98371
- "high",
98372
- "max"
98373
- ],
98374
- defaultReasoningEffort: "high",
98375
- canDisableThinking: false,
98376
- description: "混元思考模型,具有增强的推理能力"
98377
- },
98378
98907
  {
98379
98908
  id: "hy4-preview-x",
98380
98909
  name: "Hy4 preview",
@@ -98421,7 +98950,7 @@ const FALLBACK_MODELS$1 = [
98421
98950
  ],
98422
98951
  defaultReasoningEffort: "max",
98423
98952
  canDisableThinking: false,
98424
- description: "推理速度极快,编码能力强劲,并支持原生多模态输入的匿名大模型"
98953
+ description: "匿名模型 · 推理速度极快,编码能力强劲,支持原生多模态输入"
98425
98954
  },
98426
98955
  {
98427
98956
  id: "step-5-preview",
@@ -98439,7 +98968,7 @@ const FALLBACK_MODELS$1 = [
98439
98968
  ],
98440
98969
  defaultReasoningEffort: "high",
98441
98970
  canDisableThinking: false,
98442
- description: "阶跃 StepFun 面向真实任务的新一代旗舰基模"
98971
+ description: "StepFun · 新一代旗舰,编程、专业知识工作与多步骤智能体任务,支持 1M 上下文"
98443
98972
  },
98444
98973
  {
98445
98974
  id: "mimo-v2.6-pro",
@@ -98460,8 +98989,22 @@ const FALLBACK_MODELS$1 = [
98460
98989
  description: "Xiaomi · 旗舰推理模型,面向专业、复杂长程工作流,兼顾高阶科研与网络安全"
98461
98990
  },
98462
98991
  {
98463
- id: "hy4free",
98464
- name: "Hy4 Free",
98992
+ id: "hy4std",
98993
+ name: "Hy4",
98994
+ contextWindow: 1e6,
98995
+ maxContextWindow: 1e6,
98996
+ maxTokens: 64e3,
98997
+ regions: ["cn"],
98998
+ credits: { cn: "0.29" },
98999
+ supportsImage: true,
99000
+ reasoningEfforts: ["high"],
99001
+ defaultReasoningEffort: "high",
99002
+ canDisableThinking: false,
99003
+ description: "Tencent · 最新旗舰模型,擅长智能体任务与多模态理解,最大输入 960K"
99004
+ },
99005
+ {
99006
+ id: "hy4flash-free",
99007
+ name: "Hy4 Flash Free",
98465
99008
  contextWindow: 1e6,
98466
99009
  maxContextWindow: 1e6,
98467
99010
  maxTokens: 64e3,
@@ -98471,21 +99014,21 @@ const FALLBACK_MODELS$1 = [
98471
99014
  reasoningEfforts: ["high"],
98472
99015
  defaultReasoningEffort: "high",
98473
99016
  canDisableThinking: false,
98474
- description: "最新旗舰模型,Agent与多模专长"
99017
+ description: "更轻量、更高效的日常主力模型。适合日常办公等高频、规模化场景"
98475
99018
  },
98476
99019
  {
98477
- id: "hy4std",
98478
- name: "Hy4",
99020
+ id: "hy4flash",
99021
+ name: "Hy4 Flash",
98479
99022
  contextWindow: 1e6,
98480
99023
  maxContextWindow: 1e6,
98481
99024
  maxTokens: 64e3,
98482
99025
  regions: ["cn"],
98483
- credits: { cn: "0.29" },
99026
+ credits: { cn: "0.03" },
98484
99027
  supportsImage: true,
98485
99028
  reasoningEfforts: ["high"],
98486
99029
  defaultReasoningEffort: "high",
98487
99030
  canDisableThinking: false,
98488
- description: "最新旗舰模型,Agent与多模专长"
99031
+ description: "更轻量、更高效的日常主力模型。适合日常办公等高频、规模化场景"
98489
99032
  }
98490
99033
  ];
98491
99034
  /**
@@ -105566,10 +106109,21 @@ function apply(ctx, pluginConfig = {}) {
105566
106109
  getPreferences: () => preferences.status(),
105567
106110
  logger: ctx.logger
105568
106111
  });
105569
- const proxyFetch = proxyManager.createFetch();
105570
- const kimiCodeProxyFetch = proxyManager.createFetch({ headersTimeoutMs: TRANSPORT_HEADERS_TIMEOUT_MS });
106112
+ const lineProxyFetches = /* @__PURE__ */ new Map();
106113
+ const proxyFetchFor = (line) => {
106114
+ let fetchForLine = lineProxyFetches.get(line);
106115
+ if (fetchForLine === void 0) {
106116
+ fetchForLine = proxyManager.createFetch({
106117
+ line,
106118
+ ...line === "kimi-code" ? { headersTimeoutMs: TRANSPORT_HEADERS_TIMEOUT_MS } : {}
106119
+ });
106120
+ lineProxyFetches.set(line, fetchForLine);
106121
+ }
106122
+ return fetchForLine;
106123
+ };
106124
+ const proxyFetch = proxyFetchFor("codex-chatgpt");
105571
106125
  const providerLimits = readModelRequestLimits();
105572
- const baseFetchFor = (provider) => provider === "kimi-code" ? kimiCodeProxyFetch : proxyFetch;
106126
+ const baseFetchFor = (provider) => proxyFetchFor(provider === "claude" ? "claude-subscription" : provider);
105573
106127
  const modelFetch = Object.fromEntries(CONTROLLED_PROVIDERS.map((provider) => [provider, createControlledModelFetch(createDiagnosticFetch(baseFetchFor(provider), {
105574
106128
  provider,
105575
106129
  onRecord: (record) => ctx.logger.info("[provider-diagnostics] " + JSON.stringify(record))
@@ -105578,7 +106132,7 @@ function apply(ctx, pluginConfig = {}) {
105578
106132
  limits: providerLimits
105579
106133
  })]));
105580
106134
  const disposeCommandCodeRoutes = registerCommandCodeRoutes(ctx, commandCodeStore, commandCodeModelSettings, commandCodePreferences, {
105581
- fetchFn: proxyFetch,
106135
+ fetchFn: proxyFetchFor("command-code"),
105582
106136
  serving: () => commandCodeClaim.serving(),
105583
106137
  conflict: () => commandCodeClaim.conflict()
105584
106138
  }, commandCodeAccountPool);
@@ -105594,8 +106148,11 @@ function apply(ctx, pluginConfig = {}) {
105594
106148
  attachments: ctx.attachments
105595
106149
  }, ollamaAccountPool);
105596
106150
  const antigravityAcpSettings = new AntigravityAcpSettingsStore();
106151
+ const antigravityAcpBinary = new AcpBinaryCache(async (options) => {
106152
+ return resolveAcpBinary((await antigravityAcpSettings.read()).binaryPath, { download: options.download !== false });
106153
+ });
105597
106154
  const resolveAntigravityLaunch = async () => {
105598
- const resolved = await resolveAcpBinary((await antigravityAcpSettings.read()).binaryPath);
106155
+ const resolved = await antigravityAcpBinary.read({ download: true });
105599
106156
  if (resolved.binary === void 0) throw new Error(resolved.diagnostics.error ?? "No usable Antigravity CLI (agy) was found.");
105600
106157
  return {
105601
106158
  command: resolved.binary.path,
@@ -105621,7 +106178,15 @@ function apply(ctx, pluginConfig = {}) {
105621
106178
  attachments: ctx.attachments
105622
106179
  });
105623
106180
  antigravityAcpCatalog.rehydrate().catch(() => void 0);
105624
- const antigravityAcpAuth = new AcpAuthCache(() => probeAuthWithLaunch(resolveAntigravityLaunch));
106181
+ const antigravityAcpAuth = new AcpAuthCache(() => probeAuthWithLaunch(async () => {
106182
+ const resolved = await antigravityAcpBinary.read({ download: false });
106183
+ if (resolved.binary === void 0) throw new Error(resolved.diagnostics.error ?? "No usable Antigravity CLI (agy) was found.");
106184
+ return {
106185
+ command: resolved.binary.path,
106186
+ args: ["acp", "--disable-telemetry"],
106187
+ version: resolved.binary.version
106188
+ };
106189
+ }));
105625
106190
  const kimiCodeClaim = claimProviderRoute(ctx, {
105626
106191
  providerId: PROVIDER_ID$9,
105627
106192
  label: PROVIDER_NAME$8,
@@ -105644,7 +106209,7 @@ function apply(ctx, pluginConfig = {}) {
105644
106209
  const disposeOllamaRoutes = registerOllamaRoutes(ctx, {
105645
106210
  accountPool: ollamaAccountPool,
105646
106211
  modelSettings: ollamaModelSettings,
105647
- fetchFn: proxyFetch
106212
+ fetchFn: proxyFetchFor("ollama")
105648
106213
  });
105649
106214
  const antigravityAcpClaim = claimProviderRoute(ctx, {
105650
106215
  providerId: PROVIDER_ID$10,
@@ -105654,16 +106219,18 @@ function apply(ctx, pluginConfig = {}) {
105654
106219
  const disposeAntigravityAcpRoutes = registerAntigravityAcpRoutes(ctx, {
105655
106220
  settings: antigravityAcpSettings,
105656
106221
  catalog: antigravityAcpCatalog,
105657
- resolveBinary: async () => {
105658
- const resolved = await resolveAcpBinary((await antigravityAcpSettings.read()).binaryPath);
106222
+ resolveBinary: async (options) => {
106223
+ const resolved = await antigravityAcpBinary.read({ download: options?.fresh === true });
105659
106224
  return {
105660
106225
  binary: resolved.binary,
105661
- error: resolved.diagnostics.error
106226
+ error: resolved.diagnostics.error,
106227
+ deferred: resolved.diagnostics.deferred === true
105662
106228
  };
105663
106229
  },
106230
+ invalidateBinary: () => antigravityAcpBinary.invalidate(),
105664
106231
  login: async () => {
105665
106232
  try {
105666
- const started = startLogin(await resolveAntigravityLaunch());
106233
+ const started = await startLogin(await resolveAntigravityLaunch());
105667
106234
  antigravityAcpAuth.invalidate();
105668
106235
  return started;
105669
106236
  } catch (error) {
@@ -105678,7 +106245,7 @@ function apply(ctx, pluginConfig = {}) {
105678
106245
  occupancy: () => antigravityAcpAdapter.occupancy(),
105679
106246
  runDoctor: () => runDoctor({
105680
106247
  resolveBinary: async () => {
105681
- const resolved = await resolveAcpBinary((await antigravityAcpSettings.read()).binaryPath);
106248
+ const resolved = await antigravityAcpBinary.read({ download: true });
105682
106249
  return resolved.binary === void 0 ? { error: resolved.diagnostics.error } : {
105683
106250
  path: resolved.binary.path,
105684
106251
  version: resolved.binary.version,
@@ -105706,7 +106273,7 @@ function apply(ctx, pluginConfig = {}) {
105706
106273
  adapter: commandCodeAdapter
105707
106274
  });
105708
106275
  const disposeKimiCodeRoutes = registerKimiCodeRoutes(ctx, kimiCodeStore, kimiCodeModelSettings, kimiCodePreferences, {
105709
- fetchFn: proxyFetch,
106276
+ fetchFn: proxyFetchFor("kimi-code"),
105710
106277
  serving: () => kimiCodeClaim.serving(),
105711
106278
  conflict: () => kimiCodeClaim.conflict()
105712
106279
  }, kimiCodeAccountPool);
@@ -105720,7 +106287,7 @@ function apply(ctx, pluginConfig = {}) {
105720
106287
  })
105721
106288
  });
105722
106289
  const disposeGlmCodingPlanRoutes = registerGlmCodingPlanRoutes(ctx, glmCodingPlanSettingsSource(glmCodingPlanPreferences, glmCodingPlanModelSettings), {
105723
- fetchFn: proxyFetch,
106290
+ fetchFn: proxyFetchFor("glm-coding-plan"),
105724
106291
  serving: () => glmCodingPlanClaim.serving(),
105725
106292
  conflict: () => glmCodingPlanClaim.conflict(),
105726
106293
  accountPool: glmCodingPlanAccountPool
@@ -105743,7 +106310,7 @@ function apply(ctx, pluginConfig = {}) {
105743
106310
  minimaxCodeAppVersion = void 0;
105744
106311
  }
105745
106312
  const minimaxCodeCheckin = new MinimaxCodeCheckinService(minimaxCodeAccountPool, {
105746
- fetchFn: proxyFetch,
106313
+ fetchFn: proxyFetchFor("minimax-code"),
105747
106314
  settings: () => minimaxCodePreferences.status().checkin ?? { enabled: true },
105748
106315
  ready: () => minimaxCodePreferences.ready(),
105749
106316
  ...minimaxCodeAppVersion === void 0 ? {} : { appVersion: minimaxCodeAppVersion },
@@ -105757,7 +106324,7 @@ function apply(ctx, pluginConfig = {}) {
105757
106324
  const minimaxCodeCheckinTimer = setInterval(minimaxCodeCheckinTick, CHECKIN_TICK_MS$1);
105758
106325
  minimaxCodeCheckinTick();
105759
106326
  const disposeMinimaxCodeRoutes = registerMinimaxCodeRoutes(ctx, minimaxCodeStore, {
105760
- fetchFn: proxyFetch,
106327
+ fetchFn: proxyFetchFor("minimax-code"),
105761
106328
  serving: () => minimaxCodeClaim.serving(),
105762
106329
  conflict: () => minimaxCodeClaim.conflict(),
105763
106330
  accountPool: minimaxCodeAccountPool,
@@ -105774,7 +106341,7 @@ function apply(ctx, pluginConfig = {}) {
105774
106341
  })
105775
106342
  });
105776
106343
  const disposeClaudeRoutes = registerClaudeRoutes(ctx, claudeStore, claudeModelSettings, claudePreferences, {
105777
- fetchFn: proxyFetch,
106344
+ fetchFn: proxyFetchFor("claude-subscription"),
105778
106345
  serving: () => claudeClaim.serving(),
105779
106346
  conflict: () => claudeClaim.conflict(),
105780
106347
  accountPool: claudeAccountPool
@@ -105790,14 +106357,14 @@ function apply(ctx, pluginConfig = {}) {
105790
106357
  })
105791
106358
  });
105792
106359
  const disposeStepCodeRoutes = registerStepCodeRoutes(ctx, stepCodeSettingsSource(stepCodePreferences, stepCodeModelSettings), {
105793
- fetchFn: proxyFetch,
106360
+ fetchFn: proxyFetchFor("step-code"),
105794
106361
  serving: () => stepCodeClaim.serving(),
105795
106362
  conflict: () => stepCodeClaim.conflict(),
105796
106363
  accountPool: stepCodeAccountPool,
105797
106364
  promptCache: promptCacheOverrides["step-code"]
105798
106365
  });
105799
106366
  const clinePassLine = createClinePassLine(ctx, {
105800
- fetchFn: proxyFetch,
106367
+ fetchFn: proxyFetchFor("cline-pass"),
105801
106368
  modelFetchFn: modelFetch["cline-pass"],
105802
106369
  attachments: ctx.attachments
105803
106370
  });
@@ -105811,17 +106378,17 @@ function apply(ctx, pluginConfig = {}) {
105811
106378
  })
105812
106379
  });
105813
106380
  const disposeQoderRoutes = registerQoderRoutes(ctx, qoderSettingsSource(qoderPreferences, qoderModelSettings), {
105814
- fetchFn: proxyFetch,
106381
+ fetchFn: proxyFetchFor("qoder"),
105815
106382
  serving: () => qoderClaim.serving(),
105816
106383
  conflict: () => qoderClaim.conflict(),
105817
106384
  accountPool: qoderAccountPool
105818
106385
  });
105819
106386
  warmQoderCatalogOnStartup(ctx, {
105820
- fetchFn: proxyFetch,
106387
+ fetchFn: proxyFetchFor("qoder"),
105821
106388
  accountPool: qoderAccountPool
105822
106389
  }).catch(() => void 0);
105823
106390
  const openDesignLine = createOpenDesignLine(ctx, {
105824
- fetchFn: proxyFetch,
106391
+ fetchFn: proxyFetchFor("opendesign"),
105825
106392
  modelFetchFn: modelFetch["opendesign"],
105826
106393
  attachments: ctx.attachments
105827
106394
  });
@@ -105836,7 +106403,7 @@ function apply(ctx, pluginConfig = {}) {
105836
106403
  })
105837
106404
  });
105838
106405
  const workBuddyCheckin = new WorkBuddyCheckinService(workBuddyStore, {
105839
- fetchFn: proxyFetch,
106406
+ fetchFn: proxyFetchFor("workbuddy-subscription"),
105840
106407
  settings: () => workBuddyPreferences.status().checkin,
105841
106408
  ready: () => workBuddyPreferences.ready(),
105842
106409
  logger: ctx.logger
@@ -105849,7 +106416,7 @@ function apply(ctx, pluginConfig = {}) {
105849
106416
  const workBuddyCheckinTimer = setInterval(workBuddyCheckinTick, CHECKIN_TICK_MS);
105850
106417
  workBuddyCheckinTick();
105851
106418
  const disposeWorkBuddyRoutes = registerWorkBuddyRoutes(ctx, workBuddyStore, workBuddyModelSettings, workBuddyPreferences, {
105852
- fetchFn: proxyFetch,
106419
+ fetchFn: proxyFetchFor("workbuddy-subscription"),
105853
106420
  serving: () => workBuddyClaim.serving(),
105854
106421
  conflict: () => workBuddyClaim.conflict(),
105855
106422
  accountPool: workBuddyAccountPool,
@@ -106174,14 +106741,14 @@ function apply(ctx, pluginConfig = {}) {
106174
106741
  const disposeAdapter = ctx.llm.registerAdapter([PROVIDER_ID$13], adapter);
106175
106742
  const mediaToolsEnabled = pluginConfig.mediaTools?.get() !== false;
106176
106743
  const disposeImageTool = mediaToolsEnabled ? ctx.tools.register(createCodexImageTool(oauth, ctx.attachments, { fetchFn: proxyFetch })) : () => void 0;
106177
- const disposeVideoTool = mediaToolsEnabled ? ctx.tools.register(createKimiVideoTool(ctx, { fetchFn: proxyFetch })) : () => void 0;
106744
+ const disposeVideoTool = mediaToolsEnabled ? ctx.tools.register(createKimiVideoTool(ctx, { fetchFn: proxyFetchFor("kimi-code") })) : () => void 0;
106178
106745
  const minimaxMediaToolsEnabled = mediaToolsEnabled && minimaxCodePreferences.status().enabled;
106179
106746
  const disposeMinimaxUnderstandVideoTool = minimaxMediaToolsEnabled ? ctx.tools.register(createMinimaxUnderstandVideoTool(ctx, {
106180
- fetchFn: proxyFetch,
106747
+ fetchFn: proxyFetchFor("minimax-code"),
106181
106748
  pool: minimaxCodeAccountPool
106182
106749
  })) : () => void 0;
106183
106750
  const disposeMinimaxGenerateVideoTool = minimaxMediaToolsEnabled ? ctx.tools.register(createMinimaxGenerateVideoTool(ctx, {
106184
- fetchFn: proxyFetch,
106751
+ fetchFn: proxyFetchFor("minimax-code"),
106185
106752
  pool: minimaxCodeAccountPool
106186
106753
  })) : () => void 0;
106187
106754
  ctx.inject(["web"], (ctx) => {