@dereekb/openrouter 13.37.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 (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +195 -0
  3. package/firebase/index.cjs.default.js +1 -0
  4. package/firebase/index.cjs.js +666 -0
  5. package/firebase/index.cjs.mjs +2 -0
  6. package/firebase/index.d.ts +1 -0
  7. package/firebase/index.esm.js +626 -0
  8. package/firebase/package.json +25 -0
  9. package/firebase/src/index.d.ts +1 -0
  10. package/firebase/src/lib/index.d.ts +4 -0
  11. package/firebase/src/lib/openrouter.api.d.ts +226 -0
  12. package/firebase/src/lib/openrouter.id.d.ts +56 -0
  13. package/firebase/src/lib/openrouter.model.d.ts +609 -0
  14. package/firebase/src/lib/openrouter.query.d.ts +121 -0
  15. package/firebase-server/index.cjs.default.js +1 -0
  16. package/firebase-server/index.cjs.js +4520 -0
  17. package/firebase-server/index.cjs.mjs +2 -0
  18. package/firebase-server/index.d.ts +1 -0
  19. package/firebase-server/index.esm.js +4466 -0
  20. package/firebase-server/package.json +38 -0
  21. package/firebase-server/src/index.d.ts +1 -0
  22. package/firebase-server/src/lib/index.d.ts +10 -0
  23. package/firebase-server/src/lib/openrouter.action.server.d.ts +196 -0
  24. package/firebase-server/src/lib/openrouter.broadcast.d.ts +93 -0
  25. package/firebase-server/src/lib/openrouter.call.inline.d.ts +57 -0
  26. package/firebase-server/src/lib/openrouter.file.attachment.d.ts +97 -0
  27. package/firebase-server/src/lib/openrouter.module.d.ts +65 -0
  28. package/firebase-server/src/lib/openrouter.prompt.service.d.ts +109 -0
  29. package/firebase-server/src/lib/openrouter.runtask.handle.d.ts +56 -0
  30. package/firebase-server/src/lib/openrouter.runtask.service.d.ts +380 -0
  31. package/firebase-server/src/lib/openrouter.runtask.sweep.d.ts +170 -0
  32. package/firebase-server/src/lib/openrouter.state.accessor.d.ts +106 -0
  33. package/firebase-server/src/test/openrouter.fake.d.ts +134 -0
  34. package/index.cjs.default.js +1 -0
  35. package/index.cjs.js +1867 -0
  36. package/index.cjs.mjs +2 -0
  37. package/index.d.ts +1 -0
  38. package/index.esm.js +1771 -0
  39. package/package.json +32 -0
  40. package/src/index.d.ts +1 -0
  41. package/src/lib/index.d.ts +10 -0
  42. package/src/lib/openrouter.call.d.ts +268 -0
  43. package/src/lib/openrouter.config.d.ts +314 -0
  44. package/src/lib/openrouter.embedding.d.ts +87 -0
  45. package/src/lib/openrouter.generation.d.ts +46 -0
  46. package/src/lib/openrouter.input.d.ts +238 -0
  47. package/src/lib/openrouter.prompt.d.ts +79 -0
  48. package/src/lib/openrouter.request.d.ts +91 -0
  49. package/src/lib/openrouter.sdk.d.ts +37 -0
  50. package/src/lib/openrouter.tool.d.ts +99 -0
  51. package/src/lib/openrouter.type.d.ts +125 -0
@@ -0,0 +1,626 @@
1
+ import { MS_IN_DAY } from '@dereekb/util';
2
+ import { firestoreModelIdentity, snapshotConverterFunctions, optionalFirestoreArray, firestoreNumber, optionalFirestoreNumber, firestoreEnum, optionalFirestoreString, firestoreString, optionalFirestoreDate, firestoreDate, optionalFirestoreBoolean, optionalFirestorePassthroughJsonField, firestoreArray, AbstractFirestoreDocument, AbstractFirestoreDocumentWithParent, inferredTargetModelParamsType, callModelFirebaseFunctionMapFactory, where, whereDateIsOnOrBefore, orderBy, limit } from '@dereekb/firebase';
3
+ import { type } from 'arktype';
4
+ import { clearable } from '@dereekb/model';
5
+
6
+ /**
7
+ * Number of digits an {@link OpenRouterPromptVersionId} is padded to.
8
+ *
9
+ * Padding is what makes `orderBy(documentId())` on the subcollection return v2 before v10. Six digits
10
+ * is far past any realistic version count while staying readable.
11
+ */ var OPENROUTER_PROMPT_VERSION_ID_DIGITS = 6;
12
+ /**
13
+ * Converts a version number to its zero-padded document id.
14
+ *
15
+ * @param version - The version number.
16
+ * @returns The document id.
17
+ *
18
+ * @__NO_SIDE_EFFECTS__
19
+ */ function openRouterPromptVersionId(version) {
20
+ return String(version).padStart(OPENROUTER_PROMPT_VERSION_ID_DIGITS, '0');
21
+ }
22
+ /**
23
+ * Reads the version number back out of a version document id.
24
+ *
25
+ * @param id - The document id.
26
+ * @returns The version number, or NaN when the id is not a number.
27
+ *
28
+ * @__NO_SIDE_EFFECTS__
29
+ */ function openRouterPromptVersionNumberFromId(id) {
30
+ return Number(id);
31
+ }
32
+
33
+ function _assert_this_initialized(self) {
34
+ if (self === void 0) {
35
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
36
+ }
37
+ return self;
38
+ }
39
+ function _call_super(_this, derived, args) {
40
+ derived = _get_prototype_of(derived);
41
+ return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
42
+ }
43
+ function _class_call_check$1(instance, Constructor) {
44
+ if (!(instance instanceof Constructor)) {
45
+ throw new TypeError("Cannot call a class as a function");
46
+ }
47
+ }
48
+ function _defineProperties(target, props) {
49
+ for(var i = 0; i < props.length; i++){
50
+ var descriptor = props[i];
51
+ descriptor.enumerable = descriptor.enumerable || false;
52
+ descriptor.configurable = true;
53
+ if ("value" in descriptor) descriptor.writable = true;
54
+ Object.defineProperty(target, descriptor.key, descriptor);
55
+ }
56
+ }
57
+ function _create_class(Constructor, protoProps, staticProps) {
58
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
59
+ return Constructor;
60
+ }
61
+ function _get_prototype_of(o) {
62
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
63
+ return o.__proto__ || Object.getPrototypeOf(o);
64
+ };
65
+ return _get_prototype_of(o);
66
+ }
67
+ function _inherits(subClass, superClass) {
68
+ if (typeof superClass !== "function" && superClass !== null) {
69
+ throw new TypeError("Super expression must either be null or a function");
70
+ }
71
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
72
+ constructor: {
73
+ value: subClass,
74
+ writable: true,
75
+ configurable: true
76
+ }
77
+ });
78
+ if (superClass) _set_prototype_of(subClass, superClass);
79
+ }
80
+ function _possible_constructor_return(self, call) {
81
+ if (call && (_type_of(call) === "object" || typeof call === "function")) {
82
+ return call;
83
+ }
84
+ return _assert_this_initialized(self);
85
+ }
86
+ function _set_prototype_of(o, p) {
87
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
88
+ o.__proto__ = p;
89
+ return o;
90
+ };
91
+ return _set_prototype_of(o, p);
92
+ }
93
+ function _type_of(obj) {
94
+ "@swc/helpers - typeof";
95
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
96
+ }
97
+ function _is_native_reflect_construct() {
98
+ try {
99
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
100
+ } catch (_) {}
101
+ return (_is_native_reflect_construct = function() {
102
+ return !!result;
103
+ })();
104
+ }
105
+ /**
106
+ * Identity for {@link OpenRouterPrompt} documents. Model type: `openRouterPrompt`, collection: `orp`.
107
+ */ var openRouterPromptIdentity = firestoreModelIdentity('openRouterPrompt', 'orp');
108
+ /**
109
+ * Lifecycle state of an {@link OpenRouterPrompt}.
110
+ */ var OpenRouterPromptState;
111
+ (function(OpenRouterPromptState) {
112
+ /**
113
+ * Created but not yet servable. A caller resolving this prompt gets an error rather than a guess.
114
+ */ OpenRouterPromptState[OpenRouterPromptState["DRAFT"] = 0] = "DRAFT";
115
+ /**
116
+ * Servable.
117
+ */ OpenRouterPromptState[OpenRouterPromptState["ACTIVE"] = 1] = "ACTIVE";
118
+ /**
119
+ * Retired. Retained so historical runs stay explicable, but no longer servable.
120
+ */ OpenRouterPromptState[OpenRouterPromptState["ARCHIVED"] = 2] = "ARCHIVED";
121
+ })(OpenRouterPromptState || (OpenRouterPromptState = {}));
122
+ var OpenRouterPromptDocument = /*#__PURE__*/ function(AbstractFirestoreDocument) {
123
+ _inherits(OpenRouterPromptDocument, AbstractFirestoreDocument);
124
+ function OpenRouterPromptDocument() {
125
+ _class_call_check$1(this, OpenRouterPromptDocument);
126
+ return _call_super(this, OpenRouterPromptDocument, arguments);
127
+ }
128
+ _create_class(OpenRouterPromptDocument, [
129
+ {
130
+ key: "modelIdentity",
131
+ get: function get() {
132
+ return openRouterPromptIdentity;
133
+ }
134
+ }
135
+ ]);
136
+ return OpenRouterPromptDocument;
137
+ }(AbstractFirestoreDocument);
138
+ var openRouterPromptConverter = snapshotConverterFunctions({
139
+ fields: {
140
+ cat: firestoreDate({
141
+ saveDefaultAsNow: true
142
+ }),
143
+ uat: optionalFirestoreDate(),
144
+ n: firestoreString({
145
+ default: ''
146
+ }),
147
+ d: optionalFirestoreString(),
148
+ s: firestoreEnum({
149
+ default: OpenRouterPromptState.DRAFT
150
+ }),
151
+ av: optionalFirestoreNumber(),
152
+ lv: firestoreNumber({
153
+ default: 0
154
+ }),
155
+ t: optionalFirestoreArray({
156
+ filterUnique: true,
157
+ dontStoreIfEmpty: true
158
+ })
159
+ }
160
+ });
161
+ /**
162
+ * Returns the root Firestore collection reference for {@link OpenRouterPrompt} documents.
163
+ *
164
+ * @param context - The FirestoreContext used to resolve the collection.
165
+ * @returns A typed CollectionReference for the openRouterPrompt collection.
166
+ */ function openRouterPromptCollectionReference(context) {
167
+ return context.collection(openRouterPromptIdentity.collectionName);
168
+ }
169
+ /**
170
+ * Creates the Firestore collection accessor for {@link OpenRouterPrompt} documents.
171
+ *
172
+ * @param firestoreContext - The FirestoreContext used to build the collection.
173
+ * @returns An OpenRouterPromptFirestoreCollection.
174
+ */ function openRouterPromptFirestoreCollection(firestoreContext) {
175
+ return firestoreContext.firestoreCollection({
176
+ modelIdentity: openRouterPromptIdentity,
177
+ converter: openRouterPromptConverter,
178
+ collection: openRouterPromptCollectionReference(firestoreContext),
179
+ makeDocument: function makeDocument(accessor, documentAccessor) {
180
+ return new OpenRouterPromptDocument(accessor, documentAccessor);
181
+ },
182
+ firestoreContext: firestoreContext
183
+ });
184
+ }
185
+ // MARK: OpenRouterPromptVersion
186
+ /**
187
+ * Identity for {@link OpenRouterPromptVersion} documents. Subcollection of {@link OpenRouterPrompt}.
188
+ * Model type: `openRouterPromptVersion`, collection: `orpv`.
189
+ */ var openRouterPromptVersionIdentity = firestoreModelIdentity(openRouterPromptIdentity, 'openRouterPromptVersion', 'orpv');
190
+ /**
191
+ * With a parent, unlike the other documents here: a version only ever exists in a subcollection under
192
+ * the prompt it belongs to, so a holder of one — a collection-group query result especially — needs a
193
+ * way back to that prompt without parsing the path.
194
+ */ var OpenRouterPromptVersionDocument = /*#__PURE__*/ function(AbstractFirestoreDocumentWithParent) {
195
+ _inherits(OpenRouterPromptVersionDocument, AbstractFirestoreDocumentWithParent);
196
+ function OpenRouterPromptVersionDocument() {
197
+ _class_call_check$1(this, OpenRouterPromptVersionDocument);
198
+ return _call_super(this, OpenRouterPromptVersionDocument, arguments);
199
+ }
200
+ _create_class(OpenRouterPromptVersionDocument, [
201
+ {
202
+ key: "modelIdentity",
203
+ get: function get() {
204
+ return openRouterPromptVersionIdentity;
205
+ }
206
+ }
207
+ ]);
208
+ return OpenRouterPromptVersionDocument;
209
+ }(AbstractFirestoreDocumentWithParent);
210
+ var openRouterPromptVersionConverter = snapshotConverterFunctions({
211
+ fields: {
212
+ cat: firestoreDate({
213
+ saveDefaultAsNow: true
214
+ }),
215
+ v: firestoreNumber({
216
+ default: 0
217
+ }),
218
+ i: optionalFirestoreString(),
219
+ m: optionalFirestoreArray({
220
+ dontStoreIfEmpty: true
221
+ }),
222
+ c: optionalFirestorePassthroughJsonField(),
223
+ nt: optionalFirestoreString(),
224
+ by: optionalFirestoreString(),
225
+ lk: optionalFirestoreBoolean()
226
+ }
227
+ });
228
+ /**
229
+ * Creates a factory that produces {@link OpenRouterPromptVersion} subcollection references for a given
230
+ * {@link OpenRouterPromptDocument} parent.
231
+ *
232
+ * @param context - Firestore context to create subcollection references from.
233
+ * @returns A factory function that creates collection references for a given prompt parent.
234
+ *
235
+ * @__NO_SIDE_EFFECTS__
236
+ */ function openRouterPromptVersionCollectionReferenceFactory(context) {
237
+ return function(prompt) {
238
+ return context.subcollection(prompt.documentRef, openRouterPromptVersionIdentity.collectionName);
239
+ };
240
+ }
241
+ /**
242
+ * Creates an {@link OpenRouterPromptVersionFirestoreCollectionFactory} bound to the given context.
243
+ *
244
+ * @param firestoreContext - Firestore context to bind the collection factory to.
245
+ * @returns A factory that creates typed subcollections for version documents.
246
+ *
247
+ * @__NO_SIDE_EFFECTS__
248
+ */ function openRouterPromptVersionFirestoreCollectionFactory(firestoreContext) {
249
+ var factory = openRouterPromptVersionCollectionReferenceFactory(firestoreContext);
250
+ return function(parent) {
251
+ return firestoreContext.firestoreCollectionWithParent({
252
+ modelIdentity: openRouterPromptVersionIdentity,
253
+ converter: openRouterPromptVersionConverter,
254
+ collection: factory(parent),
255
+ makeDocument: function makeDocument(accessor, documentAccessor) {
256
+ return new OpenRouterPromptVersionDocument(accessor, documentAccessor);
257
+ },
258
+ firestoreContext: firestoreContext,
259
+ parent: parent
260
+ });
261
+ };
262
+ }
263
+ /**
264
+ * Creates a collection group reference for querying every {@link OpenRouterPromptVersion} across all
265
+ * prompts.
266
+ *
267
+ * @param context - Firestore context to create the collection group reference from.
268
+ * @returns A typed collection group.
269
+ */ function openRouterPromptVersionCollectionReference(context) {
270
+ return context.collectionGroup(openRouterPromptVersionIdentity.collectionName);
271
+ }
272
+ /**
273
+ * Creates a typed {@link OpenRouterPromptVersionFirestoreCollectionGroup} bound to the given context.
274
+ *
275
+ * @param firestoreContext - Firestore context to bind the collection group to.
276
+ * @returns A typed Firestore collection group.
277
+ */ function openRouterPromptVersionFirestoreCollectionGroup(firestoreContext) {
278
+ return firestoreContext.firestoreCollectionGroup({
279
+ modelIdentity: openRouterPromptVersionIdentity,
280
+ converter: openRouterPromptVersionConverter,
281
+ queryLike: openRouterPromptVersionCollectionReference(firestoreContext),
282
+ makeDocument: function makeDocument(accessor, documentAccessor) {
283
+ return new OpenRouterPromptVersionDocument(accessor, documentAccessor);
284
+ },
285
+ firestoreContext: firestoreContext
286
+ });
287
+ }
288
+ // MARK: OpenRouterRunTask
289
+ /**
290
+ * How long an OpenRouterRunTask lives before it is deleted, measured from `qat`.
291
+ *
292
+ * A design requirement rather than a tuning knob. NotificationTask already owns retrying, durable
293
+ * persistence, and delayed execution, so a run task is a short-lived execution record — letting one
294
+ * outlive a week would make it a second system of record with a second retention policy to reason about,
295
+ * for no gain.
296
+ *
297
+ * Measured from `qat` rather than a per-task expiration field because there is nothing to configure:
298
+ * a queued task runs essentially immediately, so its queue time IS its age. No field to forget to
299
+ * write, no document excluded from the retention query for lacking one.
300
+ */ var OPENROUTER_RUN_TASK_MAX_AGE = MS_IN_DAY * 7;
301
+ /**
302
+ * Identity for {@link OpenRouterRunTask} documents. Model type: `openRouterRunTask`, collection: `orrt`.
303
+ */ var openRouterRunTaskIdentity = firestoreModelIdentity('openRouterRunTask', 'orrt');
304
+ /**
305
+ * State of an {@link OpenRouterRunTask}.
306
+ */ var OpenRouterRunTaskState;
307
+ (function(OpenRouterRunTaskState) {
308
+ /**
309
+ * Enqueued and waiting for a sweep to claim it.
310
+ */ OpenRouterRunTaskState[OpenRouterRunTaskState["QUEUED"] = 0] = "QUEUED";
311
+ /**
312
+ * Claimed by a sweep and executing.
313
+ *
314
+ * A `RUNNING` document whose lease has gone stale is reclaimable — that is what makes a crashed
315
+ * sweep recoverable instead of permanently stuck.
316
+ */ OpenRouterRunTaskState[OpenRouterRunTaskState["RUNNING"] = 1] = "RUNNING";
317
+ /**
318
+ * Finished successfully. `o` / `j` hold the result.
319
+ */ OpenRouterRunTaskState[OpenRouterRunTaskState["COMPLETE"] = 2] = "COMPLETE";
320
+ /**
321
+ * Finished unsuccessfully, with the retry budget spent. `e` holds why.
322
+ */ OpenRouterRunTaskState[OpenRouterRunTaskState["FAILED"] = 3] = "FAILED";
323
+ /**
324
+ * Paused mid-run waiting on a deferred tool result from another process.
325
+ *
326
+ * Resumable: the next sweep picks it up once `utr` carries the resolutions.
327
+ */ OpenRouterRunTaskState[OpenRouterRunTaskState["AWAITING_ASYNC_TOOLS"] = 4] = "AWAITING_ASYNC_TOOLS";
328
+ })(OpenRouterRunTaskState || (OpenRouterRunTaskState = {}));
329
+ /**
330
+ * States a sweep considers claimable.
331
+ *
332
+ * `AWAITING_ASYNC_TOOLS` is in here alongside `QUEUED` because a task parked on a deferred tool whose
333
+ * results have since arrived is runnable again; `isOpenRouterRunTaskClaimable` is what decides whether
334
+ * the results actually did arrive.
335
+ */ var OPENROUTER_RUN_TASK_CLAIMABLE_STATES = [
336
+ OpenRouterRunTaskState.QUEUED,
337
+ OpenRouterRunTaskState.AWAITING_ASYNC_TOOLS
338
+ ];
339
+ /**
340
+ * States a run task will never leave.
341
+ */ var OPENROUTER_RUN_TASK_TERMINAL_STATES = [
342
+ OpenRouterRunTaskState.COMPLETE,
343
+ OpenRouterRunTaskState.FAILED
344
+ ];
345
+ /**
346
+ * Whether a state is terminal.
347
+ *
348
+ * @param state - The state to check.
349
+ * @returns True when the run will not change state again.
350
+ *
351
+ * @__NO_SIDE_EFFECTS__
352
+ */ function isOpenRouterRunTaskStateTerminal(state) {
353
+ return OPENROUTER_RUN_TASK_TERMINAL_STATES.includes(state);
354
+ }
355
+ var OpenRouterRunTaskDocument = /*#__PURE__*/ function(AbstractFirestoreDocument) {
356
+ _inherits(OpenRouterRunTaskDocument, AbstractFirestoreDocument);
357
+ function OpenRouterRunTaskDocument() {
358
+ _class_call_check$1(this, OpenRouterRunTaskDocument);
359
+ return _call_super(this, OpenRouterRunTaskDocument, arguments);
360
+ }
361
+ _create_class(OpenRouterRunTaskDocument, [
362
+ {
363
+ key: "modelIdentity",
364
+ get: function get() {
365
+ return openRouterRunTaskIdentity;
366
+ }
367
+ }
368
+ ]);
369
+ return OpenRouterRunTaskDocument;
370
+ }(AbstractFirestoreDocument);
371
+ var openRouterRunTaskConverter = snapshotConverterFunctions({
372
+ fields: {
373
+ s: firestoreEnum({
374
+ default: OpenRouterRunTaskState.QUEUED
375
+ }),
376
+ qat: firestoreDate({
377
+ saveDefaultAsNow: true
378
+ }),
379
+ sat: optionalFirestoreDate(),
380
+ fat: optionalFirestoreDate(),
381
+ lat: optionalFirestoreDate(),
382
+ lo: optionalFirestoreString(),
383
+ at: firestoreNumber({
384
+ default: 0
385
+ }),
386
+ pk: firestoreString({
387
+ default: ''
388
+ }),
389
+ pv: firestoreNumber({
390
+ default: 0
391
+ }),
392
+ in: firestoreArray({}),
393
+ fp: optionalFirestoreArray({
394
+ dontStoreIfEmpty: true
395
+ }),
396
+ fa: optionalFirestoreArray({
397
+ dontStoreIfEmpty: true
398
+ }),
399
+ co: optionalFirestorePassthroughJsonField(),
400
+ o: optionalFirestoreString(),
401
+ j: optionalFirestorePassthroughJsonField(),
402
+ gi: optionalFirestoreArray({
403
+ filterUnique: true,
404
+ dontStoreIfEmpty: true
405
+ }),
406
+ u: optionalFirestorePassthroughJsonField(),
407
+ e: optionalFirestorePassthroughJsonField(),
408
+ msg: optionalFirestoreArray({
409
+ dontStoreIfEmpty: true
410
+ }),
411
+ ptc: optionalFirestoreArray({
412
+ dontStoreIfEmpty: true
413
+ }),
414
+ utr: optionalFirestoreArray({
415
+ dontStoreIfEmpty: true
416
+ })
417
+ }
418
+ });
419
+ /**
420
+ * Returns the root Firestore collection reference for {@link OpenRouterRunTask} documents.
421
+ *
422
+ * @param context - The FirestoreContext used to resolve the collection.
423
+ * @returns A typed CollectionReference for the openRouterRunTask collection.
424
+ */ function openRouterRunTaskCollectionReference(context) {
425
+ return context.collection(openRouterRunTaskIdentity.collectionName);
426
+ }
427
+ /**
428
+ * Creates the Firestore collection accessor for {@link OpenRouterRunTask} documents.
429
+ *
430
+ * @param firestoreContext - The FirestoreContext used to build the collection.
431
+ * @returns An OpenRouterRunTaskFirestoreCollection.
432
+ */ function openRouterRunTaskFirestoreCollection(firestoreContext) {
433
+ return firestoreContext.firestoreCollection({
434
+ modelIdentity: openRouterRunTaskIdentity,
435
+ converter: openRouterRunTaskConverter,
436
+ collection: openRouterRunTaskCollectionReference(firestoreContext),
437
+ makeDocument: function makeDocument(accessor, documentAccessor) {
438
+ return new OpenRouterRunTaskDocument(accessor, documentAccessor);
439
+ },
440
+ firestoreContext: firestoreContext
441
+ });
442
+ }
443
+ // MARK: Utility
444
+ /**
445
+ * Converts a stored version document into the resolved prompt the request builder consumes.
446
+ *
447
+ * @param promptKey - The prompt key the version belongs to.
448
+ * @param version - The stored version.
449
+ * @returns The resolved prompt.
450
+ *
451
+ * @__NO_SIDE_EFFECTS__
452
+ */ function openRouterResolvedPromptForVersion(promptKey, version) {
453
+ var _version_c;
454
+ var _version_m;
455
+ return {
456
+ promptKey: promptKey,
457
+ version: version.v,
458
+ instructions: version.i,
459
+ messages: (_version_m = version.m) === null || _version_m === void 0 ? void 0 : _version_m.map(function(param) {
460
+ var r = param.r, c = param.c;
461
+ return {
462
+ role: r,
463
+ content: c
464
+ };
465
+ }),
466
+ config: (_version_c = version.c) !== null && _version_c !== void 0 ? _version_c : {}
467
+ };
468
+ }
469
+ /**
470
+ * The document id of a version, from its number.
471
+ *
472
+ * Re-exported here so a caller reading a version does not need to reach for the id module separately.
473
+ */ var openRouterPromptVersionDocumentId = openRouterPromptVersionId;
474
+
475
+ function _class_call_check(instance, Constructor) {
476
+ if (!(instance instanceof Constructor)) {
477
+ throw new TypeError("Cannot call a class as a function");
478
+ }
479
+ }
480
+ var updateOpenRouterPromptParamsType = /* @__PURE__ */ inferredTargetModelParamsType.merge(type({
481
+ 'name?': clearable('string'),
482
+ 'description?': clearable('string'),
483
+ 'tags?': clearable('string[]'),
484
+ 'state?': clearable('number'),
485
+ 'activeVersion?': clearable('number')
486
+ }));
487
+ var openRouterPromptVersionMessageParamsType = /* @__PURE__ */ type({
488
+ role: "'user' | 'system' | 'assistant' | 'developer'",
489
+ content: 'string'
490
+ });
491
+ var createOpenRouterPromptVersionParamsType = /* @__PURE__ */ type({
492
+ prompt: 'string >= 1',
493
+ 'instructions?': clearable('string'),
494
+ 'messages?': clearable(openRouterPromptVersionMessageParamsType.array()),
495
+ 'config?': clearable('object'),
496
+ 'notes?': clearable('string'),
497
+ 'activate?': clearable('boolean')
498
+ });
499
+ var updateOpenRouterPromptVersionParamsType = /* @__PURE__ */ inferredTargetModelParamsType.merge(type({
500
+ 'instructions?': clearable('string'),
501
+ 'messages?': clearable(openRouterPromptVersionMessageParamsType.array()),
502
+ 'config?': clearable('object'),
503
+ 'notes?': clearable('string')
504
+ }));
505
+ var readOpenRouterRunTaskParamsType = /* @__PURE__ */ type({
506
+ key: 'string >= 1'
507
+ });
508
+ var OPENROUTER_PROMPT_FUNCTION_TYPE_CONFIG_MAP = {};
509
+ var OPENROUTER_PROMPT_MODEL_CRUD_FUNCTIONS_CONFIG = {
510
+ openRouterPrompt: [
511
+ 'update',
512
+ 'query'
513
+ ],
514
+ openRouterPromptVersion: [
515
+ 'create',
516
+ 'update'
517
+ ]
518
+ };
519
+ /**
520
+ * Abstract class defining the callable OpenRouter prompt functions.
521
+ */ var OpenRouterPromptModelFunctions = function OpenRouterPromptModelFunctions() {
522
+ _class_call_check(this, OpenRouterPromptModelFunctions);
523
+ };
524
+ /**
525
+ * Client-side callable function map factory for OpenRouter prompt CRUD.
526
+ */ var openRouterPromptModelFunctionMap = callModelFirebaseFunctionMapFactory(OPENROUTER_PROMPT_FUNCTION_TYPE_CONFIG_MAP, OPENROUTER_PROMPT_MODEL_CRUD_FUNCTIONS_CONFIG);
527
+
528
+ /**
529
+ * Query for the prompts in one lifecycle state.
530
+ *
531
+ * Needs no composite index, and is deliberately kept that way. Unordered, so pagination falls through to
532
+ * Firestore's implicit `__name__` order — which for this model is the prompt's own readable key, already
533
+ * the order a listing wants — and state is the only filter axis: pairing it with an `array-contains` on
534
+ * `t` would buy a composite index for a collection measured in dozens of documents.
535
+ *
536
+ * @param params - The state to match.
537
+ * @returns Firestore query constraints for the prompts in that state.
538
+ *
539
+ * @dbxModelFirebaseIndex
540
+ * @dbxModelFirebaseIndexModel OpenRouterPrompt
541
+ * @dbxModelFirebaseIndexScope COLLECTION
542
+ * @dbxModelFirebaseIndexCategory admin
543
+ */ function openRouterPromptsWithStateQuery(params) {
544
+ return [
545
+ where('s', '==', params.state)
546
+ ];
547
+ }
548
+ /**
549
+ * Query for the run tasks a sweep may execute, oldest-queued first.
550
+ *
551
+ * Queue order is the ONLY order, and deliberately so. A priority column costs a second composite index
552
+ * and buys a second failure mode: Firestore sorts `null` before every number, so one task written without
553
+ * a priority jumps the entire queue. Delaying a run is `NotificationTask`'s job — it owns the delayed
554
+ * firing — which leaves nothing for a priority here to express.
555
+ *
556
+ * @param params - The page limit.
557
+ * @returns Firestore query constraints for the runnable page.
558
+ *
559
+ * @dbxModelFirebaseIndex
560
+ * @dbxModelFirebaseIndexModel OpenRouterRunTask
561
+ * @dbxModelFirebaseIndexScope COLLECTION
562
+ * @dbxModelFirebaseIndexCategory sweep
563
+ */ function openRouterRunTasksRunnableQuery(params) {
564
+ var pageLimit = params.limit;
565
+ return [
566
+ where('s', 'in', OPENROUTER_RUN_TASK_CLAIMABLE_STATES),
567
+ orderBy('qat', 'asc'),
568
+ limit(pageLimit)
569
+ ];
570
+ }
571
+ /**
572
+ * Query for RUNNING run tasks whose lease has gone stale — crash recovery.
573
+ *
574
+ * Separate from {@link openRouterRunTasksRunnableQuery} because it needs a range filter on `lat`, and
575
+ * Firestore allows the range filter on only one field, which the ordering must then lead with.
576
+ *
577
+ * The cutoff goes through `whereDateIsOnOrBefore` rather than a bare `where('lat', '<=', date)`:
578
+ * `firestoreDate` persists an ISO8601 STRING, so comparing the field against a `Date` compares a string
579
+ * to a timestamp and matches nothing — silently, with no error and an empty page, which reads exactly
580
+ * like "no crashed sweeps to recover".
581
+ *
582
+ * @param params - The page limit and lease cutoff.
583
+ * @returns Firestore query constraints for the reclaimable page.
584
+ *
585
+ * @dbxModelFirebaseIndex
586
+ * @dbxModelFirebaseIndexModel OpenRouterRunTask
587
+ * @dbxModelFirebaseIndexScope COLLECTION
588
+ * @dbxModelFirebaseIndexCategory sweep
589
+ */ function openRouterRunTasksReclaimableQuery(params) {
590
+ var pageLimit = params.limit, leaseCutoff = params.leaseCutoff;
591
+ return [
592
+ where('s', '==', OpenRouterRunTaskState.RUNNING),
593
+ whereDateIsOnOrBefore('lat', leaseCutoff),
594
+ orderBy('lat', 'asc'),
595
+ limit(pageLimit)
596
+ ];
597
+ }
598
+ /**
599
+ * Query for run tasks past their retention age, for deletion. Matches EVERY state, `RUNNING` included —
600
+ * see {@link OPENROUTER_RUN_TASK_MAX_AGE} for why the ceiling is the whole requirement.
601
+ *
602
+ * Ordered by `qat` with no state filter, so it needs no composite index at all: a single-field range with
603
+ * a matching order is served by Firestore's automatic single-field index.
604
+ *
605
+ * Firestore's NATIVE TTL policy cannot do this job, for the same reason the cutoff goes through
606
+ * `whereDateIsOnOrBefore` rather than a bare `where('qat', '<=', date)`: `firestoreDate` persists an
607
+ * ISO8601 STRING, and a TTL policy only deletes on a `Timestamp` field. Pointed at `qat` it would
608
+ * silently never fire. The app-level sweep is the mechanism here, not a stopgap for one.
609
+ *
610
+ * @param params - The retention cutoff and page limit.
611
+ * @returns Firestore query constraints for the expired page.
612
+ *
613
+ * @dbxModelFirebaseIndex
614
+ * @dbxModelFirebaseIndexModel OpenRouterRunTask
615
+ * @dbxModelFirebaseIndexScope COLLECTION
616
+ * @dbxModelFirebaseIndexCategory cleanup
617
+ */ function openRouterRunTasksExpiredQuery(params) {
618
+ var before = params.before, pageLimit = params.limit;
619
+ return [
620
+ whereDateIsOnOrBefore('qat', before),
621
+ orderBy('qat', 'asc'),
622
+ limit(pageLimit)
623
+ ];
624
+ }
625
+
626
+ export { OPENROUTER_PROMPT_FUNCTION_TYPE_CONFIG_MAP, OPENROUTER_PROMPT_MODEL_CRUD_FUNCTIONS_CONFIG, OPENROUTER_PROMPT_VERSION_ID_DIGITS, OPENROUTER_RUN_TASK_CLAIMABLE_STATES, OPENROUTER_RUN_TASK_MAX_AGE, OPENROUTER_RUN_TASK_TERMINAL_STATES, OpenRouterPromptDocument, OpenRouterPromptModelFunctions, OpenRouterPromptState, OpenRouterPromptVersionDocument, OpenRouterRunTaskDocument, OpenRouterRunTaskState, createOpenRouterPromptVersionParamsType, isOpenRouterRunTaskStateTerminal, openRouterPromptCollectionReference, openRouterPromptConverter, openRouterPromptFirestoreCollection, openRouterPromptIdentity, openRouterPromptModelFunctionMap, openRouterPromptVersionCollectionReference, openRouterPromptVersionCollectionReferenceFactory, openRouterPromptVersionConverter, openRouterPromptVersionDocumentId, openRouterPromptVersionFirestoreCollectionFactory, openRouterPromptVersionFirestoreCollectionGroup, openRouterPromptVersionId, openRouterPromptVersionIdentity, openRouterPromptVersionMessageParamsType, openRouterPromptVersionNumberFromId, openRouterPromptsWithStateQuery, openRouterResolvedPromptForVersion, openRouterRunTaskCollectionReference, openRouterRunTaskConverter, openRouterRunTaskFirestoreCollection, openRouterRunTaskIdentity, openRouterRunTasksExpiredQuery, openRouterRunTasksReclaimableQuery, openRouterRunTasksRunnableQuery, readOpenRouterRunTaskParamsType, updateOpenRouterPromptParamsType, updateOpenRouterPromptVersionParamsType };
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "@dereekb/openrouter/firebase",
3
+ "version": "13.37.0",
4
+ "peerDependencies": {
5
+ "@dereekb/date": "13.37.0",
6
+ "@dereekb/firebase": "13.37.0",
7
+ "@dereekb/model": "13.37.0",
8
+ "@dereekb/openrouter": "13.37.0",
9
+ "@dereekb/rxjs": "13.37.0",
10
+ "@dereekb/util": "13.37.0",
11
+ "arktype": "^2.2.0"
12
+ },
13
+ "exports": {
14
+ "./package.json": "./package.json",
15
+ ".": {
16
+ "module": "./index.esm.js",
17
+ "types": "./index.d.ts",
18
+ "import": "./index.cjs.mjs",
19
+ "default": "./index.cjs.js"
20
+ }
21
+ },
22
+ "module": "./index.esm.js",
23
+ "main": "./index.cjs.js",
24
+ "types": "./index.d.ts"
25
+ }
@@ -0,0 +1 @@
1
+ export * from './lib';
@@ -0,0 +1,4 @@
1
+ export * from './openrouter.model';
2
+ export * from './openrouter.api';
3
+ export * from './openrouter.id';
4
+ export * from './openrouter.query';