@omnicross/subscriptions 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,60 +1,21 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7; var _class8;
2
+
3
+
29
4
 
30
- // src/index.ts
31
- var src_exports = {};
32
- __export(src_exports, {
33
- SubscriptionAccountService: () => SubscriptionAccountService,
34
- SubscriptionDispatcher: () => SubscriptionDispatcher,
35
- SubscriptionProviderRegistry: () => SubscriptionProviderRegistry,
36
- claudeOAuth: () => claude_exports,
37
- codexOAuth: () => codex_exports,
38
- geminiOAuth: () => gemini_exports,
39
- getSubscriptionAccountService: () => getSubscriptionAccountService,
40
- getSubscriptionProviderRegistry: () => getSubscriptionProviderRegistry,
41
- setSubscriptionAccountService: () => setSubscriptionAccountService,
42
- setSubscriptionProviderRegistry: () => setSubscriptionProviderRegistry
43
- });
44
- module.exports = __toCommonJS(src_exports);
5
+ var _chunkTPW5Q25Ycjs = require('./chunk-TPW5Q25Y.cjs');
45
6
 
46
7
  // src/auth/OAuthBearerAuthStrategy.ts
47
8
  var REFRESH_LEAD_MS = 5 * 6e4;
48
- var OAuthBearerAuthStrategy = class {
49
- constructor(providerId, tokens, mutex) {
9
+ var OAuthBearerAuthStrategy = (_class = class {
10
+ constructor(providerId, tokens, mutex) {;_class.prototype.__init.call(this);
50
11
  this.tokens = tokens;
51
12
  this.mutex = mutex;
52
13
  this.providerId = providerId;
53
14
  }
54
- tokens;
55
- mutex;
56
- kind = "oauth-bearer";
57
- providerId;
15
+
16
+
17
+ __init() {this.kind = "oauth-bearer"}
18
+
58
19
  async applyHeaders(headers, _hints) {
59
20
  const token = await this.resolveAccessToken();
60
21
  if (!token) {
@@ -75,7 +36,7 @@ var OAuthBearerAuthStrategy = class {
75
36
  async describeStatus() {
76
37
  const config = await this.tokens.getFullConfig();
77
38
  const entry = this.providerId === "codex" ? config.codex : config.gemini;
78
- if (!entry?.accessToken) {
39
+ if (!_optionalChain([entry, 'optionalAccess', _ => _.accessToken])) {
79
40
  return { providerId: this.providerId, ok: false, reason: "missing-credential" };
80
41
  }
81
42
  if (entry.status === "expired") {
@@ -92,7 +53,7 @@ var OAuthBearerAuthStrategy = class {
92
53
  async resolveAccessToken() {
93
54
  const config = await this.tokens.getFullConfig();
94
55
  const entry = this.providerId === "codex" ? config.codex : config.gemini;
95
- if (!entry?.accessToken) return null;
56
+ if (!_optionalChain([entry, 'optionalAccess', _2 => _2.accessToken])) return null;
96
57
  const expiresAtMs = entry.expiresAt ? new Date(entry.expiresAt).getTime() : 0;
97
58
  const expiringSoon = expiresAtMs > 0 && Date.now() >= expiresAtMs - REFRESH_LEAD_MS;
98
59
  if (expiringSoon && entry.refreshToken) {
@@ -102,23 +63,23 @@ var OAuthBearerAuthStrategy = class {
102
63
  if (!refreshed) return null;
103
64
  const fresh = await this.tokens.getFullConfig();
104
65
  const freshEntry = this.providerId === "codex" ? fresh.codex : fresh.gemini;
105
- return freshEntry?.accessToken ?? null;
66
+ return _nullishCoalesce(_optionalChain([freshEntry, 'optionalAccess', _3 => _3.accessToken]), () => ( null));
106
67
  }
107
68
  if (entry.status === "expired") return null;
108
69
  return entry.accessToken;
109
70
  }
110
- };
71
+ }, _class);
111
72
 
112
73
  // src/auth/PassThroughAuthStrategy.ts
113
- var PassThroughAuthStrategy = class {
114
- constructor(tokens, mutex) {
74
+ var PassThroughAuthStrategy = (_class2 = class {
75
+ constructor(tokens, mutex) {;_class2.prototype.__init2.call(this);_class2.prototype.__init3.call(this);
115
76
  this.tokens = tokens;
116
77
  this.mutex = mutex;
117
78
  }
118
- tokens;
119
- mutex;
120
- kind = "pass-through";
121
- providerId = "claude";
79
+
80
+
81
+ __init2() {this.kind = "pass-through"}
82
+ __init3() {this.providerId = "claude"}
122
83
  async applyHeaders(headers, _hints) {
123
84
  const token = await this.tokens.getValidClaudeAccessToken();
124
85
  if (!token) return;
@@ -137,7 +98,7 @@ var PassThroughAuthStrategy = class {
137
98
  async describeStatus() {
138
99
  const config = await this.tokens.getFullConfig();
139
100
  const claude = config.claude;
140
- if (!claude?.accessToken) {
101
+ if (!_optionalChain([claude, 'optionalAccess', _4 => _4.accessToken])) {
141
102
  return { providerId: "claude", ok: false, reason: "missing-credential" };
142
103
  }
143
104
  if (claude.status === "expired") {
@@ -150,11 +111,11 @@ var PassThroughAuthStrategy = class {
150
111
  }
151
112
  return { providerId: "claude", ok: true, expiresAt: claude.expiresAt };
152
113
  }
153
- };
114
+ }, _class2);
154
115
 
155
116
  // src/auth/RefreshMutex.ts
156
- var RefreshMutex = class {
157
- inflight = /* @__PURE__ */ new Map();
117
+ var RefreshMutex = (_class3 = class {constructor() { _class3.prototype.__init4.call(this); }
118
+ __init4() {this.inflight = /* @__PURE__ */ new Map()}
158
119
  /**
159
120
  * Run `task()` exclusively for `key`. If another caller is already running
160
121
  * for the same key, this call awaits the existing promise instead of
@@ -173,24 +134,24 @@ var RefreshMutex = class {
173
134
  this.inflight.set(key, promise);
174
135
  return promise;
175
136
  }
176
- };
137
+ }, _class3);
177
138
 
178
139
  // src/auth/StaticBearerAuthStrategy.ts
179
140
  var ANTHROPIC_SHAPE_PATH = "/v1/messages";
180
- var StaticBearerAuthStrategy = class {
181
- constructor(tokens) {
141
+ var StaticBearerAuthStrategy = (_class4 = class {
142
+ constructor(tokens) {;_class4.prototype.__init5.call(this);_class4.prototype.__init6.call(this);
182
143
  this.tokens = tokens;
183
144
  }
184
- tokens;
185
- kind = "static-bearer";
186
- providerId = "opencodego";
145
+
146
+ __init5() {this.kind = "static-bearer"}
147
+ __init6() {this.providerId = "opencodego"}
187
148
  async applyHeaders(headers, hints) {
188
149
  const key = await this.tokens.getValidOpenCodeGoApiKey();
189
150
  if (!key) {
190
151
  return;
191
152
  }
192
153
  headers["Authorization"] = `Bearer ${key}`;
193
- if (hints?.upstreamUrl?.includes(ANTHROPIC_SHAPE_PATH)) {
154
+ if (_optionalChain([hints, 'optionalAccess', _5 => _5.upstreamUrl, 'optionalAccess', _6 => _6.includes, 'call', _7 => _7(ANTHROPIC_SHAPE_PATH)])) {
194
155
  headers["x-api-key"] = key;
195
156
  }
196
157
  }
@@ -200,7 +161,7 @@ var StaticBearerAuthStrategy = class {
200
161
  async describeStatus() {
201
162
  const config = await this.tokens.getFullConfig();
202
163
  const oc = config.opencodego;
203
- if (!oc?.apiKey) {
164
+ if (!_optionalChain([oc, 'optionalAccess', _8 => _8.apiKey])) {
204
165
  return { providerId: "opencodego", ok: false, reason: "missing-credential" };
205
166
  }
206
167
  if (oc.status === "error") {
@@ -208,7 +169,7 @@ var StaticBearerAuthStrategy = class {
208
169
  }
209
170
  return { providerId: "opencodego", ok: true };
210
171
  }
211
- };
172
+ }, _class4);
212
173
 
213
174
  // src/SubscriptionAccountService.ts
214
175
  var DISPLAY_NAMES = {
@@ -217,10 +178,10 @@ var DISPLAY_NAMES = {
217
178
  gemini: "Gemini (Google OAuth)",
218
179
  opencodego: "OpenCodeGo (Bearer key)"
219
180
  };
220
- var SubscriptionAccountService = class {
221
- mutex = new RefreshMutex();
222
- strategies;
223
- constructor(tokens) {
181
+ var SubscriptionAccountService = (_class5 = class {
182
+ __init7() {this.mutex = new RefreshMutex()}
183
+
184
+ constructor(tokens) {;_class5.prototype.__init7.call(this);
224
185
  this.strategies = /* @__PURE__ */ new Map([
225
186
  ["claude", new PassThroughAuthStrategy(tokens, this.mutex)],
226
187
  ["codex", new OAuthBearerAuthStrategy("codex", tokens, this.mutex)],
@@ -230,7 +191,7 @@ var SubscriptionAccountService = class {
230
191
  }
231
192
  /** Returns the strategy bound to a subscription provider, or `null` for unknown ids. */
232
193
  getStrategy(providerId) {
233
- return this.strategies.get(providerId) ?? null;
194
+ return _nullishCoalesce(this.strategies.get(providerId), () => ( null));
234
195
  }
235
196
  /** Diagnostic for the `subscription:status` IPC. */
236
197
  async getStatus(providerId) {
@@ -253,7 +214,7 @@ var SubscriptionAccountService = class {
253
214
  }
254
215
  return entries;
255
216
  }
256
- };
217
+ }, _class5);
257
218
  var _moduleSingleton = null;
258
219
  function setSubscriptionAccountService(svc) {
259
220
  _moduleSingleton = svc;
@@ -262,48 +223,32 @@ function getSubscriptionAccountService() {
262
223
  return _moduleSingleton;
263
224
  }
264
225
 
265
- // ../core/src/outbound-api/subscriptionRegistryPort.ts
266
- var _registry = null;
267
- function setSubscriptionRegistryForOutbound(registry) {
268
- _registry = registry;
269
- }
226
+ // src/SubscriptionProviderRegistry.ts
270
227
 
271
- // ../core/src/transformer/transformers/GeminiCodeAssistTransformer.ts
272
- var DEFAULT_CODE_ASSIST_ENDPOINT = "https://cloudcode-pa.googleapis.com";
273
- var DEFAULT_CODE_ASSIST_API_VERSION = "v1internal";
274
- function resolveCodeAssistEndpoint() {
275
- return (process.env.CODE_ASSIST_ENDPOINT || DEFAULT_CODE_ASSIST_ENDPOINT).replace(/\/+$/, "");
276
- }
277
- function resolveCodeAssistApiVersion() {
278
- return process.env.CODE_ASSIST_API_VERSION || DEFAULT_CODE_ASSIST_API_VERSION;
279
- }
280
- function buildCodeAssistUrl(stream) {
281
- const base = resolveCodeAssistEndpoint();
282
- const version = resolveCodeAssistApiVersion();
283
- const method = stream ? "streamGenerateContent?alt=sse" : "generateContent";
284
- return `${base}/${version}:${method}`;
285
- }
228
+
229
+ var _subscriptionRegistryPort = require('@omnicross/core/outbound-api/subscriptionRegistryPort');
230
+ var _GeminiCodeAssistTransformer = require('@omnicross/core/transformer/transformers/GeminiCodeAssistTransformer');
286
231
 
287
232
  // src/opencodego/CircuitBreaker.ts
288
- var CircuitBreaker = class {
289
- state = "closed";
233
+ var CircuitBreaker = (_class6 = class {
234
+ __init8() {this.state = "closed"}
290
235
  /** CONSECUTIVE failures while closed (reset by any closed success). */
291
- failureCount = 0;
236
+ __init9() {this.failureCount = 0}
292
237
  /** Successes accumulated in the current half-open probe window. */
293
- successCount = 0;
238
+ __init10() {this.successCount = 0}
294
239
  /** Test calls admitted in the current half-open window (cap = halfOpenMaxCalls). */
295
- halfOpenCalls = 0;
240
+ __init11() {this.halfOpenCalls = 0}
296
241
  /** `now()` at the last recorded failure — drives the open→half-open elapsed check. */
297
- lastFailureTime = 0;
298
- threshold;
299
- openMs;
300
- halfOpenMaxCalls;
301
- now;
302
- constructor(opts = {}) {
303
- this.threshold = opts.threshold ?? 3;
304
- this.openMs = opts.openMs ?? 3e4;
305
- this.halfOpenMaxCalls = opts.halfOpenMaxCalls ?? 3;
306
- this.now = opts.now ?? Date.now;
242
+ __init12() {this.lastFailureTime = 0}
243
+
244
+
245
+
246
+
247
+ constructor(opts = {}) {;_class6.prototype.__init8.call(this);_class6.prototype.__init9.call(this);_class6.prototype.__init10.call(this);_class6.prototype.__init11.call(this);_class6.prototype.__init12.call(this);
248
+ this.threshold = _nullishCoalesce(opts.threshold, () => ( 3));
249
+ this.openMs = _nullishCoalesce(opts.openMs, () => ( 3e4));
250
+ this.halfOpenMaxCalls = _nullishCoalesce(opts.halfOpenMaxCalls, () => ( 3));
251
+ this.now = _nullishCoalesce(opts.now, () => ( Date.now));
307
252
  }
308
253
  /** Current state (diagnostics / tests). */
309
254
  getState() {
@@ -382,13 +327,13 @@ var CircuitBreaker = class {
382
327
  this.state = "open";
383
328
  }
384
329
  }
385
- };
386
- var CircuitBreakerRegistry = class {
387
- constructor(options = {}) {
330
+ }, _class6);
331
+ var CircuitBreakerRegistry = (_class7 = class {
332
+ constructor(options = {}) {;_class7.prototype.__init13.call(this);
388
333
  this.options = options;
389
334
  }
390
- options;
391
- breakers = /* @__PURE__ */ new Map();
335
+
336
+ __init13() {this.breakers = /* @__PURE__ */ new Map()}
392
337
  /** Get (or lazily create) the breaker for a model id. */
393
338
  get(modelId) {
394
339
  let breaker = this.breakers.get(modelId);
@@ -410,7 +355,7 @@ var CircuitBreakerRegistry = class {
410
355
  recordFailure(modelId) {
411
356
  this.get(modelId).recordFailure();
412
357
  }
413
- };
358
+ }, _class7);
414
359
 
415
360
  // src/opencodego/defaults.ts
416
361
  var DEFAULT_OPENCODEGO_LONG_CONTEXT_THRESHOLD = 8e4;
@@ -545,7 +490,7 @@ function classifyZenShape(modelId) {
545
490
  return "chat";
546
491
  }
547
492
  function resolveOpenCodeGoShape(entry) {
548
- const half = entry.provider ?? "go";
493
+ const half = _nullishCoalesce(entry.provider, () => ( "go"));
549
494
  if (half === "zen") return classifyZenShape(entry.modelId);
550
495
  const normalized = entry.modelId.toLowerCase();
551
496
  if (GO_ANTHROPIC_SHAPE_PREFIXES.some((p) => normalized.startsWith(p))) {
@@ -555,12 +500,12 @@ function resolveOpenCodeGoShape(entry) {
555
500
  }
556
501
  function resolveOpenCodeGoHalf(modelId, config) {
557
502
  if (!config) return "go";
558
- for (const entry of Object.values(config.modelMap ?? {})) {
559
- if (entry?.modelId === modelId) return entry.provider ?? "go";
503
+ for (const entry of Object.values(_nullishCoalesce(config.modelMap, () => ( {})))) {
504
+ if (_optionalChain([entry, 'optionalAccess', _9 => _9.modelId]) === modelId) return _nullishCoalesce(entry.provider, () => ( "go"));
560
505
  }
561
- for (const list of Object.values(config.fallbacks ?? {})) {
562
- for (const entry of list ?? []) {
563
- if (entry?.modelId === modelId) return entry.provider ?? "go";
506
+ for (const list of Object.values(_nullishCoalesce(config.fallbacks, () => ( {})))) {
507
+ for (const entry of _nullishCoalesce(list, () => ( []))) {
508
+ if (_optionalChain([entry, 'optionalAccess', _10 => _10.modelId]) === modelId) return _nullishCoalesce(entry.provider, () => ( "go"));
564
509
  }
565
510
  }
566
511
  return "go";
@@ -660,11 +605,11 @@ function hasBackgroundPattern(loweredSlices) {
660
605
  return containsAny(loweredSlices, BACKGROUND_KEYWORDS);
661
606
  }
662
607
  function resolveOpenCodeGoScenario(summary, config) {
663
- const longContextThreshold = config?.modelMap?.long_context?.contextThreshold ?? DEFAULT_OPENCODEGO_LONG_CONTEXT_THRESHOLD;
608
+ const longContextThreshold = _nullishCoalesce(_optionalChain([config, 'optionalAccess', _11 => _11.modelMap, 'optionalAccess', _12 => _12.long_context, 'optionalAccess', _13 => _13.contextThreshold]), () => ( DEFAULT_OPENCODEGO_LONG_CONTEXT_THRESHOLD));
664
609
  if (summary.estimatedInputTokens >= longContextThreshold) {
665
610
  return "long_context";
666
611
  }
667
- const rawSlices = summary.matchText ?? [];
612
+ const rawSlices = _nullishCoalesce(summary.matchText, () => ( []));
668
613
  const loweredSlices = toLowerSlices(summary.matchText);
669
614
  if (hasComplexPattern(loweredSlices)) return "complex";
670
615
  if (hasThinkingPattern(loweredSlices, rawSlices)) return "think";
@@ -692,8 +637,8 @@ function resolveOpenCodeGoTarget(modelId, config) {
692
637
  const shape = resolveOpenCodeGoShape({ provider: half, modelId });
693
638
  return { half, shape };
694
639
  }
695
- var SubscriptionProviderRegistry = class {
696
- constructor(accounts, tokens) {
640
+ var SubscriptionProviderRegistry = (_class8 = class {
641
+ constructor(accounts, tokens) {;_class8.prototype.__init14.call(this);
697
642
  this.accounts = accounts;
698
643
  this.tokens = tokens;
699
644
  const claude = this.accounts.getStrategy("claude");
@@ -765,7 +710,7 @@ var SubscriptionProviderRegistry = class {
765
710
  // (resolved once per account via `GeminiCodeAssistProjectResolver`).
766
711
  // `resolveUpstreamUrl` ignores the model (Code Assist has no per-model
767
712
  // path); the URL is the version-segment colon-method endpoint.
768
- resolveUpstreamUrl: (_model) => buildCodeAssistUrl(false),
713
+ resolveUpstreamUrl: (_model) => _GeminiCodeAssistTransformer.buildCodeAssistUrl.call(void 0, false),
769
714
  providerTransformerNames: ["gemini-code-assist"],
770
715
  modelTransformerNames: []
771
716
  }
@@ -790,7 +735,7 @@ var SubscriptionProviderRegistry = class {
790
735
  resolveUpstreamUrl: (model, config) => {
791
736
  const oc = config;
792
737
  const { half, shape } = resolveOpenCodeGoTarget(model, oc);
793
- const override = half === "zen" ? oc?.zenBaseUrl : oc?.baseUrl;
738
+ const override = half === "zen" ? _optionalChain([oc, 'optionalAccess', _14 => _14.zenBaseUrl]) : _optionalChain([oc, 'optionalAccess', _15 => _15.baseUrl]);
794
739
  return buildOpenCodeGoUrl(half, shape, override);
795
740
  },
796
741
  // zen seam (Decision 3): vary the provider transformer chain by resolved
@@ -808,7 +753,7 @@ var SubscriptionProviderRegistry = class {
808
753
  modelTransformerNames: [],
809
754
  modelMapper: (sdkModel, summary, config) => {
810
755
  const scenario = resolveOpenCodeGoScenario(summary, config);
811
- const entry = config?.modelMap?.[scenario] ?? config?.modelMap?.default ?? DEFAULT_OPENCODEGO_MODEL_MAP[scenario] ?? DEFAULT_OPENCODEGO_MODEL_MAP.default;
756
+ const entry = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([config, 'optionalAccess', _16 => _16.modelMap, 'optionalAccess', _17 => _17[scenario]]), () => ( _optionalChain([config, 'optionalAccess', _18 => _18.modelMap, 'optionalAccess', _19 => _19.default]))), () => ( DEFAULT_OPENCODEGO_MODEL_MAP[scenario])), () => ( DEFAULT_OPENCODEGO_MODEL_MAP.default));
812
757
  if (!entry) {
813
758
  return { resolvedModel: sdkModel, scenario };
814
759
  }
@@ -827,7 +772,7 @@ var SubscriptionProviderRegistry = class {
827
772
  // wedge permanently in half-open). When NO circuit is open this returns
828
773
  // the same first non-attempted entry as the prior `!attempted` filter.
829
774
  nextFallback: (scenario, attempted, config) => {
830
- const list = config?.fallbacks?.[scenario] ?? DEFAULT_OPENCODEGO_FALLBACKS[scenario] ?? [];
775
+ const list = _nullishCoalesce(_nullishCoalesce(_optionalChain([config, 'optionalAccess', _20 => _20.fallbacks, 'optionalAccess', _21 => _21[scenario]]), () => ( DEFAULT_OPENCODEGO_FALLBACKS[scenario])), () => ( []));
831
776
  for (const entry of list) {
832
777
  if (attempted.includes(entry.modelId)) continue;
833
778
  if (this.breaker.allowRequest(entry.modelId)) return entry;
@@ -846,9 +791,9 @@ var SubscriptionProviderRegistry = class {
846
791
  ]
847
792
  ]);
848
793
  }
849
- accounts;
850
- tokens;
851
- profiles;
794
+
795
+
796
+
852
797
  /**
853
798
  * Per-model circuit breaker for opencodego routing (D5). ONE registry-owned
854
799
  * process singleton, built here and captured by the opencodego profile's
@@ -858,12 +803,12 @@ var SubscriptionProviderRegistry = class {
858
803
  * exactly the reference's long-lived `FallbackHandler`. Constructed with the
859
804
  * default reference thresholds (3 / 30s / 3) and the default `Date.now` clock.
860
805
  */
861
- breaker = new CircuitBreakerRegistry();
806
+ __init14() {this.breaker = new CircuitBreakerRegistry()}
862
807
  /** Returns the dispatch profile for a known subscription provider, or
863
808
  * `null` for unknown ids (callers must treat null as "fall back to the
864
809
  * legacy LLM provider DB lookup"). */
865
810
  getProfile(providerId) {
866
- return this.profiles.get(providerId) ?? null;
811
+ return _nullishCoalesce(this.profiles.get(providerId), () => ( null));
867
812
  }
868
813
  /** Read the currently-stored OpenCodeGo config so the proxy can pick up
869
814
  * user overrides (modelMap / fallbacks / baseUrl). Wraps the injected
@@ -873,116 +818,20 @@ var SubscriptionProviderRegistry = class {
873
818
  const full = await this.tokens.getFullConfig();
874
819
  return full.opencodego;
875
820
  }
876
- };
821
+ }, _class8);
877
822
  var _moduleSingleton2 = null;
878
823
  function setSubscriptionProviderRegistry(svc) {
879
824
  _moduleSingleton2 = svc;
880
- setSubscriptionRegistryForOutbound(svc ?? null);
825
+ _subscriptionRegistryPort.setSubscriptionRegistryForOutbound.call(void 0, _nullishCoalesce(svc, () => ( null)));
881
826
  }
882
827
  function getSubscriptionProviderRegistry() {
883
828
  return _moduleSingleton2;
884
829
  }
885
830
 
886
- // ../core/src/ports/gemini-code-assist-resolver.ts
887
- var resolver = null;
888
- function getGeminiCodeAssistResolver() {
889
- return resolver;
890
- }
891
-
892
- // ../core/src/provider-proxy/matchText.ts
893
- var MATCH_TEXT_PER_MESSAGE_CAP = 8192;
894
- var MATCH_TEXT_RECENT_MESSAGES = 6;
895
- function flattenMatchText(value) {
896
- if (typeof value === "string") return value;
897
- if (Array.isArray(value)) {
898
- const parts = [];
899
- for (const item of value) {
900
- const text = flattenMatchText(item);
901
- if (text) parts.push(text);
902
- }
903
- return parts.join("\n");
904
- }
905
- if (value && typeof value === "object") {
906
- const obj = value;
907
- if (obj.type === "tool_result" && obj.content !== void 0) {
908
- return flattenMatchText(obj.content);
909
- }
910
- if (typeof obj.text === "string") return obj.text;
911
- }
912
- return "";
913
- }
914
- function collectMatchText(anthropicBody) {
915
- const messages = Array.isArray(anthropicBody.messages) ? anthropicBody.messages : [];
916
- const slices = [];
917
- const sys = flattenMatchText(anthropicBody.system).trim();
918
- if (sys) slices.push(sys.slice(0, MATCH_TEXT_PER_MESSAGE_CAP));
919
- const recent = [];
920
- for (let i = messages.length - 1; i >= 0 && recent.length < MATCH_TEXT_RECENT_MESSAGES; i--) {
921
- const message = messages[i];
922
- if (!message || typeof message !== "object") continue;
923
- const role = message.role;
924
- if (role !== "user" && role !== "system") continue;
925
- const text = flattenMatchText(message.content).trim();
926
- if (text) recent.push(text.slice(0, MATCH_TEXT_PER_MESSAGE_CAP));
927
- }
928
- for (let i = recent.length - 1; i >= 0; i--) slices.push(recent[i]);
929
- return slices;
930
- }
931
-
932
- // ../core/src/serializeError.ts
933
- function serializeError(err) {
934
- if (err == null) return "Unknown error (null)";
935
- if (err instanceof Error) {
936
- let msg = err.message || err.name || "Error";
937
- if (err.cause) {
938
- msg += ` [cause: ${serializeError(err.cause)}]`;
939
- }
940
- const anyErr = err;
941
- if (anyErr.status != null) msg += ` (status: ${anyErr.status})`;
942
- else if (anyErr.code != null) msg += ` (code: ${anyErr.code})`;
943
- return msg;
944
- }
945
- if (typeof err === "string") return err || "Empty error string";
946
- if (typeof err !== "object") return String(err);
947
- const obj = err;
948
- if (typeof obj.message === "string" && obj.message) {
949
- let msg = obj.message;
950
- if (obj.status != null) msg += ` (status: ${obj.status})`;
951
- else if (obj.code != null) msg += ` (code: ${obj.code})`;
952
- if (typeof obj.type === "string") msg += ` [type: ${obj.type}]`;
953
- return msg;
954
- }
955
- if (typeof obj.error === "string" && obj.error) {
956
- return obj.error;
957
- }
958
- if (obj.error && typeof obj.error === "object") {
959
- const inner = obj.error;
960
- if (typeof inner.message === "string" && inner.message) {
961
- let msg = inner.message;
962
- if (typeof inner.type === "string") msg += ` [type: ${inner.type}]`;
963
- return msg;
964
- }
965
- }
966
- try {
967
- const json = JSON.stringify(err, getCircularReplacer(), 2);
968
- if (json && json.length > 1e3) {
969
- return json.slice(0, 1e3) + "... (truncated)";
970
- }
971
- return json || "Unserializable error";
972
- } catch {
973
- return `Unserializable error: ${Object.prototype.toString.call(err)}`;
974
- }
975
- }
976
- function getCircularReplacer() {
977
- const seen = /* @__PURE__ */ new WeakSet();
978
- return (_key, value) => {
979
- if (typeof value === "object" && value !== null) {
980
- if (seen.has(value)) return "[Circular]";
981
- seen.add(value);
982
- }
983
- return value;
984
- };
985
- }
831
+ // src/SubscriptionDispatcher.ts
832
+ var _geminicodeassistresolver = require('@omnicross/core/ports/gemini-code-assist-resolver');
833
+ var _matchText = require('@omnicross/core/provider-proxy/matchText');
834
+ var _serializeError = require('@omnicross/core/serializeError');
986
835
 
987
836
  // src/opencodego/token-count.ts
988
837
  var cachedEncode = null;
@@ -1001,9 +850,9 @@ var SubscriptionDispatcher = class {
1001
850
  this.hooks = hooks;
1002
851
  this.getOpenCodeGoConfig = getOpenCodeGoConfig;
1003
852
  }
1004
- profile;
1005
- hooks;
1006
- getOpenCodeGoConfig;
853
+
854
+
855
+
1007
856
  /**
1008
857
  * Entry point — called by the host proxy's request handler after model
1009
858
  * resolution and probe-detection.
@@ -1019,7 +868,7 @@ var SubscriptionDispatcher = class {
1019
868
  scenario = mapped.scenario;
1020
869
  req.anthropicBody.model = resolvedModel;
1021
870
  }
1022
- const upstreamUrl = this.profile.resolveUpstreamUrl?.(resolvedModel, ocConfig);
871
+ const upstreamUrl = _optionalChain([this, 'access', _22 => _22.profile, 'access', _23 => _23.resolveUpstreamUrl, 'optionalCall', _24 => _24(resolvedModel, ocConfig)]);
1023
872
  if (!upstreamUrl) {
1024
873
  throw new Error(`[SubscriptionDispatcher] profile=${this.profile.providerId} missing resolveUpstreamUrl`);
1025
874
  }
@@ -1047,27 +896,27 @@ var SubscriptionDispatcher = class {
1047
896
  );
1048
897
  try {
1049
898
  const upstream = await this.hooks.fetchWithRetry(upstreamUrl, headers, req.anthropicBody, currentModel);
1050
- this.profile.recordModelOutcome?.(currentModel, true);
899
+ _optionalChain([this, 'access', _25 => _25.profile, 'access', _26 => _26.recordModelOutcome, 'optionalCall', _27 => _27(currentModel, true)]);
1051
900
  await this.hooks.writeProxyResponse(req.res, upstream, req.isStream, req.reqId);
1052
901
  return;
1053
902
  } catch (err) {
1054
903
  const handled = await this.maybeRetryAfterError(err, headers, req, currentModel);
1055
904
  if (handled.retryOnce) {
1056
905
  const upstream = await this.hooks.fetchWithRetry(upstreamUrl, handled.headers, req.anthropicBody, currentModel);
1057
- this.profile.recordModelOutcome?.(currentModel, true);
906
+ _optionalChain([this, 'access', _28 => _28.profile, 'access', _29 => _29.recordModelOutcome, 'optionalCall', _30 => _30(currentModel, true)]);
1058
907
  await this.hooks.writeProxyResponse(req.res, upstream, req.isStream, req.reqId);
1059
908
  return;
1060
909
  }
1061
910
  if (caughtErrorBreakerOutcome(err) === "failure") {
1062
- this.profile.recordModelOutcome?.(currentModel, false);
911
+ _optionalChain([this, 'access', _31 => _31.profile, 'access', _32 => _32.recordModelOutcome, 'optionalCall', _33 => _33(currentModel, false)]);
1063
912
  }
1064
- const next = this.profile.nextFallback?.(scenario, attempted, ocConfig);
913
+ const next = _optionalChain([this, 'access', _34 => _34.profile, 'access', _35 => _35.nextFallback, 'optionalCall', _36 => _36(scenario, attempted, ocConfig)]);
1065
914
  if (!next || attempted.length >= MAX_FALLBACK_ATTEMPTS_LOCAL) {
1066
915
  throw err;
1067
916
  }
1068
917
  console.warn(
1069
918
  `[AgentProxy:subscription] REQ#${req.reqId} | opencodego fallback ${currentModel} -> ${next.modelId} after error:`,
1070
- serializeError(err)
919
+ _serializeError.serializeError.call(void 0, err)
1071
920
  );
1072
921
  currentModel = next.modelId;
1073
922
  }
@@ -1075,7 +924,7 @@ var SubscriptionDispatcher = class {
1075
924
  }
1076
925
  /** Standard subscription transformer chain — Codex/Gemini/OpenCodeGo OpenAI-shape. */
1077
926
  async dispatchTransformerChain(req, upstreamUrl, resolvedModel, scenario, ocConfig) {
1078
- const providerNames = this.profile.resolveProviderTransformerNames?.(resolvedModel, ocConfig) ?? this.profile.providerTransformerNames;
927
+ const providerNames = _nullishCoalesce(_optionalChain([this, 'access', _37 => _37.profile, 'access', _38 => _38.resolveProviderTransformerNames, 'optionalCall', _39 => _39(resolvedModel, ocConfig)]), () => ( this.profile.providerTransformerNames));
1079
928
  const providerTransformers = this.resolveTransformers(providerNames);
1080
929
  const modelTransformers = this.resolveTransformers(this.profile.modelTransformerNames);
1081
930
  const transformerProvider = {
@@ -1106,13 +955,13 @@ var SubscriptionDispatcher = class {
1106
955
  };
1107
956
  stripAuthHeaders(headers);
1108
957
  await this.applyHeadersWithRetry(headers, { upstreamUrl, resolvedModel: currentModel });
1109
- const fetchUrl = usesResponsesChain(providerNames) ? upstreamUrl : resolveConfigUrl(config.url) ?? upstreamUrl;
958
+ const fetchUrl = usesResponsesChain(providerNames) ? upstreamUrl : _nullishCoalesce(resolveConfigUrl(config.url), () => ( upstreamUrl));
1110
959
  console.info(
1111
960
  `[AgentProxy:subscription] REQ#${req.reqId} | provider=${this.profile.providerId} -> ${fetchUrl} model=${currentModel} attempt=${attempted.length}`
1112
961
  );
1113
962
  try {
1114
963
  const upstream = await this.hooks.fetchWithRetry(fetchUrl, headers, requestBody, currentModel);
1115
- this.profile.recordModelOutcome?.(currentModel, true);
964
+ _optionalChain([this, 'access', _40 => _40.profile, 'access', _41 => _41.recordModelOutcome, 'optionalCall', _42 => _42(currentModel, true)]);
1116
965
  const finalResponse = await this.hooks.executor.executeResponseChain(
1117
966
  requestBody,
1118
967
  upstream,
@@ -1126,7 +975,7 @@ var SubscriptionDispatcher = class {
1126
975
  const handled = await this.maybeRetryAfterError(err, headers, req, currentModel);
1127
976
  if (handled.retryOnce) {
1128
977
  const upstream = await this.hooks.fetchWithRetry(fetchUrl, handled.headers, requestBody, currentModel);
1129
- this.profile.recordModelOutcome?.(currentModel, true);
978
+ _optionalChain([this, 'access', _43 => _43.profile, 'access', _44 => _44.recordModelOutcome, 'optionalCall', _45 => _45(currentModel, true)]);
1130
979
  const finalResponse = await this.hooks.executor.executeResponseChain(
1131
980
  requestBody,
1132
981
  upstream,
@@ -1138,15 +987,15 @@ var SubscriptionDispatcher = class {
1138
987
  return;
1139
988
  }
1140
989
  if (caughtErrorBreakerOutcome(err) === "failure") {
1141
- this.profile.recordModelOutcome?.(currentModel, false);
990
+ _optionalChain([this, 'access', _46 => _46.profile, 'access', _47 => _47.recordModelOutcome, 'optionalCall', _48 => _48(currentModel, false)]);
1142
991
  }
1143
- const next = this.profile.nextFallback?.(scenario, attempted, ocConfig);
992
+ const next = _optionalChain([this, 'access', _49 => _49.profile, 'access', _50 => _50.nextFallback, 'optionalCall', _51 => _51(scenario, attempted, ocConfig)]);
1144
993
  if (!next || attempted.length >= MAX_FALLBACK_ATTEMPTS_LOCAL) {
1145
994
  throw err;
1146
995
  }
1147
996
  console.warn(
1148
997
  `[AgentProxy:subscription] REQ#${req.reqId} | ${this.profile.providerId} fallback ${currentModel} -> ${next.modelId} after error:`,
1149
- serializeError(err)
998
+ _serializeError.serializeError.call(void 0, err)
1150
999
  );
1151
1000
  currentModel = next.modelId;
1152
1001
  }
@@ -1170,7 +1019,7 @@ var SubscriptionDispatcher = class {
1170
1019
  return { firstModel: primaryModel, attempted: [] };
1171
1020
  }
1172
1021
  const skipped = [primaryModel];
1173
- const firstAdmitting = this.profile.nextFallback?.(scenario, skipped, ocConfig);
1022
+ const firstAdmitting = _optionalChain([this, 'access', _52 => _52.profile, 'access', _53 => _53.nextFallback, 'optionalCall', _54 => _54(scenario, skipped, ocConfig)]);
1174
1023
  if (firstAdmitting) {
1175
1024
  console.warn(
1176
1025
  `[AgentProxy:subscription] opencodego primary ${primaryModel} circuit open -> first admitting fallback ${firstAdmitting.modelId}`
@@ -1188,7 +1037,7 @@ var SubscriptionDispatcher = class {
1188
1037
  * successfully (caller should retry once); otherwise re-throws.
1189
1038
  */
1190
1039
  async maybeRetryAfterError(err, headers, req, resolvedModel) {
1191
- const status = err?.status ?? 0;
1040
+ const status = _nullishCoalesce(_optionalChain([err, 'optionalAccess', _55 => _55.status]), () => ( 0));
1192
1041
  if (status !== 401) {
1193
1042
  return { retryOnce: false, headers };
1194
1043
  }
@@ -1208,7 +1057,7 @@ var SubscriptionDispatcher = class {
1208
1057
  try {
1209
1058
  await this.profile.authStrategy.applyHeaders(headers, hints);
1210
1059
  } catch (err) {
1211
- console.warn("[AgentProxy:subscription] authStrategy.applyHeaders threw:", serializeError(err));
1060
+ console.warn("[AgentProxy:subscription] authStrategy.applyHeaders threw:", _serializeError.serializeError.call(void 0, err));
1212
1061
  }
1213
1062
  }
1214
1063
  /**
@@ -1222,12 +1071,12 @@ var SubscriptionDispatcher = class {
1222
1071
  async resolveGeminiProject() {
1223
1072
  const probe = {};
1224
1073
  await this.applyHeadersWithRetry(probe, { upstreamUrl: "", resolvedModel: "" });
1225
- const bearer = probe.Authorization ?? probe.authorization ?? "";
1074
+ const bearer = _nullishCoalesce(_nullishCoalesce(probe.Authorization, () => ( probe.authorization)), () => ( ""));
1226
1075
  const accessToken = bearer.replace(/^Bearer\s+/i, "").trim();
1227
1076
  if (!accessToken) return void 0;
1228
- const resolver2 = getGeminiCodeAssistResolver();
1229
- if (!resolver2) return void 0;
1230
- return resolver2.resolveProject(accessToken);
1077
+ const resolver = _geminicodeassistresolver.getGeminiCodeAssistResolver.call(void 0, );
1078
+ if (!resolver) return void 0;
1079
+ return resolver.resolveProject(accessToken);
1231
1080
  }
1232
1081
  resolveTransformers(names) {
1233
1082
  if (!names || names.length === 0) return [];
@@ -1253,7 +1102,7 @@ var SubscriptionDispatcher = class {
1253
1102
  } else if (Array.isArray(system)) {
1254
1103
  for (const block of system) {
1255
1104
  if (block && typeof block === "object" && "text" in block) {
1256
- totalChars += String(block.text ?? "").length;
1105
+ totalChars += String(_nullishCoalesce(block.text, () => ( ""))).length;
1257
1106
  }
1258
1107
  }
1259
1108
  }
@@ -1282,13 +1131,13 @@ var SubscriptionDispatcher = class {
1282
1131
  // and the core `/v1/messages` path produce IDENTICAL `matchText` for the
1283
1132
  // same body — equivalence by construction. `@omnicross/subscriptions` →
1284
1133
  // `@omnicross/core` is the allowed direction; core imports nothing back.
1285
- matchText: collectMatchText(anthropicBody)
1134
+ matchText: _matchText.collectMatchText.call(void 0, anthropicBody)
1286
1135
  };
1287
1136
  }
1288
1137
  };
1289
1138
  var MAX_FALLBACK_ATTEMPTS_LOCAL = 3;
1290
1139
  function caughtErrorBreakerOutcome(err) {
1291
- const status = err?.status;
1140
+ const status = _optionalChain([err, 'optionalAccess', _56 => _56.status]);
1292
1141
  if (typeof status !== "number") return "failure";
1293
1142
  if (status === 0) return "neutral";
1294
1143
  if (status >= 500 || status === 429) return "failure";
@@ -1312,368 +1161,14 @@ function stripAuthHeaders(headers) {
1312
1161
  delete headers["X-Goog-Api-Key"];
1313
1162
  }
1314
1163
 
1315
- // src/oauth/flows/claude.ts
1316
- var claude_exports = {};
1317
- __export(claude_exports, {
1318
- exchangeCodeForTokens: () => exchangeCodeForTokens,
1319
- exchangeSetupTokenCode: () => exchangeSetupTokenCode,
1320
- generateAuthParams: () => generateAuthParams,
1321
- generateSetupTokenParams: () => generateSetupTokenParams,
1322
- refreshAccessToken: () => refreshAccessToken
1323
- });
1324
- var import_node_crypto = __toESM(require("crypto"), 1);
1325
1164
 
1326
- // src/oauth/fetchPort.ts
1327
- function errorMessage(error, errorDescription) {
1328
- if (errorDescription) return errorDescription;
1329
- if (typeof error === "string") return error;
1330
- if (error && typeof error === "object") {
1331
- const e = error;
1332
- if (typeof e.message === "string" && e.message) return e.message;
1333
- if (typeof e.error_description === "string" && e.error_description) {
1334
- return e.error_description;
1335
- }
1336
- return JSON.stringify(error);
1337
- }
1338
- return String(error);
1339
- }
1340
- async function postForm(fetchImpl, url, params, parseErrorMessage) {
1341
- const response = await fetchImpl(url, {
1342
- method: "POST",
1343
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
1344
- body: params.toString()
1345
- });
1346
- const responseData = await response.text();
1347
- let data;
1348
- try {
1349
- data = JSON.parse(responseData);
1350
- } catch {
1351
- throw new Error(parseErrorMessage);
1352
- }
1353
- if (data.error) {
1354
- throw new Error(errorMessage(data.error, data.error_description));
1355
- }
1356
- return data;
1357
- }
1358
- async function postJson(fetchImpl, url, body, parseErrorMessage, extraHeaders = {}) {
1359
- const response = await fetchImpl(url, {
1360
- method: "POST",
1361
- headers: { "Content-Type": "application/json", ...extraHeaders },
1362
- body: JSON.stringify(body)
1363
- });
1364
- const responseData = await response.text();
1365
- let data;
1366
- try {
1367
- data = JSON.parse(responseData);
1368
- } catch {
1369
- throw new Error(parseErrorMessage);
1370
- }
1371
- if (data.error) {
1372
- throw new Error(errorMessage(data.error, data.error_description));
1373
- }
1374
- return data;
1375
- }
1376
1165
 
1377
- // src/oauth/flows/claude.ts
1378
- var CLAUDE_TOKEN_HEADERS = {
1379
- "User-Agent": "claude-cli/1.0.56 (external, cli)",
1380
- Accept: "application/json, text/plain, */*",
1381
- "Accept-Language": "en-US,en;q=0.9",
1382
- Referer: "https://claude.ai/",
1383
- Origin: "https://claude.ai"
1384
- };
1385
- var CLAUDE_OAUTH_CONFIG = {
1386
- clientId: "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
1387
- authorizationEndpoint: "https://claude.ai/oauth/authorize",
1388
- // The token endpoint stays on console.anthropic.com (still the live value —
1389
- // matches the official Claude Code CLI / claude-relay-service reference); only
1390
- // the OAuth callback moved to platform.claude.com (2026). The redirect_uri MUST
1391
- // match what the client is registered for AND match between authorize + token
1392
- // exchange. Scopes mirror the live Claude Code authorize URL.
1393
- tokenEndpoint: "https://console.anthropic.com/v1/oauth/token",
1394
- redirectUri: "https://platform.claude.com/oauth/code/callback",
1395
- scopes: [
1396
- "org:create_api_key",
1397
- "user:profile",
1398
- "user:inference",
1399
- "user:sessions:claude_code",
1400
- "user:mcp_servers",
1401
- "user:file_upload"
1402
- ]
1403
- };
1404
- var SETUP_TOKEN_CONFIG = {
1405
- scopes: ["user:inference"]
1406
- // Only inference permission, no API key creation
1407
- };
1408
- function generatePkce() {
1409
- const codeVerifier = import_node_crypto.default.randomBytes(32).toString("base64url");
1410
- const codeChallenge = import_node_crypto.default.createHash("sha256").update(codeVerifier).digest("base64url");
1411
- const state = import_node_crypto.default.randomBytes(16).toString("hex");
1412
- return { codeVerifier, codeChallenge, state };
1413
- }
1414
- function generateAuthParams() {
1415
- const { codeVerifier, codeChallenge, state } = generatePkce();
1416
- const params = new URLSearchParams({
1417
- code: "true",
1418
- client_id: CLAUDE_OAUTH_CONFIG.clientId,
1419
- response_type: "code",
1420
- redirect_uri: CLAUDE_OAUTH_CONFIG.redirectUri,
1421
- scope: CLAUDE_OAUTH_CONFIG.scopes.join(" "),
1422
- code_challenge: codeChallenge,
1423
- code_challenge_method: "S256",
1424
- state
1425
- });
1426
- const authUrl = `${CLAUDE_OAUTH_CONFIG.authorizationEndpoint}?${params.toString()}`;
1427
- return { authUrl, codeVerifier, state };
1428
- }
1429
- function generateSetupTokenParams() {
1430
- const { codeVerifier, codeChallenge, state } = generatePkce();
1431
- const params = new URLSearchParams({
1432
- code: "true",
1433
- client_id: CLAUDE_OAUTH_CONFIG.clientId,
1434
- response_type: "code",
1435
- redirect_uri: CLAUDE_OAUTH_CONFIG.redirectUri,
1436
- scope: SETUP_TOKEN_CONFIG.scopes.join(" "),
1437
- code_challenge: codeChallenge,
1438
- code_challenge_method: "S256",
1439
- state
1440
- });
1441
- const authUrl = `${CLAUDE_OAUTH_CONFIG.authorizationEndpoint}?${params.toString()}`;
1442
- return { authUrl, codeVerifier, state };
1443
- }
1444
- async function exchangeCodeForTokens(request, fetchImpl) {
1445
- const { authorizationCode, codeVerifier, state } = request;
1446
- const code = authorizationCode.split("#")[0]?.split("&")[0] ?? authorizationCode;
1447
- const data = await postJson(
1448
- fetchImpl,
1449
- CLAUDE_OAUTH_CONFIG.tokenEndpoint,
1450
- {
1451
- grant_type: "authorization_code",
1452
- client_id: CLAUDE_OAUTH_CONFIG.clientId,
1453
- code,
1454
- code_verifier: codeVerifier,
1455
- redirect_uri: CLAUDE_OAUTH_CONFIG.redirectUri,
1456
- state
1457
- },
1458
- "Failed to parse token response",
1459
- CLAUDE_TOKEN_HEADERS
1460
- );
1461
- return {
1462
- accessToken: data.access_token,
1463
- // The authorization_code grant always returns a refresh_token; the original
1464
- // helper read it from an untyped `data` and declared the field `string`.
1465
- refreshToken: data.refresh_token,
1466
- expiresIn: data.expires_in,
1467
- scopes: data.scope?.split(" ") || CLAUDE_OAUTH_CONFIG.scopes
1468
- };
1469
- }
1470
- async function exchangeSetupTokenCode(request, fetchImpl) {
1471
- const { authorizationCode, codeVerifier, state } = request;
1472
- const code = authorizationCode.split("#")[0]?.split("&")[0] ?? authorizationCode;
1473
- const data = await postJson(
1474
- fetchImpl,
1475
- CLAUDE_OAUTH_CONFIG.tokenEndpoint,
1476
- {
1477
- grant_type: "authorization_code",
1478
- client_id: CLAUDE_OAUTH_CONFIG.clientId,
1479
- code,
1480
- code_verifier: codeVerifier,
1481
- redirect_uri: CLAUDE_OAUTH_CONFIG.redirectUri,
1482
- state
1483
- },
1484
- "Failed to parse setup token response",
1485
- CLAUDE_TOKEN_HEADERS
1486
- );
1487
- return {
1488
- accessToken: data.access_token,
1489
- expiresIn: data.expires_in,
1490
- scopes: data.scope?.split(" ") || SETUP_TOKEN_CONFIG.scopes
1491
- };
1492
- }
1493
- async function refreshAccessToken(refreshToken, fetchImpl) {
1494
- const data = await postJson(
1495
- fetchImpl,
1496
- CLAUDE_OAUTH_CONFIG.tokenEndpoint,
1497
- {
1498
- grant_type: "refresh_token",
1499
- client_id: CLAUDE_OAUTH_CONFIG.clientId,
1500
- refresh_token: refreshToken
1501
- },
1502
- "Failed to parse refresh response",
1503
- CLAUDE_TOKEN_HEADERS
1504
- );
1505
- return {
1506
- accessToken: data.access_token,
1507
- refreshToken: data.refresh_token || refreshToken,
1508
- expiresIn: data.expires_in
1509
- };
1510
- }
1511
1166
 
1512
- // src/oauth/flows/codex.ts
1513
- var codex_exports = {};
1514
- __export(codex_exports, {
1515
- exchangeCodeForTokens: () => exchangeCodeForTokens2,
1516
- generateAuthParams: () => generateAuthParams2,
1517
- refreshAccessToken: () => refreshAccessToken2
1518
- });
1519
- var import_node_crypto2 = __toESM(require("crypto"), 1);
1520
- var CODEX_OAUTH_CONFIG = {
1521
- clientId: "app_EMoamEEZ73f0CkXaXp7hrann",
1522
- authorizationEndpoint: "https://auth.openai.com/oauth/authorize",
1523
- tokenEndpoint: "https://auth.openai.com/oauth/token",
1524
- redirectUri: "http://localhost:1455/auth/callback",
1525
- scopes: ["openid", "profile", "email", "offline_access"]
1526
- };
1527
- function generateAuthParams2() {
1528
- const codeVerifier = import_node_crypto2.default.randomBytes(64).toString("hex");
1529
- const codeChallenge = import_node_crypto2.default.createHash("sha256").update(codeVerifier).digest("base64url");
1530
- const state = import_node_crypto2.default.randomBytes(16).toString("hex");
1531
- const params = new URLSearchParams({
1532
- response_type: "code",
1533
- client_id: CODEX_OAUTH_CONFIG.clientId,
1534
- redirect_uri: CODEX_OAUTH_CONFIG.redirectUri,
1535
- scope: CODEX_OAUTH_CONFIG.scopes.join(" "),
1536
- code_challenge: codeChallenge,
1537
- code_challenge_method: "S256",
1538
- state
1539
- });
1540
- const authUrl = `${CODEX_OAUTH_CONFIG.authorizationEndpoint}?${params.toString()}`;
1541
- return { authUrl, codeVerifier, state };
1542
- }
1543
- async function exchangeCodeForTokens2(request, fetchImpl) {
1544
- const { authorizationCode, codeVerifier } = request;
1545
- const params = new URLSearchParams({
1546
- grant_type: "authorization_code",
1547
- client_id: CODEX_OAUTH_CONFIG.clientId,
1548
- code: authorizationCode,
1549
- code_verifier: codeVerifier,
1550
- redirect_uri: CODEX_OAUTH_CONFIG.redirectUri
1551
- });
1552
- const data = await postForm(
1553
- fetchImpl,
1554
- CODEX_OAUTH_CONFIG.tokenEndpoint,
1555
- params,
1556
- "Failed to parse token response"
1557
- );
1558
- return {
1559
- accessToken: data.access_token,
1560
- // authorization_code grant returns both; the original helper read them from
1561
- // an untyped `data` and declared the fields `string`.
1562
- refreshToken: data.refresh_token,
1563
- idToken: data.id_token,
1564
- expiresIn: data.expires_in
1565
- };
1566
- }
1567
- async function refreshAccessToken2(refreshToken, fetchImpl) {
1568
- const params = new URLSearchParams({
1569
- grant_type: "refresh_token",
1570
- client_id: CODEX_OAUTH_CONFIG.clientId,
1571
- refresh_token: refreshToken,
1572
- scope: "openid profile email"
1573
- });
1574
- const data = await postForm(
1575
- fetchImpl,
1576
- CODEX_OAUTH_CONFIG.tokenEndpoint,
1577
- params,
1578
- "Failed to parse refresh response"
1579
- );
1580
- return {
1581
- accessToken: data.access_token,
1582
- idToken: data.id_token,
1583
- refreshToken: data.refresh_token || refreshToken,
1584
- expiresIn: data.expires_in || 3600
1585
- };
1586
- }
1587
1167
 
1588
- // src/oauth/flows/gemini.ts
1589
- var gemini_exports = {};
1590
- __export(gemini_exports, {
1591
- exchangeCodeForTokens: () => exchangeCodeForTokens3,
1592
- generateAuthParams: () => generateAuthParams3,
1593
- refreshAccessToken: () => refreshAccessToken3
1594
- });
1595
- var import_node_crypto3 = __toESM(require("crypto"), 1);
1596
- var GEMINI_OAUTH_CONFIG = {
1597
- clientId: "681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com",
1598
- // The Gemini CLI's *public* installed-app OAuth client secret (mirrors the
1599
- // upstream CLI). Per Google's OAuth docs, native-app client secrets are not
1600
- // treated as confidential — not a leaked key.
1601
- clientSecret: "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",
1602
- // allowlist-secret
1603
- authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
1604
- tokenEndpoint: "https://oauth2.googleapis.com/token",
1605
- redirectUri: "urn:ietf:wg:oauth:2.0:oob",
1606
- scopes: ["https://www.googleapis.com/auth/cloud-platform"]
1607
- };
1608
- function generateAuthParams3() {
1609
- const codeVerifier = import_node_crypto3.default.randomBytes(32).toString("base64url");
1610
- const codeChallenge = import_node_crypto3.default.createHash("sha256").update(codeVerifier).digest("base64url");
1611
- const state = import_node_crypto3.default.randomBytes(16).toString("hex");
1612
- const params = new URLSearchParams({
1613
- client_id: GEMINI_OAUTH_CONFIG.clientId,
1614
- redirect_uri: GEMINI_OAUTH_CONFIG.redirectUri,
1615
- scope: GEMINI_OAUTH_CONFIG.scopes.join(" "),
1616
- response_type: "code",
1617
- code_challenge: codeChallenge,
1618
- code_challenge_method: "S256",
1619
- state,
1620
- access_type: "offline",
1621
- prompt: "consent"
1622
- });
1623
- const authUrl = `${GEMINI_OAUTH_CONFIG.authorizationEndpoint}?${params.toString()}`;
1624
- return { authUrl, codeVerifier, state };
1625
- }
1626
- async function exchangeCodeForTokens3(authorizationCode, codeVerifier, fetchImpl) {
1627
- const params = new URLSearchParams({
1628
- grant_type: "authorization_code",
1629
- client_id: GEMINI_OAUTH_CONFIG.clientId,
1630
- client_secret: GEMINI_OAUTH_CONFIG.clientSecret,
1631
- code: authorizationCode,
1632
- code_verifier: codeVerifier,
1633
- redirect_uri: GEMINI_OAUTH_CONFIG.redirectUri
1634
- });
1635
- const data = await postForm(
1636
- fetchImpl,
1637
- GEMINI_OAUTH_CONFIG.tokenEndpoint,
1638
- params,
1639
- "Failed to parse token response"
1640
- );
1641
- return {
1642
- accessToken: data.access_token,
1643
- // authorization_code grant returns a refresh_token; the original helper read
1644
- // it from an untyped `data` and declared the field `string`.
1645
- refreshToken: data.refresh_token,
1646
- expiresIn: data.expires_in
1647
- };
1648
- }
1649
- async function refreshAccessToken3(refreshToken, fetchImpl) {
1650
- const params = new URLSearchParams({
1651
- grant_type: "refresh_token",
1652
- client_id: GEMINI_OAUTH_CONFIG.clientId,
1653
- client_secret: GEMINI_OAUTH_CONFIG.clientSecret,
1654
- refresh_token: refreshToken
1655
- });
1656
- const data = await postForm(
1657
- fetchImpl,
1658
- GEMINI_OAUTH_CONFIG.tokenEndpoint,
1659
- params,
1660
- "Failed to parse refresh response"
1661
- );
1662
- return {
1663
- accessToken: data.access_token,
1664
- expiresIn: data.expires_in
1665
- };
1666
- }
1667
- // Annotate the CommonJS export names for ESM import in node:
1668
- 0 && (module.exports = {
1669
- SubscriptionAccountService,
1670
- SubscriptionDispatcher,
1671
- SubscriptionProviderRegistry,
1672
- claudeOAuth,
1673
- codexOAuth,
1674
- geminiOAuth,
1675
- getSubscriptionAccountService,
1676
- getSubscriptionProviderRegistry,
1677
- setSubscriptionAccountService,
1678
- setSubscriptionProviderRegistry
1679
- });
1168
+
1169
+
1170
+
1171
+
1172
+
1173
+
1174
+ exports.SubscriptionAccountService = SubscriptionAccountService; exports.SubscriptionDispatcher = SubscriptionDispatcher; exports.SubscriptionProviderRegistry = SubscriptionProviderRegistry; exports.claudeOAuth = _chunkTPW5Q25Ycjs.claude_exports; exports.codexOAuth = _chunkTPW5Q25Ycjs.codex_exports; exports.geminiOAuth = _chunkTPW5Q25Ycjs.gemini_exports; exports.getSubscriptionAccountService = getSubscriptionAccountService; exports.getSubscriptionProviderRegistry = getSubscriptionProviderRegistry; exports.setSubscriptionAccountService = setSubscriptionAccountService; exports.setSubscriptionProviderRegistry = setSubscriptionProviderRegistry;