@dereekb/openrouter 13.38.0 → 13.40.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.
@@ -1,4520 +0,0 @@
1
- 'use strict';
2
-
3
- var firebase$1 = require('@dereekb/firebase');
4
- var util = require('@dereekb/util');
5
- var openrouter = require('@dereekb/openrouter');
6
- var firebase = require('@dereekb/openrouter/firebase');
7
-
8
- function asyncGeneratorStep$8(gen, resolve, reject, _next, _throw, key, arg) {
9
- try {
10
- var info = gen[key](arg);
11
- var value = info.value;
12
- } catch (error) {
13
- reject(error);
14
- return;
15
- }
16
- if (info.done) {
17
- resolve(value);
18
- } else {
19
- Promise.resolve(value).then(_next, _throw);
20
- }
21
- }
22
- function _async_to_generator$8(fn) {
23
- return function() {
24
- var self = this, args = arguments;
25
- return new Promise(function(resolve, reject) {
26
- var gen = fn.apply(self, args);
27
- function _next(value) {
28
- asyncGeneratorStep$8(gen, resolve, reject, _next, _throw, "next", value);
29
- }
30
- function _throw(err) {
31
- asyncGeneratorStep$8(gen, resolve, reject, _next, _throw, "throw", err);
32
- }
33
- _next(undefined);
34
- });
35
- };
36
- }
37
- function _class_call_check$3(instance, Constructor) {
38
- if (!(instance instanceof Constructor)) {
39
- throw new TypeError("Cannot call a class as a function");
40
- }
41
- }
42
- function _define_property$3(obj, key, value) {
43
- if (key in obj) {
44
- Object.defineProperty(obj, key, {
45
- value: value,
46
- enumerable: true,
47
- configurable: true,
48
- writable: true
49
- });
50
- } else {
51
- obj[key] = value;
52
- }
53
- return obj;
54
- }
55
- function _object_spread$2(target) {
56
- for(var i = 1; i < arguments.length; i++){
57
- var source = arguments[i] != null ? arguments[i] : {};
58
- var ownKeys = Object.keys(source);
59
- if (typeof Object.getOwnPropertySymbols === "function") {
60
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
61
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
62
- }));
63
- }
64
- ownKeys.forEach(function(key) {
65
- _define_property$3(target, key, source[key]);
66
- });
67
- }
68
- return target;
69
- }
70
- function _ts_generator$8(thisArg, body) {
71
- var f, y, t, _ = {
72
- label: 0,
73
- sent: function() {
74
- if (t[0] & 1) throw t[1];
75
- return t[1];
76
- },
77
- trys: [],
78
- ops: []
79
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
80
- return d(g, "next", {
81
- value: verb(0)
82
- }), d(g, "throw", {
83
- value: verb(1)
84
- }), d(g, "return", {
85
- value: verb(2)
86
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
87
- value: function() {
88
- return this;
89
- }
90
- }), g;
91
- function verb(n) {
92
- return function(v) {
93
- return step([
94
- n,
95
- v
96
- ]);
97
- };
98
- }
99
- function step(op) {
100
- if (f) throw new TypeError("Generator is already executing.");
101
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
102
- 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;
103
- if (y = 0, t) op = [
104
- op[0] & 2,
105
- t.value
106
- ];
107
- switch(op[0]){
108
- case 0:
109
- case 1:
110
- t = op;
111
- break;
112
- case 4:
113
- _.label++;
114
- return {
115
- value: op[1],
116
- done: false
117
- };
118
- case 5:
119
- _.label++;
120
- y = op[1];
121
- op = [
122
- 0
123
- ];
124
- continue;
125
- case 7:
126
- op = _.ops.pop();
127
- _.trys.pop();
128
- continue;
129
- default:
130
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
131
- _ = 0;
132
- continue;
133
- }
134
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
135
- _.label = op[1];
136
- break;
137
- }
138
- if (op[0] === 6 && _.label < t[1]) {
139
- _.label = t[1];
140
- t = op;
141
- break;
142
- }
143
- if (t && _.label < t[2]) {
144
- _.label = t[2];
145
- _.ops.push(op);
146
- break;
147
- }
148
- if (t[2]) _.ops.pop();
149
- _.trys.pop();
150
- continue;
151
- }
152
- op = body.call(thisArg, _);
153
- } catch (e) {
154
- op = [
155
- 6,
156
- e
157
- ];
158
- y = 0;
159
- } finally{
160
- f = t = 0;
161
- }
162
- if (op[0] & 5) throw op[1];
163
- return {
164
- value: op[0] ? op[1] : void 0,
165
- done: true
166
- };
167
- }
168
- }
169
- /**
170
- * Server actions for managing prompts.
171
- *
172
- * The writes exist instead of an Angular UI: they reach the model API, and the existing callModel MCP
173
- * surface makes them callable without building a screen for it. Reads are absent because the prompt and
174
- * version model services already make both fetchable by key through model-get, and listing is the
175
- * model API's standard query operation over {@link openRouterPromptsWithStateQuery}.
176
- */ var OpenRouterPromptServerActions = function OpenRouterPromptServerActions() {
177
- _class_call_check$3(this, OpenRouterPromptServerActions);
178
- };
179
- /**
180
- * Creates the {@link OpenRouterPromptServerActions}.
181
- *
182
- * @param context - The actions context.
183
- * @returns The server actions.
184
- */ function openRouterPromptServerActions(context) {
185
- return {
186
- createOpenRouterPrompt: createOpenRouterPromptFactory(context),
187
- updateOpenRouterPrompt: updateOpenRouterPromptFactory(context),
188
- createOpenRouterPromptVersion: createOpenRouterPromptVersionFactory(context),
189
- updateOpenRouterPromptVersion: updateOpenRouterPromptVersionFactory(context),
190
- seedOpenRouterPrompts: seedOpenRouterPromptsFactory(context)
191
- };
192
- }
193
- /**
194
- * Creates a new prompt at its caller-supplied key, refusing a key that already exists.
195
- *
196
- * Takes its params directly rather than through an arktype-validated action: the only callers are a
197
- * seed and a test, both of them server-side.
198
- *
199
- * @param context - The actions context.
200
- * @returns The create action.
201
- */ function createOpenRouterPromptFactory(context) {
202
- var openRouterPromptCollection = context.openRouterPromptCollection;
203
- return function(params) {
204
- return _async_to_generator$8(function() {
205
- var key, name, description, tags;
206
- return _ts_generator$8(this, function(_state) {
207
- key = params.key, name = params.name, description = params.description, tags = params.tags;
208
- return [
209
- 2,
210
- openRouterPromptCollection.firestoreContext.runTransaction(function(transaction) {
211
- return _async_to_generator$8(function() {
212
- var document, exists;
213
- return _ts_generator$8(this, function(_state) {
214
- switch(_state.label){
215
- case 0:
216
- document = openRouterPromptCollection.documentAccessorForTransaction(transaction).loadDocumentForId(key);
217
- return [
218
- 4,
219
- document.accessor.exists()
220
- ];
221
- case 1:
222
- exists = _state.sent();
223
- if (exists) {
224
- throw new Error('An OpenRouterPrompt with the key "'.concat(key, '" already exists.'));
225
- }
226
- return [
227
- 4,
228
- document.accessor.set({
229
- cat: new Date(),
230
- n: name,
231
- d: description,
232
- s: firebase.OpenRouterPromptState.DRAFT,
233
- lv: 0,
234
- t: tags
235
- })
236
- ];
237
- case 2:
238
- _state.sent();
239
- return [
240
- 2,
241
- openRouterPromptCollection.documentAccessor().loadDocumentForId(key)
242
- ];
243
- }
244
- });
245
- })();
246
- })
247
- ];
248
- });
249
- })();
250
- };
251
- }
252
- /**
253
- * Updates a prompt's metadata, lifecycle state, or active version, then drops its cached resolution.
254
- *
255
- * @param context - The actions context.
256
- * @returns The update action.
257
- */ function updateOpenRouterPromptFactory(context) {
258
- var firebaseServerActionTransformFunctionFactory = context.firebaseServerActionTransformFunctionFactory, openRouterPromptCollection = context.openRouterPromptCollection, openRouterPromptVersionCollectionFactory = context.openRouterPromptVersionCollectionFactory, openRouterPromptService = context.openRouterPromptService;
259
- return firebaseServerActionTransformFunctionFactory(firebase.updateOpenRouterPromptParamsType, function(params) {
260
- return _async_to_generator$8(function() {
261
- var name, description, tags, state, activeVersion;
262
- return _ts_generator$8(this, function(_state) {
263
- name = params.name, description = params.description, tags = params.tags, state = params.state, activeVersion = params.activeVersion;
264
- return [
265
- 2,
266
- function(document) {
267
- return _async_to_generator$8(function() {
268
- return _ts_generator$8(this, function(_state) {
269
- switch(_state.label){
270
- case 0:
271
- return [
272
- 4,
273
- openRouterPromptCollection.firestoreContext.runTransaction(function(transaction) {
274
- return _async_to_generator$8(function() {
275
- var inTransaction, prompt, versionDocument, versionExists;
276
- return _ts_generator$8(this, function(_state) {
277
- switch(_state.label){
278
- case 0:
279
- inTransaction = openRouterPromptCollection.documentAccessorForTransaction(transaction).loadDocument(document.documentRef);
280
- return [
281
- 4,
282
- inTransaction.snapshotData()
283
- ];
284
- case 1:
285
- prompt = _state.sent();
286
- if (prompt == null) {
287
- throw new Error('The OpenRouterPrompt "'.concat(document.id, '" does not exist.'));
288
- }
289
- if (!(activeVersion != null)) return [
290
- 3,
291
- 3
292
- ];
293
- // Promoting to a version that was never published would leave every unpinned caller failing to
294
- // resolve, so the pointer is only allowed to move to a version that exists.
295
- versionDocument = openRouterPromptVersionCollectionFactory(inTransaction).documentAccessorForTransaction(transaction).loadDocumentForId(firebase.openRouterPromptVersionId(activeVersion));
296
- return [
297
- 4,
298
- versionDocument.accessor.exists()
299
- ];
300
- case 2:
301
- versionExists = _state.sent();
302
- if (!versionExists) {
303
- throw new Error("Cannot set activeVersion to ".concat(activeVersion, ' on OpenRouterPrompt "').concat(document.id, '": that version does not exist.'));
304
- }
305
- _state.label = 3;
306
- case 3:
307
- return [
308
- 4,
309
- inTransaction.update({
310
- n: name !== null && name !== void 0 ? name : undefined,
311
- d: description,
312
- t: tags,
313
- s: state !== null && state !== void 0 ? state : undefined,
314
- av: activeVersion,
315
- uat: new Date()
316
- })
317
- ];
318
- case 4:
319
- _state.sent();
320
- return [
321
- 2
322
- ];
323
- }
324
- });
325
- })();
326
- })
327
- ];
328
- case 1:
329
- _state.sent();
330
- openRouterPromptService.clearCachedPrompt(document.id);
331
- return [
332
- 2,
333
- document
334
- ];
335
- }
336
- });
337
- })();
338
- }
339
- ];
340
- });
341
- })();
342
- });
343
- }
344
- /**
345
- * Creates a new version, allocating its number inside the transaction, locking the version it succeeds,
346
- * and optionally promoting it.
347
- *
348
- * @param context - The actions context.
349
- * @returns The create version action.
350
- */ function createOpenRouterPromptVersionFactory(context) {
351
- var firebaseServerActionTransformFunctionFactory = context.firebaseServerActionTransformFunctionFactory, openRouterPromptCollection = context.openRouterPromptCollection, openRouterPromptVersionCollectionFactory = context.openRouterPromptVersionCollectionFactory, openRouterPromptService = context.openRouterPromptService;
352
- return firebaseServerActionTransformFunctionFactory(firebase.createOpenRouterPromptVersionParamsType, function(params) {
353
- return _async_to_generator$8(function() {
354
- var instructions, messages, config, notes, activate;
355
- return _ts_generator$8(this, function(_state) {
356
- instructions = params.instructions, messages = params.messages, config = params.config, notes = params.notes, activate = params.activate;
357
- return [
358
- 2,
359
- function(document) {
360
- return _async_to_generator$8(function() {
361
- var modelConfig, validation, result;
362
- return _ts_generator$8(this, function(_state) {
363
- switch(_state.label){
364
- case 0:
365
- modelConfig = config !== null && config !== void 0 ? config : undefined;
366
- validation = openrouter.validateOpenRouterModelConfig(modelConfig !== null && modelConfig !== void 0 ? modelConfig : {});
367
- if (!validation.valid) {
368
- throw new Error('Cannot create a version of OpenRouterPrompt "'.concat(document.id, '": ').concat(validation.errors.join(' ')));
369
- }
370
- return [
371
- 4,
372
- openRouterPromptCollection.firestoreContext.runTransaction(function(transaction) {
373
- return _async_to_generator$8(function() {
374
- var inTransaction, prompt, version, versionCollection, versionDocument, previousVersionDocument, previousVersionExists, _tmp, versionData;
375
- return _ts_generator$8(this, function(_state) {
376
- switch(_state.label){
377
- case 0:
378
- inTransaction = openRouterPromptCollection.documentAccessorForTransaction(transaction).loadDocument(document.documentRef);
379
- return [
380
- 4,
381
- inTransaction.snapshotData()
382
- ];
383
- case 1:
384
- prompt = _state.sent();
385
- if (prompt == null) {
386
- throw new Error('The OpenRouterPrompt "'.concat(document.id, '" does not exist.'));
387
- }
388
- // Allocated from the prompt document inside the transaction rather than supplied by the caller:
389
- // two concurrent creates picking the same number would silently overwrite one another.
390
- version = prompt.lv + 1;
391
- versionCollection = openRouterPromptVersionCollectionFactory(inTransaction).documentAccessorForTransaction(transaction);
392
- versionDocument = versionCollection.loadDocumentForId(firebase.openRouterPromptVersionId(version));
393
- // The outgoing version stops being editable the moment it stops being the head — in the same
394
- // transaction, so there is no window in which two versions are both unlocked. Read first:
395
- // Firestore forbids a read after a write in a transaction, and a `set` on a version that was
396
- // deleted out from under us would resurrect it as a document holding nothing but a lock.
397
- previousVersionDocument = prompt.lv > 0 ? versionCollection.loadDocumentForId(firebase.openRouterPromptVersionId(prompt.lv)) : undefined;
398
- if (!(previousVersionDocument == null)) return [
399
- 3,
400
- 2
401
- ];
402
- _tmp = false;
403
- return [
404
- 3,
405
- 4
406
- ];
407
- case 2:
408
- return [
409
- 4,
410
- previousVersionDocument.accessor.exists()
411
- ];
412
- case 3:
413
- _tmp = _state.sent();
414
- _state.label = 4;
415
- case 4:
416
- previousVersionExists = _tmp;
417
- versionData = {
418
- cat: new Date(),
419
- v: version,
420
- i: instructions,
421
- m: messages === null || messages === void 0 ? void 0 : messages.map(function(param) {
422
- var role = param.role, content = param.content;
423
- return {
424
- r: role,
425
- c: content
426
- };
427
- }),
428
- c: modelConfig,
429
- nt: notes
430
- };
431
- if (!(previousVersionDocument != null && previousVersionExists)) return [
432
- 3,
433
- 6
434
- ];
435
- return [
436
- 4,
437
- previousVersionDocument.update({
438
- lk: true
439
- })
440
- ];
441
- case 5:
442
- _state.sent();
443
- _state.label = 6;
444
- case 6:
445
- return [
446
- 4,
447
- versionDocument.accessor.set(versionData)
448
- ];
449
- case 7:
450
- _state.sent();
451
- return [
452
- 4,
453
- inTransaction.update(_object_spread$2({
454
- lv: version,
455
- uat: new Date()
456
- }, activate ? {
457
- av: version,
458
- s: firebase.OpenRouterPromptState.ACTIVE
459
- } : undefined))
460
- ];
461
- case 8:
462
- _state.sent();
463
- // The version document's own path, not the prompt's: a create reports what it created.
464
- return [
465
- 2,
466
- {
467
- modelKeys: [
468
- versionDocument.documentRef.path
469
- ],
470
- version: version,
471
- activated: activate === true,
472
- warnings: validation.warnings
473
- }
474
- ];
475
- }
476
- });
477
- })();
478
- })
479
- ];
480
- case 1:
481
- result = _state.sent();
482
- openRouterPromptService.clearCachedPrompt(document.id);
483
- return [
484
- 2,
485
- result
486
- ];
487
- }
488
- });
489
- })();
490
- }
491
- ];
492
- });
493
- })();
494
- });
495
- }
496
- /**
497
- * Edits the latest version of a prompt in place, refusing one the next version has locked.
498
- *
499
- * The lock is re-read inside the transaction rather than trusted from the caller's snapshot: a create
500
- * racing this edit would otherwise let the write land on a version that had just stopped being the head.
501
- *
502
- * @param context - The actions context.
503
- * @returns The update version action.
504
- */ function updateOpenRouterPromptVersionFactory(context) {
505
- var firebaseServerActionTransformFunctionFactory = context.firebaseServerActionTransformFunctionFactory, openRouterPromptCollection = context.openRouterPromptCollection, openRouterPromptVersionCollectionGroup = context.openRouterPromptVersionCollectionGroup, openRouterPromptService = context.openRouterPromptService;
506
- return firebaseServerActionTransformFunctionFactory(firebase.updateOpenRouterPromptVersionParamsType, function(params) {
507
- return _async_to_generator$8(function() {
508
- var instructions, messages, config, notes;
509
- return _ts_generator$8(this, function(_state) {
510
- instructions = params.instructions, messages = params.messages, config = params.config, notes = params.notes;
511
- return [
512
- 2,
513
- function(document) {
514
- return _async_to_generator$8(function() {
515
- var inputConfig, validation;
516
- return _ts_generator$8(this, function(_state) {
517
- switch(_state.label){
518
- case 0:
519
- inputConfig = config;
520
- return [
521
- 4,
522
- openRouterPromptCollection.firestoreContext.runTransaction(function(transaction) {
523
- return _async_to_generator$8(function() {
524
- var _ref, inTransaction, version, result;
525
- return _ts_generator$8(this, function(_state) {
526
- switch(_state.label){
527
- case 0:
528
- inTransaction = openRouterPromptVersionCollectionGroup.documentAccessorForTransaction(transaction).loadDocument(document.documentRef);
529
- return [
530
- 4,
531
- inTransaction.snapshotData()
532
- ];
533
- case 1:
534
- version = _state.sent();
535
- if (version == null) {
536
- throw new Error('The OpenRouterPromptVersion "'.concat(document.key, '" does not exist.'));
537
- }
538
- if (version.lk) {
539
- throw new Error('The OpenRouterPromptVersion "'.concat(document.key, '" is locked, because a newer version exists. Create a new version instead.'));
540
- }
541
- // Validated against what the version will SAY once written, not against the patch: an edit that
542
- // touches only the instructions must not be judged against an empty config and refused for
543
- // naming no model. An explicitly null config is judged as the empty config it would leave behind,
544
- // which is exactly the refusal that should happen.
545
- result = openrouter.validateOpenRouterModelConfig((_ref = config === undefined ? version.c : inputConfig) !== null && _ref !== void 0 ? _ref : {});
546
- if (!result.valid) {
547
- throw new Error('Cannot update OpenRouterPromptVersion "'.concat(document.key, '": ').concat(result.errors.join(' ')));
548
- }
549
- // Undefined fields are stripped before the write, so an omitted field is left as it was. `null`
550
- // is passed through for the fields that can meaningfully carry nothing.
551
- return [
552
- 4,
553
- inTransaction.update({
554
- i: instructions,
555
- m: messages == null ? messages : messages.map(function(param) {
556
- var role = param.role, content = param.content;
557
- return {
558
- r: role,
559
- c: content
560
- };
561
- }),
562
- c: inputConfig,
563
- nt: notes
564
- })
565
- ];
566
- case 2:
567
- _state.sent();
568
- return [
569
- 2,
570
- result
571
- ];
572
- }
573
- });
574
- })();
575
- })
576
- ];
577
- case 1:
578
- validation = _state.sent();
579
- // Keyed by the parent prompt, which is the id the cache and the resolver both work in.
580
- openRouterPromptService.clearCachedPrompt(firebase$1.firestoreModelId(firebase$1.firestoreModelKeyParentKey(document)));
581
- return [
582
- 2,
583
- {
584
- warnings: validation.warnings
585
- }
586
- ];
587
- }
588
- });
589
- })();
590
- }
591
- ];
592
- });
593
- })();
594
- });
595
- }
596
- /**
597
- * How many definitions {@link seedOpenRouterPromptsFactory} publishes at a time.
598
- *
599
- * Each definition's writes are their own commit against documents no other definition touches, so the
600
- * bound is not a correctness requirement — it keeps a large registry from opening one connection per
601
- * prompt against Firestore all at once.
602
- */ var OPENROUTER_SEED_PROMPTS_MAX_PARALLEL_UPDATES = 25;
603
- /**
604
- * Publishes each code definition the prompt service carries at ITS OWN declared version number.
605
- *
606
- * The number is a compile-time constant rather than one allocated from `lv`, which is the whole point:
607
- * an auto-allocating writer cannot converge on a number chosen in code, because its write address moves
608
- * with its own effect — so a store seeded by {@link createOpenRouterPromptVersionFactory} sits
609
- * permanently behind the definition and the resolver stands in for it forever. Pinning makes the write
610
- * address a pure function of the definition, so a re-seed is a no-op rather than a step toward
611
- * convergence, and a scheduled reseed can keep the store in step with deploys.
612
- *
613
- * Publishing is gated on `lv` rather than `av`: `lv` is the allocator and is monotone, while `av` is a
614
- * pointer an operator can move backwards — gating on it would let a demotion re-trigger a publish on
615
- * every scheduled tick, forever.
616
- *
617
- * Deliberately NOT built on {@link createOpenRouterPromptVersionFactory}: that action is reachable over
618
- * callModel/MCP, and its in-transaction allocation is a race-safety contract on a public surface rather
619
- * than an implementation detail. A seed needs no allocator at all, because the number it writes is a
620
- * compile-time constant — something `CreateOpenRouterPromptVersionParams` cannot assert about an
621
- * arbitrary caller.
622
- *
623
- * No transaction, at any scope. A version document carries a whole prompt's text, so a registry of them
624
- * can put megabytes through a single commit, and a commit — transaction or write batch alike — is capped
625
- * around 10MB. The run is instead one read pass over every prompt document, then each definition
626
- * published independently through its OWN write batch, at most
627
- * {@link OPENROUTER_SEED_PROMPTS_MAX_PARALLEL_UPDATES} at a time. The batch is what keeps a publish
628
- * atomic — the version, the lock on the head it replaces, and the pointer move land together or not at
629
- * all — while holding any one commit to the three documents a single definition touches.
630
- *
631
- * What that costs is the transaction's read set: the check that nothing else already holds the number
632
- * being written is now a read taken shortly before the commit rather than a conflict detected at it.
633
- * Losing that window means a seed overwrites a version an operator published under the same number in
634
- * the same instant — narrow enough to trade for a run whose size cannot refuse it.
635
- *
636
- * @param context - The actions context.
637
- * @returns The seed action.
638
- */ function seedOpenRouterPromptsFactory(context) {
639
- var openRouterPromptCollection = context.openRouterPromptCollection, openRouterPromptVersionCollectionFactory = context.openRouterPromptVersionCollectionFactory, openRouterPromptService = context.openRouterPromptService;
640
- return function(params) {
641
- return _async_to_generator$8(function() {
642
- var promptKeys, keyFilter, definitions, warnings, promptDocumentAccessor, promptTuples, targets, outcomes, promptsCreated, versionsPublished, upToDate, skipped;
643
- /**
644
- * Publishes one definition, starting from the prompt the opening read already produced.
645
- *
646
- * @param target - The definition and the prompt document it seeds.
647
- * @returns What the write did.
648
- */ function seedTarget(target) {
649
- return _async_to_generator$8(function() {
650
- var _ref, definition, promptDocument, prompt, promptKey, version, latestVersion, archived, outcome, versionCollection, versionAccessor, targetVersionId, targetVersionExists, _definition_messages, previousVersionId, previousVersionExists, _tmp, versionData, writeBatch, versionWriteAccessor, promptWriteDocument;
651
- return _ts_generator$8(this, function(_state) {
652
- switch(_state.label){
653
- case 0:
654
- definition = target.definition, promptDocument = target.promptDocument, prompt = target.prompt;
655
- promptKey = definition.promptKey, version = definition.version;
656
- latestVersion = (_ref = prompt === null || prompt === void 0 ? void 0 : prompt.lv) !== null && _ref !== void 0 ? _ref : 0;
657
- // An ARCHIVED prompt is never resurrected: retirement is a deliberate act, and a scheduled
658
- // reseed silently undoing it is the same class of bug as reverting an operator's rename. Decided
659
- // from the prompt alone, so an archived definition costs no further read.
660
- archived = (prompt === null || prompt === void 0 ? void 0 : prompt.s) === firebase.OpenRouterPromptState.ARCHIVED;
661
- if (!archived) return [
662
- 3,
663
- 1
664
- ];
665
- outcome = 'skipped';
666
- return [
667
- 3,
668
- 15
669
- ];
670
- case 1:
671
- versionCollection = openRouterPromptVersionCollectionFactory(promptDocument);
672
- versionAccessor = versionCollection.documentAccessor();
673
- targetVersionId = firebase.openRouterPromptVersionId(version);
674
- return [
675
- 4,
676
- versionAccessor.loadDocumentForId(targetVersionId).accessor.exists()
677
- ];
678
- case 2:
679
- targetVersionExists = _state.sent();
680
- if (!(version > latestVersion && !targetVersionExists)) return [
681
- 3,
682
- 14
683
- ];
684
- // The outgoing head's address comes from the prompt's own `lv`, and `version > latestVersion`
685
- // above is what guarantees it is not the document about to be written. Existence-checked
686
- // because a batched `update` on a missing document fails the whole commit, and a `set` on a
687
- // deleted version would resurrect it holding nothing but a lock.
688
- previousVersionId = latestVersion > 0 ? firebase.openRouterPromptVersionId(latestVersion) : undefined;
689
- if (!(previousVersionId == null)) return [
690
- 3,
691
- 3
692
- ];
693
- _tmp = false;
694
- return [
695
- 3,
696
- 5
697
- ];
698
- case 3:
699
- return [
700
- 4,
701
- versionAccessor.loadDocumentForId(previousVersionId).accessor.exists()
702
- ];
703
- case 4:
704
- _tmp = _state.sent();
705
- _state.label = 5;
706
- case 5:
707
- previousVersionExists = _tmp;
708
- versionData = {
709
- cat: new Date(),
710
- v: version,
711
- i: definition.instructions,
712
- m: (_definition_messages = definition.messages) === null || _definition_messages === void 0 ? void 0 : _definition_messages.map(function(param) {
713
- var role = param.role, content = param.content;
714
- return {
715
- r: role,
716
- c: content
717
- };
718
- }),
719
- c: definition.config,
720
- nt: "Seeded from the code definition declaring version ".concat(version, ".")
721
- };
722
- // One batch for this definition and nothing else. Atomic, so a prompt never ends up pointing
723
- // at a version the run failed to write, and bounded, so the commit carries one prompt's text
724
- // rather than the registry's.
725
- writeBatch = openRouterPromptCollection.firestoreContext.batch();
726
- versionWriteAccessor = versionCollection.documentAccessorForWriteBatch(writeBatch);
727
- promptWriteDocument = openRouterPromptCollection.documentAccessorForWriteBatch(writeBatch).loadDocumentForId(promptKey);
728
- if (!(previousVersionId != null && previousVersionExists)) return [
729
- 3,
730
- 7
731
- ];
732
- return [
733
- 4,
734
- versionWriteAccessor.loadDocumentForId(previousVersionId).update({
735
- lk: true
736
- })
737
- ];
738
- case 6:
739
- _state.sent();
740
- _state.label = 7;
741
- case 7:
742
- return [
743
- 4,
744
- versionWriteAccessor.loadDocumentForId(targetVersionId).accessor.set(versionData)
745
- ];
746
- case 8:
747
- _state.sent();
748
- if (!(prompt == null)) return [
749
- 3,
750
- 10
751
- ];
752
- return [
753
- 4,
754
- promptWriteDocument.accessor.set({
755
- cat: new Date(),
756
- n: definition.name,
757
- d: definition.description,
758
- s: firebase.OpenRouterPromptState.ACTIVE,
759
- lv: version,
760
- av: version
761
- })
762
- ];
763
- case 9:
764
- _state.sent();
765
- return [
766
- 3,
767
- 12
768
- ];
769
- case 10:
770
- // `n`/`d`/`t` are deliberately untouched: they are operator-editable through
771
- // updateOpenRouterPrompt, and a scheduled reseed reverting a rename is a silent regression.
772
- return [
773
- 4,
774
- promptWriteDocument.update({
775
- lv: version,
776
- av: version,
777
- s: firebase.OpenRouterPromptState.ACTIVE,
778
- uat: new Date()
779
- })
780
- ];
781
- case 11:
782
- _state.sent();
783
- _state.label = 12;
784
- case 12:
785
- return [
786
- 4,
787
- writeBatch.commit()
788
- ];
789
- case 13:
790
- _state.sent();
791
- // Only the prompts that actually changed, and only once the commit landed. Missing this
792
- // leaves a scheduled reseed invisible for the whole OPENROUTER_PROMPT_CACHE_DURATION window.
793
- openRouterPromptService.clearCachedPrompt(promptKey);
794
- outcome = prompt == null ? 'created' : 'published';
795
- return [
796
- 3,
797
- 15
798
- ];
799
- case 14:
800
- // The only way to land on `upToDate` is a prompt whose `lv` already covers the declared
801
- // number AND whose document at that number is present — anything else is drift the seed
802
- // refuses to paper over by overwriting a number someone else wrote.
803
- outcome = version > latestVersion || !targetVersionExists ? 'skipped' : 'upToDate';
804
- _state.label = 15;
805
- case 15:
806
- return [
807
- 2,
808
- outcome
809
- ];
810
- }
811
- });
812
- })();
813
- }
814
- return _ts_generator$8(this, function(_state) {
815
- switch(_state.label){
816
- case 0:
817
- promptKeys = params.promptKeys;
818
- keyFilter = promptKeys == null ? undefined : new Set(promptKeys);
819
- return [
820
- 4,
821
- openRouterPromptService.loadPromptDefinitions()
822
- ];
823
- case 1:
824
- definitions = _state.sent().filter(function(x) {
825
- return keyFilter == null || keyFilter.has(x.promptKey);
826
- });
827
- warnings = [];
828
- // Every definition is validated before anything is written: half-seeding a registry because entry
829
- // three is broken leaves a state no rerun explains.
830
- definitions.forEach(function(definition) {
831
- var promptKey = definition.promptKey, version = definition.version, config = definition.config;
832
- if (!Number.isInteger(version) || version < 1) {
833
- throw new Error('Cannot seed OpenRouterPrompt "'.concat(promptKey, '": the definition declares version ').concat(version, ", which is not an integer >= 1."));
834
- }
835
- var validation = openrouter.validateOpenRouterModelConfig(config);
836
- if (!validation.valid) {
837
- throw new Error('Cannot seed OpenRouterPrompt "'.concat(promptKey, '": ').concat(validation.errors.join(' ')));
838
- }
839
- validation.warnings.forEach(function(warning) {
840
- return warnings.push("".concat(promptKey, ": ").concat(warning));
841
- });
842
- });
843
- // Every prompt document up front, in one pass, before a single write: the addresses are the keys the
844
- // definitions declare, so they all resolve together, and reading them here is what lets the write
845
- // phase decide each definition without a transaction to re-read them in.
846
- promptDocumentAccessor = openRouterPromptCollection.documentAccessor();
847
- return [
848
- 4,
849
- firebase$1.getDocumentSnapshotDataTuples(definitions.map(function(x) {
850
- return promptDocumentAccessor.loadDocumentForId(x.promptKey);
851
- }))
852
- ];
853
- case 2:
854
- promptTuples = _state.sent();
855
- targets = definitions.map(function(definition, i) {
856
- return {
857
- definition: definition,
858
- promptDocument: promptTuples[i][0],
859
- prompt: promptTuples[i][1]
860
- };
861
- });
862
- return [
863
- 4,
864
- util.runAsyncTasksForValues(targets, seedTarget, {
865
- maxParallelTasks: OPENROUTER_SEED_PROMPTS_MAX_PARALLEL_UPDATES
866
- })
867
- ];
868
- case 3:
869
- outcomes = _state.sent();
870
- promptsCreated = 0;
871
- versionsPublished = 0;
872
- upToDate = 0;
873
- skipped = 0;
874
- outcomes.forEach(function(outcome) {
875
- switch(outcome){
876
- case 'created':
877
- promptsCreated += 1;
878
- versionsPublished += 1;
879
- break;
880
- case 'published':
881
- versionsPublished += 1;
882
- break;
883
- case 'upToDate':
884
- upToDate += 1;
885
- break;
886
- case 'skipped':
887
- skipped += 1;
888
- break;
889
- }
890
- });
891
- return [
892
- 2,
893
- {
894
- considered: definitions.length,
895
- promptsCreated: promptsCreated,
896
- versionsPublished: versionsPublished,
897
- upToDate: upToDate,
898
- skipped: skipped,
899
- warnings: warnings
900
- }
901
- ];
902
- }
903
- });
904
- })();
905
- };
906
- }
907
-
908
- function asyncGeneratorStep$7(gen, resolve, reject, _next, _throw, key, arg) {
909
- try {
910
- var info = gen[key](arg);
911
- var value = info.value;
912
- } catch (error) {
913
- reject(error);
914
- return;
915
- }
916
- if (info.done) {
917
- resolve(value);
918
- } else {
919
- Promise.resolve(value).then(_next, _throw);
920
- }
921
- }
922
- function _async_to_generator$7(fn) {
923
- return function() {
924
- var self = this, args = arguments;
925
- return new Promise(function(resolve, reject) {
926
- var gen = fn.apply(self, args);
927
- function _next(value) {
928
- asyncGeneratorStep$7(gen, resolve, reject, _next, _throw, "next", value);
929
- }
930
- function _throw(err) {
931
- asyncGeneratorStep$7(gen, resolve, reject, _next, _throw, "throw", err);
932
- }
933
- _next(undefined);
934
- });
935
- };
936
- }
937
- function _ts_generator$7(thisArg, body) {
938
- var f, y, t, _ = {
939
- label: 0,
940
- sent: function() {
941
- if (t[0] & 1) throw t[1];
942
- return t[1];
943
- },
944
- trys: [],
945
- ops: []
946
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
947
- return d(g, "next", {
948
- value: verb(0)
949
- }), d(g, "throw", {
950
- value: verb(1)
951
- }), d(g, "return", {
952
- value: verb(2)
953
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
954
- value: function() {
955
- return this;
956
- }
957
- }), g;
958
- function verb(n) {
959
- return function(v) {
960
- return step([
961
- n,
962
- v
963
- ]);
964
- };
965
- }
966
- function step(op) {
967
- if (f) throw new TypeError("Generator is already executing.");
968
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
969
- 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;
970
- if (y = 0, t) op = [
971
- op[0] & 2,
972
- t.value
973
- ];
974
- switch(op[0]){
975
- case 0:
976
- case 1:
977
- t = op;
978
- break;
979
- case 4:
980
- _.label++;
981
- return {
982
- value: op[1],
983
- done: false
984
- };
985
- case 5:
986
- _.label++;
987
- y = op[1];
988
- op = [
989
- 0
990
- ];
991
- continue;
992
- case 7:
993
- op = _.ops.pop();
994
- _.trys.pop();
995
- continue;
996
- default:
997
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
998
- _ = 0;
999
- continue;
1000
- }
1001
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1002
- _.label = op[1];
1003
- break;
1004
- }
1005
- if (op[0] === 6 && _.label < t[1]) {
1006
- _.label = t[1];
1007
- t = op;
1008
- break;
1009
- }
1010
- if (t && _.label < t[2]) {
1011
- _.label = t[2];
1012
- _.ops.push(op);
1013
- break;
1014
- }
1015
- if (t[2]) _.ops.pop();
1016
- _.trys.pop();
1017
- continue;
1018
- }
1019
- op = body.call(thisArg, _);
1020
- } catch (e) {
1021
- op = [
1022
- 6,
1023
- e
1024
- ];
1025
- y = 0;
1026
- } finally{
1027
- f = t = 0;
1028
- }
1029
- if (op[0] & 5) throw op[1];
1030
- return {
1031
- value: op[0] ? op[1] : void 0,
1032
- done: true
1033
- };
1034
- }
1035
- }
1036
- /**
1037
- * The attribute key OpenRouter surfaces a `trace: { runTaskKey }` property under.
1038
- *
1039
- * OpenRouter's docs: "custom metadata from the `trace` field is included as span attributes in the OTLP
1040
- * JSON payload". The exact prefix is not contractual, so several candidates are checked.
1041
- */ var OPENROUTER_BROADCAST_RUN_TASK_KEY_ATTRIBUTES = [
1042
- 'runTaskKey',
1043
- 'trace.runTaskKey',
1044
- 'openrouter.trace.runTaskKey',
1045
- 'gen_ai.trace.runTaskKey'
1046
- ];
1047
- /**
1048
- * Reads the run task key out of a span's attribute map.
1049
- *
1050
- * @param attributes - The flattened span attributes.
1051
- * @returns The run task key, when the span carries one.
1052
- */ function openRouterRunTaskKeyFromBroadcastAttributes(attributes) {
1053
- var result;
1054
- if (attributes != null) {
1055
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1056
- try {
1057
- for(var _iterator = OPENROUTER_BROADCAST_RUN_TASK_KEY_ATTRIBUTES[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1058
- var key = _step.value;
1059
- var value = attributes.get(key);
1060
- if (value != null) {
1061
- result = String(value);
1062
- break;
1063
- }
1064
- }
1065
- } catch (err) {
1066
- _didIteratorError = true;
1067
- _iteratorError = err;
1068
- } finally{
1069
- try {
1070
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1071
- _iterator.return();
1072
- }
1073
- } finally{
1074
- if (_didIteratorError) {
1075
- throw _iteratorError;
1076
- }
1077
- }
1078
- }
1079
- }
1080
- return result;
1081
- }
1082
- /**
1083
- * Reconciles generation id, usage, and cost onto a run task from a broadcast span.
1084
- *
1085
- * This exists for the one thing the runner cannot always know: cost is finalised server-side, so the
1086
- * value the runner wrote from the response can be provisional.
1087
- *
1088
- * TELEMETRY ONLY — it never changes `s`, and a span it cannot match is dropped silently. Broadcast is
1089
- * enabled account-wide rather than per request, delivery is asynchronous and best-effort, and a dropped
1090
- * trace must not be able to strand a task. Putting control flow here would make a missing trace look
1091
- * exactly like a stuck run.
1092
- *
1093
- * @param params - The collections, run task key, and generation info.
1094
- * @returns Whether anything was written.
1095
- */ function reconcileOpenRouterRunTaskFromBroadcast(params) {
1096
- return _async_to_generator$7(function() {
1097
- var collections, key, generation, reconciled, document, task, generationIds, usage;
1098
- return _ts_generator$7(this, function(_state) {
1099
- switch(_state.label){
1100
- case 0:
1101
- collections = params.collections, key = params.key, generation = params.generation;
1102
- reconciled = false;
1103
- if (!key) return [
1104
- 3,
1105
- 3
1106
- ];
1107
- document = collections.openRouterRunTaskCollection.documentAccessor().loadDocumentForId(key);
1108
- return [
1109
- 4,
1110
- document.snapshotData()
1111
- ];
1112
- case 1:
1113
- task = _state.sent();
1114
- if (!(task != null)) return [
1115
- 3,
1116
- 3
1117
- ];
1118
- generationIds = generation.generationId == null ? task.gi : util.concatArraysUnique(task.gi, [
1119
- generation.generationId
1120
- ]);
1121
- usage = mergeOpenRouterRunUsage(task.u, generation);
1122
- return [
1123
- 4,
1124
- document.update({
1125
- gi: generationIds,
1126
- u: usage
1127
- })
1128
- ];
1129
- case 2:
1130
- _state.sent();
1131
- reconciled = true;
1132
- _state.label = 3;
1133
- case 3:
1134
- return [
1135
- 2,
1136
- {
1137
- reconciled: reconciled
1138
- }
1139
- ];
1140
- }
1141
- });
1142
- })();
1143
- }
1144
- /**
1145
- * Merges broadcast-reported usage into the usage already stored on a task.
1146
- *
1147
- * The broadcast value wins where it is present — it is the later, authoritative measurement — and the
1148
- * stored value is kept where the span is silent, so an incomplete span cannot erase what the runner knew.
1149
- *
1150
- * The filter MUST be `NULL`, not `mergeObjects`' default of `UNDEFINED`. Every field here is a `Maybe`, so a
1151
- * span reporting `cost: null` means "did not measure" — and under the default filter that `null` would win
1152
- * and erase the cost the runner actually recorded.
1153
- *
1154
- * `reasoningTokens` / `cachedTokens` / `isByok` are absent from the literal because a broadcast span carries
1155
- * none of them; they ride along from `existing` untouched.
1156
- *
1157
- * @param existing - Usage already stored.
1158
- * @param generation - The span's generation info.
1159
- * @returns The merged usage.
1160
- *
1161
- * @__NO_SIDE_EFFECTS__
1162
- */ function mergeOpenRouterRunUsage(existing, generation) {
1163
- var inputTokens = generation.promptTokens, outputTokens = generation.completionTokens, totalTokens = generation.totalTokens, cost = generation.cost;
1164
- return util.mergeObjects([
1165
- existing,
1166
- {
1167
- inputTokens: inputTokens,
1168
- outputTokens: outputTokens,
1169
- totalTokens: totalTokens,
1170
- cost: cost
1171
- }
1172
- ], util.KeyValueTypleValueFilter.NULL);
1173
- }
1174
-
1175
- function asyncGeneratorStep$6(gen, resolve, reject, _next, _throw, key, arg) {
1176
- try {
1177
- var info = gen[key](arg);
1178
- var value = info.value;
1179
- } catch (error) {
1180
- reject(error);
1181
- return;
1182
- }
1183
- if (info.done) {
1184
- resolve(value);
1185
- } else {
1186
- Promise.resolve(value).then(_next, _throw);
1187
- }
1188
- }
1189
- function _async_to_generator$6(fn) {
1190
- return function() {
1191
- var self = this, args = arguments;
1192
- return new Promise(function(resolve, reject) {
1193
- var gen = fn.apply(self, args);
1194
- function _next(value) {
1195
- asyncGeneratorStep$6(gen, resolve, reject, _next, _throw, "next", value);
1196
- }
1197
- function _throw(err) {
1198
- asyncGeneratorStep$6(gen, resolve, reject, _next, _throw, "throw", err);
1199
- }
1200
- _next(undefined);
1201
- });
1202
- };
1203
- }
1204
- function _ts_generator$6(thisArg, body) {
1205
- var f, y, t, _ = {
1206
- label: 0,
1207
- sent: function() {
1208
- if (t[0] & 1) throw t[1];
1209
- return t[1];
1210
- },
1211
- trys: [],
1212
- ops: []
1213
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
1214
- return d(g, "next", {
1215
- value: verb(0)
1216
- }), d(g, "throw", {
1217
- value: verb(1)
1218
- }), d(g, "return", {
1219
- value: verb(2)
1220
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
1221
- value: function() {
1222
- return this;
1223
- }
1224
- }), g;
1225
- function verb(n) {
1226
- return function(v) {
1227
- return step([
1228
- n,
1229
- v
1230
- ]);
1231
- };
1232
- }
1233
- function step(op) {
1234
- if (f) throw new TypeError("Generator is already executing.");
1235
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
1236
- 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;
1237
- if (y = 0, t) op = [
1238
- op[0] & 2,
1239
- t.value
1240
- ];
1241
- switch(op[0]){
1242
- case 0:
1243
- case 1:
1244
- t = op;
1245
- break;
1246
- case 4:
1247
- _.label++;
1248
- return {
1249
- value: op[1],
1250
- done: false
1251
- };
1252
- case 5:
1253
- _.label++;
1254
- y = op[1];
1255
- op = [
1256
- 0
1257
- ];
1258
- continue;
1259
- case 7:
1260
- op = _.ops.pop();
1261
- _.trys.pop();
1262
- continue;
1263
- default:
1264
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1265
- _ = 0;
1266
- continue;
1267
- }
1268
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1269
- _.label = op[1];
1270
- break;
1271
- }
1272
- if (op[0] === 6 && _.label < t[1]) {
1273
- _.label = t[1];
1274
- t = op;
1275
- break;
1276
- }
1277
- if (t && _.label < t[2]) {
1278
- _.label = t[2];
1279
- _.ops.push(op);
1280
- break;
1281
- }
1282
- if (t[2]) _.ops.pop();
1283
- _.trys.pop();
1284
- continue;
1285
- }
1286
- op = body.call(thisArg, _);
1287
- } catch (e) {
1288
- op = [
1289
- 6,
1290
- e
1291
- ];
1292
- y = 0;
1293
- } finally{
1294
- f = t = 0;
1295
- }
1296
- if (op[0] & 5) throw op[1];
1297
- return {
1298
- value: op[0] ? op[1] : void 0,
1299
- done: true
1300
- };
1301
- }
1302
- }
1303
- /**
1304
- * Runs a prompt INLINE and returns the result, with no run task document.
1305
- *
1306
- * Use this wherever a call reliably finishes in a few seconds. The queue exists for calls that do not,
1307
- * and paying for a document, a lease, and a sweep interval on a two-second call buys nothing.
1308
- *
1309
- * @param params - The client, prompt service, prompt, and input.
1310
- * @returns The normalized call result.
1311
- */ function callModelForPrompt(params) {
1312
- return _async_to_generator$6(function() {
1313
- var client, promptService, promptKey, version, input, configOverrides, files, tools, trace, prompt, request;
1314
- return _ts_generator$6(this, function(_state) {
1315
- switch(_state.label){
1316
- case 0:
1317
- client = params.client, promptService = params.promptService, promptKey = params.promptKey, version = params.version, input = params.input, configOverrides = params.configOverrides, files = params.files, tools = params.tools, trace = params.trace;
1318
- return [
1319
- 4,
1320
- promptService.resolvePrompt({
1321
- promptKey: promptKey,
1322
- version: version
1323
- })
1324
- ];
1325
- case 1:
1326
- prompt = _state.sent();
1327
- request = openrouter.openRouterPromptRequest({
1328
- prompt: prompt,
1329
- input: input,
1330
- overrides: configOverrides,
1331
- files: files,
1332
- trace: trace
1333
- });
1334
- return [
1335
- 2,
1336
- openrouter.callModelForOpenRouterRequest({
1337
- client: client,
1338
- request: request,
1339
- tools: tools !== null && tools !== void 0 ? tools : undefined
1340
- })
1341
- ];
1342
- }
1343
- });
1344
- })();
1345
- }
1346
-
1347
- function asyncGeneratorStep$5(gen, resolve, reject, _next, _throw, key, arg) {
1348
- try {
1349
- var info = gen[key](arg);
1350
- var value = info.value;
1351
- } catch (error) {
1352
- reject(error);
1353
- return;
1354
- }
1355
- if (info.done) {
1356
- resolve(value);
1357
- } else {
1358
- Promise.resolve(value).then(_next, _throw);
1359
- }
1360
- }
1361
- function _async_to_generator$5(fn) {
1362
- return function() {
1363
- var self = this, args = arguments;
1364
- return new Promise(function(resolve, reject) {
1365
- var gen = fn.apply(self, args);
1366
- function _next(value) {
1367
- asyncGeneratorStep$5(gen, resolve, reject, _next, _throw, "next", value);
1368
- }
1369
- function _throw(err) {
1370
- asyncGeneratorStep$5(gen, resolve, reject, _next, _throw, "throw", err);
1371
- }
1372
- _next(undefined);
1373
- });
1374
- };
1375
- }
1376
- function _ts_generator$5(thisArg, body) {
1377
- var f, y, t, _ = {
1378
- label: 0,
1379
- sent: function() {
1380
- if (t[0] & 1) throw t[1];
1381
- return t[1];
1382
- },
1383
- trys: [],
1384
- ops: []
1385
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
1386
- return d(g, "next", {
1387
- value: verb(0)
1388
- }), d(g, "throw", {
1389
- value: verb(1)
1390
- }), d(g, "return", {
1391
- value: verb(2)
1392
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
1393
- value: function() {
1394
- return this;
1395
- }
1396
- }), g;
1397
- function verb(n) {
1398
- return function(v) {
1399
- return step([
1400
- n,
1401
- v
1402
- ]);
1403
- };
1404
- }
1405
- function step(op) {
1406
- if (f) throw new TypeError("Generator is already executing.");
1407
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
1408
- 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;
1409
- if (y = 0, t) op = [
1410
- op[0] & 2,
1411
- t.value
1412
- ];
1413
- switch(op[0]){
1414
- case 0:
1415
- case 1:
1416
- t = op;
1417
- break;
1418
- case 4:
1419
- _.label++;
1420
- return {
1421
- value: op[1],
1422
- done: false
1423
- };
1424
- case 5:
1425
- _.label++;
1426
- y = op[1];
1427
- op = [
1428
- 0
1429
- ];
1430
- continue;
1431
- case 7:
1432
- op = _.ops.pop();
1433
- _.trys.pop();
1434
- continue;
1435
- default:
1436
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1437
- _ = 0;
1438
- continue;
1439
- }
1440
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1441
- _.label = op[1];
1442
- break;
1443
- }
1444
- if (op[0] === 6 && _.label < t[1]) {
1445
- _.label = t[1];
1446
- t = op;
1447
- break;
1448
- }
1449
- if (t && _.label < t[2]) {
1450
- _.label = t[2];
1451
- _.ops.push(op);
1452
- break;
1453
- }
1454
- if (t[2]) _.ops.pop();
1455
- _.trys.pop();
1456
- continue;
1457
- }
1458
- op = body.call(thisArg, _);
1459
- } catch (e) {
1460
- op = [
1461
- 6,
1462
- e
1463
- ];
1464
- y = 0;
1465
- } finally{
1466
- f = t = 0;
1467
- }
1468
- if (op[0] & 5) throw op[1];
1469
- return {
1470
- value: op[0] ? op[1] : void 0,
1471
- done: true
1472
- };
1473
- }
1474
- }
1475
- /**
1476
- * Default lifetime of a signed url minted for one attempt.
1477
- *
1478
- * Deliberately short. The url only has to survive the single request it is attached to, and every
1479
- * attempt gets a freshly signed one — so a short TTL costs nothing and narrows the window in which a
1480
- * third party holds a bearer credential to the object.
1481
- */ var DEFAULT_OPENROUTER_SIGNED_URL_TTL = util.MS_IN_MINUTE * 5;
1482
- /**
1483
- * Cap on the size of a file carried inline.
1484
- *
1485
- * Base64 inflates the payload by roughly a third, and the cost is re-paid on EVERY attempt rather than
1486
- * amortized the way a url is — so this is a guard against turning a retry loop into a bandwidth bill,
1487
- * not a correctness limit.
1488
- */ var DEFAULT_OPENROUTER_MAX_INLINE_FILE_SIZE_BYTES = 256 * 1024;
1489
- /**
1490
- * Content type assumed for an inlined object whose metadata reports none.
1491
- *
1492
- * Matches {@link openRouterInputFileDataPart}'s own default, so the two cannot disagree.
1493
- */ var DEFAULT_OPENROUTER_INLINE_FILE_CONTENT_TYPE = 'application/pdf';
1494
- /**
1495
- * The mode a config resolves to.
1496
- *
1497
- * Order: the explicit override, then the environment service, then `signedUrl`.
1498
- *
1499
- * Gated on `isProduction` rather than `isTestingEnv`, because the question is whether OpenRouter can
1500
- * reach the object, not whether this is a test. Every non-production environment here is a localhost
1501
- * one — the emulator under `nx serve` as much as a spec run — and `isTestingEnv` is only
1502
- * `NODE_ENV === 'test'`, so it covered the spec run and left the emulator handing OpenRouter a
1503
- * `127.0.0.1` url that it rejects outright.
1504
- *
1505
- * @param config - The resolver config.
1506
- * @returns The mode.
1507
- *
1508
- * @__NO_SIDE_EFFECTS__
1509
- */ function openRouterFileAttachmentModeForConfig(config) {
1510
- var mode = config.mode, envService = config.envService;
1511
- // `=== false` rather than a negation, so a config with no env service still resolves to `signedUrl`.
1512
- return mode !== null && mode !== void 0 ? mode : (envService === null || envService === void 0 ? void 0 : envService.isProduction) === false ? 'inlineData' : 'signedUrl';
1513
- }
1514
- /**
1515
- * Creates an {@link OpenRouterFileAttachmentResolver}.
1516
- *
1517
- * Called once per attempt, never at enqueue time: both transports produce something that is only valid
1518
- * for the request it is attached to.
1519
- *
1520
- * @param config - The storage context, environment service, and transport settings.
1521
- * @returns The resolver.
1522
- */ function openRouterFileAttachmentResolver(config) {
1523
- var storageContext = config.storageContext, signedUrlTtl = config.signedUrlTtl, maxInlineFileSizeBytes = config.maxInlineFileSizeBytes;
1524
- var mode = openRouterFileAttachmentModeForConfig(config);
1525
- var urlTtl = signedUrlTtl !== null && signedUrlTtl !== void 0 ? signedUrlTtl : DEFAULT_OPENROUTER_SIGNED_URL_TTL;
1526
- var maxInlineBytes = maxInlineFileSizeBytes !== null && maxInlineFileSizeBytes !== void 0 ? maxInlineFileSizeBytes : DEFAULT_OPENROUTER_MAX_INLINE_FILE_SIZE_BYTES;
1527
- return function resolveAttachments(files) {
1528
- return _async_to_generator$5(function() {
1529
- var result, defaultBucketId;
1530
- return _ts_generator$5(this, function(_state) {
1531
- switch(_state.label){
1532
- case 0:
1533
- result = [];
1534
- if (!(files != null && files.length > 0)) return [
1535
- 3,
1536
- 2
1537
- ];
1538
- if (storageContext == null) {
1539
- throw new Error('An OpenRouterRunTask carries files but no storageContext was configured to attach them with.');
1540
- }
1541
- defaultBucketId = storageContext.defaultBucket();
1542
- return [
1543
- 4,
1544
- Promise.all(files.map(function(file) {
1545
- return _async_to_generator$5(function() {
1546
- var _file_bucket, path, accessorFile, attached, _metadata_contentType, bytes, metadata, contentType, _tmp;
1547
- return _ts_generator$5(this, function(_state) {
1548
- switch(_state.label){
1549
- case 0:
1550
- path = {
1551
- bucketId: (_file_bucket = file.bucket) !== null && _file_bucket !== void 0 ? _file_bucket : defaultBucketId,
1552
- pathString: file.storagePath
1553
- };
1554
- accessorFile = storageContext.file(path);
1555
- if (!(mode === 'inlineData')) return [
1556
- 3,
1557
- 3
1558
- ];
1559
- if (accessorFile.getBytes == null) {
1560
- throw new Error('The configured FirebaseStorageContext cannot read file bytes, which inline file attachment requires.');
1561
- }
1562
- return [
1563
- 4,
1564
- accessorFile.getBytes(maxInlineBytes)
1565
- ];
1566
- case 1:
1567
- bytes = _state.sent();
1568
- return [
1569
- 4,
1570
- accessorFile.getMetadata()
1571
- ];
1572
- case 2:
1573
- metadata = _state.sent();
1574
- contentType = (_metadata_contentType = metadata.contentType) !== null && _metadata_contentType !== void 0 ? _metadata_contentType : DEFAULT_OPENROUTER_INLINE_FILE_CONTENT_TYPE;
1575
- attached = {
1576
- file: file,
1577
- fileData: "data:".concat(contentType, ";base64,").concat(Buffer.from(bytes).toString('base64'))
1578
- };
1579
- return [
1580
- 3,
1581
- 5
1582
- ];
1583
- case 3:
1584
- if (accessorFile.getSignedUrl == null) {
1585
- throw new Error('The configured FirebaseStorageContext cannot mint signed urls.');
1586
- }
1587
- _tmp = {
1588
- file: file
1589
- };
1590
- return [
1591
- 4,
1592
- accessorFile.getSignedUrl({
1593
- action: 'read',
1594
- expiresIn: urlTtl
1595
- })
1596
- ];
1597
- case 4:
1598
- attached = (_tmp.fileUrl = _state.sent(), _tmp);
1599
- _state.label = 5;
1600
- case 5:
1601
- return [
1602
- 2,
1603
- attached
1604
- ];
1605
- }
1606
- });
1607
- })();
1608
- }))
1609
- ];
1610
- case 1:
1611
- result = _state.sent();
1612
- _state.label = 2;
1613
- case 2:
1614
- return [
1615
- 2,
1616
- result
1617
- ];
1618
- }
1619
- });
1620
- })();
1621
- };
1622
- }
1623
-
1624
- function _array_like_to_array$1(arr, len) {
1625
- if (len == null || len > arr.length) len = arr.length;
1626
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1627
- return arr2;
1628
- }
1629
- function _array_without_holes$1(arr) {
1630
- if (Array.isArray(arr)) return _array_like_to_array$1(arr);
1631
- }
1632
- function _class_call_check$2(instance, Constructor) {
1633
- if (!(instance instanceof Constructor)) {
1634
- throw new TypeError("Cannot call a class as a function");
1635
- }
1636
- }
1637
- function _iterable_to_array$1(iter) {
1638
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
1639
- }
1640
- function _non_iterable_spread$1() {
1641
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1642
- }
1643
- function _to_consumable_array$1(arr) {
1644
- return _array_without_holes$1(arr) || _iterable_to_array$1(arr) || _unsupported_iterable_to_array$1(arr) || _non_iterable_spread$1();
1645
- }
1646
- function _unsupported_iterable_to_array$1(o, minLen) {
1647
- if (!o) return;
1648
- if (typeof o === "string") return _array_like_to_array$1(o, minLen);
1649
- var n = Object.prototype.toString.call(o).slice(8, -1);
1650
- if (n === "Object" && o.constructor) n = o.constructor.name;
1651
- if (n === "Map" || n === "Set") return Array.from(n);
1652
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$1(o, minLen);
1653
- }
1654
- /**
1655
- * Builds the module metadata for an app's OpenRouter module.
1656
- *
1657
- * @param config - The dependency module and server-actions provider.
1658
- * @returns The module metadata.
1659
- */ function appOpenRouterModuleMetadata(config) {
1660
- var dependencyModule = config.dependencyModule, serverActionsProvider = config.serverActionsProvider, providers = config.providers, exports = config.exports;
1661
- return {
1662
- imports: [
1663
- dependencyModule
1664
- ],
1665
- providers: [
1666
- serverActionsProvider
1667
- ].concat(_to_consumable_array$1(providers !== null && providers !== void 0 ? providers : [])),
1668
- exports: [
1669
- OpenRouterPromptServerActions
1670
- ].concat(_to_consumable_array$1(exports !== null && exports !== void 0 ? exports : []))
1671
- };
1672
- }
1673
- /**
1674
- * Base class an app's OpenRouter module extends.
1675
- */ var AbstractAppOpenRouterModule = function AbstractAppOpenRouterModule() {
1676
- _class_call_check$2(this, AbstractAppOpenRouterModule);
1677
- };
1678
- /**
1679
- * Injection token for the {@link OpenRouterPromptService}.
1680
- */ var OPENROUTER_PROMPT_SERVICE_TOKEN = 'OPENROUTER_PROMPT_SERVICE_TOKEN';
1681
- /**
1682
- * Injection token for the {@link OpenRouterRunTaskService}.
1683
- */ var OPENROUTER_RUN_TASK_SERVICE_TOKEN = 'OPENROUTER_RUN_TASK_SERVICE_TOKEN';
1684
-
1685
- function _assert_this_initialized(self) {
1686
- if (self === void 0) {
1687
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
1688
- }
1689
- return self;
1690
- }
1691
- function asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, key, arg) {
1692
- try {
1693
- var info = gen[key](arg);
1694
- var value = info.value;
1695
- } catch (error) {
1696
- reject(error);
1697
- return;
1698
- }
1699
- if (info.done) {
1700
- resolve(value);
1701
- } else {
1702
- Promise.resolve(value).then(_next, _throw);
1703
- }
1704
- }
1705
- function _async_to_generator$4(fn) {
1706
- return function() {
1707
- var self = this, args = arguments;
1708
- return new Promise(function(resolve, reject) {
1709
- var gen = fn.apply(self, args);
1710
- function _next(value) {
1711
- asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, "next", value);
1712
- }
1713
- function _throw(err) {
1714
- asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, "throw", err);
1715
- }
1716
- _next(undefined);
1717
- });
1718
- };
1719
- }
1720
- function _call_super(_this, derived, args) {
1721
- derived = _get_prototype_of(derived);
1722
- return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
1723
- }
1724
- function _class_call_check$1(instance, Constructor) {
1725
- if (!(instance instanceof Constructor)) {
1726
- throw new TypeError("Cannot call a class as a function");
1727
- }
1728
- }
1729
- function _construct(Parent, args, Class) {
1730
- if (_is_native_reflect_construct()) {
1731
- _construct = Reflect.construct;
1732
- } else {
1733
- _construct = function construct(Parent, args, Class) {
1734
- var a = [
1735
- null
1736
- ];
1737
- a.push.apply(a, args);
1738
- var Constructor = Function.bind.apply(Parent, a);
1739
- var instance = new Constructor();
1740
- if (Class) _set_prototype_of(instance, Class.prototype);
1741
- return instance;
1742
- };
1743
- }
1744
- return _construct.apply(null, arguments);
1745
- }
1746
- function _define_property$2(obj, key, value) {
1747
- if (key in obj) {
1748
- Object.defineProperty(obj, key, {
1749
- value: value,
1750
- enumerable: true,
1751
- configurable: true,
1752
- writable: true
1753
- });
1754
- } else {
1755
- obj[key] = value;
1756
- }
1757
- return obj;
1758
- }
1759
- function _get_prototype_of(o) {
1760
- _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
1761
- return o.__proto__ || Object.getPrototypeOf(o);
1762
- };
1763
- return _get_prototype_of(o);
1764
- }
1765
- function _inherits(subClass, superClass) {
1766
- if (typeof superClass !== "function" && superClass !== null) {
1767
- throw new TypeError("Super expression must either be null or a function");
1768
- }
1769
- subClass.prototype = Object.create(superClass && superClass.prototype, {
1770
- constructor: {
1771
- value: subClass,
1772
- writable: true,
1773
- configurable: true
1774
- }
1775
- });
1776
- if (superClass) _set_prototype_of(subClass, superClass);
1777
- }
1778
- function _is_native_function(fn) {
1779
- return Function.toString.call(fn).indexOf("[native code]") !== -1;
1780
- }
1781
- function _possible_constructor_return(self, call) {
1782
- if (call && (_type_of$1(call) === "object" || typeof call === "function")) {
1783
- return call;
1784
- }
1785
- return _assert_this_initialized(self);
1786
- }
1787
- function _set_prototype_of(o, p) {
1788
- _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
1789
- o.__proto__ = p;
1790
- return o;
1791
- };
1792
- return _set_prototype_of(o, p);
1793
- }
1794
- function _type_of$1(obj) {
1795
- "@swc/helpers - typeof";
1796
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
1797
- }
1798
- function _wrap_native_super(Class) {
1799
- var _cache = typeof Map === "function" ? new Map() : undefined;
1800
- _wrap_native_super = function wrapNativeSuper(Class) {
1801
- if (Class === null || !_is_native_function(Class)) return Class;
1802
- if (typeof Class !== "function") {
1803
- throw new TypeError("Super expression must either be null or a function");
1804
- }
1805
- if (typeof _cache !== "undefined") {
1806
- if (_cache.has(Class)) return _cache.get(Class);
1807
- _cache.set(Class, Wrapper);
1808
- }
1809
- function Wrapper() {
1810
- return _construct(Class, arguments, _get_prototype_of(this).constructor);
1811
- }
1812
- Wrapper.prototype = Object.create(Class.prototype, {
1813
- constructor: {
1814
- value: Wrapper,
1815
- enumerable: false,
1816
- writable: true,
1817
- configurable: true
1818
- }
1819
- });
1820
- return _set_prototype_of(Wrapper, Class);
1821
- };
1822
- return _wrap_native_super(Class);
1823
- }
1824
- function _is_native_reflect_construct() {
1825
- try {
1826
- var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1827
- } catch (_) {}
1828
- return (_is_native_reflect_construct = function() {
1829
- return !!result;
1830
- })();
1831
- }
1832
- function _ts_generator$4(thisArg, body) {
1833
- var f, y, t, _ = {
1834
- label: 0,
1835
- sent: function() {
1836
- if (t[0] & 1) throw t[1];
1837
- return t[1];
1838
- },
1839
- trys: [],
1840
- ops: []
1841
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
1842
- return d(g, "next", {
1843
- value: verb(0)
1844
- }), d(g, "throw", {
1845
- value: verb(1)
1846
- }), d(g, "return", {
1847
- value: verb(2)
1848
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
1849
- value: function() {
1850
- return this;
1851
- }
1852
- }), g;
1853
- function verb(n) {
1854
- return function(v) {
1855
- return step([
1856
- n,
1857
- v
1858
- ]);
1859
- };
1860
- }
1861
- function step(op) {
1862
- if (f) throw new TypeError("Generator is already executing.");
1863
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
1864
- 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;
1865
- if (y = 0, t) op = [
1866
- op[0] & 2,
1867
- t.value
1868
- ];
1869
- switch(op[0]){
1870
- case 0:
1871
- case 1:
1872
- t = op;
1873
- break;
1874
- case 4:
1875
- _.label++;
1876
- return {
1877
- value: op[1],
1878
- done: false
1879
- };
1880
- case 5:
1881
- _.label++;
1882
- y = op[1];
1883
- op = [
1884
- 0
1885
- ];
1886
- continue;
1887
- case 7:
1888
- op = _.ops.pop();
1889
- _.trys.pop();
1890
- continue;
1891
- default:
1892
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1893
- _ = 0;
1894
- continue;
1895
- }
1896
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1897
- _.label = op[1];
1898
- break;
1899
- }
1900
- if (op[0] === 6 && _.label < t[1]) {
1901
- _.label = t[1];
1902
- t = op;
1903
- break;
1904
- }
1905
- if (t && _.label < t[2]) {
1906
- _.label = t[2];
1907
- _.ops.push(op);
1908
- break;
1909
- }
1910
- if (t[2]) _.ops.pop();
1911
- _.trys.pop();
1912
- continue;
1913
- }
1914
- op = body.call(thisArg, _);
1915
- } catch (e) {
1916
- op = [
1917
- 6,
1918
- e
1919
- ];
1920
- y = 0;
1921
- } finally{
1922
- f = t = 0;
1923
- }
1924
- if (op[0] & 5) throw op[1];
1925
- return {
1926
- value: op[0] ? op[1] : void 0,
1927
- done: true
1928
- };
1929
- }
1930
- }
1931
- /**
1932
- * Error thrown when a prompt cannot be resolved.
1933
- */ var OpenRouterPromptResolutionError = /*#__PURE__*/ function(Error1) {
1934
- _inherits(OpenRouterPromptResolutionError, Error1);
1935
- function OpenRouterPromptResolutionError(promptKey, message, version) {
1936
- _class_call_check$1(this, OpenRouterPromptResolutionError);
1937
- var _this;
1938
- _this = _call_super(this, OpenRouterPromptResolutionError, [
1939
- 'OpenRouter prompt "'.concat(promptKey, '"').concat(version == null ? '' : " version ".concat(version), ": ").concat(message)
1940
- ]), _define_property$2(_this, "promptKey", void 0), _define_property$2(_this, "version", void 0);
1941
- _this.promptKey = promptKey;
1942
- _this.version = version;
1943
- return _this;
1944
- }
1945
- return OpenRouterPromptResolutionError;
1946
- }(_wrap_native_super(Error));
1947
- /**
1948
- * Default time a resolved prompt is cached for.
1949
- *
1950
- * What can go stale is which version is active, and what the latest — still editable — version says.
1951
- * Neither is critical to serve to the second: a run that used the previous text for a few minutes is a
1952
- * run against a prompt that was live a few minutes ago, not a wrong run. Bounded rather than permanent
1953
- * is the requirement, so the change lands on its own rather than at the next cold start.
1954
- */ var OPENROUTER_PROMPT_CACHE_DURATION = util.MS_IN_MINUTE * 5;
1955
- /**
1956
- * Loads prompts and resolves their versions.
1957
- */ var OpenRouterPromptService = function OpenRouterPromptService() {
1958
- _class_call_check$1(this, OpenRouterPromptService);
1959
- };
1960
- /**
1961
- * Creates an {@link OpenRouterPromptService}.
1962
- *
1963
- * @param config - The collections and cache configuration.
1964
- * @returns The service.
1965
- */ function openRouterPromptService(config) {
1966
- var collections = config.collections, definitions = config.definitions, cacheDuration = config.cacheDuration, rejectInvalidConfig = config.rejectInvalidConfig;
1967
- var openRouterPromptCollection = collections.openRouterPromptCollection, openRouterPromptVersionCollectionFactory = collections.openRouterPromptVersionCollectionFactory;
1968
- var duration = cacheDuration !== null && cacheDuration !== void 0 ? cacheDuration : OPENROUTER_PROMPT_CACHE_DURATION;
1969
- var definitionsByKey = util.arrayToMap(definitions !== null && definitions !== void 0 ? definitions : [], function(definition) {
1970
- return definition.promptKey;
1971
- });
1972
- var cache = new Map();
1973
- function loadPromptDefinitions() {
1974
- return _async_to_generator$4(function() {
1975
- return _ts_generator$4(this, function(_state) {
1976
- // A fresh array each call rather than one built at construction: the returned type is mutable, and
1977
- // handing every caller the same array would let a seeder's own filtering reach the registry
1978
- // resolution reads.
1979
- return [
1980
- 2,
1981
- Array.from(definitionsByKey.values())
1982
- ];
1983
- });
1984
- })();
1985
- }
1986
- function loadPromptDocument(promptKey) {
1987
- return openRouterPromptCollection.documentAccessor().loadDocumentForId(promptKey);
1988
- }
1989
- function loadPrompt(promptKey) {
1990
- return _async_to_generator$4(function() {
1991
- return _ts_generator$4(this, function(_state) {
1992
- return [
1993
- 2,
1994
- loadPromptDocument(promptKey).snapshotData()
1995
- ];
1996
- });
1997
- })();
1998
- }
1999
- /**
2000
- * Reads one published version.
2001
- *
2002
- * @param promptDocument - The parent prompt document.
2003
- * @param promptKey - The prompt's key, recorded on the resolution.
2004
- * @param version - The version to read.
2005
- * @returns The resolved version, or undefined when that version was never published.
2006
- */ function readStoredVersion(promptDocument, promptKey, version) {
2007
- return _async_to_generator$4(function() {
2008
- var versionDocument, versionData;
2009
- return _ts_generator$4(this, function(_state) {
2010
- switch(_state.label){
2011
- case 0:
2012
- versionDocument = openRouterPromptVersionCollectionFactory(promptDocument).documentAccessor().loadDocumentForId(firebase.openRouterPromptVersionId(version));
2013
- return [
2014
- 4,
2015
- versionDocument.snapshotData()
2016
- ];
2017
- case 1:
2018
- versionData = _state.sent();
2019
- return [
2020
- 2,
2021
- versionData == null ? undefined : firebase.openRouterResolvedPromptForVersion(promptKey, versionData)
2022
- ];
2023
- }
2024
- });
2025
- })();
2026
- }
2027
- function resolveVersion(promptKey, inputVersion) {
2028
- return _async_to_generator$4(function() {
2029
- var definition, promptDocument, prompt, storedActiveVersion, resolved, _tmp, validation;
2030
- return _ts_generator$4(this, function(_state) {
2031
- switch(_state.label){
2032
- case 0:
2033
- definition = definitionsByKey.get(promptKey);
2034
- promptDocument = loadPromptDocument(promptKey);
2035
- return [
2036
- 4,
2037
- promptDocument.snapshotData()
2038
- ];
2039
- case 1:
2040
- prompt = _state.sent();
2041
- // The version the store would serve an unpinned caller. A prompt that is missing, not ACTIVE, or has
2042
- // never had a version promoted cannot serve one — which is precisely when a code definition stands in.
2043
- // A pinned caller is still allowed to read a draft/archived prompt: that is how a version is tested
2044
- // before promotion, and how a historical run is replayed after retirement.
2045
- storedActiveVersion = (prompt === null || prompt === void 0 ? void 0 : prompt.s) === firebase.OpenRouterPromptState.ACTIVE ? prompt.av : undefined;
2046
- if (!(inputVersion != null)) return [
2047
- 3,
2048
- 5
2049
- ];
2050
- if (!(prompt == null)) return [
2051
- 3,
2052
- 2
2053
- ];
2054
- _tmp = undefined;
2055
- return [
2056
- 3,
2057
- 4
2058
- ];
2059
- case 2:
2060
- return [
2061
- 4,
2062
- readStoredVersion(promptDocument, promptKey, inputVersion)
2063
- ];
2064
- case 3:
2065
- _tmp = _state.sent();
2066
- _state.label = 4;
2067
- case 4:
2068
- // Pinned. The store wins whenever it actually holds that version, so a version published under the
2069
- // same number after a run was queued is picked up on the run's next attempt. The definition covers
2070
- // the rest, which is what lets a run enqueued against a definition still dispatch.
2071
- resolved = _tmp;
2072
- if (resolved == null && (definition === null || definition === void 0 ? void 0 : definition.version) === inputVersion) {
2073
- resolved = definition;
2074
- }
2075
- return [
2076
- 3,
2077
- 8
2078
- ];
2079
- case 5:
2080
- if (!(definition != null && (storedActiveVersion == null || definition.version > storedActiveVersion))) return [
2081
- 3,
2082
- 6
2083
- ];
2084
- // Unpinned, and code is either standing in for the store or ahead of it.
2085
- resolved = definition;
2086
- return [
2087
- 3,
2088
- 8
2089
- ];
2090
- case 6:
2091
- if (!(storedActiveVersion != null)) return [
2092
- 3,
2093
- 8
2094
- ];
2095
- return [
2096
- 4,
2097
- readStoredVersion(promptDocument, promptKey, storedActiveVersion)
2098
- ];
2099
- case 7:
2100
- resolved = _state.sent();
2101
- _state.label = 8;
2102
- case 8:
2103
- if (resolved == null) {
2104
- // Reported against what was actually missing, since "no prompt", "nothing promoted", and "that one
2105
- // version is gone" need different fixes.
2106
- if (prompt == null) {
2107
- throw new OpenRouterPromptResolutionError(promptKey, 'does not exist.', inputVersion);
2108
- } else if (inputVersion != null) {
2109
- throw new OpenRouterPromptResolutionError(promptKey, 'version does not exist.', inputVersion);
2110
- } else if (prompt.s === firebase.OpenRouterPromptState.ACTIVE) {
2111
- throw new OpenRouterPromptResolutionError(promptKey, 'has no activeVersion, and no version was pinned.');
2112
- } else {
2113
- throw new OpenRouterPromptResolutionError(promptKey, "is not ACTIVE (state ".concat(prompt.s, "), and no version was pinned."));
2114
- }
2115
- }
2116
- if (rejectInvalidConfig) {
2117
- validation = openrouter.validateOpenRouterModelConfig(resolved.config);
2118
- if (!validation.valid) {
2119
- throw new OpenRouterPromptResolutionError(promptKey, "has an invalid config: ".concat(validation.errors.join(' ')), resolved.version);
2120
- }
2121
- }
2122
- return [
2123
- 2,
2124
- resolved
2125
- ];
2126
- }
2127
- });
2128
- })();
2129
- }
2130
- function cacheKey(promptKey, version) {
2131
- return "".concat(promptKey, ":").concat(version !== null && version !== void 0 ? version : '_');
2132
- }
2133
- function resolvePrompt(params) {
2134
- return _async_to_generator$4(function() {
2135
- var promptKey, version, key, getter, load, result, e;
2136
- return _ts_generator$4(this, function(_state) {
2137
- switch(_state.label){
2138
- case 0:
2139
- promptKey = params.promptKey, version = params.version;
2140
- key = cacheKey(promptKey, version);
2141
- getter = cache.get(key);
2142
- if (getter == null) {
2143
- load = function load() {
2144
- return resolveVersion(promptKey, version);
2145
- };
2146
- // Everything expires, pinned resolutions included. A version is only immutable once it LOCKS, which
2147
- // happens when the next version is created — until then the head version is editable in place, and
2148
- // a permanently cached pin of it would serve the pre-edit text forever on every instance except the
2149
- // one that handled the edit. Telling the two apart would cost a read of the lock, which is the same
2150
- // read the expiry already pays for.
2151
- getter = util.expiringCachedGetter({
2152
- getter: load,
2153
- ttl: duration
2154
- });
2155
- cache.set(key, getter);
2156
- }
2157
- _state.label = 1;
2158
- case 1:
2159
- _state.trys.push([
2160
- 1,
2161
- 3,
2162
- ,
2163
- 4
2164
- ]);
2165
- return [
2166
- 4,
2167
- getter()
2168
- ];
2169
- case 2:
2170
- result = _state.sent();
2171
- return [
2172
- 3,
2173
- 4
2174
- ];
2175
- case 3:
2176
- e = _state.sent();
2177
- // Never cache a rejected promise: a prompt created moments after a failed lookup would keep
2178
- // failing for the whole cache window.
2179
- cache.delete(key);
2180
- throw e;
2181
- case 4:
2182
- return [
2183
- 2,
2184
- result
2185
- ];
2186
- }
2187
- });
2188
- })();
2189
- }
2190
- function clearCachedPrompt(promptKey) {
2191
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2192
- try {
2193
- // Every version of the prompt goes, pinned entries included: a publish or promote can change what any
2194
- // of them resolve to. Deleting the current entry mid-iteration is well-defined for a Map iterator, so
2195
- // no snapshot copy is needed.
2196
- for(var _iterator = cache.keys()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2197
- var key = _step.value;
2198
- if (key.startsWith("".concat(promptKey, ":"))) {
2199
- cache.delete(key);
2200
- }
2201
- }
2202
- } catch (err) {
2203
- _didIteratorError = true;
2204
- _iteratorError = err;
2205
- } finally{
2206
- try {
2207
- if (!_iteratorNormalCompletion && _iterator.return != null) {
2208
- _iterator.return();
2209
- }
2210
- } finally{
2211
- if (_didIteratorError) {
2212
- throw _iteratorError;
2213
- }
2214
- }
2215
- }
2216
- }
2217
- return {
2218
- loadPromptDefinitions: loadPromptDefinitions,
2219
- loadPrompt: loadPrompt,
2220
- resolvePrompt: resolvePrompt,
2221
- clearCachedPrompt: clearCachedPrompt
2222
- };
2223
- }
2224
-
2225
- function asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, key, arg) {
2226
- try {
2227
- var info = gen[key](arg);
2228
- var value = info.value;
2229
- } catch (error) {
2230
- reject(error);
2231
- return;
2232
- }
2233
- if (info.done) {
2234
- resolve(value);
2235
- } else {
2236
- Promise.resolve(value).then(_next, _throw);
2237
- }
2238
- }
2239
- function _async_to_generator$3(fn) {
2240
- return function() {
2241
- var self = this, args = arguments;
2242
- return new Promise(function(resolve, reject) {
2243
- var gen = fn.apply(self, args);
2244
- function _next(value) {
2245
- asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "next", value);
2246
- }
2247
- function _throw(err) {
2248
- asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "throw", err);
2249
- }
2250
- _next(undefined);
2251
- });
2252
- };
2253
- }
2254
- function _ts_generator$3(thisArg, body) {
2255
- var f, y, t, _ = {
2256
- label: 0,
2257
- sent: function() {
2258
- if (t[0] & 1) throw t[1];
2259
- return t[1];
2260
- },
2261
- trys: [],
2262
- ops: []
2263
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
2264
- return d(g, "next", {
2265
- value: verb(0)
2266
- }), d(g, "throw", {
2267
- value: verb(1)
2268
- }), d(g, "return", {
2269
- value: verb(2)
2270
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
2271
- value: function() {
2272
- return this;
2273
- }
2274
- }), g;
2275
- function verb(n) {
2276
- return function(v) {
2277
- return step([
2278
- n,
2279
- v
2280
- ]);
2281
- };
2282
- }
2283
- function step(op) {
2284
- if (f) throw new TypeError("Generator is already executing.");
2285
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
2286
- 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;
2287
- if (y = 0, t) op = [
2288
- op[0] & 2,
2289
- t.value
2290
- ];
2291
- switch(op[0]){
2292
- case 0:
2293
- case 1:
2294
- t = op;
2295
- break;
2296
- case 4:
2297
- _.label++;
2298
- return {
2299
- value: op[1],
2300
- done: false
2301
- };
2302
- case 5:
2303
- _.label++;
2304
- y = op[1];
2305
- op = [
2306
- 0
2307
- ];
2308
- continue;
2309
- case 7:
2310
- op = _.ops.pop();
2311
- _.trys.pop();
2312
- continue;
2313
- default:
2314
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
2315
- _ = 0;
2316
- continue;
2317
- }
2318
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
2319
- _.label = op[1];
2320
- break;
2321
- }
2322
- if (op[0] === 6 && _.label < t[1]) {
2323
- _.label = t[1];
2324
- t = op;
2325
- break;
2326
- }
2327
- if (t && _.label < t[2]) {
2328
- _.label = t[2];
2329
- _.ops.push(op);
2330
- break;
2331
- }
2332
- if (t[2]) _.ops.pop();
2333
- _.trys.pop();
2334
- continue;
2335
- }
2336
- op = body.call(thisArg, _);
2337
- } catch (e) {
2338
- op = [
2339
- 6,
2340
- e
2341
- ];
2342
- y = 0;
2343
- } finally{
2344
- f = t = 0;
2345
- }
2346
- if (op[0] & 5) throw op[1];
2347
- return {
2348
- value: op[0] ? op[1] : void 0,
2349
- done: true
2350
- };
2351
- }
2352
- }
2353
- /**
2354
- * Classifies a run task into an outcome.
2355
- *
2356
- * `AWAITING_ASYNC_TOOLS` reports as `queued`: from the caller's side it is indistinguishable from
2357
- * waiting, because it is waiting — just on a tool result rather than on a sweep.
2358
- *
2359
- * @param task - The run task, or null when it does not exist.
2360
- * @returns The outcome.
2361
- *
2362
- * @__NO_SIDE_EFFECTS__
2363
- */ function openRouterRunTaskOutcome(task) {
2364
- var result;
2365
- if (task == null) {
2366
- result = 'missing';
2367
- } else {
2368
- switch(task.s){
2369
- case firebase.OpenRouterRunTaskState.COMPLETE:
2370
- result = 'complete';
2371
- break;
2372
- case firebase.OpenRouterRunTaskState.FAILED:
2373
- result = 'failure';
2374
- break;
2375
- case firebase.OpenRouterRunTaskState.QUEUED:
2376
- case firebase.OpenRouterRunTaskState.RUNNING:
2377
- case firebase.OpenRouterRunTaskState.AWAITING_ASYNC_TOOLS:
2378
- default:
2379
- result = 'queued';
2380
- break;
2381
- }
2382
- }
2383
- return result;
2384
- }
2385
- /**
2386
- * Creates a reusable dispatcher for a fixed set of handlers.
2387
- *
2388
- * @param handlers - The per-outcome handlers.
2389
- * @returns A function that dispatches a run task.
2390
- *
2391
- * @__NO_SIDE_EFFECTS__
2392
- */ function handleOpenRouterRunTaskResultFactory(handlers) {
2393
- return function(task) {
2394
- return _async_to_generator$3(function() {
2395
- var outcome, result;
2396
- return _ts_generator$3(this, function(_state) {
2397
- switch(_state.label){
2398
- case 0:
2399
- outcome = openRouterRunTaskOutcome(task);
2400
- switch(outcome){
2401
- case 'complete':
2402
- return [
2403
- 3,
2404
- 1
2405
- ];
2406
- case 'queued':
2407
- return [
2408
- 3,
2409
- 3
2410
- ];
2411
- case 'failure':
2412
- return [
2413
- 3,
2414
- 5
2415
- ];
2416
- case 'missing':
2417
- return [
2418
- 3,
2419
- 7
2420
- ];
2421
- }
2422
- return [
2423
- 3,
2424
- 7
2425
- ];
2426
- case 1:
2427
- return [
2428
- 4,
2429
- handlers.onComplete(task)
2430
- ];
2431
- case 2:
2432
- result = _state.sent();
2433
- return [
2434
- 3,
2435
- 9
2436
- ];
2437
- case 3:
2438
- return [
2439
- 4,
2440
- handlers.onQueued(task)
2441
- ];
2442
- case 4:
2443
- result = _state.sent();
2444
- return [
2445
- 3,
2446
- 9
2447
- ];
2448
- case 5:
2449
- return [
2450
- 4,
2451
- handlers.onFailure(task)
2452
- ];
2453
- case 6:
2454
- result = _state.sent();
2455
- return [
2456
- 3,
2457
- 9
2458
- ];
2459
- case 7:
2460
- return [
2461
- 4,
2462
- handlers.onMissing()
2463
- ];
2464
- case 8:
2465
- result = _state.sent();
2466
- return [
2467
- 3,
2468
- 9
2469
- ];
2470
- case 9:
2471
- return [
2472
- 2,
2473
- result
2474
- ];
2475
- }
2476
- });
2477
- })();
2478
- };
2479
- }
2480
-
2481
- function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) {
2482
- try {
2483
- var info = gen[key](arg);
2484
- var value = info.value;
2485
- } catch (error) {
2486
- reject(error);
2487
- return;
2488
- }
2489
- if (info.done) {
2490
- resolve(value);
2491
- } else {
2492
- Promise.resolve(value).then(_next, _throw);
2493
- }
2494
- }
2495
- function _async_to_generator$2(fn) {
2496
- return function() {
2497
- var self = this, args = arguments;
2498
- return new Promise(function(resolve, reject) {
2499
- var gen = fn.apply(self, args);
2500
- function _next(value) {
2501
- asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "next", value);
2502
- }
2503
- function _throw(err) {
2504
- asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "throw", err);
2505
- }
2506
- _next(undefined);
2507
- });
2508
- };
2509
- }
2510
- function _define_property$1(obj, key, value) {
2511
- if (key in obj) {
2512
- Object.defineProperty(obj, key, {
2513
- value: value,
2514
- enumerable: true,
2515
- configurable: true,
2516
- writable: true
2517
- });
2518
- } else {
2519
- obj[key] = value;
2520
- }
2521
- return obj;
2522
- }
2523
- function _object_spread$1(target) {
2524
- for(var i = 1; i < arguments.length; i++){
2525
- var source = arguments[i] != null ? arguments[i] : {};
2526
- var ownKeys = Object.keys(source);
2527
- if (typeof Object.getOwnPropertySymbols === "function") {
2528
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
2529
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
2530
- }));
2531
- }
2532
- ownKeys.forEach(function(key) {
2533
- _define_property$1(target, key, source[key]);
2534
- });
2535
- }
2536
- return target;
2537
- }
2538
- function ownKeys$1(object, enumerableOnly) {
2539
- var keys = Object.keys(object);
2540
- if (Object.getOwnPropertySymbols) {
2541
- var symbols = Object.getOwnPropertySymbols(object);
2542
- keys.push.apply(keys, symbols);
2543
- }
2544
- return keys;
2545
- }
2546
- function _object_spread_props$1(target, source) {
2547
- source = source != null ? source : {};
2548
- if (Object.getOwnPropertyDescriptors) {
2549
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
2550
- } else {
2551
- ownKeys$1(Object(source)).forEach(function(key) {
2552
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
2553
- });
2554
- }
2555
- return target;
2556
- }
2557
- function _ts_generator$2(thisArg, body) {
2558
- var f, y, t, _ = {
2559
- label: 0,
2560
- sent: function() {
2561
- if (t[0] & 1) throw t[1];
2562
- return t[1];
2563
- },
2564
- trys: [],
2565
- ops: []
2566
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
2567
- return d(g, "next", {
2568
- value: verb(0)
2569
- }), d(g, "throw", {
2570
- value: verb(1)
2571
- }), d(g, "return", {
2572
- value: verb(2)
2573
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
2574
- value: function() {
2575
- return this;
2576
- }
2577
- }), g;
2578
- function verb(n) {
2579
- return function(v) {
2580
- return step([
2581
- n,
2582
- v
2583
- ]);
2584
- };
2585
- }
2586
- function step(op) {
2587
- if (f) throw new TypeError("Generator is already executing.");
2588
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
2589
- 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;
2590
- if (y = 0, t) op = [
2591
- op[0] & 2,
2592
- t.value
2593
- ];
2594
- switch(op[0]){
2595
- case 0:
2596
- case 1:
2597
- t = op;
2598
- break;
2599
- case 4:
2600
- _.label++;
2601
- return {
2602
- value: op[1],
2603
- done: false
2604
- };
2605
- case 5:
2606
- _.label++;
2607
- y = op[1];
2608
- op = [
2609
- 0
2610
- ];
2611
- continue;
2612
- case 7:
2613
- op = _.ops.pop();
2614
- _.trys.pop();
2615
- continue;
2616
- default:
2617
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
2618
- _ = 0;
2619
- continue;
2620
- }
2621
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
2622
- _.label = op[1];
2623
- break;
2624
- }
2625
- if (op[0] === 6 && _.label < t[1]) {
2626
- _.label = t[1];
2627
- t = op;
2628
- break;
2629
- }
2630
- if (t && _.label < t[2]) {
2631
- _.label = t[2];
2632
- _.ops.push(op);
2633
- break;
2634
- }
2635
- if (t[2]) _.ops.pop();
2636
- _.trys.pop();
2637
- continue;
2638
- }
2639
- op = body.call(thisArg, _);
2640
- } catch (e) {
2641
- op = [
2642
- 6,
2643
- e
2644
- ];
2645
- y = 0;
2646
- } finally{
2647
- f = t = 0;
2648
- }
2649
- if (op[0] & 5) throw op[1];
2650
- return {
2651
- value: op[0] ? op[1] : void 0,
2652
- done: true
2653
- };
2654
- }
2655
- }
2656
- /**
2657
- * Maps a run task state to the SDK's conversation status.
2658
- *
2659
- * @param state - The run task state.
2660
- * @returns The conversation status.
2661
- *
2662
- * @__NO_SIDE_EFFECTS__
2663
- */ function conversationStatusForOpenRouterRunTaskState(state) {
2664
- var result;
2665
- switch(state){
2666
- case firebase.OpenRouterRunTaskState.COMPLETE:
2667
- result = 'complete';
2668
- break;
2669
- case firebase.OpenRouterRunTaskState.FAILED:
2670
- result = 'interrupted';
2671
- break;
2672
- case firebase.OpenRouterRunTaskState.AWAITING_ASYNC_TOOLS:
2673
- // The SDK's vocabulary for "paused holding tool calls we did not execute ourselves".
2674
- result = 'awaiting_approval';
2675
- break;
2676
- case firebase.OpenRouterRunTaskState.RUNNING:
2677
- result = 'in_progress';
2678
- break;
2679
- case firebase.OpenRouterRunTaskState.QUEUED:
2680
- default:
2681
- result = 'in_progress';
2682
- break;
2683
- }
2684
- return result;
2685
- }
2686
- /**
2687
- * Maps a conversation status back to the run task state to persist.
2688
- *
2689
- * @param status - The conversation status.
2690
- * @param hasPendingToolCalls - Whether the state carries tool calls this process cannot resolve.
2691
- * @returns The run task state.
2692
- *
2693
- * @__NO_SIDE_EFFECTS__
2694
- */ function openRouterRunTaskStateForConversationStatus(status, hasPendingToolCalls) {
2695
- var result;
2696
- if (hasPendingToolCalls) {
2697
- // Pending calls win over the reported status: whatever the SDK called it, the run cannot proceed
2698
- // until something outside this process supplies those results.
2699
- result = firebase.OpenRouterRunTaskState.AWAITING_ASYNC_TOOLS;
2700
- } else {
2701
- switch(status){
2702
- case 'complete':
2703
- result = firebase.OpenRouterRunTaskState.COMPLETE;
2704
- break;
2705
- case 'awaiting_approval':
2706
- result = firebase.OpenRouterRunTaskState.AWAITING_ASYNC_TOOLS;
2707
- break;
2708
- case 'interrupted':
2709
- case 'in_progress':
2710
- default:
2711
- result = firebase.OpenRouterRunTaskState.RUNNING;
2712
- break;
2713
- }
2714
- }
2715
- return result;
2716
- }
2717
- /**
2718
- * Builds a {@link ConversationState} from a run task.
2719
- *
2720
- * `updatedAt` is derived rather than stored: the run task's existing timestamps already order the
2721
- * lifecycle (`fat` > `lat` > `sat` > `qat`), and the SDK uses the value informationally.
2722
- *
2723
- * @param key - The run task key, which is the conversation id.
2724
- * @param task - The run task.
2725
- * @returns The conversation state.
2726
- *
2727
- * @__NO_SIDE_EFFECTS__
2728
- */ function conversationStateForOpenRouterRunTask(key, task) {
2729
- var _ref, _ref1, _task_fat, _task_msg, _task_ptc, _task_utr;
2730
- var updatedAt = (_ref = (_ref1 = (_task_fat = task.fat) !== null && _task_fat !== void 0 ? _task_fat : task.lat) !== null && _ref1 !== void 0 ? _ref1 : task.sat) !== null && _ref !== void 0 ? _ref : task.qat;
2731
- return {
2732
- id: key,
2733
- messages: (_task_msg = task.msg) !== null && _task_msg !== void 0 ? _task_msg : [],
2734
- pendingToolCalls: ((_task_ptc = task.ptc) !== null && _task_ptc !== void 0 ? _task_ptc : []).map(function(call) {
2735
- return {
2736
- id: call.callId,
2737
- name: call.name,
2738
- arguments: call.arguments
2739
- };
2740
- }),
2741
- unsentToolResults: ((_task_utr = task.utr) !== null && _task_utr !== void 0 ? _task_utr : []).map(function(result) {
2742
- var _result_error;
2743
- return {
2744
- callId: result.callId,
2745
- name: result.name,
2746
- output: result.output,
2747
- error: (_result_error = result.error) !== null && _result_error !== void 0 ? _result_error : undefined
2748
- };
2749
- }),
2750
- status: conversationStatusForOpenRouterRunTaskState(task.s),
2751
- createdAt: task.qat.getTime(),
2752
- updatedAt: updatedAt.getTime()
2753
- };
2754
- }
2755
- /**
2756
- * Builds the run task update for a conversation state.
2757
- *
2758
- * @param state - The conversation state to persist.
2759
- * @returns The fields to write.
2760
- *
2761
- * @__NO_SIDE_EFFECTS__
2762
- */ function openRouterRunTaskUpdateForConversationState(state) {
2763
- var _state_pendingToolCalls, _state_messages, _state_unsentToolResults;
2764
- var pendingToolCalls = (_state_pendingToolCalls = state.pendingToolCalls) !== null && _state_pendingToolCalls !== void 0 ? _state_pendingToolCalls : [];
2765
- return {
2766
- s: openRouterRunTaskStateForConversationStatus(state.status, pendingToolCalls.length > 0),
2767
- // Attachment payloads are stripped on the way in. They are resolved per attempt — a signed url has
2768
- // already expired and inline base64 is the whole file — and `msg` is a Firestore field with a 1 MiB
2769
- // document budget behind it. `load()` re-points the stripped parts, so nothing is lost.
2770
- msg: openRouterConversationValueForFirestore(openrouter.openRouterMessagesWithoutFileAttachmentData((_state_messages = state.messages) !== null && _state_messages !== void 0 ? _state_messages : [])),
2771
- ptc: pendingToolCalls.map(function(call) {
2772
- var _openRouterConversationValueForFirestore;
2773
- return {
2774
- callId: call.id,
2775
- name: call.name,
2776
- taskId: call.id,
2777
- arguments: (_openRouterConversationValueForFirestore = openRouterConversationValueForFirestore(call.arguments)) !== null && _openRouterConversationValueForFirestore !== void 0 ? _openRouterConversationValueForFirestore : null
2778
- };
2779
- }),
2780
- utr: ((_state_unsentToolResults = state.unsentToolResults) !== null && _state_unsentToolResults !== void 0 ? _state_unsentToolResults : []).map(function(result) {
2781
- var _openRouterConversationValueForFirestore, _result_error;
2782
- return {
2783
- callId: result.callId,
2784
- name: result.name,
2785
- output: (_openRouterConversationValueForFirestore = openRouterConversationValueForFirestore(result.output)) !== null && _openRouterConversationValueForFirestore !== void 0 ? _openRouterConversationValueForFirestore : null,
2786
- error: (_result_error = result.error) !== null && _result_error !== void 0 ? _result_error : null
2787
- };
2788
- })
2789
- };
2790
- }
2791
- /**
2792
- * Strips `undefined` out of a value on its way into Firestore, at ANY DEPTH.
2793
- *
2794
- * Conversation state is whatever the SDK hands back, arbitrarily nested, and its response items carry
2795
- * explicit `undefined`s for absent optional fields at every level. Firestore rejects `undefined` outright,
2796
- * so persisting one unfiltered fails the whole write — and it fails inside the SDK's `saveStateSafely`,
2797
- * which surfaces as an opaque "Failed to persist conversation state" rather than as the run-task write it
2798
- * actually is.
2799
- *
2800
- * A JSON round-trip rather than `copyValueWithoutUndefinedValues` (which filters just as deeply, and is
2801
- * what the run task converter's passthrough-JSON fields use): the round-trip additionally flattens
2802
- * anything that is not wire json — a `Date`, a class instance with a `toJSON` — which is correct here
2803
- * precisely because this data IS json. It came off the wire, and `load()` hands it straight back to the
2804
- * SDK expecting the same shapes. The converter's fields, by contrast, must leave a `Date`/`Timestamp`
2805
- * intact for Firestore.
2806
- *
2807
- * @param value - The value to sanitize.
2808
- * @returns The value with every `undefined` removed.
2809
- *
2810
- * @__NO_SIDE_EFFECTS__
2811
- */ function openRouterConversationValueForFirestore(value) {
2812
- // NOT `structuredClone`. It PRESERVES `undefined`-valued keys, which is the one thing this function
2813
- // exists to remove — so `unicorn/prefer-structured-clone`'s autofix would silently break it.
2814
- // eslint-disable-next-line unicorn/prefer-structured-clone
2815
- return value === undefined ? value : JSON.parse(JSON.stringify(value));
2816
- }
2817
- /**
2818
- * Creates a {@link StateAccessor} backed by a run task document.
2819
- *
2820
- * This is the persistent backend the SDK's docs ask for — its own example is a `Map`, with the note to
2821
- * "implement `StateAccessor` with a persistent backend". Because OpenRouter allocates no conversation
2822
- * id (and rejects `previous_response_id` outright), the conversation id is ours: the run task key.
2823
- *
2824
- * A single-shot run simply never populates `msg` / `ptc` / `utr`, so nothing is paid for not using it.
2825
- *
2826
- * @param document - The run task document to read and write.
2827
- * @param config - The initial conversation and this attempt's attached files.
2828
- * @returns The state accessor.
2829
- */ function firestoreOpenRouterStateAccessor(document, config) {
2830
- var _ref = config !== null && config !== void 0 ? config : {}, initialMessages = _ref.initialMessages, attachedFiles = _ref.attachedFiles;
2831
- return {
2832
- load: function load() {
2833
- return _async_to_generator$2(function() {
2834
- var task, result, _task_msg, stored, messages;
2835
- return _ts_generator$2(this, function(_state) {
2836
- switch(_state.label){
2837
- case 0:
2838
- return [
2839
- 4,
2840
- document.snapshotData()
2841
- ];
2842
- case 1:
2843
- task = _state.sent();
2844
- if (task != null) {
2845
- stored = (_task_msg = task.msg) !== null && _task_msg !== void 0 ? _task_msg : [];
2846
- messages = openrouter.openRouterMessagesWithFreshFileAttachments(stored.length > 0 ? stored : initialMessages !== null && initialMessages !== void 0 ? initialMessages : [], attachedFiles);
2847
- result = conversationStateForOpenRouterRunTask(document.id, _object_spread_props$1(_object_spread$1({}, task), {
2848
- msg: messages
2849
- }));
2850
- }
2851
- return [
2852
- 2,
2853
- result !== null && result !== void 0 ? result : null
2854
- ];
2855
- }
2856
- });
2857
- })();
2858
- },
2859
- save: function save(state) {
2860
- return _async_to_generator$2(function() {
2861
- return _ts_generator$2(this, function(_state) {
2862
- switch(_state.label){
2863
- case 0:
2864
- return [
2865
- 4,
2866
- document.update(openRouterRunTaskUpdateForConversationState(state))
2867
- ];
2868
- case 1:
2869
- _state.sent();
2870
- return [
2871
- 2
2872
- ];
2873
- }
2874
- });
2875
- })();
2876
- }
2877
- };
2878
- }
2879
-
2880
- function _array_like_to_array(arr, len) {
2881
- if (len == null || len > arr.length) len = arr.length;
2882
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
2883
- return arr2;
2884
- }
2885
- function _array_with_holes(arr) {
2886
- if (Array.isArray(arr)) return arr;
2887
- }
2888
- function _array_without_holes(arr) {
2889
- if (Array.isArray(arr)) return _array_like_to_array(arr);
2890
- }
2891
- function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
2892
- try {
2893
- var info = gen[key](arg);
2894
- var value = info.value;
2895
- } catch (error) {
2896
- reject(error);
2897
- return;
2898
- }
2899
- if (info.done) {
2900
- resolve(value);
2901
- } else {
2902
- Promise.resolve(value).then(_next, _throw);
2903
- }
2904
- }
2905
- function _async_to_generator$1(fn) {
2906
- return function() {
2907
- var self = this, args = arguments;
2908
- return new Promise(function(resolve, reject) {
2909
- var gen = fn.apply(self, args);
2910
- function _next(value) {
2911
- asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
2912
- }
2913
- function _throw(err) {
2914
- asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
2915
- }
2916
- _next(undefined);
2917
- });
2918
- };
2919
- }
2920
- function _class_call_check(instance, Constructor) {
2921
- if (!(instance instanceof Constructor)) {
2922
- throw new TypeError("Cannot call a class as a function");
2923
- }
2924
- }
2925
- function _define_property(obj, key, value) {
2926
- if (key in obj) {
2927
- Object.defineProperty(obj, key, {
2928
- value: value,
2929
- enumerable: true,
2930
- configurable: true,
2931
- writable: true
2932
- });
2933
- } else {
2934
- obj[key] = value;
2935
- }
2936
- return obj;
2937
- }
2938
- function _instanceof(left, right) {
2939
- "@swc/helpers - instanceof";
2940
- if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
2941
- return !!right[Symbol.hasInstance](left);
2942
- } else {
2943
- return left instanceof right;
2944
- }
2945
- }
2946
- function _iterable_to_array(iter) {
2947
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
2948
- }
2949
- function _iterable_to_array_limit(arr, i) {
2950
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
2951
- if (_i == null) return;
2952
- var _arr = [];
2953
- var _n = true;
2954
- var _d = false;
2955
- var _s, _e;
2956
- try {
2957
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
2958
- _arr.push(_s.value);
2959
- if (i && _arr.length === i) break;
2960
- }
2961
- } catch (err) {
2962
- _d = true;
2963
- _e = err;
2964
- } finally{
2965
- try {
2966
- if (!_n && _i["return"] != null) _i["return"]();
2967
- } finally{
2968
- if (_d) throw _e;
2969
- }
2970
- }
2971
- return _arr;
2972
- }
2973
- function _non_iterable_rest() {
2974
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
2975
- }
2976
- function _non_iterable_spread() {
2977
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
2978
- }
2979
- function _object_spread(target) {
2980
- for(var i = 1; i < arguments.length; i++){
2981
- var source = arguments[i] != null ? arguments[i] : {};
2982
- var ownKeys = Object.keys(source);
2983
- if (typeof Object.getOwnPropertySymbols === "function") {
2984
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
2985
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
2986
- }));
2987
- }
2988
- ownKeys.forEach(function(key) {
2989
- _define_property(target, key, source[key]);
2990
- });
2991
- }
2992
- return target;
2993
- }
2994
- function ownKeys(object, enumerableOnly) {
2995
- var keys = Object.keys(object);
2996
- if (Object.getOwnPropertySymbols) {
2997
- var symbols = Object.getOwnPropertySymbols(object);
2998
- keys.push.apply(keys, symbols);
2999
- }
3000
- return keys;
3001
- }
3002
- function _object_spread_props(target, source) {
3003
- source = source != null ? source : {};
3004
- if (Object.getOwnPropertyDescriptors) {
3005
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
3006
- } else {
3007
- ownKeys(Object(source)).forEach(function(key) {
3008
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
3009
- });
3010
- }
3011
- return target;
3012
- }
3013
- function _sliced_to_array(arr, i) {
3014
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
3015
- }
3016
- function _to_consumable_array(arr) {
3017
- return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
3018
- }
3019
- function _type_of(obj) {
3020
- "@swc/helpers - typeof";
3021
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
3022
- }
3023
- function _unsupported_iterable_to_array(o, minLen) {
3024
- if (!o) return;
3025
- if (typeof o === "string") return _array_like_to_array(o, minLen);
3026
- var n = Object.prototype.toString.call(o).slice(8, -1);
3027
- if (n === "Object" && o.constructor) n = o.constructor.name;
3028
- if (n === "Map" || n === "Set") return Array.from(n);
3029
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
3030
- }
3031
- function _ts_generator$1(thisArg, body) {
3032
- var f, y, t, _ = {
3033
- label: 0,
3034
- sent: function() {
3035
- if (t[0] & 1) throw t[1];
3036
- return t[1];
3037
- },
3038
- trys: [],
3039
- ops: []
3040
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
3041
- return d(g, "next", {
3042
- value: verb(0)
3043
- }), d(g, "throw", {
3044
- value: verb(1)
3045
- }), d(g, "return", {
3046
- value: verb(2)
3047
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
3048
- value: function() {
3049
- return this;
3050
- }
3051
- }), g;
3052
- function verb(n) {
3053
- return function(v) {
3054
- return step([
3055
- n,
3056
- v
3057
- ]);
3058
- };
3059
- }
3060
- function step(op) {
3061
- if (f) throw new TypeError("Generator is already executing.");
3062
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
3063
- 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;
3064
- if (y = 0, t) op = [
3065
- op[0] & 2,
3066
- t.value
3067
- ];
3068
- switch(op[0]){
3069
- case 0:
3070
- case 1:
3071
- t = op;
3072
- break;
3073
- case 4:
3074
- _.label++;
3075
- return {
3076
- value: op[1],
3077
- done: false
3078
- };
3079
- case 5:
3080
- _.label++;
3081
- y = op[1];
3082
- op = [
3083
- 0
3084
- ];
3085
- continue;
3086
- case 7:
3087
- op = _.ops.pop();
3088
- _.trys.pop();
3089
- continue;
3090
- default:
3091
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
3092
- _ = 0;
3093
- continue;
3094
- }
3095
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
3096
- _.label = op[1];
3097
- break;
3098
- }
3099
- if (op[0] === 6 && _.label < t[1]) {
3100
- _.label = t[1];
3101
- t = op;
3102
- break;
3103
- }
3104
- if (t && _.label < t[2]) {
3105
- _.label = t[2];
3106
- _.ops.push(op);
3107
- break;
3108
- }
3109
- if (t[2]) _.ops.pop();
3110
- _.trys.pop();
3111
- continue;
3112
- }
3113
- op = body.call(thisArg, _);
3114
- } catch (e) {
3115
- op = [
3116
- 6,
3117
- e
3118
- ];
3119
- y = 0;
3120
- } finally{
3121
- f = t = 0;
3122
- }
3123
- if (op[0] & 5) throw op[1];
3124
- return {
3125
- value: op[0] ? op[1] : void 0,
3126
- done: true
3127
- };
3128
- }
3129
- }
3130
- /**
3131
- * Default lease duration. A `RUNNING` task whose lease is older than this is reclaimable.
3132
- *
3133
- * Comfortably longer than any single inference plus its retries, so a healthy run is never stolen from
3134
- * itself, and short enough that a crashed sweep's work resumes on the next tick or two.
3135
- */ var DEFAULT_OPENROUTER_LEASE_DURATION = util.MS_IN_MINUTE * 10;
3136
- /**
3137
- * Default number of attempts before a task is marked FAILED.
3138
- *
3139
- * Spent only on a failure {@link isRetryableOpenRouterError} classifies as transient; a deterministic
3140
- * failure reaches `FAILED` on its first attempt.
3141
- */ var DEFAULT_OPENROUTER_MAX_ATTEMPTS = 3;
3142
- /**
3143
- * Maximum tasks one retention page may delete.
3144
- *
3145
- * A page's deletes go out as a single Firestore write batch, and a batch takes at most 500 writes.
3146
- */ var OPENROUTER_MAX_EXPIRED_RUN_TASK_DELETE_PAGE_SIZE = 500;
3147
- /**
3148
- * Manages the app-owned run-task queue: the replacement for OpenAI's `background: true` plus its
3149
- * server-side job store, neither of which OpenRouter has.
3150
- */ var OpenRouterRunTaskService = function OpenRouterRunTaskService() {
3151
- _class_call_check(this, OpenRouterRunTaskService);
3152
- };
3153
- /**
3154
- * Creates an {@link OpenRouterRunTaskService}.
3155
- *
3156
- * @param config - The collections, prompt service, client, and execution settings.
3157
- * @returns The service.
3158
- */ function openRouterRunTaskService(config) {
3159
- var collections = config.collections, promptService = config.promptService, client = config.client, storageContext = config.storageContext, envService = config.envService, fileAttachmentMode = config.fileAttachmentMode, maxInlineFileSizeBytes = config.maxInlineFileSizeBytes, tools = config.tools, onTerminalState = config.onTerminalState, signedUrlTtl = config.signedUrlTtl, inputMaxAttempts = config.maxAttempts, inputLeaseDuration = config.leaseDuration;
3160
- var openRouterRunTaskCollection = collections.openRouterRunTaskCollection;
3161
- var attachFilesForAttempt = openRouterFileAttachmentResolver({
3162
- storageContext: storageContext,
3163
- envService: envService,
3164
- mode: fileAttachmentMode,
3165
- signedUrlTtl: signedUrlTtl,
3166
- maxInlineFileSizeBytes: maxInlineFileSizeBytes
3167
- });
3168
- var maxAttempts = inputMaxAttempts !== null && inputMaxAttempts !== void 0 ? inputMaxAttempts : DEFAULT_OPENROUTER_MAX_ATTEMPTS;
3169
- var defaultLeaseDuration = inputLeaseDuration !== null && inputLeaseDuration !== void 0 ? inputLeaseDuration : DEFAULT_OPENROUTER_LEASE_DURATION;
3170
- function runTaskDocument(key) {
3171
- return openRouterRunTaskCollection.documentAccessor().loadDocumentForId(key);
3172
- }
3173
- function readRunTask(key) {
3174
- return _async_to_generator$1(function() {
3175
- return _ts_generator$1(this, function(_state) {
3176
- return [
3177
- 2,
3178
- runTaskDocument(key).snapshotData()
3179
- ];
3180
- });
3181
- })();
3182
- }
3183
- function enqueueRunTask(params) {
3184
- return _async_to_generator$1(function() {
3185
- var key, promptKey, version, input, files, configOverrides, continueFrom, restart, document, existing, created, task, resolved, history, _tmp;
3186
- return _ts_generator$1(this, function(_state) {
3187
- switch(_state.label){
3188
- case 0:
3189
- key = params.key, promptKey = params.promptKey, version = params.version, input = params.input, files = params.files, configOverrides = params.configOverrides, continueFrom = params.continueFrom, restart = params.restart;
3190
- document = runTaskDocument(key);
3191
- return [
3192
- 4,
3193
- document.snapshotData()
3194
- ];
3195
- case 1:
3196
- existing = _state.sent();
3197
- if (!(existing != null && !restart)) return [
3198
- 3,
3199
- 2
3200
- ];
3201
- created = false;
3202
- task = existing;
3203
- return [
3204
- 3,
3205
- 8
3206
- ];
3207
- case 2:
3208
- return [
3209
- 4,
3210
- promptService.resolvePrompt({
3211
- promptKey: promptKey,
3212
- version: version
3213
- })
3214
- ];
3215
- case 3:
3216
- resolved = _state.sent();
3217
- if (!(continueFrom == null)) return [
3218
- 3,
3219
- 4
3220
- ];
3221
- _tmp = undefined;
3222
- return [
3223
- 3,
3224
- 6
3225
- ];
3226
- case 4:
3227
- return [
3228
- 4,
3229
- historyForRunTask(continueFrom)
3230
- ];
3231
- case 5:
3232
- _tmp = _state.sent();
3233
- _state.label = 6;
3234
- case 6:
3235
- history = _tmp;
3236
- task = {
3237
- s: firebase.OpenRouterRunTaskState.QUEUED,
3238
- // Write-once from here on: the retention ceiling and the claim order both read it as the task's age.
3239
- qat: new Date(),
3240
- at: 0,
3241
- pk: promptKey,
3242
- pv: resolved.version,
3243
- in: openrouter.openRouterInputMessages(input),
3244
- fp: files,
3245
- co: configOverrides,
3246
- msg: history
3247
- };
3248
- created = true;
3249
- return [
3250
- 4,
3251
- document.accessor.set(task)
3252
- ];
3253
- case 7:
3254
- _state.sent();
3255
- _state.label = 8;
3256
- case 8:
3257
- return [
3258
- 2,
3259
- {
3260
- key: key,
3261
- document: document,
3262
- created: created,
3263
- task: task
3264
- }
3265
- ];
3266
- }
3267
- });
3268
- })();
3269
- }
3270
- function historyForRunTask(key) {
3271
- return _async_to_generator$1(function() {
3272
- var prior, result, _prior_in, messages;
3273
- return _ts_generator$1(this, function(_state) {
3274
- switch(_state.label){
3275
- case 0:
3276
- return [
3277
- 4,
3278
- readRunTask(key)
3279
- ];
3280
- case 1:
3281
- prior = _state.sent();
3282
- if (prior != null) {
3283
- // Prefer the recorded conversation history; a single-shot prior run has none, in which case its
3284
- // input plus its output text is the history.
3285
- if (prior.msg != null && prior.msg.length > 0) {
3286
- result = prior.msg;
3287
- } else {
3288
- messages = _to_consumable_array((_prior_in = prior.in) !== null && _prior_in !== void 0 ? _prior_in : []);
3289
- if (prior.o) {
3290
- messages.push({
3291
- role: 'assistant',
3292
- content: prior.o
3293
- });
3294
- }
3295
- result = messages.length > 0 ? messages : undefined;
3296
- }
3297
- }
3298
- return [
3299
- 2,
3300
- result
3301
- ];
3302
- }
3303
- });
3304
- })();
3305
- }
3306
- function claimNextRunTasks(params) {
3307
- return _async_to_generator$1(function() {
3308
- var pageLimit, leaseOwner, leaseDuration, now, leaseCutoff, _ref, runnable, reclaimable, candidates, claimed;
3309
- return _ts_generator$1(this, function(_state) {
3310
- switch(_state.label){
3311
- case 0:
3312
- pageLimit = params.limit, leaseOwner = params.leaseOwner, leaseDuration = params.leaseDuration;
3313
- now = new Date();
3314
- leaseCutoff = util.addMilliseconds(now, -(leaseDuration !== null && leaseDuration !== void 0 ? leaseDuration : defaultLeaseDuration));
3315
- return [
3316
- 4,
3317
- Promise.all([
3318
- openRouterRunTaskCollection.queryDocument(firebase.openRouterRunTasksRunnableQuery({
3319
- limit: pageLimit
3320
- })).getDocs(),
3321
- openRouterRunTaskCollection.queryDocument(firebase.openRouterRunTasksReclaimableQuery({
3322
- limit: pageLimit,
3323
- leaseCutoff: leaseCutoff
3324
- })).getDocs()
3325
- ])
3326
- ];
3327
- case 1:
3328
- _ref = _sliced_to_array.apply(void 0, [
3329
- _state.sent(),
3330
- 2
3331
- ]), runnable = _ref[0], reclaimable = _ref[1];
3332
- // A task can appear in both pages, so the merged list is de-duplicated by id. First occurrence wins,
3333
- // which keeps the runnable page's queue order ahead of the reclaimable page's lease order.
3334
- candidates = util.filterUniqueValues(util.mergeArrays([
3335
- runnable,
3336
- reclaimable
3337
- ]), function(x) {
3338
- return x.id;
3339
- }).slice(0, pageLimit);
3340
- return [
3341
- 4,
3342
- Promise.all(candidates.map(function(document) {
3343
- return claimRunTask(document, leaseOwner, now, leaseCutoff);
3344
- }))
3345
- ];
3346
- case 2:
3347
- claimed = _state.sent();
3348
- return [
3349
- 2,
3350
- util.filterMaybeArrayValues(claimed)
3351
- ];
3352
- }
3353
- });
3354
- })();
3355
- }
3356
- function deleteExpiredRunTasks(params) {
3357
- return _async_to_generator$1(function() {
3358
- var inputLimit, before, pageLimit, cutoff, documents, keys, writeBatch, writeBatchAccessor;
3359
- return _ts_generator$1(this, function(_state) {
3360
- switch(_state.label){
3361
- case 0:
3362
- inputLimit = params.limit, before = params.before;
3363
- pageLimit = Math.min(inputLimit, OPENROUTER_MAX_EXPIRED_RUN_TASK_DELETE_PAGE_SIZE);
3364
- cutoff = before !== null && before !== void 0 ? before : util.addMilliseconds(new Date(), -firebase.OPENROUTER_RUN_TASK_MAX_AGE);
3365
- return [
3366
- 4,
3367
- openRouterRunTaskCollection.queryDocument(firebase.openRouterRunTasksExpiredQuery({
3368
- before: cutoff,
3369
- limit: pageLimit
3370
- })).getDocs()
3371
- ];
3372
- case 1:
3373
- documents = _state.sent();
3374
- keys = documents.map(function(x) {
3375
- return x.id;
3376
- });
3377
- if (!(documents.length > 0)) return [
3378
- 3,
3379
- 4
3380
- ];
3381
- // One write batch per page rather than N loose deletes: a page either goes away or it does not, and
3382
- // one round trip replaces up to 500.
3383
- writeBatch = openRouterRunTaskCollection.firestoreContext.batch();
3384
- writeBatchAccessor = openRouterRunTaskCollection.documentAccessorForWriteBatch(writeBatch);
3385
- return [
3386
- 4,
3387
- Promise.all(documents.map(function(document) {
3388
- return writeBatchAccessor.loadDocumentFrom(document).accessor.delete();
3389
- }))
3390
- ];
3391
- case 2:
3392
- _state.sent();
3393
- return [
3394
- 4,
3395
- writeBatch.commit()
3396
- ];
3397
- case 3:
3398
- _state.sent();
3399
- _state.label = 4;
3400
- case 4:
3401
- return [
3402
- 2,
3403
- {
3404
- deleted: keys.length,
3405
- keys: keys
3406
- }
3407
- ];
3408
- }
3409
- });
3410
- })();
3411
- }
3412
- function claimRunTask(document, leaseOwner, now, leaseCutoff) {
3413
- return _async_to_generator$1(function() {
3414
- return _ts_generator$1(this, function(_state) {
3415
- return [
3416
- 2,
3417
- openRouterRunTaskCollection.firestoreContext.runTransaction(function(transaction) {
3418
- return _async_to_generator$1(function() {
3419
- var transactionDocument, task, result;
3420
- return _ts_generator$1(this, function(_state) {
3421
- switch(_state.label){
3422
- case 0:
3423
- transactionDocument = runTaskDocumentInTransaction(document, transaction);
3424
- return [
3425
- 4,
3426
- transactionDocument.snapshotData()
3427
- ];
3428
- case 1:
3429
- task = _state.sent();
3430
- if (!(task != null && isOpenRouterRunTaskClaimable(task, leaseCutoff))) return [
3431
- 3,
3432
- 3
3433
- ];
3434
- return [
3435
- 4,
3436
- transactionDocument.update({
3437
- s: firebase.OpenRouterRunTaskState.RUNNING,
3438
- sat: now,
3439
- lat: now,
3440
- lo: leaseOwner,
3441
- at: task.at + 1
3442
- })
3443
- ];
3444
- case 2:
3445
- _state.sent();
3446
- result = document;
3447
- _state.label = 3;
3448
- case 3:
3449
- return [
3450
- 2,
3451
- result
3452
- ];
3453
- }
3454
- });
3455
- })();
3456
- })
3457
- ];
3458
- });
3459
- })();
3460
- }
3461
- function runTaskDocumentInTransaction(document, transaction) {
3462
- return openRouterRunTaskCollection.documentAccessorForTransaction(transaction).loadDocumentFrom(document);
3463
- }
3464
- function executeRunTask(document) {
3465
- return _async_to_generator$1(function() {
3466
- var key, task, executionResult, e;
3467
- return _ts_generator$1(this, function(_state) {
3468
- switch(_state.label){
3469
- case 0:
3470
- key = document.id;
3471
- return [
3472
- 4,
3473
- document.snapshotData()
3474
- ];
3475
- case 1:
3476
- task = _state.sent();
3477
- if (!(task == null)) return [
3478
- 3,
3479
- 2
3480
- ];
3481
- executionResult = {
3482
- key: key,
3483
- state: firebase.OpenRouterRunTaskState.FAILED,
3484
- error: new Error('The run task no longer exists.')
3485
- };
3486
- return [
3487
- 3,
3488
- 6
3489
- ];
3490
- case 2:
3491
- _state.trys.push([
3492
- 2,
3493
- 4,
3494
- ,
3495
- 6
3496
- ]);
3497
- return [
3498
- 4,
3499
- executeRunTaskData(document, task)
3500
- ];
3501
- case 3:
3502
- executionResult = _state.sent();
3503
- return [
3504
- 3,
3505
- 6
3506
- ];
3507
- case 4:
3508
- e = _state.sent();
3509
- return [
3510
- 4,
3511
- document.accessor.exists()
3512
- ];
3513
- case 5:
3514
- // A task deleted mid-flight by the retention sweep is the expected cause: every write in
3515
- // executeRunTaskData goes through `document.update()`, which throws NOT_FOUND on a deleted document —
3516
- // including the write recordFailure() makes while handling the first throw, which is outside any try
3517
- // and would otherwise reject the whole sweep and discard every result already collected.
3518
- //
3519
- // The existence re-read is what keeps this from swallowing real defects: anything thrown while the
3520
- // document is still there is rethrown untouched.
3521
- if (_state.sent()) {
3522
- throw e;
3523
- }
3524
- executionResult = {
3525
- key: key,
3526
- state: firebase.OpenRouterRunTaskState.FAILED,
3527
- error: e
3528
- };
3529
- return [
3530
- 3,
3531
- 6
3532
- ];
3533
- case 6:
3534
- if (!(onTerminalState != null && firebase.isOpenRouterRunTaskStateTerminal(executionResult.state))) return [
3535
- 3,
3536
- 8
3537
- ];
3538
- return [
3539
- 4,
3540
- onTerminalState(document, executionResult)
3541
- ];
3542
- case 7:
3543
- _state.sent();
3544
- _state.label = 8;
3545
- case 8:
3546
- return [
3547
- 2,
3548
- executionResult
3549
- ];
3550
- }
3551
- });
3552
- })();
3553
- }
3554
- function executeRunTaskData(document, task) {
3555
- return _async_to_generator$1(function() {
3556
- var key, executionResult, resolved, attachedFiles, hasTools, request, result, afterCall, _tmp, pausedForTools, finishedAt, e, failure;
3557
- return _ts_generator$1(this, function(_state) {
3558
- switch(_state.label){
3559
- case 0:
3560
- key = document.id;
3561
- _state.label = 1;
3562
- case 1:
3563
- _state.trys.push([
3564
- 1,
3565
- 16,
3566
- ,
3567
- 18
3568
- ]);
3569
- return [
3570
- 4,
3571
- promptService.resolvePrompt({
3572
- promptKey: task.pk,
3573
- version: task.pv
3574
- })
3575
- ];
3576
- case 2:
3577
- resolved = _state.sent();
3578
- return [
3579
- 4,
3580
- attachFilesForAttempt(task.fp)
3581
- ];
3582
- case 3:
3583
- attachedFiles = _state.sent();
3584
- hasTools = tools != null && tools.length > 0;
3585
- request = openrouter.openRouterPromptRequest({
3586
- prompt: resolved,
3587
- input: task.in,
3588
- overrides: task.co,
3589
- files: attachedFiles,
3590
- fileAnnotations: task.fa,
3591
- // With tools in play the conversation lives in the state accessor, which appends to it across
3592
- // turns; passing it here as well would send every prior turn twice.
3593
- history: hasTools ? undefined : task.msg,
3594
- trace: {
3595
- runTaskKey: key
3596
- }
3597
- });
3598
- if (!hasTools) return [
3599
- 3,
3600
- 5
3601
- ];
3602
- return [
3603
- 4,
3604
- appendDeferredToolResultsToConversation(document, task)
3605
- ];
3606
- case 4:
3607
- _state.sent();
3608
- _state.label = 5;
3609
- case 5:
3610
- return [
3611
- 4,
3612
- openrouter.callModelForOpenRouterRequest({
3613
- client: client,
3614
- // The whole conversation is supplied through the state accessor, so the request carries no input
3615
- // of its own — the SDK appends `input` to the loaded state, and the seeded state already is it.
3616
- request: hasTools ? _object_spread_props(_object_spread({}, request), {
3617
- input: []
3618
- }) : request,
3619
- tools: tools !== null && tools !== void 0 ? tools : undefined,
3620
- // The state accessor is only wired when tools are in play. For a single-shot run it would write
3621
- // conversation history nobody reads, and on a doc whose state the runner is about to set anyway.
3622
- state: hasTools ? firestoreOpenRouterStateAccessor(document, {
3623
- initialMessages: request.input,
3624
- attachedFiles: attachedFiles
3625
- }) : undefined
3626
- })
3627
- ];
3628
- case 6:
3629
- result = _state.sent();
3630
- if (!hasTools) return [
3631
- 3,
3632
- 8
3633
- ];
3634
- return [
3635
- 4,
3636
- document.snapshotData()
3637
- ];
3638
- case 7:
3639
- _tmp = _state.sent();
3640
- return [
3641
- 3,
3642
- 9
3643
- ];
3644
- case 8:
3645
- _tmp = task;
3646
- _state.label = 9;
3647
- case 9:
3648
- afterCall = _tmp;
3649
- pausedForTools = (afterCall === null || afterCall === void 0 ? void 0 : afterCall.s) === firebase.OpenRouterRunTaskState.AWAITING_ASYNC_TOOLS;
3650
- finishedAt = new Date();
3651
- if (!pausedForTools) return [
3652
- 3,
3653
- 11
3654
- ];
3655
- return [
3656
- 4,
3657
- document.update({
3658
- lat: null,
3659
- lo: null
3660
- })
3661
- ];
3662
- case 10:
3663
- _state.sent();
3664
- executionResult = {
3665
- key: key,
3666
- state: firebase.OpenRouterRunTaskState.AWAITING_ASYNC_TOOLS,
3667
- result: result
3668
- };
3669
- return [
3670
- 3,
3671
- 15
3672
- ];
3673
- case 11:
3674
- if (!(result.error == null)) return [
3675
- 3,
3676
- 13
3677
- ];
3678
- return [
3679
- 4,
3680
- document.update({
3681
- s: firebase.OpenRouterRunTaskState.COMPLETE,
3682
- fat: finishedAt,
3683
- o: result.outputText,
3684
- j: result.outputJson,
3685
- // Appended rather than replaced: a retried task produced real generations on its earlier attempts
3686
- // too, and those are exactly what an audit of a flaky run needs.
3687
- gi: util.concatArraysUnique(task.gi, result.generationIds),
3688
- u: result.usage,
3689
- e: null,
3690
- lat: null,
3691
- lo: null
3692
- })
3693
- ];
3694
- case 12:
3695
- _state.sent();
3696
- executionResult = {
3697
- key: key,
3698
- state: firebase.OpenRouterRunTaskState.COMPLETE,
3699
- result: result
3700
- };
3701
- return [
3702
- 3,
3703
- 15
3704
- ];
3705
- case 13:
3706
- return [
3707
- 4,
3708
- recordFailure({
3709
- document: document,
3710
- task: task,
3711
- error: result.error,
3712
- cause: result.error,
3713
- at: finishedAt,
3714
- result: result
3715
- })
3716
- ];
3717
- case 14:
3718
- executionResult = _state.sent();
3719
- _state.label = 15;
3720
- case 15:
3721
- return [
3722
- 3,
3723
- 18
3724
- ];
3725
- case 16:
3726
- e = _state.sent();
3727
- return [
3728
- 4,
3729
- recordFailure({
3730
- document: document,
3731
- task: task,
3732
- error: {
3733
- code: openRouterErrorCode(e),
3734
- message: openRouterErrorMessage(e)
3735
- },
3736
- cause: e,
3737
- at: new Date()
3738
- })
3739
- ];
3740
- case 17:
3741
- failure = _state.sent();
3742
- executionResult = _object_spread_props(_object_spread({}, failure), {
3743
- error: e
3744
- });
3745
- return [
3746
- 3,
3747
- 18
3748
- ];
3749
- case 18:
3750
- return [
3751
- 2,
3752
- executionResult
3753
- ];
3754
- }
3755
- });
3756
- })();
3757
- }
3758
- /**
3759
- * Folds resolved deferred-tool results into the persisted conversation, so the resumed call sends the
3760
- * model the answers it was waiting on.
3761
- *
3762
- * Done here rather than through the SDK because `@openrouter/sdk@1.2.x` has no route back in for a
3763
- * result produced by another process: its only resume path re-runs the tool locally (a manual tool has
3764
- * no `execute`) or rejects it. Appending the `function_call_output` items to the conversation and
3765
- * re-sending it is the same thing the SDK would have put on the wire, minus the API it does not have.
3766
- *
3767
- * A no-op unless every pending call has a recorded result — a partially-resolved run has nothing new
3768
- * to say and must stay parked.
3769
- */ function appendDeferredToolResultsToConversation(document, task) {
3770
- return _async_to_generator$1(function() {
3771
- var _task_ptc, _task_utr, pending, unsent, allResolved, _task_msg, outputItems;
3772
- return _ts_generator$1(this, function(_state) {
3773
- switch(_state.label){
3774
- case 0:
3775
- pending = (_task_ptc = task.ptc) !== null && _task_ptc !== void 0 ? _task_ptc : [];
3776
- unsent = (_task_utr = task.utr) !== null && _task_utr !== void 0 ? _task_utr : [];
3777
- // The length guard means "and there is something to send" — an empty `ptc` satisfies the predicate
3778
- // vacuously, and appending nothing would clear `ptc` / `utr` for no reason.
3779
- allResolved = pending.length > 0 && !hasUnresolvedOpenRouterPendingToolCalls(pending, unsent);
3780
- if (!allResolved) return [
3781
- 3,
3782
- 2
3783
- ];
3784
- outputItems = openrouter.openRouterFunctionCallOutputItems(unsent);
3785
- return [
3786
- 4,
3787
- document.update({
3788
- msg: _to_consumable_array((_task_msg = task.msg) !== null && _task_msg !== void 0 ? _task_msg : []).concat(_to_consumable_array(outputItems)),
3789
- ptc: null,
3790
- utr: null
3791
- })
3792
- ];
3793
- case 1:
3794
- _state.sent();
3795
- _state.label = 2;
3796
- case 2:
3797
- return [
3798
- 2
3799
- ];
3800
- }
3801
- });
3802
- })();
3803
- }
3804
- function recordFailure(params) {
3805
- return _async_to_generator$1(function() {
3806
- var document, task, error, cause, at, result, retryable, attemptsExhausted, finished, state;
3807
- return _ts_generator$1(this, function(_state) {
3808
- switch(_state.label){
3809
- case 0:
3810
- document = params.document, task = params.task, error = params.error, cause = params.cause, at = params.at, result = params.result;
3811
- // A deterministic failure — a bad key, a 402, a model id that does not exist — cannot succeed on a
3812
- // second attempt, so it spends none of the budget and goes straight to FAILED.
3813
- retryable = isRetryableOpenRouterError(cause);
3814
- // The attempt counter was already incremented by the claim, so `task.at` is the number of attempts made
3815
- // INCLUDING this one — which is why nothing is added to it here. Adding one would spend the budget a
3816
- // tick early and mark a task FAILED with a retry still owed to it.
3817
- attemptsExhausted = task.at >= maxAttempts;
3818
- finished = !retryable || attemptsExhausted;
3819
- state = finished ? firebase.OpenRouterRunTaskState.FAILED : firebase.OpenRouterRunTaskState.QUEUED;
3820
- return [
3821
- 4,
3822
- document.update({
3823
- s: state,
3824
- // Releasing the lease is what makes the task claimable again on the next sweep.
3825
- lat: null,
3826
- lo: null,
3827
- fat: finished ? at : null,
3828
- e: error,
3829
- gi: result == null ? undefined : util.concatArraysUnique(task.gi, result.generationIds),
3830
- u: result === null || result === void 0 ? void 0 : result.usage
3831
- })
3832
- ];
3833
- case 1:
3834
- _state.sent();
3835
- return [
3836
- 2,
3837
- {
3838
- key: document.id,
3839
- state: state,
3840
- result: result
3841
- }
3842
- ];
3843
- }
3844
- });
3845
- })();
3846
- }
3847
- function resolveDeferredTool(params) {
3848
- return _async_to_generator$1(function() {
3849
- var key, taskId, output, error;
3850
- return _ts_generator$1(this, function(_state) {
3851
- key = params.key, taskId = params.taskId, output = params.output, error = params.error;
3852
- return [
3853
- 2,
3854
- openRouterRunTaskCollection.firestoreContext.runTransaction(function(transaction) {
3855
- return _async_to_generator$1(function() {
3856
- var document, task, result, _task_ptc, _task_utr, pending, call, alreadySettled, _task_utr1, unsent, ready;
3857
- return _ts_generator$1(this, function(_state) {
3858
- switch(_state.label){
3859
- case 0:
3860
- document = openRouterRunTaskCollection.documentAccessorForTransaction(transaction).loadDocumentForId(key);
3861
- return [
3862
- 4,
3863
- document.snapshotData()
3864
- ];
3865
- case 1:
3866
- task = _state.sent();
3867
- result = {
3868
- resolved: false,
3869
- ready: false
3870
- };
3871
- if (!(task != null)) return [
3872
- 3,
3873
- 3
3874
- ];
3875
- pending = (_task_ptc = task.ptc) !== null && _task_ptc !== void 0 ? _task_ptc : [];
3876
- call = pending.find(function(x) {
3877
- return x.taskId === taskId;
3878
- });
3879
- alreadySettled = ((_task_utr = task.utr) !== null && _task_utr !== void 0 ? _task_utr : []).some(function(x) {
3880
- return x.callId === (call === null || call === void 0 ? void 0 : call.callId);
3881
- });
3882
- if (!(call != null && !alreadySettled)) return [
3883
- 3,
3884
- 3
3885
- ];
3886
- // Preserves today's semantics exactly: an `output` of `null` is a real result and is kept, while an
3887
- // absent `error` is dropped rather than written as `undefined`, which Firestore rejects outright.
3888
- unsent = _to_consumable_array((_task_utr1 = task.utr) !== null && _task_utr1 !== void 0 ? _task_utr1 : []).concat([
3889
- util.filterUndefinedValues({
3890
- callId: call.callId,
3891
- name: call.name,
3892
- output: output,
3893
- error: error !== null && error !== void 0 ? error : undefined
3894
- })
3895
- ]);
3896
- ready = !hasUnresolvedOpenRouterPendingToolCalls(pending, unsent);
3897
- // `qat` is deliberately NOT moved. It is the task's age for retention, so a task cycling through
3898
- // tool resolutions would otherwise keep pushing its own age forward and never age out — and keeping
3899
- // the original also orders correctly: a run waiting on a tool since yesterday should be claimed
3900
- // ahead of one queued a minute ago.
3901
- return [
3902
- 4,
3903
- document.update(_object_spread({
3904
- utr: unsent
3905
- }, ready ? {
3906
- s: firebase.OpenRouterRunTaskState.QUEUED
3907
- } : undefined))
3908
- ];
3909
- case 2:
3910
- _state.sent();
3911
- result = {
3912
- resolved: true,
3913
- ready: ready
3914
- };
3915
- _state.label = 3;
3916
- case 3:
3917
- return [
3918
- 2,
3919
- result
3920
- ];
3921
- }
3922
- });
3923
- })();
3924
- })
3925
- ];
3926
- });
3927
- })();
3928
- }
3929
- return {
3930
- enqueueRunTask: enqueueRunTask,
3931
- readRunTask: readRunTask,
3932
- runTaskDocument: runTaskDocument,
3933
- claimNextRunTasks: claimNextRunTasks,
3934
- executeRunTask: executeRunTask,
3935
- resolveDeferredTool: resolveDeferredTool,
3936
- deleteExpiredRunTasks: deleteExpiredRunTasks,
3937
- attachFilesForAttempt: attachFilesForAttempt
3938
- };
3939
- }
3940
- /**
3941
- * Whether a task may be claimed by a sweep running at the given lease cutoff.
3942
- *
3943
- * A `RUNNING` task is claimable exactly when its lease has gone stale — that is crash recovery, and it
3944
- * generalises the ad-hoc "unstick anything processing for over an hour" logic it replaces.
3945
- *
3946
- * @param task - The task to check.
3947
- * @param leaseCutoff - Leases taken at or before this date are stale.
3948
- * @returns True when the task may be claimed.
3949
- *
3950
- * @__NO_SIDE_EFFECTS__
3951
- */ function isOpenRouterRunTaskClaimable(task, leaseCutoff) {
3952
- var result;
3953
- switch(task.s){
3954
- case firebase.OpenRouterRunTaskState.QUEUED:
3955
- result = true;
3956
- break;
3957
- case firebase.OpenRouterRunTaskState.RUNNING:
3958
- result = task.lat == null || task.lat.getTime() <= leaseCutoff.getTime();
3959
- break;
3960
- case firebase.OpenRouterRunTaskState.AWAITING_ASYNC_TOOLS:
3961
- // Only once every pending call has a recorded result; otherwise there is nothing new to send.
3962
- //
3963
- // Vacuously true for an EMPTY `ptc`, deliberately. Such a task gets claimed, no-ops the append, and can
3964
- // still complete — whereas refusing to claim it would strand it permanently with nothing able to move it.
3965
- result = !hasUnresolvedOpenRouterPendingToolCalls(task.ptc, task.utr);
3966
- break;
3967
- default:
3968
- result = false;
3969
- break;
3970
- }
3971
- return result;
3972
- }
3973
- /**
3974
- * Whether any pending deferred tool call is still missing its recorded result.
3975
- *
3976
- * The one predicate behind "is this run ready to resume": the claim check, the resolution's `ready` flag,
3977
- * and the conversation append all ask it, and three hand-written copies had already drifted apart.
3978
- *
3979
- * @param pending - The pending deferred tool calls.
3980
- * @param unsent - The recorded-but-unsent tool results.
3981
- * @returns True when at least one pending call has no recorded result.
3982
- *
3983
- * @__NO_SIDE_EFFECTS__
3984
- */ function hasUnresolvedOpenRouterPendingToolCalls(pending, unsent) {
3985
- return (pending !== null && pending !== void 0 ? pending : []).some(function(call) {
3986
- return !(unsent !== null && unsent !== void 0 ? unsent : []).some(function(result) {
3987
- return result.callId === call.callId;
3988
- });
3989
- });
3990
- }
3991
- /**
3992
- * Extracts an error code from a thrown value.
3993
- *
3994
- * @param e - The thrown value.
3995
- * @returns The code, when one is discernible.
3996
- *
3997
- * @__NO_SIDE_EFFECTS__
3998
- */ function openRouterErrorCode(e) {
3999
- var result;
4000
- if (e != null && (typeof e === "undefined" ? "undefined" : _type_of(e)) === 'object') {
4001
- var _e_code;
4002
- var candidate = (_e_code = e.code) !== null && _e_code !== void 0 ? _e_code : e.name;
4003
- if (candidate != null) {
4004
- result = String(candidate);
4005
- }
4006
- }
4007
- return result;
4008
- }
4009
- /**
4010
- * Extracts an error message from a thrown value.
4011
- *
4012
- * @param e - The thrown value.
4013
- * @returns The message.
4014
- *
4015
- * @__NO_SIDE_EFFECTS__
4016
- */ function openRouterErrorMessage(e) {
4017
- return _instanceof(e, Error) ? e.message : String(e);
4018
- }
4019
- /**
4020
- * HTTP statuses a retry cannot fix.
4021
- *
4022
- * 400 is a malformed request (an invalid model id, a JSON schema the provider rejects), 401/403 are a
4023
- * credential problem, 402 is an empty account, and 404 is a route or resource that does not exist. Each of
4024
- * them answers identically on every attempt, so spending the budget on them only delays the FAILED that
4025
- * the owning work is waiting for.
4026
- */ var OPENROUTER_PERMANENT_ERROR_STATUSES = [
4027
- 400,
4028
- 401,
4029
- 402,
4030
- 403,
4031
- 404
4032
- ];
4033
- /**
4034
- * Whether a failure is worth another attempt.
4035
- *
4036
- * What this encodes is a whitelist of the KNOWN-PERMANENT, not a whitelist of the retryable: anything
4037
- * unrecognized defaults to RETRYABLE. An unknown failure is far more likely to be a transient upstream blip
4038
- * than a permanent one, and the attempt budget bounds the cost of being wrong either way — whereas
4039
- * defaulting the other way would turn one bad minute at a provider into a definitively failed run.
4040
- *
4041
- * So the retryable side needs no list of its own. 408 / 409 / 429 and every 5xx, socket-level failures
4042
- * (`ECONNRESET`, `ETIMEDOUT`, `ECONNREFUSED`, `EAI_AGAIN`), and the Google-infrastructure transients
4043
- * (`UNAVAILABLE`, `DEADLINE_EXCEEDED`, `ABORTED`) a Firestore or GCS call raises mid-run all reach the
4044
- * default and are retried.
4045
- *
4046
- * Permanent is two cases. {@link OPENROUTER_PERMANENT_ERROR_STATUSES}, read off `status` / `statusCode` /
4047
- * `code` — which covers both routes into `recordFailure`: a thrown SDK/HTTP error, and the numeric
4048
- * `error.code` OpenRouter reports in a response body without throwing at all. And an
4049
- * {@link OpenRouterPromptResolutionError}, which is deterministic by construction: the prompt either exists
4050
- * at that version or it never will, so re-resolving it is guaranteed to fail identically.
4051
- *
4052
- * @param e - The thrown value, or the error reported on a response.
4053
- * @returns True when another attempt could plausibly succeed.
4054
- *
4055
- * @__NO_SIDE_EFFECTS__
4056
- */ function isRetryableOpenRouterError(e) {
4057
- var status = openRouterErrorStatus(e);
4058
- return !_instanceof(e, OpenRouterPromptResolutionError) && (status == null || !OPENROUTER_PERMANENT_ERROR_STATUSES.includes(status));
4059
- }
4060
- /**
4061
- * Extracts an HTTP status from a thrown value or a reported response error.
4062
- *
4063
- * `code` is read as a status too, because OpenRouter reports a NUMERIC code in a response body's `error`
4064
- * object where an SDK error would carry `status`.
4065
- *
4066
- * @param e - The thrown value.
4067
- * @returns The status, when the value carries a numeric one.
4068
- *
4069
- * @__NO_SIDE_EFFECTS__
4070
- */ function openRouterErrorStatus(e) {
4071
- var result;
4072
- if (e != null && (typeof e === "undefined" ? "undefined" : _type_of(e)) === 'object') {
4073
- var _ref, _e_status;
4074
- var candidate = (_ref = (_e_status = e.status) !== null && _e_status !== void 0 ? _e_status : e.statusCode) !== null && _ref !== void 0 ? _ref : e.code;
4075
- if (typeof candidate === 'number') {
4076
- result = candidate;
4077
- } else if (typeof candidate === 'string' && /^\d{3}$/.test(candidate)) {
4078
- // A three-digit string is a status OpenRouter reported as text; anything else is a symbolic code
4079
- // (`ECONNRESET`, `server_error`) and is left for the default-retryable path.
4080
- result = Number(candidate);
4081
- }
4082
- }
4083
- return result;
4084
- }
4085
- /**
4086
- * The deferred-tool resolutions recorded on a task, in the form the core package's resolver consumes.
4087
- *
4088
- * @param task - The run task.
4089
- * @returns The resolutions.
4090
- *
4091
- * @__NO_SIDE_EFFECTS__
4092
- */ function openRouterDeferredToolResolutionsForRunTask(task) {
4093
- var _task_ptc, _task_utr;
4094
- var pending = (_task_ptc = task.ptc) !== null && _task_ptc !== void 0 ? _task_ptc : [];
4095
- return util.filterMaybeArrayValues(((_task_utr = task.utr) !== null && _task_utr !== void 0 ? _task_utr : []).map(function(unsent) {
4096
- var call = pending.find(function(x) {
4097
- return x.callId === unsent.callId;
4098
- });
4099
- var result;
4100
- if (call != null) {
4101
- result = unsent.error == null ? {
4102
- taskId: call.taskId,
4103
- output: unsent.output
4104
- } : {
4105
- taskId: call.taskId,
4106
- error: unsent.error
4107
- };
4108
- }
4109
- return result;
4110
- }));
4111
- }
4112
-
4113
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
4114
- try {
4115
- var info = gen[key](arg);
4116
- var value = info.value;
4117
- } catch (error) {
4118
- reject(error);
4119
- return;
4120
- }
4121
- if (info.done) {
4122
- resolve(value);
4123
- } else {
4124
- Promise.resolve(value).then(_next, _throw);
4125
- }
4126
- }
4127
- function _async_to_generator(fn) {
4128
- return function() {
4129
- var self = this, args = arguments;
4130
- return new Promise(function(resolve, reject) {
4131
- var gen = fn.apply(self, args);
4132
- function _next(value) {
4133
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
4134
- }
4135
- function _throw(err) {
4136
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
4137
- }
4138
- _next(undefined);
4139
- });
4140
- };
4141
- }
4142
- function _ts_generator(thisArg, body) {
4143
- var f, y, t, _ = {
4144
- label: 0,
4145
- sent: function() {
4146
- if (t[0] & 1) throw t[1];
4147
- return t[1];
4148
- },
4149
- trys: [],
4150
- ops: []
4151
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
4152
- return d(g, "next", {
4153
- value: verb(0)
4154
- }), d(g, "throw", {
4155
- value: verb(1)
4156
- }), d(g, "return", {
4157
- value: verb(2)
4158
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
4159
- value: function() {
4160
- return this;
4161
- }
4162
- }), g;
4163
- function verb(n) {
4164
- return function(v) {
4165
- return step([
4166
- n,
4167
- v
4168
- ]);
4169
- };
4170
- }
4171
- function step(op) {
4172
- if (f) throw new TypeError("Generator is already executing.");
4173
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
4174
- 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;
4175
- if (y = 0, t) op = [
4176
- op[0] & 2,
4177
- t.value
4178
- ];
4179
- switch(op[0]){
4180
- case 0:
4181
- case 1:
4182
- t = op;
4183
- break;
4184
- case 4:
4185
- _.label++;
4186
- return {
4187
- value: op[1],
4188
- done: false
4189
- };
4190
- case 5:
4191
- _.label++;
4192
- y = op[1];
4193
- op = [
4194
- 0
4195
- ];
4196
- continue;
4197
- case 7:
4198
- op = _.ops.pop();
4199
- _.trys.pop();
4200
- continue;
4201
- default:
4202
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
4203
- _ = 0;
4204
- continue;
4205
- }
4206
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
4207
- _.label = op[1];
4208
- break;
4209
- }
4210
- if (op[0] === 6 && _.label < t[1]) {
4211
- _.label = t[1];
4212
- t = op;
4213
- break;
4214
- }
4215
- if (t && _.label < t[2]) {
4216
- _.label = t[2];
4217
- _.ops.push(op);
4218
- break;
4219
- }
4220
- if (t[2]) _.ops.pop();
4221
- _.trys.pop();
4222
- continue;
4223
- }
4224
- op = body.call(thisArg, _);
4225
- } catch (e) {
4226
- op = [
4227
- 6,
4228
- e
4229
- ];
4230
- y = 0;
4231
- } finally{
4232
- f = t = 0;
4233
- }
4234
- if (op[0] & 5) throw op[1];
4235
- return {
4236
- value: op[0] ? op[1] : void 0,
4237
- done: true
4238
- };
4239
- }
4240
- }
4241
- /**
4242
- * Default number of tasks executed concurrently by one sweep.
4243
- */ var DEFAULT_OPENROUTER_SWEEP_MAX_PARALLEL_TASKS = 10;
4244
- /**
4245
- * Default wall-clock budget for one sweep.
4246
- */ var DEFAULT_OPENROUTER_SWEEP_MAX_RUN_TIME = util.MS_IN_MINUTE * 4;
4247
- /**
4248
- * Default number of tasks claimed per page.
4249
- */ var DEFAULT_OPENROUTER_SWEEP_PAGE_SIZE = 20;
4250
- /**
4251
- * Default number of expired tasks deleted per retention page.
4252
- *
4253
- * Well under the 500-write batch ceiling: retention runs on its own far slower schedule, so there is
4254
- * nothing to gain from maximising a single page.
4255
- */ var DEFAULT_OPENROUTER_EXPIRATION_SWEEP_PAGE_SIZE = 200;
4256
- /**
4257
- * Default wall-clock budget for one retention sweep.
4258
- */ var DEFAULT_OPENROUTER_EXPIRATION_SWEEP_MAX_RUN_TIME = util.MS_IN_MINUTE * 2;
4259
- var randomSweepId = util.randomNumberFactory({
4260
- min: 0,
4261
- max: 1000000000,
4262
- round: 'floor'
4263
- });
4264
- /**
4265
- * Drains the run-task queue within a strict time budget.
4266
- *
4267
- * Claim a page by lease, run `maxParallelTasks` at a time, write results, repeat — until the queue is
4268
- * empty or the budget is spent. Mount it on a schedule the app already runs; it does not need one of its
4269
- * own, and it must not assume it is the only tenant of the one it gets.
4270
- *
4271
- * @param params - The service and budget settings.
4272
- * @returns What the sweep did.
4273
- */ function openRouterRunTaskSweep(params) {
4274
- return _async_to_generator(function() {
4275
- var service, maxParallelTasks, maxRunTimeMs, pageSize, inputLeaseOwner, leaseDuration, maxPages, startedAt, budget, parallelTasks, limitPerPage, leaseOwner, results, pages, stoppedForTimeBudget, elapsed, claimed, durationMs;
4276
- return _ts_generator(this, function(_state) {
4277
- switch(_state.label){
4278
- case 0:
4279
- service = params.service, maxParallelTasks = params.maxParallelTasks, maxRunTimeMs = params.maxRunTimeMs, pageSize = params.pageSize, inputLeaseOwner = params.leaseOwner, leaseDuration = params.leaseDuration, maxPages = params.maxPages;
4280
- startedAt = Date.now();
4281
- budget = maxRunTimeMs !== null && maxRunTimeMs !== void 0 ? maxRunTimeMs : DEFAULT_OPENROUTER_SWEEP_MAX_RUN_TIME;
4282
- parallelTasks = maxParallelTasks !== null && maxParallelTasks !== void 0 ? maxParallelTasks : DEFAULT_OPENROUTER_SWEEP_MAX_PARALLEL_TASKS;
4283
- limitPerPage = pageSize !== null && pageSize !== void 0 ? pageSize : DEFAULT_OPENROUTER_SWEEP_PAGE_SIZE;
4284
- leaseOwner = inputLeaseOwner !== null && inputLeaseOwner !== void 0 ? inputLeaseOwner : "openRouterRunTaskSweep_".concat(startedAt, "_").concat(randomSweepId());
4285
- results = [];
4286
- pages = 0;
4287
- stoppedForTimeBudget = false;
4288
- elapsed = function elapsed() {
4289
- return Date.now() - startedAt;
4290
- };
4291
- _state.label = 1;
4292
- case 1:
4293
- if (elapsed() >= budget) {
4294
- stoppedForTimeBudget = true;
4295
- return [
4296
- 3,
4297
- 5
4298
- ];
4299
- }
4300
- if (maxPages != null && pages >= maxPages) {
4301
- return [
4302
- 3,
4303
- 5
4304
- ];
4305
- }
4306
- return [
4307
- 4,
4308
- service.claimNextRunTasks({
4309
- limit: limitPerPage,
4310
- leaseOwner: leaseOwner,
4311
- leaseDuration: leaseDuration
4312
- })
4313
- ];
4314
- case 2:
4315
- claimed = _state.sent();
4316
- if (claimed.length === 0) {
4317
- return [
4318
- 3,
4319
- 5
4320
- ];
4321
- }
4322
- pages += 1;
4323
- // Every claimed task IS executed, even if the budget expires mid-page: it already holds a lease and
4324
- // its attempt counter is already spent, so abandoning it would leave a RUNNING document waiting on
4325
- // lease reclamation for no reason.
4326
- return [
4327
- 4,
4328
- util.performTasksInParallel(claimed, {
4329
- maxParallelTasks: parallelTasks,
4330
- taskFactory: function taskFactory(document) {
4331
- return _async_to_generator(function() {
4332
- var result;
4333
- return _ts_generator(this, function(_state) {
4334
- switch(_state.label){
4335
- case 0:
4336
- return [
4337
- 4,
4338
- service.executeRunTask(document)
4339
- ];
4340
- case 1:
4341
- result = _state.sent();
4342
- results.push(result);
4343
- return [
4344
- 2
4345
- ];
4346
- }
4347
- });
4348
- })();
4349
- }
4350
- })
4351
- ];
4352
- case 3:
4353
- _state.sent();
4354
- _state.label = 4;
4355
- case 4:
4356
- return [
4357
- 3,
4358
- 1
4359
- ];
4360
- case 5:
4361
- durationMs = elapsed();
4362
- return [
4363
- 2,
4364
- {
4365
- executed: results.length,
4366
- completed: results.filter(function(x) {
4367
- return x.state === firebase.OpenRouterRunTaskState.COMPLETE;
4368
- }).length,
4369
- failed: results.filter(function(x) {
4370
- return x.state === firebase.OpenRouterRunTaskState.FAILED;
4371
- }).length,
4372
- requeued: results.filter(function(x) {
4373
- return x.state === firebase.OpenRouterRunTaskState.QUEUED;
4374
- }).length,
4375
- awaitingAsyncTools: results.filter(function(x) {
4376
- return x.state === firebase.OpenRouterRunTaskState.AWAITING_ASYNC_TOOLS;
4377
- }).length,
4378
- pages: pages,
4379
- stoppedForTimeBudget: stoppedForTimeBudget,
4380
- durationMs: durationMs,
4381
- results: results
4382
- }
4383
- ];
4384
- }
4385
- });
4386
- })();
4387
- }
4388
- /**
4389
- * Deletes every run task past its retention age, within a strict time budget.
4390
- *
4391
- * A SEPARATE sweep from {@link openRouterRunTaskSweep}, on a far slower schedule: the drain tick runs every
4392
- * minute and there is nothing a week-old document gains from being looked at that often.
4393
- *
4394
- * @param params - The service and budget settings.
4395
- * @returns What the sweep deleted.
4396
- */ function openRouterRunTaskExpirationSweep(params) {
4397
- return _async_to_generator(function() {
4398
- var service, before, pageSize, maxRunTimeMs, maxPages, startedAt, budget, limitPerPage, cutoff, deleted, pages, stoppedForTimeBudget, elapsed, page;
4399
- return _ts_generator(this, function(_state) {
4400
- switch(_state.label){
4401
- case 0:
4402
- service = params.service, before = params.before, pageSize = params.pageSize, maxRunTimeMs = params.maxRunTimeMs, maxPages = params.maxPages;
4403
- startedAt = Date.now();
4404
- budget = maxRunTimeMs !== null && maxRunTimeMs !== void 0 ? maxRunTimeMs : DEFAULT_OPENROUTER_EXPIRATION_SWEEP_MAX_RUN_TIME;
4405
- limitPerPage = pageSize !== null && pageSize !== void 0 ? pageSize : DEFAULT_OPENROUTER_EXPIRATION_SWEEP_PAGE_SIZE;
4406
- // The cutoff is PINNED once for the whole run rather than re-derived per page. A cutoff advancing with the
4407
- // clock would let a task that ages mid-sweep join a page not yet reached, making the pass unbounded.
4408
- cutoff = before !== null && before !== void 0 ? before : new Date(startedAt - firebase.OPENROUTER_RUN_TASK_MAX_AGE);
4409
- deleted = 0;
4410
- pages = 0;
4411
- stoppedForTimeBudget = false;
4412
- elapsed = function elapsed() {
4413
- return Date.now() - startedAt;
4414
- };
4415
- _state.label = 1;
4416
- case 1:
4417
- if (elapsed() >= budget) {
4418
- stoppedForTimeBudget = true;
4419
- return [
4420
- 3,
4421
- 4
4422
- ];
4423
- }
4424
- if (maxPages != null && pages >= maxPages) {
4425
- return [
4426
- 3,
4427
- 4
4428
- ];
4429
- }
4430
- return [
4431
- 4,
4432
- service.deleteExpiredRunTasks({
4433
- limit: limitPerPage,
4434
- before: cutoff
4435
- })
4436
- ];
4437
- case 2:
4438
- page = _state.sent();
4439
- if (page.deleted === 0) {
4440
- return [
4441
- 3,
4442
- 4
4443
- ];
4444
- }
4445
- deleted += page.deleted;
4446
- pages += 1;
4447
- _state.label = 3;
4448
- case 3:
4449
- return [
4450
- 3,
4451
- 1
4452
- ];
4453
- case 4:
4454
- return [
4455
- 2,
4456
- {
4457
- deleted: deleted,
4458
- pages: pages,
4459
- stoppedForTimeBudget: stoppedForTimeBudget,
4460
- durationMs: elapsed()
4461
- }
4462
- ];
4463
- }
4464
- });
4465
- })();
4466
- }
4467
-
4468
- exports.AbstractAppOpenRouterModule = AbstractAppOpenRouterModule;
4469
- exports.DEFAULT_OPENROUTER_EXPIRATION_SWEEP_MAX_RUN_TIME = DEFAULT_OPENROUTER_EXPIRATION_SWEEP_MAX_RUN_TIME;
4470
- exports.DEFAULT_OPENROUTER_EXPIRATION_SWEEP_PAGE_SIZE = DEFAULT_OPENROUTER_EXPIRATION_SWEEP_PAGE_SIZE;
4471
- exports.DEFAULT_OPENROUTER_INLINE_FILE_CONTENT_TYPE = DEFAULT_OPENROUTER_INLINE_FILE_CONTENT_TYPE;
4472
- exports.DEFAULT_OPENROUTER_LEASE_DURATION = DEFAULT_OPENROUTER_LEASE_DURATION;
4473
- exports.DEFAULT_OPENROUTER_MAX_ATTEMPTS = DEFAULT_OPENROUTER_MAX_ATTEMPTS;
4474
- exports.DEFAULT_OPENROUTER_MAX_INLINE_FILE_SIZE_BYTES = DEFAULT_OPENROUTER_MAX_INLINE_FILE_SIZE_BYTES;
4475
- exports.DEFAULT_OPENROUTER_SIGNED_URL_TTL = DEFAULT_OPENROUTER_SIGNED_URL_TTL;
4476
- exports.DEFAULT_OPENROUTER_SWEEP_MAX_PARALLEL_TASKS = DEFAULT_OPENROUTER_SWEEP_MAX_PARALLEL_TASKS;
4477
- exports.DEFAULT_OPENROUTER_SWEEP_MAX_RUN_TIME = DEFAULT_OPENROUTER_SWEEP_MAX_RUN_TIME;
4478
- exports.DEFAULT_OPENROUTER_SWEEP_PAGE_SIZE = DEFAULT_OPENROUTER_SWEEP_PAGE_SIZE;
4479
- exports.OPENROUTER_BROADCAST_RUN_TASK_KEY_ATTRIBUTES = OPENROUTER_BROADCAST_RUN_TASK_KEY_ATTRIBUTES;
4480
- exports.OPENROUTER_MAX_EXPIRED_RUN_TASK_DELETE_PAGE_SIZE = OPENROUTER_MAX_EXPIRED_RUN_TASK_DELETE_PAGE_SIZE;
4481
- exports.OPENROUTER_PERMANENT_ERROR_STATUSES = OPENROUTER_PERMANENT_ERROR_STATUSES;
4482
- exports.OPENROUTER_PROMPT_CACHE_DURATION = OPENROUTER_PROMPT_CACHE_DURATION;
4483
- exports.OPENROUTER_PROMPT_SERVICE_TOKEN = OPENROUTER_PROMPT_SERVICE_TOKEN;
4484
- exports.OPENROUTER_RUN_TASK_SERVICE_TOKEN = OPENROUTER_RUN_TASK_SERVICE_TOKEN;
4485
- exports.OPENROUTER_SEED_PROMPTS_MAX_PARALLEL_UPDATES = OPENROUTER_SEED_PROMPTS_MAX_PARALLEL_UPDATES;
4486
- exports.OpenRouterPromptResolutionError = OpenRouterPromptResolutionError;
4487
- exports.OpenRouterPromptServerActions = OpenRouterPromptServerActions;
4488
- exports.OpenRouterPromptService = OpenRouterPromptService;
4489
- exports.OpenRouterRunTaskService = OpenRouterRunTaskService;
4490
- exports.appOpenRouterModuleMetadata = appOpenRouterModuleMetadata;
4491
- exports.callModelForPrompt = callModelForPrompt;
4492
- exports.conversationStateForOpenRouterRunTask = conversationStateForOpenRouterRunTask;
4493
- exports.conversationStatusForOpenRouterRunTaskState = conversationStatusForOpenRouterRunTaskState;
4494
- exports.createOpenRouterPromptFactory = createOpenRouterPromptFactory;
4495
- exports.createOpenRouterPromptVersionFactory = createOpenRouterPromptVersionFactory;
4496
- exports.firestoreOpenRouterStateAccessor = firestoreOpenRouterStateAccessor;
4497
- exports.handleOpenRouterRunTaskResultFactory = handleOpenRouterRunTaskResultFactory;
4498
- exports.hasUnresolvedOpenRouterPendingToolCalls = hasUnresolvedOpenRouterPendingToolCalls;
4499
- exports.isOpenRouterRunTaskClaimable = isOpenRouterRunTaskClaimable;
4500
- exports.isRetryableOpenRouterError = isRetryableOpenRouterError;
4501
- exports.mergeOpenRouterRunUsage = mergeOpenRouterRunUsage;
4502
- exports.openRouterConversationValueForFirestore = openRouterConversationValueForFirestore;
4503
- exports.openRouterDeferredToolResolutionsForRunTask = openRouterDeferredToolResolutionsForRunTask;
4504
- exports.openRouterErrorCode = openRouterErrorCode;
4505
- exports.openRouterErrorMessage = openRouterErrorMessage;
4506
- exports.openRouterFileAttachmentModeForConfig = openRouterFileAttachmentModeForConfig;
4507
- exports.openRouterFileAttachmentResolver = openRouterFileAttachmentResolver;
4508
- exports.openRouterPromptServerActions = openRouterPromptServerActions;
4509
- exports.openRouterPromptService = openRouterPromptService;
4510
- exports.openRouterRunTaskExpirationSweep = openRouterRunTaskExpirationSweep;
4511
- exports.openRouterRunTaskKeyFromBroadcastAttributes = openRouterRunTaskKeyFromBroadcastAttributes;
4512
- exports.openRouterRunTaskOutcome = openRouterRunTaskOutcome;
4513
- exports.openRouterRunTaskService = openRouterRunTaskService;
4514
- exports.openRouterRunTaskStateForConversationStatus = openRouterRunTaskStateForConversationStatus;
4515
- exports.openRouterRunTaskSweep = openRouterRunTaskSweep;
4516
- exports.openRouterRunTaskUpdateForConversationState = openRouterRunTaskUpdateForConversationState;
4517
- exports.reconcileOpenRouterRunTaskFromBroadcast = reconcileOpenRouterRunTaskFromBroadcast;
4518
- exports.seedOpenRouterPromptsFactory = seedOpenRouterPromptsFactory;
4519
- exports.updateOpenRouterPromptFactory = updateOpenRouterPromptFactory;
4520
- exports.updateOpenRouterPromptVersionFactory = updateOpenRouterPromptVersionFactory;