runbios-sdk 0.2.1-rc.98 → 0.2.2-dev.171

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.
@@ -0,0 +1,1189 @@
1
+ /**
2
+ * The Conscious Loop -- capture what your model was asked and answered, record
3
+ * whether it was right, and turn those judgements into training data.
4
+ *
5
+ * Nothing is captured until you turn it on for a source, and you can turn it
6
+ * off again at any time. Anything that looks like a credential or a personal
7
+ * detail is removed before the record is written, never afterwards.
8
+ *
9
+ * Requires an API key carrying `loop:read` and/or `loop:write`. Those scopes are
10
+ * deliberately absent from the Read Only preset, because what they return is
11
+ * your raw prompts and completions rather than catalog metadata.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * // 1. Decide that this source is recorded.
16
+ * await client.loop.setConfig('my-agent', { enabled: true, retention_days: 30 });
17
+ *
18
+ * // 2. Send what your model was asked and what it answered. Works whoever
19
+ * // served it -- us, another provider, or your own servers.
20
+ * const { trace_id } = await client.loop.capture({
21
+ * deployment_id: 'my-agent',
22
+ * model: 'gpt-4o',
23
+ * messages: [{ role: 'user', content: 'what is our refund window' }],
24
+ * completion: 'thirty days',
25
+ * });
26
+ *
27
+ * // 3. Say whether it was right. A rewrite is the most valuable answer here:
28
+ * // the model learns your version AND learns to avoid its own.
29
+ * await client.loop.signal(trace_id, {
30
+ * verdict: 'edited',
31
+ * correction: 'Thirty days from delivery, no questions asked.',
32
+ * });
33
+ *
34
+ * // 4. Turn the judgements into a training set and take the file.
35
+ * const ds = await client.loop.createDataset({ name: 'support', method: 'sft' });
36
+ * const jsonl = await client.loop.downloadDataset(ds.id);
37
+ * ```
38
+ */
39
+ export class Loop {
40
+ _http;
41
+ /** @internal */
42
+ constructor(_http) {
43
+ this._http = _http;
44
+ }
45
+ // ── capture ───────────────────────────────────────────────────────────
46
+ /**
47
+ * Send one exchange to be captured.
48
+ *
49
+ * Works regardless of who served the model: ours, OpenAI, Fireworks, your own
50
+ * own servers, an agent framework. Pass `tool_calls` and `tools` when the turn
51
+ * invoked a function -- without them a tool-using exchange trains the model to
52
+ * answer in prose where it should have called something.
53
+ *
54
+ * The returned `trace_id` is OURS. If you pass your own `request_id` it is
55
+ * kept as an idempotency handle: sending the same one again returns the same
56
+ * trace rather than storing a second copy, so a retry is safe.
57
+ *
58
+ * When the source is not enabled this resolves with `captured: false` and a
59
+ * reason instead of throwing -- capture must never be the thing that breaks
60
+ * your application.
61
+ */
62
+ async capture(params) {
63
+ return this._http.fetchPost('/api/loop/traces', params);
64
+ }
65
+ /**
66
+ * Bring data you already have into the loop.
67
+ *
68
+ * This does NOT create a training set. It creates conversations, in the same
69
+ * place captured ones live and subject to the same review, rules, judges and
70
+ * labels. A row becomes trainable when something says it is good, never
71
+ * because it arrived in a file -- which is the one guarantee that separates
72
+ * a corpus from a pile.
73
+ *
74
+ * Each row is read for what it actually is. A `prompt`/`chosen`/`rejected`
75
+ * triple becomes a preference pair; an answer plus a yes-or-no becomes a
76
+ * thumbs verdict; a question and an answer waits for review; a question with
77
+ * no answer waits for an answer; a paragraph of prose is refused, because it
78
+ * is not a conversation.
79
+ *
80
+ * A verdict that arrives *with* the file is kept -- discarding somebody's
81
+ * judgement would be worse -- but it is recorded as having come from your
82
+ * earlier process rather than from a reviewer here, and the conversation
83
+ * records that it was imported. Neither fact can be reconstructed later, so
84
+ * both are written at the door.
85
+ *
86
+ * `source` is required and becomes the id every imported conversation is
87
+ * filed under: "everything in one bucket called import" is a corpus nobody
88
+ * can slice afterwards. At most 5000 rows per call, because the call is
89
+ * synchronous and somebody is waiting on it.
90
+ *
91
+ * WHAT COMES BACK. `imported` is what this call created and `trace_ids` names
92
+ * the conversations from the file that are now in the loop, so a caller can
93
+ * label, review or delete them. `by_shape`, `reviewed` and `needs_review`
94
+ * count what THIS CALL created, not what was merely recognised and not rows
95
+ * an earlier import already had, and the sentences in `notes` are written
96
+ * from those counts, so the numbers and the prose describe the same call and
97
+ * a re-send cannot report a reviewed conversation as waiting for review.
98
+ * `refused` is rows whose shape could not be read, which the file fixes;
99
+ * `not_saved` is rows that were understood and then could not be stored,
100
+ * which the file cannot fix.
101
+ *
102
+ * A call with any `not_saved`, or any `verdicts_not_saved` (the conversation
103
+ * stored and the judgement that came with it did not), REJECTS with
104
+ * `LoopImportIncompleteError`, whose `outcome` carries all of the above and
105
+ * whose `notSavedRows` and `verdictsNotSavedRows` name the positions.
106
+ *
107
+ * HOW A RETRY IS SAFE. Every response carries `import_id`, the token this
108
+ * call was filed under. Send the same rows again with it, and rows that
109
+ * already arrived come back on `already_present` instead of being stored
110
+ * twice, while a verdict that failed to write is attempted again. A call that
111
+ * repeats no token is its own import, deliberately: two calls carrying the
112
+ * same rows are as likely to be two pages of one export as one call twice,
113
+ * and guessing "retry" silently drops the second copy of every conversation a
114
+ * file lists more than once.
115
+ *
116
+ * SENDING A FILE IN PAGES. Either give each row its own `row_ids` entry, and
117
+ * then chunking, ordering and subsets all stop mattering; or send one
118
+ * `import_id` with the `row_offset` each page starts at. Do not send back
119
+ * only the rows `notSavedRows` names unless you used `row_ids`: without them
120
+ * a shorter list moves every row after the gap and imports it again.
121
+ */
122
+ async importRows(params) {
123
+ return this._http.fetchPost('/api/loop/import', params);
124
+ }
125
+ // ── traces ────────────────────────────────────────────────────────────
126
+ /** List captured conversations, newest first. */
127
+ async listTraces(params = {}) {
128
+ const q = new URLSearchParams();
129
+ if (params.deployment_id)
130
+ q.set('deployment_id', params.deployment_id);
131
+ if (params.conversation_id)
132
+ q.set('conversation_id', params.conversation_id);
133
+ if (params.from)
134
+ q.set('from', params.from);
135
+ if (params.to)
136
+ q.set('to', params.to);
137
+ if (params.signalled)
138
+ q.set('signalled', 'true');
139
+ if (params.label)
140
+ q.set('label', params.label);
141
+ // Repeated rather than comma-joined: a value containing a comma would
142
+ // otherwise silently split into two filters that match nothing.
143
+ for (const [k, v] of Object.entries(params.attributes ?? {})) {
144
+ if (k && v)
145
+ q.append('attr', `${k}:${v}`);
146
+ }
147
+ if (params.model)
148
+ q.set('model', params.model);
149
+ if (params.origin)
150
+ q.set('origin', params.origin);
151
+ if (params.unlabelled)
152
+ q.set('unlabelled', 'true');
153
+ if (params.limit != null)
154
+ q.set('limit', String(params.limit));
155
+ if (params.offset != null)
156
+ q.set('offset', String(params.offset));
157
+ const qs = q.toString();
158
+ return this._http.fetchGet(`/api/loop/traces${qs ? `?${qs}` : ''}`);
159
+ }
160
+ /** Read one conversation, with every verdict recorded on it. */
161
+ async getTrace(id) {
162
+ const res = await this._http.fetchGet(`/api/loop/traces/${encodeURIComponent(id)}`);
163
+ return res.trace;
164
+ }
165
+ /**
166
+ * Delete a conversation.
167
+ *
168
+ * It also leaves every training set built from it, including sets already
169
+ * exported -- so a customer asking you to delete a conversation genuinely
170
+ * removes it from what the model will learn next. Training runs that have
171
+ * already finished are not affected.
172
+ */
173
+ async deleteTrace(id) {
174
+ return this._http.fetchDelete(`/api/loop/traces/${encodeURIComponent(id)}`);
175
+ }
176
+ // ── feedback ──────────────────────────────────────────────────────────
177
+ /**
178
+ * Record a verdict on a conversation.
179
+ *
180
+ * Append-only: posting a second verdict does not replace the first. Two
181
+ * reviewers disagreeing about an answer is information worth keeping.
182
+ *
183
+ * `source` says who judged: `human`, `verifier` (a deterministic check --
184
+ * tests passed, schema valid), `judge` (a model grading a model), or
185
+ * `behavioural` (what the user did next). When several disagree, a human
186
+ * outranks a verifier, a verifier outranks a judge, and a judge outranks a
187
+ * behavioural hint.
188
+ */
189
+ async signal(traceId, params) {
190
+ const res = await this._http.fetchPost(`/api/loop/traces/${encodeURIComponent(traceId)}/signals`, params);
191
+ return res.signal;
192
+ }
193
+ /**
194
+ * Thumbs up: this answer was good. Shorthand for `signal(id, { verdict:
195
+ * 'accepted' })` — there is one stored vocabulary behind both, so a thumbs-up
196
+ * and an "accepted" can never disagree in your corpus.
197
+ */
198
+ async upvote(traceId, reason) {
199
+ return this.signal(traceId, { verdict: 'accepted', reason });
200
+ }
201
+ /**
202
+ * Thumbs down: this answer was bad, and you have nothing better to offer.
203
+ *
204
+ * On its own this REMOVES the answer from training rather than teaching
205
+ * anything — there is no better version to learn. If you know what it should
206
+ * have said, `correct()` is worth far more.
207
+ */
208
+ async downvote(traceId, reason) {
209
+ return this.signal(traceId, { verdict: 'rejected', reason });
210
+ }
211
+ /**
212
+ * The model was wrong; here is what it should have said.
213
+ *
214
+ * The most valuable feedback there is, because it produces BOTH halves of a
215
+ * preference pair from one action: the model learns your answer and learns to
216
+ * avoid its own.
217
+ */
218
+ async correct(traceId, answer, reason) {
219
+ return this.signal(traceId, { verdict: 'edited', correction: answer, reason });
220
+ }
221
+ /**
222
+ * Record the GOLD answer for this question — the reference, regardless of
223
+ * what the model happened to say.
224
+ *
225
+ * Different from `correct()` in a way that matters: a correction asserts the
226
+ * model was wrong, so the original becomes the rejected half of a pair. A gold
227
+ * answer asserts nothing about the model, so if it MATCHES what was said, no
228
+ * preference pair is invented — but SFT still learns it.
229
+ *
230
+ * It is the most reusable thing you can record: it trains SFT, forms a DPO
231
+ * pair when it differs from the answer, and stands in as the GRPO reference
232
+ * when you have not supplied a separate ground truth.
233
+ */
234
+ async gold(traceId, answer, reason) {
235
+ return this.signal(traceId, { verdict: 'gold', correction: answer, reason });
236
+ }
237
+ /** Every verdict on one conversation, oldest first. */
238
+ async listSignals(traceId) {
239
+ const res = await this._http.fetchGet(`/api/loop/traces/${encodeURIComponent(traceId)}/signals`);
240
+ return res.signals;
241
+ }
242
+ // ── alternative answers ───────────────────────────────────────────────
243
+ /**
244
+ * Submit an alternative answer to a prompt already captured.
245
+ *
246
+ * This is what makes preference learning scale. A human rewrite is the best
247
+ * signal there is and the least available -- somebody has to sit down and
248
+ * write it. Sample the model several times for the same prompt, score the
249
+ * samples, and a DPO pair falls out automatically: best becomes chosen,
250
+ * worst becomes rejected. Point a stronger model at the prompt instead and
251
+ * the same machinery does distillation.
252
+ *
253
+ * Score them, or they cannot pair: an unscored alternative says nothing about
254
+ * which answer anybody prefers. `score_source` is required alongside a score,
255
+ * because precedence between a verifier, a judge and a person is the whole
256
+ * reason we record who judged.
257
+ *
258
+ * A human correction always outranks any score.
259
+ *
260
+ * @example
261
+ * ```ts
262
+ * for (const sample of await sampleMyModel(prompt, 4)) {
263
+ * await client.loop.addCandidate(traceId, {
264
+ * completion: sample.text,
265
+ * score: await myVerifier(sample.text),
266
+ * score_source: 'verifier',
267
+ * });
268
+ * }
269
+ * ```
270
+ */
271
+ async addCandidate(traceId, params) {
272
+ const res = await this._http.fetchPost(`/api/loop/traces/${encodeURIComponent(traceId)}/candidates`, params);
273
+ return res.candidate;
274
+ }
275
+ /** Every alternative answer recorded for one prompt, oldest first. */
276
+ async listCandidates(traceId) {
277
+ const res = await this._http.fetchGet(`/api/loop/traces/${encodeURIComponent(traceId)}/candidates`);
278
+ return res.candidates;
279
+ }
280
+ // ── labels ────────────────────────────────────────────────────────────
281
+ /**
282
+ * Label a conversation, so it can be selected later.
283
+ *
284
+ * An average over everything is the least useful thing to train on. A model
285
+ * weak at refunds is fixed with refund examples, and you can only select
286
+ * those if you said so when the conversation arrived.
287
+ *
288
+ * A label may name a `parent`, which is what makes a MASTER GROUP: labelling
289
+ * something `refunds` with parent `billing` makes it selectable as either,
290
+ * and selecting `billing` later gathers every child without you maintaining
291
+ * a list of them.
292
+ *
293
+ * Labels are lowercased and trimmed, so `Refunds` and `refunds` are one label.
294
+ */
295
+ async label(traceId, labels, parent, attributes) {
296
+ const res = await this._http.fetchPost(`/api/loop/traces/${encodeURIComponent(traceId)}/labels`, { labels, parent, attributes });
297
+ return res.labels;
298
+ }
299
+ /**
300
+ * Set named dimensions on a conversation: `{ category: 'billing',
301
+ * language: 'es' }`.
302
+ *
303
+ * An upsert per dimension, so correcting `category` leaves `task` and any
304
+ * bare tags exactly where they were — no delete-then-add.
305
+ */
306
+ async setAttributes(traceId, attributes) {
307
+ const res = await this._http.fetchPost(`/api/loop/traces/${encodeURIComponent(traceId)}/labels`, { attributes });
308
+ return res.labels;
309
+ }
310
+ async unlabel(traceId, label, key) {
311
+ const q = key ? `?key=${encodeURIComponent(key)}` : '';
312
+ return this._http.fetchDelete(`/api/loop/traces/${encodeURIComponent(traceId)}/labels/${encodeURIComponent(label)}${q}`);
313
+ }
314
+ /**
315
+ * Every label in the workspace, with how many conversations carry it and
316
+ * which master groups those conversations are in.
317
+ *
318
+ * TWO FIELDS ANSWER THE GROUP QUESTION, AND THEY ANSWER DIFFERENT ONES.
319
+ * `parent` is the group ALL of a label's conversations are in, and it is
320
+ * null the moment they disagree. `parents` is every group ANY of them are
321
+ * in, with how many of them are in each.
322
+ *
323
+ * Build a list of master groups out of `parents`. A label with 12
324
+ * conversations, 5 of them under `support`, reports `parent: null` and
325
+ * `parents: [{parent: 'support', traces: 5}]`, so code that reads only
326
+ * `parent` sees no group at all for it. The registry used to answer
327
+ * `parent: "support"` for all twelve, which named the group but put seven
328
+ * conversations in it that nobody had put there.
329
+ */
330
+ async listLabels() {
331
+ const res = await this._http.fetchGet('/api/loop/labels');
332
+ return res.labels;
333
+ }
334
+ // ── training sets ─────────────────────────────────────────────────────
335
+ /**
336
+ * Build a training set from the feedback recorded so far.
337
+ *
338
+ * The three methods need genuinely different things, so one set cannot be
339
+ * reshaped into another afterwards:
340
+ *
341
+ * - `sft` -- answers you marked right, and answers you rewrote.
342
+ * - `dpo` -- answers you REWROTE, so a better and a worse version of the same
343
+ * reply exist. Nothing else produces a pair.
344
+ * - `grpo` -- answers with a value or fact they can be checked against, or
345
+ * a judge rubric, which scores answers the run has not written yet.
346
+ * - `kto` -- anything carrying a yes or a no, INCLUDING a thumbs-down with
347
+ * nothing written. That row trains nothing under the other three methods,
348
+ * which is why this one exists: it is the feedback people actually give.
349
+ *
350
+ * `holdout_percent` holds back your most recent work rather than a random
351
+ * slice, so the evaluation measures whether the model generalised instead of
352
+ * memorised the same week.
353
+ *
354
+ * The result always reports `rejected_counts`: why rows were left out. A
355
+ * small set with a reason is useful; a small set without one is just alarming.
356
+ */
357
+ async createDataset(params) {
358
+ const res = await this._http.fetchPost('/api/loop/datasets', params);
359
+ return res.dataset;
360
+ }
361
+ /** List training sets, newest first. */
362
+ // ── build rules ───────────────────────────────────────────────────────
363
+ /**
364
+ * Stand up a rule that builds a set whenever enough new work exists.
365
+ *
366
+ * The manual path asks somebody to notice that enough conversations have
367
+ * been reviewed, remember which filters describe the slice they want, and
368
+ * press build — every time. A rule is that instruction, stored.
369
+ *
370
+ * `spec` is the same selection `createDataset` takes and is replayed
371
+ * verbatim, so an automatic set is identical to a hand-made one.
372
+ *
373
+ * `min_new_rows` counts only work reviewed SINCE THE LAST BUILD. Counting
374
+ * the whole corpus would fire the rule every interval forever, because a
375
+ * total that has crossed a threshold stays across it.
376
+ */
377
+ async createBuildRule(params) {
378
+ const res = await this._http.fetchPost('/api/loop/build-rules', params);
379
+ return res.rule;
380
+ }
381
+ /**
382
+ * Every build rule, with what each one last did and why.
383
+ *
384
+ * `last_reason` is the field worth reading: a rule quiet because it is
385
+ * waiting looks exactly like one quiet because it is broken.
386
+ */
387
+ async listBuildRules() {
388
+ const res = await this._http.fetchGet('/api/loop/build-rules');
389
+ return res.rules ?? [];
390
+ }
391
+ /** Stop a standing build rule. Sets it already produced are untouched. */
392
+ async deleteBuildRule(id) {
393
+ return this._http.fetchDelete(`/api/loop/build-rules/${encodeURIComponent(id)}`);
394
+ }
395
+ async listDatasets(params = {}) {
396
+ const q = new URLSearchParams();
397
+ if (params.method)
398
+ q.set('method', params.method);
399
+ if (params.limit != null)
400
+ q.set('limit', String(params.limit));
401
+ if (params.offset != null)
402
+ q.set('offset', String(params.offset));
403
+ const qs = q.toString();
404
+ const res = await this._http.fetchGet(`/api/loop/datasets${qs ? `?${qs}` : ''}`);
405
+ return res.datasets;
406
+ }
407
+ /** Read one training set and its curation report. */
408
+ async getDataset(id) {
409
+ const res = await this._http.fetchGet(`/api/loop/datasets/${encodeURIComponent(id)}`);
410
+ return res.dataset;
411
+ }
412
+ /**
413
+ * Page through the rows a training set actually contains.
414
+ *
415
+ * Worth reading before you spend money on a run: each row carries the address
416
+ * of the conversation it was built from.
417
+ */
418
+ async listDatasetItems(id, params = {}) {
419
+ const q = new URLSearchParams();
420
+ if (params.limit != null)
421
+ q.set('limit', String(params.limit));
422
+ if (params.offset != null)
423
+ q.set('offset', String(params.offset));
424
+ const qs = q.toString();
425
+ const res = await this._http.fetchGet(`/api/loop/datasets/${encodeURIComponent(id)}/items${qs ? `?${qs}` : ''}`);
426
+ return res.items;
427
+ }
428
+ /**
429
+ * Download a training set as JSONL -- one training row per line, the format
430
+ * every trainer in this space reads.
431
+ *
432
+ * `split` defaults to the training rows; pass `holdout` for the slice held
433
+ * back, or `all` for both.
434
+ */
435
+ async downloadDataset(id, split) {
436
+ const qs = split ? `?split=${split}` : '';
437
+ return this._http.fetchGet(`/api/loop/datasets/${encodeURIComponent(id)}/download${qs}`);
438
+ }
439
+ /**
440
+ * Delete a training set.
441
+ *
442
+ * The conversations it was built from are untouched -- a set is a selection,
443
+ * and discarding the selection must not discard the evidence.
444
+ */
445
+ async deleteDataset(id) {
446
+ return this._http.fetchDelete(`/api/loop/datasets/${encodeURIComponent(id)}`);
447
+ }
448
+ // ── graders ───────────────────────────────────────────────────────────
449
+ /**
450
+ * Write a rule that scores answers without a person.
451
+ *
452
+ * Human review is the most trustworthy feedback and the least available. A
453
+ * grader is written once and applied to every answer afterwards: did it
454
+ * contain the required phrase, did it parse as the schema you asked for, is
455
+ * the number within tolerance of the known answer, did it call the function
456
+ * it should have.
457
+ *
458
+ * Every kind here is DETERMINISTIC -- no model call, no network. That is why
459
+ * a verifier outranks a judge when they disagree: it cannot be flattered and
460
+ * it cannot drift between runs.
461
+ *
462
+ * `weight` is the multiplier: a criterion that matters twice as much gets
463
+ * twice the weight, and the combined score is the weighted mean over the
464
+ * rules that actually applied.
465
+ *
466
+ * `matches_gold` needs no `expected`: it compares each answer to the gold
467
+ * answer recorded on that same conversation, or the human correction when
468
+ * there is no gold, and scores sampled alternatives against the same gold.
469
+ * A conversation with neither is skipped, not failed, so one rule checks
470
+ * every labelled question without punishing the unlabelled ones. An
471
+ * optional `tolerance` widens the match when both sides are bare numbers.
472
+ *
473
+ * A caution worth knowing before you write a set: a rule made only of
474
+ * `forbidden` phrases is satisfied VACUOUSLY by an answer that says nothing.
475
+ * Pair it with a `required` phrase, or you are rewarding silence.
476
+ */
477
+ async createGrader(params) {
478
+ const res = await this._http.fetchPost('/api/loop/graders', params);
479
+ return res.grader;
480
+ }
481
+ /** Every rule this workspace has written. */
482
+ async listGraders() {
483
+ const res = await this._http.fetchGet('/api/loop/graders');
484
+ return res.graders;
485
+ }
486
+ async deleteGrader(id) {
487
+ return this._http.fetchDelete(`/api/loop/graders/${encodeURIComponent(id)}`);
488
+ }
489
+ /**
490
+ * Apply this workspace's rules to one captured answer AND to every
491
+ * alternative sampled for it.
492
+ *
493
+ * Grading both in one pass is the point: scoring only the original gives a
494
+ * verdict, while scoring the samples as well gives the preference pair. Sample
495
+ * your model, call this, and you have DPO data with nobody reading anything.
496
+ *
497
+ * A run where no rule could apply writes NOTHING -- no verdict, no scores.
498
+ * Recording a zero that no rule produced would poison curation with a
499
+ * judgement nobody reached, so `applied: 0` is reported instead.
500
+ */
501
+ async grade(traceId) {
502
+ return this._http.fetchPost(`/api/loop/traces/${encodeURIComponent(traceId)}/grade`);
503
+ }
504
+ // ── capture settings ──────────────────────────────────────────────────
505
+ /** Every source this workspace has configured. */
506
+ async listConfigs() {
507
+ const res = await this._http.fetchGet('/api/loop/configs');
508
+ return res.configs;
509
+ }
510
+ /**
511
+ * Read the capture setting for one source. A source nobody has configured
512
+ * reads back as disabled rather than missing, because "we are not recording
513
+ * this" is the honest answer.
514
+ */
515
+ async getConfig(source) {
516
+ const res = await this._http.fetchGet(`/api/loop/configs/${encodeURIComponent(source)}`);
517
+ return res.config;
518
+ }
519
+ /**
520
+ * Turn capture on or off for a source, and choose how long it is kept.
521
+ *
522
+ * This is the consent decision the whole feature rests on: nothing is
523
+ * recorded until it is made, and the row remembers who made it and when.
524
+ * `sample_rate` below 1 records a deterministic fraction, chosen so that every
525
+ * turn of one conversation is captured or skipped together -- half a
526
+ * conversation makes training rows with holes in them.
527
+ */
528
+ async setConfig(source, params) {
529
+ const res = await this._http.fetchPut(`/api/loop/configs/${encodeURIComponent(source)}`, params);
530
+ return res.config;
531
+ }
532
+ /**
533
+ * How much there is, and how much of it each method could actually use.
534
+ *
535
+ * The `ready` numbers are upper bounds: duplicate questions are folded into
536
+ * one row while a set is built, so the finished count can be lower.
537
+ */
538
+ async stats() {
539
+ const res = await this._http.fetchGet('/api/loop/stats');
540
+ return res.stats;
541
+ }
542
+ // ── judges ────────────────────────────────────────────────────────────
543
+ //
544
+ // A grader is a rule: deterministic, cheap, and blind to anything it was not
545
+ // told to look for. A judge is a rubric handed to a model, which is the only
546
+ // thing that can answer "was this answer actually helpful".
547
+ //
548
+ // YOU run the model. This service stores raw prompts and completions and
549
+ // holds them with no outbound credentials at all, which is most of the reason
550
+ // it is safe to store them there -- so it hands the work out instead. Open a
551
+ // run, take the batch, send each `prompt` to whatever model you like, and
552
+ // post the scores back.
553
+ /** Write a rubric: what makes an answer good here, and what to score. */
554
+ async createJudge(params) {
555
+ const res = await this._http.fetchPost('/api/loop/judges', params);
556
+ return res.judge;
557
+ }
558
+ async listJudges() {
559
+ const res = await this._http.fetchGet('/api/loop/judges');
560
+ return res.judges;
561
+ }
562
+ /**
563
+ * Rewrite a rubric. Runs already recorded keep the instructions they used:
564
+ * a verdict has to keep meaning what it meant when it was given.
565
+ */
566
+ async updateJudge(judgeId, params) {
567
+ const res = await this._http.fetchPut(`/api/loop/judges/${encodeURIComponent(judgeId)}`, params);
568
+ return res.judge;
569
+ }
570
+ /**
571
+ * Retire a rubric. Its runs go with it; the verdicts they wrote stay. A score
572
+ * is evidence about an answer, and it does not stop being true because the
573
+ * rubric was retired.
574
+ */
575
+ async deleteJudge(judgeId) {
576
+ await this._http.fetchDelete(`/api/loop/judges/${encodeURIComponent(judgeId)}`);
577
+ }
578
+ /**
579
+ * Open a run: select the conversations now, and freeze the rubric onto them.
580
+ *
581
+ * The selection is fixed at this moment on purpose. A run whose selection is
582
+ * a live query silently grows as conversations arrive, so "we scored the
583
+ * refunds slice" becomes a claim about a set that no longer exists.
584
+ */
585
+ async startRun(judgeId, limit) {
586
+ const res = await this._http.fetchPost(`/api/loop/judges/${encodeURIComponent(judgeId)}/runs`, limit ? { limit } : {});
587
+ return res.run;
588
+ }
589
+ async listRuns(judgeId) {
590
+ const path = judgeId
591
+ ? `/api/loop/judges/${encodeURIComponent(judgeId)}/runs`
592
+ : '/api/loop/runs';
593
+ const res = await this._http.fetchGet(path);
594
+ return res.runs;
595
+ }
596
+ async getRun(runId) {
597
+ const res = await this._http.fetchGet(`/api/loop/runs/${encodeURIComponent(runId)}`);
598
+ return res.run;
599
+ }
600
+ /**
601
+ * Take the next conversations to score, each rendered into a ready-to-send
602
+ * prompt. Nothing is marked taken, so a caller that dies half way loses
603
+ * nothing: ask again and the same items come back.
604
+ */
605
+ async takeWork(runId, limit = 20) {
606
+ return this._http.fetchGet(`/api/loop/runs/${encodeURIComponent(runId)}/work?limit=${limit}`);
607
+ }
608
+ /**
609
+ * What happened to each conversation in a run, and why.
610
+ *
611
+ * `takeWork` hands out what is still PENDING, so a finished run answers it
612
+ * with an empty list. This answers with every item and the outcome on it:
613
+ * `status`, `scored_at`, and `error` — the reason the caller gave for an
614
+ * item it could not score, which is where a wrong model slug or a refused
615
+ * key actually shows up. A run that ends "scored 0, failed 3" is otherwise a
616
+ * number with no detail behind it.
617
+ *
618
+ * Pass `status: 'failed'` for the usual question. At most 500 items come
619
+ * back at a time; when `has_more` is true, call again with the `next_offset`
620
+ * from the reply.
621
+ */
622
+ async listRunItems(runId, opts = {}) {
623
+ const qs = new URLSearchParams();
624
+ if (opts.status)
625
+ qs.set('status', opts.status);
626
+ if (opts.limit != null)
627
+ qs.set('limit', String(opts.limit));
628
+ if (opts.offset)
629
+ qs.set('offset', String(opts.offset));
630
+ const suffix = qs.toString() ? `?${qs.toString()}` : '';
631
+ return this._http.fetchGet(`/api/loop/runs/${encodeURIComponent(runId)}/items${suffix}`);
632
+ }
633
+ /**
634
+ * Hand the scores back. A verdict for a conversation outside this run, or
635
+ * scoring something the rubric never asked for, is refused and reported in
636
+ * `rejected` rather than silently dropped.
637
+ *
638
+ * Pass `finish` to close the run in the same call once you have nothing left
639
+ * to send. To close a run WITHOUT scores, call `stopRun`: an empty verdict
640
+ * list with `finish` does the same thing and reads like a mistake.
641
+ */
642
+ async postVerdicts(runId, verdicts, finish = false) {
643
+ return this._http.fetchPost(`/api/loop/runs/${encodeURIComponent(runId)}/verdicts`, { verdicts, finish });
644
+ }
645
+ /**
646
+ * Close a run that has not finished.
647
+ *
648
+ * A judge may have one open run of its own at a time, so an open run BLOCKS
649
+ * the next one, and the runs that most need closing are the ones nobody can
650
+ * wait out: a run the agent has parked on an empty balance or a refused key
651
+ * stays open until the reason is fixed or somebody stops it.
652
+ *
653
+ * Nothing is deleted. Every verdict already recorded stays recorded, the
654
+ * counters keep saying how much of the selection was covered, and the
655
+ * conversations the run was holding are free for the next one. The run ends
656
+ * as `stopped` rather than `done`, so an interrupted pass and a completed
657
+ * one do not read alike.
658
+ *
659
+ * A run that finished on its own is not rewritten: stopping one answers 409.
660
+ *
661
+ * Returns the stopped run itself, like `startRun` and `getRun`, not the
662
+ * `{run}` envelope the service sends. Every other single-run method in this
663
+ * class unwraps, and `Loop.stop_run` in the Python SDK does too, so a
664
+ * caller who wrote `(await loop.stopRun(id)).status` against one of its
665
+ * siblings is right here as well.
666
+ */
667
+ async stopRun(runId) {
668
+ const res = await this._http.fetchPost(`/api/loop/runs/${encodeURIComponent(runId)}/stop`, {});
669
+ return res.run;
670
+ }
671
+ // ── the agent ─────────────────────────────────────────────────────────
672
+ //
673
+ // The worker that calls a model on the workspace's behalf: it applies
674
+ // automatic judges and writes sample answers. It spends through a managed
675
+ // serverless key OF THIS WORKSPACE, so every call is billed exactly like
676
+ // one of your own, and turning it off revokes that key.
677
+ /**
678
+ * Can an agent run here, is one running, and is it on for this workspace.
679
+ * `available` is about the environment; `online` about the worker;
680
+ * `credential` about this workspace.
681
+ */
682
+ async agentStatus() {
683
+ return this._http.fetchGet('/api/loop/agent');
684
+ }
685
+ /**
686
+ * Turn the agent on: mints the workspace's managed serverless key and
687
+ * resumes the automatic judges a previous turn-off paused. After this,
688
+ * automatic judges and sample runs make model calls billed to the
689
+ * workspace. Idempotent.
690
+ *
691
+ * A judge whose model the serving gateway will not route is NOT resumed:
692
+ * making it automatic would buy a run that fails every conversation. It
693
+ * stays paused, `judges_still_paused` counts those, and each one carries
694
+ * `auto_pause_reason` saying so. Point it at a model that is served and
695
+ * turn the agent on again.
696
+ *
697
+ * `monthly_spend_cap_cents` caps what that key may spend on model calls in
698
+ * a calendar month. Omitted = no cap on a fresh key, and an existing cap is
699
+ * left as it is; sent while the agent is already on, it moves the cap on
700
+ * the existing key without minting a new one. When the cap is reached the
701
+ * agent's model calls are refused until next month and its runs pause with
702
+ * that reason.
703
+ */
704
+ async enableAgent(opts = {}) {
705
+ const body = {};
706
+ if (opts.monthly_spend_cap_cents != null)
707
+ body.monthly_spend_cap_cents = opts.monthly_spend_cap_cents;
708
+ const res = await this._http.fetchPost('/api/loop/agent', body);
709
+ return res.credential;
710
+ }
711
+ /**
712
+ * Turn the agent off: revokes its key and pauses every automatic judge in
713
+ * the workspace (`judges_paused`; each judge shows `auto_paused`). Turning
714
+ * it back on resumes exactly those judges. Open runs stop where they are
715
+ * and continue if it is turned back on. Nothing already scored or written
716
+ * is removed.
717
+ */
718
+ async disableAgent() {
719
+ return this._http.fetchDelete('/api/loop/agent');
720
+ }
721
+ /**
722
+ * Ask the agent to write `n` alternative answers to each conversation in a
723
+ * slice with `model`, score each with `judge_id`, and store them as
724
+ * candidates. This is how preference pairs are made without a person
725
+ * writing each one: the curation pass pairs the best sample against the
726
+ * worst wherever the gap is real.
727
+ *
728
+ * Cost: up to `n` calls to write plus `n` to judge, per conversation, at the
729
+ * workspace's serverless rate; `selection.sample` caps the conversations
730
+ * (max 200) and `n` is capped at 8. Opening a run turns the agent on if it
731
+ * is off.
732
+ */
733
+ async createSampleRun(params) {
734
+ const res = await this._http.fetchPost('/api/loop/sample-runs', params);
735
+ return res.run;
736
+ }
737
+ async listSampleRuns() {
738
+ const res = await this._http.fetchGet('/api/loop/sample-runs');
739
+ return res.runs;
740
+ }
741
+ async getSampleRun(runId) {
742
+ const res = await this._http.fetchGet(`/api/loop/sample-runs/${encodeURIComponent(runId)}`);
743
+ return res.run;
744
+ }
745
+ // ── automatic training ────────────────────────────────────────────────
746
+ //
747
+ // A training rule is a STANDING INSTRUCTION, not a job. Once it is accepted
748
+ // the platform builds a set, trains a model, books a candidate, compares it
749
+ // against what serves your traffic today and -- if you asked for that --
750
+ // re-points the alias at the winner, on its own schedule, with nobody
751
+ // watching. Every one of those steps spends money from the authorising
752
+ // member's wallet.
753
+ //
754
+ // So the order is always the same: preflight for the estimate and the exact
755
+ // words of the terms, show them to the person whose wallet pays, and only
756
+ // then create with `accept_terms` carrying the `terms_version` they read.
757
+ // Money-bearing edits bump `revision`, clear the consent and stop the rule
758
+ // firing until someone accepts the new amounts.
759
+ //
760
+ // Requires `loop:write` for every mutation, including `preflightTrainingRule`:
761
+ // it is the estimate step of a create, and a key that may not create a rule
762
+ // has no reason to price one.
763
+ /**
764
+ * Price a training rule before anyone agrees to it. Writes nothing.
765
+ *
766
+ * Takes the create body without `accept_terms` and answers with the estimate
767
+ * a member has to see first: the pinned model revision, the worst hourly
768
+ * price each GPU ladder can reach, how many hours each ceiling buys, any
769
+ * refusals that would stop a create, the API keys that cannot follow a
770
+ * cutover because they lack `deployments:read`, and `terms_text` -- the
771
+ * exact sentence to show, with real figures in it.
772
+ *
773
+ * Send the `terms_version` it returns back in `createTrainingRule`. Read the
774
+ * figures out of this response rather than inventing ceilings of your own.
775
+ *
776
+ * `valid: false` with an EMPTY `refusals` list is not nothing: check
777
+ * `unreachable`, which names every peer the platform could not reach. The
778
+ * rule is savable in that state and would be paused, but the estimate around
779
+ * it is not trustworthy -- both `worst_hourly_*` are `0`, and so are both
780
+ * `max_*_hours` beside them -- so do not quote those figures to anyone.
781
+ * `model_revision` is empty unless training-service actually pinned a
782
+ * commit; test `unreachable.length > 0` to tell a degraded pass from a
783
+ * refusal.
784
+ */
785
+ async preflightTrainingRule(params) {
786
+ return this._http.fetchPost('/api/loop/training-rules/preflight', params);
787
+ }
788
+ /**
789
+ * Create a training rule and record the consent that pays for it.
790
+ *
791
+ * ACCEPTING THE TERMS AUTHORISES SPENDING FROM YOUR WALLET WHILE YOU ARE NOT
792
+ * PRESENT. From here on the platform may, on its own schedule and without
793
+ * asking again, build a training set, run a training job on rented GPUs,
794
+ * book a second deployment to compare against the one serving your traffic,
795
+ * and pay for the model calls that judge the two. Those charges come out of
796
+ * the wallet of the member whose credentials make this call, up to the
797
+ * ceilings in `money`, and they keep recurring for as long as the rule is
798
+ * enabled. If `promotion.auto_promote` is set, the platform will also
799
+ * re-point your public handle at the new model with nobody reviewing it.
800
+ *
801
+ * `accept_terms` is therefore required, and this method refuses to send the
802
+ * request without it rather than letting the server decide. Call
803
+ * {@link preflightTrainingRule} first, show the person whose wallet pays the
804
+ * `terms_text` and the figures it returns, get an explicit yes, and send the
805
+ * `terms_version` they were shown. Do not invent ceilings or price caps on
806
+ * their behalf.
807
+ *
808
+ * @example
809
+ * ```ts
810
+ * const estimate = await client.loop.preflightTrainingRule(draft);
811
+ * // show estimate.terms_text and the ceilings to the member, get a yes
812
+ * const rule = await client.loop.createTrainingRule({
813
+ * ...draft,
814
+ * accept_terms: { terms_version: estimate.terms_version },
815
+ * });
816
+ * ```
817
+ */
818
+ async createTrainingRule(params) {
819
+ // Refused here rather than on the wire: a create without a recorded
820
+ // acceptance is a request to spend somebody's money with no record that
821
+ // they agreed, and the SDK should never be the thing that sends it.
822
+ if (!params.accept_terms || !params.accept_terms.terms_version) {
823
+ throw new Error('RunBiOS: createTrainingRule requires accept_terms.terms_version. '
824
+ + 'Call preflightTrainingRule, show the member terms_text and the ceilings, '
825
+ + 'and send back the terms_version they accepted -- this rule spends from their wallet.');
826
+ }
827
+ const res = await this._http.fetchPost('/api/loop/training-rules', params);
828
+ return res.rule;
829
+ }
830
+ /**
831
+ * Every training rule in the workspace, with what each one last did and why.
832
+ *
833
+ * `last_reason` and `paused_reason` are the fields worth reading: a rule
834
+ * quiet because it is waiting looks exactly like one quiet because its
835
+ * consent went stale.
836
+ */
837
+ async listTrainingRules(params = {}) {
838
+ const q = new URLSearchParams();
839
+ if (params.enabled != null)
840
+ q.set('enabled', String(params.enabled));
841
+ if (params.limit != null)
842
+ q.set('limit', String(params.limit));
843
+ if (params.offset != null)
844
+ q.set('offset', String(params.offset));
845
+ const qs = q.toString();
846
+ return this._http.fetchGet(`/api/loop/training-rules${qs ? `?${qs}` : ''}`);
847
+ }
848
+ /**
849
+ * Read one rule with its recent runs, what it has spent this month, and how
850
+ * far its judge agrees with your own reviewers.
851
+ *
852
+ * Returned whole rather than unwrapped to the rule: `month_spent_cents` is
853
+ * the number that says whether the monthly ceiling is about to stop it.
854
+ */
855
+ async getTrainingRule(id) {
856
+ return this._http.fetchGet(`/api/loop/training-rules/${encodeURIComponent(id)}`);
857
+ }
858
+ /**
859
+ * Edit or pause a rule. Absent means unchanged; a null clears the fields
860
+ * that can be cleared.
861
+ *
862
+ * A money-bearing change -- a ceiling, a model, a GPU ladder, the promotion
863
+ * policy -- bumps `revision`, clears the recorded consent and STOPS the rule
864
+ * firing until someone accepts the new amounts. The reply says so in
865
+ * `consent_required`, and carries a fresh `preflight` with the new figures.
866
+ * Pass `expected_revision` to be refused with `REVISION_MISMATCH` rather
867
+ * than overwrite an edit somebody else made in the meantime.
868
+ */
869
+ async updateTrainingRule(id, params) {
870
+ return this._http.fetchPut(`/api/loop/training-rules/${encodeURIComponent(id)}`, params);
871
+ }
872
+ /**
873
+ * Accept the rule's current terms, so it may fire again.
874
+ *
875
+ * ACCEPTING THE TERMS AUTHORISES SPENDING FROM YOUR WALLET WHILE YOU ARE NOT
876
+ * PRESENT, on the amounts as they stand right now. This is the same
877
+ * authorisation {@link createTrainingRule} records, given again because a
878
+ * money-bearing edit cleared the old one: training, a candidate deployment
879
+ * and the judge's model calls are charged to the wallet of the member making
880
+ * this call, up to the rule's ceilings, every time it fires.
881
+ *
882
+ * Show the member the current `terms_text` from a fresh
883
+ * {@link preflightTrainingRule} or from the `preflight` on the update reply,
884
+ * and send the `revision` those figures belong to. A stale revision is
885
+ * refused with `409`, which is the point: it means the amounts moved again
886
+ * after they were read.
887
+ */
888
+ async consentTrainingRule(id, params) {
889
+ const res = await this._http.fetchPost(`/api/loop/training-rules/${encodeURIComponent(id)}/consent`, params);
890
+ return res.rule;
891
+ }
892
+ /**
893
+ * Fire a rule now, without waiting for its cadence.
894
+ *
895
+ * Bypasses the schedule and `min_new_rows` only. The row floors, the money
896
+ * ceilings and the consent all still apply, so this can answer `409
897
+ * CONSENT_REQUIRED` or `422 NOT_ENOUGH_ROWS` with the counts it needed.
898
+ */
899
+ async runTrainingRule(id) {
900
+ const res = await this._http.fetchPost(`/api/loop/training-rules/${encodeURIComponent(id)}/run`, {});
901
+ return res.run;
902
+ }
903
+ /**
904
+ * Delete a rule. An active run is cancelled; runs that already finished, and
905
+ * anything already promoted, are kept.
906
+ */
907
+ async deleteTrainingRule(id) {
908
+ return this._http.fetchDelete(`/api/loop/training-rules/${encodeURIComponent(id)}`);
909
+ }
910
+ /**
911
+ * Edit or pause a build rule -- the standing instruction that assembles the
912
+ * training set a training rule then trains on.
913
+ *
914
+ * Changing `spec.deployment_id` while an enabled training rule owns this
915
+ * build rule is refused with `409`: it would silently retrain the next model
916
+ * on a different source's conversations.
917
+ */
918
+ async updateBuildRule(id, params) {
919
+ const res = await this._http.fetchPut(`/api/loop/build-rules/${encodeURIComponent(id)}`, params);
920
+ return res.rule;
921
+ }
922
+ // ── training runs ─────────────────────────────────────────────────────
923
+ /** Firings, newest first. Filter by rule or by the state they are sitting in. */
924
+ async listTrainingRuns(params = {}) {
925
+ const q = new URLSearchParams();
926
+ if (params.rule_id)
927
+ q.set('rule_id', params.rule_id);
928
+ if (params.state)
929
+ q.set('state', params.state);
930
+ if (params.limit != null)
931
+ q.set('limit', String(params.limit));
932
+ if (params.offset != null)
933
+ q.set('offset', String(params.offset));
934
+ const qs = q.toString();
935
+ return this._http.fetchGet(`/api/loop/training-runs${qs ? `?${qs}` : ''}`);
936
+ }
937
+ /**
938
+ * One run with its timeline, the addresses of everything it created, and
939
+ * what you may do with it right now.
940
+ *
941
+ * `timeline` is written in the same transaction as each state change, so it
942
+ * is the record of what actually happened rather than a reconstruction.
943
+ * `available_actions` is the honest answer to "can I promote this": a button
944
+ * that cannot work should never be offered.
945
+ */
946
+ async getTrainingRun(id) {
947
+ return this._http.fetchGet(`/api/loop/training-runs/${encodeURIComponent(id)}`);
948
+ }
949
+ /**
950
+ * Promote the candidate by hand: re-point the public handle at the new model.
951
+ *
952
+ * This changes what answers your customers. Pass `expected_revision` to be
953
+ * refused rather than promote against a consent that moved underneath the
954
+ * decision, and `force` only to promote a comparison the evaluation called
955
+ * inconclusive -- without it that case is refused with
956
+ * `INCONCLUSIVE_REQUIRES_FORCE`.
957
+ */
958
+ async promoteTrainingRun(id, params = {}) {
959
+ return this._http.fetchPost(`/api/loop/training-runs/${encodeURIComponent(id)}/promote`, params);
960
+ }
961
+ /** Retire the candidate. What serves your traffic does not change. */
962
+ async rejectTrainingRun(id, params = {}) {
963
+ return this._http.fetchPost(`/api/loop/training-runs/${encodeURIComponent(id)}/reject`, params);
964
+ }
965
+ /**
966
+ * Undo a promotion, inside the rollback window the run reports in
967
+ * `rollback_available_until` (30 days).
968
+ *
969
+ * The reply carries `serving`: this is the one action besides promotion that
970
+ * changes what answers your traffic, so what it was put back to is returned
971
+ * rather than left to be looked up.
972
+ */
973
+ async rollbackTrainingRun(id, params = {}) {
974
+ return this._http.fetchPost(`/api/loop/training-runs/${encodeURIComponent(id)}/rollback`, params);
975
+ }
976
+ /**
977
+ * Stop a run that is still moving. Work already paid for is still billed --
978
+ * cancelling a training job does not refund the hours it burned.
979
+ */
980
+ async cancelTrainingRun(id, params = {}) {
981
+ return this._http.fetchPost(`/api/loop/training-runs/${encodeURIComponent(id)}/cancel`, params);
982
+ }
983
+ // ── the comparison report ─────────────────────────────────────────────
984
+ /**
985
+ * The comparison behind a verdict: both models on the same held-out rows,
986
+ * with identical decoding, judge and grader names resolved.
987
+ *
988
+ * Read `warnings` before you read `win_rate`. A win rate over a holdout too
989
+ * small to mean anything, or one measured by a judge that disagrees with
990
+ * your own reviewers, is reported with the warning that says so rather than
991
+ * withheld. `margin_used` is the thresholds this verdict was measured
992
+ * against, frozen with the report, so a later policy change cannot rewrite
993
+ * what a past decision meant.
994
+ */
995
+ async getEvaluation(id) {
996
+ return this._http.fetchGet(`/api/loop/evaluations/${encodeURIComponent(id)}`);
997
+ }
998
+ /**
999
+ * The paired conversations behind the numbers: one prompt, both answers, the
1000
+ * scores each earned, and which won.
1001
+ *
1002
+ * Filter by `winner` to read the losses first, which is where a verdict is
1003
+ * actually checked. `limit` is capped at 100 by the service.
1004
+ */
1005
+ async listEvaluationItems(id, params = {}) {
1006
+ const q = new URLSearchParams();
1007
+ if (params.winner)
1008
+ q.set('winner', params.winner);
1009
+ if (params.limit != null)
1010
+ q.set('limit', String(params.limit));
1011
+ if (params.offset != null)
1012
+ q.set('offset', String(params.offset));
1013
+ const qs = q.toString();
1014
+ return this._http.fetchGet(`/api/loop/evaluations/${encodeURIComponent(id)}/items${qs ? `?${qs}` : ''}`);
1015
+ }
1016
+ /**
1017
+ * How far a judge agrees with your own reviewers, over the conversations
1018
+ * both have scored.
1019
+ *
1020
+ * This is a gate, not a badge: a rule's `min_judge_agreement` refuses to
1021
+ * promote on the word of a judge that does not agree with the people whose
1022
+ * product it is. `enough_pairs` is the field to read first -- "not enough
1023
+ * reviewer overlap yet" is an answer, and 100% of two pairs is not.
1024
+ */
1025
+ async getJudgeAgreement(judgeId, params = {}) {
1026
+ const q = new URLSearchParams();
1027
+ if (params.from)
1028
+ q.set('from', params.from);
1029
+ if (params.to)
1030
+ q.set('to', params.to);
1031
+ const qs = q.toString();
1032
+ return this._http.fetchGet(`/api/loop/judges/${encodeURIComponent(judgeId)}/agreement${qs ? `?${qs}` : ''}`);
1033
+ }
1034
+ // ── the standing benchmark ────────────────────────────────────────────
1035
+ /**
1036
+ * Pin a fixed set of conversations, with a judge frozen beside them, and
1037
+ * measure every future run against it.
1038
+ *
1039
+ * The comparison answers "is this candidate better than what serves today".
1040
+ * It cannot answer "is my model getting better", because its rows, its
1041
+ * opponent and its judge all move between runs. A benchmark is the other
1042
+ * instrument: the same conversations, the same oracle, the same decoding,
1043
+ * replayed against both models on every run that finishes its comparison,
1044
+ * and reported as two absolute numbers on a scale that does not move.
1045
+ *
1046
+ * 10 to 200 conversations. A named conversation with nothing to ask a model
1047
+ * is refused rather than skipped, because pinning 47 of the 50 you chose is
1048
+ * the set being wrong from the first day and you would never find out.
1049
+ *
1050
+ * It raises no amount you have already agreed to. The replay's calls come
1051
+ * out of the rule's existing `eval_ceiling_cents`, and
1052
+ * `per_run_ceiling_cents` can only lower what is spent inside that.
1053
+ */
1054
+ async createBenchmark(params) {
1055
+ const res = await this._http.fetchPost('/api/loop/benchmarks', params);
1056
+ return res.benchmark;
1057
+ }
1058
+ /** Your benchmarks, newest first. Filter by `status` to hide retired ones. */
1059
+ async listBenchmarks(params = {}) {
1060
+ const q = new URLSearchParams();
1061
+ if (params.status)
1062
+ q.set('status', params.status);
1063
+ if (params.limit != null)
1064
+ q.set('limit', String(params.limit));
1065
+ if (params.offset != null)
1066
+ q.set('offset', String(params.offset));
1067
+ const qs = q.toString();
1068
+ return this._http.fetchGet(`/api/loop/benchmarks${qs ? `?${qs}` : ''}`);
1069
+ }
1070
+ /**
1071
+ * One benchmark: the frozen oracle, the scoring rule and the fingerprint of
1072
+ * the set.
1073
+ *
1074
+ * `items_digest` is recomputed from the rows and compared at the start of
1075
+ * every replay, so "the set cannot drift" is something you can check rather
1076
+ * than something the platform promises.
1077
+ */
1078
+ async getBenchmark(id) {
1079
+ const res = await this._http.fetchGet(`/api/loop/benchmarks/${encodeURIComponent(id)}`);
1080
+ return res.benchmark;
1081
+ }
1082
+ /**
1083
+ * The pinned conversations, paged. `limit` is capped at 100 by the service.
1084
+ *
1085
+ * `source_trace_id` and `source_trace_url` come back null once the
1086
+ * conversation a row was copied from has been deleted. The row itself stays
1087
+ * and every number already measured against it stays exactly as comparable
1088
+ * as it was: retention cannot shrink a benchmark.
1089
+ */
1090
+ async listBenchmarkItems(id, params = {}) {
1091
+ const q = new URLSearchParams();
1092
+ if (params.limit != null)
1093
+ q.set('limit', String(params.limit));
1094
+ if (params.offset != null)
1095
+ q.set('offset', String(params.offset));
1096
+ const qs = q.toString();
1097
+ return this._http.fetchGet(`/api/loop/benchmarks/${encodeURIComponent(id)}/items${qs ? `?${qs}` : ''}`);
1098
+ }
1099
+ /**
1100
+ * The trend: every score this benchmark has produced, newest first, each
1101
+ * beside the checkpoint that produced it and what you then did about it.
1102
+ *
1103
+ * EVERY REPLAY IS A POINT, including the ones with no numbers on them. A
1104
+ * series that silently dropped the runs where the benchmark could not be
1105
+ * scored would read as an unbroken line and not be one, so those points come
1106
+ * back with `candidate_score` null and `status_reason` saying why.
1107
+ */
1108
+ async getBenchmarkHistory(id, params = {}) {
1109
+ const q = new URLSearchParams();
1110
+ if (params.limit != null)
1111
+ q.set('limit', String(params.limit));
1112
+ if (params.offset != null)
1113
+ q.set('offset', String(params.offset));
1114
+ const qs = q.toString();
1115
+ return this._http.fetchGet(`/api/loop/benchmarks/${encodeURIComponent(id)}/history${qs ? `?${qs}` : ''}`);
1116
+ }
1117
+ /**
1118
+ * Stop replaying a benchmark, and detach it from every rule that names it.
1119
+ *
1120
+ * Nothing measured is removed. There is no delete and no update on purpose:
1121
+ * the series of numbers measured against a set is what a benchmark is for,
1122
+ * so an edit would make everything before it incomparable with everything
1123
+ * after it and a delete would throw the series away. Changing the set means
1124
+ * pinning a new benchmark, and retiring the old one releases its name.
1125
+ *
1126
+ * Retiring twice is somebody pressing a button twice: the second call
1127
+ * answers with the retired benchmark rather than a refusal.
1128
+ */
1129
+ async retireBenchmark(id, params = {}) {
1130
+ const res = await this._http.fetchPost(`/api/loop/benchmarks/${encodeURIComponent(id)}/retire`, params);
1131
+ return res.benchmark;
1132
+ }
1133
+ /**
1134
+ * One replay in full: both absolute scores, the difference between them on
1135
+ * the same set, the per-dimension breakdown and what it cost.
1136
+ *
1137
+ * Read `status` before you read the scores. A replay that did not score
1138
+ * every pinned conversation publishes no score at all -- all three of
1139
+ * `candidate_score`, `incumbent_score` and `score_delta` are null and
1140
+ * `status_reason` is the sentence that explains it -- because a mean over
1141
+ * whichever conversations happened to succeed is a measurement of a
1142
+ * different set, which is the exact defect a standing benchmark removes.
1143
+ */
1144
+ async getBenchmarkRun(id) {
1145
+ const res = await this._http.fetchGet(`/api/loop/benchmark-runs/${encodeURIComponent(id)}`);
1146
+ return res.benchmark_run;
1147
+ }
1148
+ /**
1149
+ * Attach a benchmark to a rule, or send `{ benchmark_id: null }` to detach
1150
+ * it.
1151
+ *
1152
+ * Its own route rather than a field on the rule body, because it is a
1153
+ * decision to replay a fixed set on every future run of this rule for as
1154
+ * long as it stands, and its refusals -- retired, or belonging to another
1155
+ * workspace -- are about the benchmark rather than about the rule.
1156
+ *
1157
+ * It does not invalidate consent and the reply says so: attaching raises
1158
+ * neither the amount set aside for judge calls nor the amount set aside for
1159
+ * keeping the new model available, so nobody is asked to read the same
1160
+ * sentence again. A retired benchmark is refused with `BENCHMARK_RETIRED`,
1161
+ * because a rule pointed at one would report no number on every run and say
1162
+ * nothing about why.
1163
+ */
1164
+ async setTrainingRuleBenchmark(id, params) {
1165
+ return this._http.fetchPut(`/api/loop/training-rules/${encodeURIComponent(id)}/benchmark`, params);
1166
+ }
1167
+ // ── agent settings ────────────────────────────────────────────────────
1168
+ /**
1169
+ * The workspace's agent options: which model it defaults to, the system
1170
+ * prompts it judges and samples with, and the monthly cap on what its model
1171
+ * calls may spend.
1172
+ */
1173
+ async getAgentSettings() {
1174
+ const res = await this._http.fetchGet('/api/loop/agent/settings');
1175
+ return res.settings;
1176
+ }
1177
+ /**
1178
+ * Change them. An absent key leaves that setting exactly where it is; a
1179
+ * present null returns it to the platform default. Those are three
1180
+ * instructions, not two, so `{}` changes nothing.
1181
+ *
1182
+ * `eval_monthly_cap_cents` is pushed to the workspace's managed key, so it
1183
+ * caps what the agent can spend even if a rule's own ceilings are higher.
1184
+ */
1185
+ async updateAgentSettings(params) {
1186
+ const res = await this._http.fetchPut('/api/loop/agent/settings', params);
1187
+ return res.settings;
1188
+ }
1189
+ }