@positronic/cloudflare 0.0.67 → 0.0.69

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 (37) hide show
  1. package/dist/src/api/auth-middleware.js +25 -0
  2. package/dist/src/api/brains.js +67 -16
  3. package/dist/src/api/secrets.js +3 -0
  4. package/dist/src/brain-runner-do.js +51 -5
  5. package/dist/src/create-r2-store.js +319 -0
  6. package/dist/src/dev-server.js +19 -1
  7. package/dist/src/governor-client-wrapper.js +364 -0
  8. package/dist/src/governor-do.js +387 -0
  9. package/dist/src/index.js +3 -0
  10. package/dist/src/monitor-do.js +25 -12
  11. package/dist/src/rate-limit-headers.js +199 -0
  12. package/dist/src/schedule-do.js +38 -22
  13. package/dist/src/token-estimator.js +39 -0
  14. package/dist/types/api/auth-middleware.d.ts +5 -0
  15. package/dist/types/api/auth-middleware.d.ts.map +1 -1
  16. package/dist/types/api/brains.d.ts.map +1 -1
  17. package/dist/types/api/secrets.d.ts.map +1 -1
  18. package/dist/types/brain-runner-do.d.ts +9 -1
  19. package/dist/types/brain-runner-do.d.ts.map +1 -1
  20. package/dist/types/create-r2-store.d.ts +14 -0
  21. package/dist/types/create-r2-store.d.ts.map +1 -0
  22. package/dist/types/dev-server.d.ts.map +1 -1
  23. package/dist/types/governor-client-wrapper.d.ts +15 -0
  24. package/dist/types/governor-client-wrapper.d.ts.map +1 -0
  25. package/dist/types/governor-do.d.ts +25 -0
  26. package/dist/types/governor-do.d.ts.map +1 -0
  27. package/dist/types/index.d.ts +3 -0
  28. package/dist/types/index.d.ts.map +1 -1
  29. package/dist/types/monitor-do.d.ts +13 -4
  30. package/dist/types/monitor-do.d.ts.map +1 -1
  31. package/dist/types/rate-limit-headers.d.ts +10 -0
  32. package/dist/types/rate-limit-headers.d.ts.map +1 -0
  33. package/dist/types/schedule-do.d.ts +11 -3
  34. package/dist/types/schedule-do.d.ts.map +1 -1
  35. package/dist/types/token-estimator.d.ts +9 -0
  36. package/dist/types/token-estimator.d.ts.map +1 -0
  37. package/package.json +5 -4
@@ -0,0 +1,387 @@
1
+ function _assert_this_initialized(self) {
2
+ if (self === void 0) {
3
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
4
+ }
5
+ return self;
6
+ }
7
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
8
+ try {
9
+ var info = gen[key](arg);
10
+ var value = info.value;
11
+ } catch (error) {
12
+ reject(error);
13
+ return;
14
+ }
15
+ if (info.done) {
16
+ resolve(value);
17
+ } else {
18
+ Promise.resolve(value).then(_next, _throw);
19
+ }
20
+ }
21
+ function _async_to_generator(fn) {
22
+ return function() {
23
+ var self = this, args = arguments;
24
+ return new Promise(function(resolve, reject) {
25
+ var gen = fn.apply(self, args);
26
+ function _next(value) {
27
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
28
+ }
29
+ function _throw(err) {
30
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
31
+ }
32
+ _next(undefined);
33
+ });
34
+ };
35
+ }
36
+ function _call_super(_this, derived, args) {
37
+ derived = _get_prototype_of(derived);
38
+ return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
39
+ }
40
+ function _class_call_check(instance, Constructor) {
41
+ if (!(instance instanceof Constructor)) {
42
+ throw new TypeError("Cannot call a class as a function");
43
+ }
44
+ }
45
+ function _defineProperties(target, props) {
46
+ for(var i = 0; i < props.length; i++){
47
+ var descriptor = props[i];
48
+ descriptor.enumerable = descriptor.enumerable || false;
49
+ descriptor.configurable = true;
50
+ if ("value" in descriptor) descriptor.writable = true;
51
+ Object.defineProperty(target, descriptor.key, descriptor);
52
+ }
53
+ }
54
+ function _create_class(Constructor, protoProps, staticProps) {
55
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
56
+ if (staticProps) _defineProperties(Constructor, staticProps);
57
+ return Constructor;
58
+ }
59
+ function _define_property(obj, key, value) {
60
+ if (key in obj) {
61
+ Object.defineProperty(obj, key, {
62
+ value: value,
63
+ enumerable: true,
64
+ configurable: true,
65
+ writable: true
66
+ });
67
+ } else {
68
+ obj[key] = value;
69
+ }
70
+ return obj;
71
+ }
72
+ function _get_prototype_of(o) {
73
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
74
+ return o.__proto__ || Object.getPrototypeOf(o);
75
+ };
76
+ return _get_prototype_of(o);
77
+ }
78
+ function _inherits(subClass, superClass) {
79
+ if (typeof superClass !== "function" && superClass !== null) {
80
+ throw new TypeError("Super expression must either be null or a function");
81
+ }
82
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
83
+ constructor: {
84
+ value: subClass,
85
+ writable: true,
86
+ configurable: true
87
+ }
88
+ });
89
+ if (superClass) _set_prototype_of(subClass, superClass);
90
+ }
91
+ function _possible_constructor_return(self, call) {
92
+ if (call && (_type_of(call) === "object" || typeof call === "function")) {
93
+ return call;
94
+ }
95
+ return _assert_this_initialized(self);
96
+ }
97
+ function _set_prototype_of(o, p) {
98
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
99
+ o.__proto__ = p;
100
+ return o;
101
+ };
102
+ return _set_prototype_of(o, p);
103
+ }
104
+ function _type_of(obj) {
105
+ "@swc/helpers - typeof";
106
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
107
+ }
108
+ function _is_native_reflect_construct() {
109
+ try {
110
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
111
+ } catch (_) {}
112
+ return (_is_native_reflect_construct = function() {
113
+ return !!result;
114
+ })();
115
+ }
116
+ function _ts_generator(thisArg, body) {
117
+ var f, y, t, _ = {
118
+ label: 0,
119
+ sent: function() {
120
+ if (t[0] & 1) throw t[1];
121
+ return t[1];
122
+ },
123
+ trys: [],
124
+ ops: []
125
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
126
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
127
+ return this;
128
+ }), g;
129
+ function verb(n) {
130
+ return function(v) {
131
+ return step([
132
+ n,
133
+ v
134
+ ]);
135
+ };
136
+ }
137
+ function step(op) {
138
+ if (f) throw new TypeError("Generator is already executing.");
139
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
140
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
141
+ if (y = 0, t) op = [
142
+ op[0] & 2,
143
+ t.value
144
+ ];
145
+ switch(op[0]){
146
+ case 0:
147
+ case 1:
148
+ t = op;
149
+ break;
150
+ case 4:
151
+ _.label++;
152
+ return {
153
+ value: op[1],
154
+ done: false
155
+ };
156
+ case 5:
157
+ _.label++;
158
+ y = op[1];
159
+ op = [
160
+ 0
161
+ ];
162
+ continue;
163
+ case 7:
164
+ op = _.ops.pop();
165
+ _.trys.pop();
166
+ continue;
167
+ default:
168
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
169
+ _ = 0;
170
+ continue;
171
+ }
172
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
173
+ _.label = op[1];
174
+ break;
175
+ }
176
+ if (op[0] === 6 && _.label < t[1]) {
177
+ _.label = t[1];
178
+ t = op;
179
+ break;
180
+ }
181
+ if (t && _.label < t[2]) {
182
+ _.label = t[2];
183
+ _.ops.push(op);
184
+ break;
185
+ }
186
+ if (t[2]) _.ops.pop();
187
+ _.trys.pop();
188
+ continue;
189
+ }
190
+ op = body.call(thisArg, _);
191
+ } catch (e) {
192
+ op = [
193
+ 6,
194
+ e
195
+ ];
196
+ y = 0;
197
+ } finally{
198
+ f = t = 0;
199
+ }
200
+ if (op[0] & 5) throw op[1];
201
+ return {
202
+ value: op[0] ? op[1] : void 0,
203
+ done: true
204
+ };
205
+ }
206
+ }
207
+ import { DurableObject } from 'cloudflare:workers';
208
+ import { parseRateLimitHeaders, getGoogleModelDefaults } from './rate-limit-headers.js';
209
+ export var GovernorDO = /*#__PURE__*/ function(DurableObject) {
210
+ "use strict";
211
+ _inherits(GovernorDO, DurableObject);
212
+ function GovernorDO(state, env) {
213
+ _class_call_check(this, GovernorDO);
214
+ var _this;
215
+ _this = _call_super(this, GovernorDO, [
216
+ state,
217
+ env
218
+ ]), _define_property(_this, "storage", void 0), _define_property(_this, "waitQueue", []), _define_property(_this, "loopRunning", false), _define_property(_this, "rpmLimit", null), _define_property(_this, "tpmLimit", null), _define_property(_this, "limitsLoaded", false), _define_property(_this, "lastAdmitTime", 0), _define_property(_this, "lastDelay", 0);
219
+ _this.storage = state.storage.sql;
220
+ _this.storage.exec("\n CREATE TABLE IF NOT EXISTS rate_limits (\n id INTEGER PRIMARY KEY DEFAULT 1,\n rpm_limit INTEGER,\n tpm_limit INTEGER\n );\n ");
221
+ _this.loadLimits();
222
+ return _this;
223
+ }
224
+ _create_class(GovernorDO, [
225
+ {
226
+ key: "loadLimits",
227
+ value: function loadLimits() {
228
+ var rows = this.storage.exec("SELECT rpm_limit, tpm_limit FROM rate_limits WHERE id = 1").toArray();
229
+ if (rows.length > 0) {
230
+ this.rpmLimit = rows[0].rpm_limit;
231
+ this.tpmLimit = rows[0].tpm_limit;
232
+ if (this.rpmLimit !== null || this.tpmLimit !== null) {
233
+ this.limitsLoaded = true;
234
+ }
235
+ }
236
+ }
237
+ },
238
+ {
239
+ key: "persistLimits",
240
+ value: function persistLimits() {
241
+ this.storage.exec("INSERT INTO rate_limits (id, rpm_limit, tpm_limit)\n VALUES (1, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n rpm_limit = excluded.rpm_limit,\n tpm_limit = excluded.tpm_limit", this.rpmLimit, this.tpmLimit);
242
+ }
243
+ },
244
+ {
245
+ key: "waitForCapacity",
246
+ value: function waitForCapacity(modelId, estimatedTokens) {
247
+ return _async_to_generator(function() {
248
+ var _this, defaults;
249
+ return _ts_generator(this, function(_state) {
250
+ _this = this;
251
+ if (!this.limitsLoaded) {
252
+ defaults = getGoogleModelDefaults(modelId);
253
+ if (defaults) {
254
+ this.rpmLimit = defaults.rpm;
255
+ this.tpmLimit = defaults.tpm;
256
+ this.limitsLoaded = true;
257
+ this.persistLimits();
258
+ }
259
+ }
260
+ if (!this.limitsLoaded) {
261
+ return [
262
+ 2
263
+ ];
264
+ }
265
+ return [
266
+ 2,
267
+ new Promise(function(resolve) {
268
+ _this.waitQueue.push({
269
+ estimatedTokens: estimatedTokens,
270
+ resolve: resolve
271
+ });
272
+ _this.kickLoop();
273
+ })
274
+ ];
275
+ });
276
+ }).call(this);
277
+ }
278
+ },
279
+ {
280
+ key: "reportHeaders",
281
+ value: function reportHeaders(headers) {
282
+ return _async_to_generator(function() {
283
+ var parsed;
284
+ return _ts_generator(this, function(_state) {
285
+ parsed = parseRateLimitHeaders(headers);
286
+ if (!parsed) return [
287
+ 2
288
+ ];
289
+ if (parsed.requestsLimit !== null) {
290
+ this.rpmLimit = parsed.requestsLimit;
291
+ }
292
+ if (parsed.tokensLimit !== null) {
293
+ this.tpmLimit = parsed.tokensLimit;
294
+ }
295
+ this.persistLimits();
296
+ this.limitsLoaded = true;
297
+ return [
298
+ 2
299
+ ];
300
+ });
301
+ }).call(this);
302
+ }
303
+ },
304
+ {
305
+ key: "kickLoop",
306
+ value: function kickLoop() {
307
+ if (this.loopRunning) return;
308
+ this.runLoop();
309
+ }
310
+ },
311
+ {
312
+ key: "runLoop",
313
+ value: function runLoop() {
314
+ return _async_to_generator(function() {
315
+ var elapsed, remaining, item;
316
+ return _ts_generator(this, function(_state) {
317
+ switch(_state.label){
318
+ case 0:
319
+ this.loopRunning = true;
320
+ _state.label = 1;
321
+ case 1:
322
+ if (!(this.waitQueue.length > 0)) return [
323
+ 3,
324
+ 4
325
+ ];
326
+ if (!(this.lastAdmitTime > 0 && this.lastDelay > 0)) return [
327
+ 3,
328
+ 3
329
+ ];
330
+ elapsed = Date.now() - this.lastAdmitTime;
331
+ remaining = this.lastDelay - elapsed;
332
+ if (!(remaining > 0)) return [
333
+ 3,
334
+ 3
335
+ ];
336
+ return [
337
+ 4,
338
+ this.sleep(remaining)
339
+ ];
340
+ case 2:
341
+ _state.sent();
342
+ _state.label = 3;
343
+ case 3:
344
+ item = this.waitQueue.shift();
345
+ this.lastAdmitTime = Date.now();
346
+ this.lastDelay = this.calculateDelay(item.estimatedTokens);
347
+ item.resolve();
348
+ return [
349
+ 3,
350
+ 1
351
+ ];
352
+ case 4:
353
+ this.loopRunning = false;
354
+ return [
355
+ 2
356
+ ];
357
+ }
358
+ });
359
+ }).call(this);
360
+ }
361
+ },
362
+ {
363
+ key: "calculateDelay",
364
+ value: function calculateDelay(estimatedTokens) {
365
+ if (this.rpmLimit === null && this.tpmLimit === null) return 0;
366
+ var tokenDelay = 0;
367
+ var rpmDelay = 0;
368
+ if (this.tpmLimit !== null && this.tpmLimit > 0) {
369
+ tokenDelay = estimatedTokens / (this.tpmLimit * 0.9) * 60000;
370
+ }
371
+ if (this.rpmLimit !== null && this.rpmLimit > 0) {
372
+ rpmDelay = 60000 / this.rpmLimit;
373
+ }
374
+ return Math.max(tokenDelay, rpmDelay);
375
+ }
376
+ },
377
+ {
378
+ key: "sleep",
379
+ value: function sleep(ms) {
380
+ return new Promise(function(resolve) {
381
+ return setTimeout(resolve, ms);
382
+ });
383
+ }
384
+ }
385
+ ]);
386
+ return GovernorDO;
387
+ }(DurableObject);
package/dist/src/index.js CHANGED
@@ -2,5 +2,8 @@ export { BrainRunnerDO, setBrainRunner, setManifest, setWebhookManifest } from '
2
2
  export { MonitorDO } from './monitor-do.js';
3
3
  export { ScheduleDO } from './schedule-do.js';
4
4
  export { AuthDO } from './auth-do.js';
5
+ export { GovernorDO } from './governor-do.js';
6
+ export { rateGoverned, setGovernorBinding } from './governor-client-wrapper.js';
7
+ export { createR2Backend } from './create-r2-store.js';
5
8
  export { PositronicManifest } from './manifest.js';
6
9
  export { default as api } from './api/index.js';
@@ -265,6 +265,12 @@ export var MonitorDO = /*#__PURE__*/ function(DurableObject) {
265
265
  } catch (e) {
266
266
  // Column already exists
267
267
  }
268
+ // Migration: add user_id column to brain_runs for ownership tracking
269
+ try {
270
+ _this.storage.exec("ALTER TABLE brain_runs ADD COLUMN user_id TEXT");
271
+ } catch (e) {
272
+ // Column already exists
273
+ }
268
274
  return _this;
269
275
  }
270
276
  _create_class(MonitorDO, [
@@ -310,7 +316,9 @@ export var MonitorDO = /*#__PURE__*/ function(DurableObject) {
310
316
  } else {
311
317
  // All other events have brainTitle/brainDescription (BrainBaseEvent types)
312
318
  var brainEvent = event;
313
- this.storage.exec("\n INSERT INTO brain_runs (\n run_id, brain_title, brain_description, type, status,\n options, error, created_at, started_at, completed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(run_id) DO UPDATE SET\n type = excluded.type,\n status = excluded.status,\n error = excluded.error,\n completed_at = excluded.completed_at\n ", brainRunId, brainEvent.brainTitle, brainEvent.brainDescription || null, event.type, status, JSON.stringify(event.options || {}), error, currentTime, startTime, completeTime);
319
+ // Extract user_id from START event (set once, never updated)
320
+ var userId = event.type === BRAIN_EVENTS.START ? event.currentUser.id : null;
321
+ this.storage.exec("\n INSERT INTO brain_runs (\n run_id, brain_title, brain_description, type, status,\n options, error, created_at, started_at, completed_at, user_id\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(run_id) DO UPDATE SET\n type = excluded.type,\n status = excluded.status,\n error = excluded.error,\n completed_at = excluded.completed_at\n ", brainRunId, brainEvent.brainTitle, brainEvent.brainDescription || null, event.type, status, JSON.stringify(event.options || {}), error, currentTime, startTime, completeTime, userId);
314
322
  }
315
323
  // Clean up registrations and in-memory state when brain terminates
316
324
  if (isTerminalStatus) {
@@ -445,10 +453,12 @@ export var MonitorDO = /*#__PURE__*/ function(DurableObject) {
445
453
  {
446
454
  /**
447
455
  * Get detailed information about a specific brain run
448
- * Returns null if run not found
456
+ * Returns null if run not found or not owned by userId
457
+ * Pass null for userId to skip ownership check (root access)
449
458
  */ key: "getRun",
450
459
  value: function getRun(brainRunId) {
451
- var results = this.storage.exec("\n SELECT\n run_id as brainRunId,\n brain_title as brainTitle,\n brain_description as brainDescription,\n type,\n status,\n options,\n error,\n created_at as createdAt,\n started_at as startedAt,\n completed_at as completedAt\n FROM brain_runs\n WHERE run_id = ?\n ", brainRunId).toArray();
460
+ var userId = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : null;
461
+ var results = this.storage.exec("\n SELECT\n run_id as brainRunId,\n brain_title as brainTitle,\n brain_description as brainDescription,\n type,\n status,\n options,\n error,\n created_at as createdAt,\n started_at as startedAt,\n completed_at as completedAt,\n user_id as userId\n FROM brain_runs\n WHERE run_id = ?\n AND (? IS NULL OR user_id = ?)\n ", brainRunId, userId, userId).toArray();
452
462
  if (results.length === 0) {
453
463
  return null;
454
464
  }
@@ -461,20 +471,23 @@ export var MonitorDO = /*#__PURE__*/ function(DurableObject) {
461
471
  }
462
472
  },
463
473
  {
464
- // Update history method parameter and query
465
- key: "history",
474
+ /**
475
+ * Get run history for a brain.
476
+ * Pass null for userId to skip ownership filter (root access).
477
+ */ key: "history",
466
478
  value: function history(brainTitle) {
467
- var limit = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 10;
468
- // Renamed parameter
469
- // Update select query with aliases and filter by brain_title
470
- return this.storage.exec("\n SELECT\n run_id as brainRunId,\n brain_title as brainTitle,\n brain_description as brainDescription,\n type,\n status,\n options,\n error,\n created_at as createdAt,\n started_at as startedAt,\n completed_at as completedAt\n FROM brain_runs\n WHERE brain_title = ? -- Filter by new column name\n ORDER BY created_at DESC\n LIMIT ?\n ", brainTitle, limit).toArray(); // Use renamed parameter
479
+ var limit = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 10, userId = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : null;
480
+ return this.storage.exec("\n SELECT\n run_id as brainRunId,\n brain_title as brainTitle,\n brain_description as brainDescription,\n type,\n status,\n options,\n error,\n created_at as createdAt,\n started_at as startedAt,\n completed_at as completedAt,\n user_id as userId\n FROM brain_runs\n WHERE brain_title = ?\n AND (? IS NULL OR user_id = ?)\n ORDER BY created_at DESC\n LIMIT ?\n ", brainTitle, userId, userId, limit).toArray();
471
481
  }
472
482
  },
473
483
  {
474
- // Get active brain runs for a specific brain (running, paused, or waiting)
475
- key: "activeRuns",
484
+ /**
485
+ * Get active brain runs for a specific brain (running, paused, or waiting).
486
+ * Pass null for userId to skip ownership filter (root access).
487
+ */ key: "activeRuns",
476
488
  value: function activeRuns(brainTitle) {
477
- return this.storage.exec("\n SELECT\n run_id as brainRunId,\n brain_title as brainTitle,\n brain_description as brainDescription,\n type,\n status,\n options,\n error,\n created_at as createdAt,\n started_at as startedAt,\n completed_at as completedAt\n FROM brain_runs\n WHERE brain_title = ? AND status IN (?, ?, ?)\n ORDER BY created_at DESC\n ", brainTitle, STATUS.RUNNING, STATUS.PAUSED, STATUS.WAITING).toArray();
489
+ var userId = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : null;
490
+ return this.storage.exec("\n SELECT\n run_id as brainRunId,\n brain_title as brainTitle,\n brain_description as brainDescription,\n type,\n status,\n options,\n error,\n created_at as createdAt,\n started_at as startedAt,\n completed_at as completedAt,\n user_id as userId\n FROM brain_runs\n WHERE brain_title = ? AND status IN (?, ?, ?)\n AND (? IS NULL OR user_id = ?)\n ORDER BY created_at DESC\n ", brainTitle, STATUS.RUNNING, STATUS.PAUSED, STATUS.WAITING, userId, userId).toArray();
478
491
  }
479
492
  },
480
493
  {
@@ -0,0 +1,199 @@
1
+ function _array_like_to_array(arr, len) {
2
+ if (len == null || len > arr.length) len = arr.length;
3
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
4
+ return arr2;
5
+ }
6
+ function _array_with_holes(arr) {
7
+ if (Array.isArray(arr)) return arr;
8
+ }
9
+ function _iterable_to_array_limit(arr, i) {
10
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
11
+ if (_i == null) return;
12
+ var _arr = [];
13
+ var _n = true;
14
+ var _d = false;
15
+ var _s, _e;
16
+ try {
17
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
18
+ _arr.push(_s.value);
19
+ if (i && _arr.length === i) break;
20
+ }
21
+ } catch (err) {
22
+ _d = true;
23
+ _e = err;
24
+ } finally{
25
+ try {
26
+ if (!_n && _i["return"] != null) _i["return"]();
27
+ } finally{
28
+ if (_d) throw _e;
29
+ }
30
+ }
31
+ return _arr;
32
+ }
33
+ function _non_iterable_rest() {
34
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
35
+ }
36
+ function _sliced_to_array(arr, i) {
37
+ return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
38
+ }
39
+ function _unsupported_iterable_to_array(o, minLen) {
40
+ if (!o) return;
41
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
42
+ var n = Object.prototype.toString.call(o).slice(8, -1);
43
+ if (n === "Object" && o.constructor) n = o.constructor.name;
44
+ if (n === "Map" || n === "Set") return Array.from(n);
45
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
46
+ }
47
+ var ANTHROPIC_PREFIX = 'anthropic-ratelimit-';
48
+ var OPENAI_PREFIX = 'x-ratelimit-';
49
+ var ANTHROPIC_KEYS = {
50
+ 'requests-limit': 'requestsLimit',
51
+ 'tokens-limit': 'tokensLimit'
52
+ };
53
+ var OPENAI_KEYS = {
54
+ 'limit-requests': 'requestsLimit',
55
+ 'limit-tokens': 'tokensLimit'
56
+ };
57
+ // Google Gemini doesn't return rate-limit headers, so we hardcode known limits.
58
+ var GOOGLE_MODEL_LIMITS = {
59
+ 'gemini-2.5-flash-lite': {
60
+ rpm: 4000,
61
+ tpm: 4000000
62
+ },
63
+ 'gemini-2.5-flash': {
64
+ rpm: 1000,
65
+ tpm: 1000000
66
+ },
67
+ 'gemini-2.5-pro': {
68
+ rpm: 150,
69
+ tpm: 2000000
70
+ },
71
+ 'gemini-2-flash-lite': {
72
+ rpm: 4000,
73
+ tpm: 4000000
74
+ },
75
+ 'gemini-2-flash-exp': {
76
+ rpm: 10,
77
+ tpm: 250000
78
+ },
79
+ 'gemini-2-flash': {
80
+ rpm: 2000,
81
+ tpm: 4000000
82
+ },
83
+ 'gemini-3.1-pro': {
84
+ rpm: 25,
85
+ tpm: 1000000
86
+ },
87
+ 'gemini-3-pro': {
88
+ rpm: 25,
89
+ tpm: 1000000
90
+ },
91
+ 'gemini-3-flash': {
92
+ rpm: 1000,
93
+ tpm: 1000000
94
+ },
95
+ 'gemini-3.1-flash-lite-preview': {
96
+ rpm: 4000,
97
+ tpm: 4000000
98
+ }
99
+ };
100
+ export function getGoogleModelDefaults(modelId) {
101
+ // Strip "models/" prefix used by some Google SDKs
102
+ var normalized = modelId.startsWith('models/') ? modelId.slice(7) : modelId;
103
+ var entry = GOOGLE_MODEL_LIMITS[normalized];
104
+ if (!entry) return null;
105
+ return entry;
106
+ }
107
+ function parseNumeric(value) {
108
+ var num = parseInt(value, 10);
109
+ return isNaN(num) ? null : num;
110
+ }
111
+ export function parseRateLimitHeaders(headers) {
112
+ // Normalize all header keys to lowercase
113
+ var normalized = {};
114
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
115
+ try {
116
+ for(var _iterator = Object.entries(headers)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
117
+ var _step_value = _sliced_to_array(_step.value, 2), key = _step_value[0], value = _step_value[1];
118
+ normalized[key.toLowerCase()] = value;
119
+ }
120
+ } catch (err) {
121
+ _didIteratorError = true;
122
+ _iteratorError = err;
123
+ } finally{
124
+ try {
125
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
126
+ _iterator.return();
127
+ }
128
+ } finally{
129
+ if (_didIteratorError) {
130
+ throw _iteratorError;
131
+ }
132
+ }
133
+ }
134
+ // Detect provider by checking for known prefixes
135
+ var keyMap = null;
136
+ var prefix = null;
137
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
138
+ try {
139
+ for(var _iterator1 = Object.keys(normalized)[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
140
+ var key1 = _step1.value;
141
+ if (key1.startsWith(ANTHROPIC_PREFIX)) {
142
+ keyMap = ANTHROPIC_KEYS;
143
+ prefix = ANTHROPIC_PREFIX;
144
+ break;
145
+ }
146
+ if (key1.startsWith(OPENAI_PREFIX)) {
147
+ keyMap = OPENAI_KEYS;
148
+ prefix = OPENAI_PREFIX;
149
+ break;
150
+ }
151
+ }
152
+ } catch (err) {
153
+ _didIteratorError1 = true;
154
+ _iteratorError1 = err;
155
+ } finally{
156
+ try {
157
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
158
+ _iterator1.return();
159
+ }
160
+ } finally{
161
+ if (_didIteratorError1) {
162
+ throw _iteratorError1;
163
+ }
164
+ }
165
+ }
166
+ if (!keyMap || !prefix) return null;
167
+ var result = {
168
+ requestsLimit: null,
169
+ tokensLimit: null
170
+ };
171
+ var hasAnyValue = false;
172
+ var _iteratorNormalCompletion2 = true, _didIteratorError2 = false, _iteratorError2 = undefined;
173
+ try {
174
+ for(var _iterator2 = Object.entries(keyMap)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true){
175
+ var _step_value1 = _sliced_to_array(_step2.value, 2), suffix = _step_value1[0], field = _step_value1[1];
176
+ var headerKey = prefix + suffix;
177
+ var value1 = normalized[headerKey];
178
+ if (value1 === undefined) continue;
179
+ result[field] = parseNumeric(value1);
180
+ if (result[field] !== null) {
181
+ hasAnyValue = true;
182
+ }
183
+ }
184
+ } catch (err) {
185
+ _didIteratorError2 = true;
186
+ _iteratorError2 = err;
187
+ } finally{
188
+ try {
189
+ if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
190
+ _iterator2.return();
191
+ }
192
+ } finally{
193
+ if (_didIteratorError2) {
194
+ throw _iteratorError2;
195
+ }
196
+ }
197
+ }
198
+ return hasAnyValue ? result : null;
199
+ }