@orkestrel/study 0.0.0-stage → 0.0.1

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,2066 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _orkestrel_contract = require("@orkestrel/contract");
3
+ let _orkestrel_timeout = require("@orkestrel/timeout");
4
+ let _orkestrel_budget = require("@orkestrel/budget");
5
+ let _orkestrel_abort = require("@orkestrel/abort");
6
+ //#region src/core/constants.ts
7
+ /**
8
+ * Keys the own self-identity every study error stamps on itself.
9
+ * @remarks
10
+ * The global symbol registry lets every package, ESM, CommonJS and captured copy read the same
11
+ * key. The registry makes the key discoverable; it is a recognition mechanism, not an
12
+ * unforgeable provenance marker.
13
+ */
14
+ var STUDY_ERROR_BRAND = Symbol.for("@orkestrel/study.error");
15
+ /** Caps a declared trial population before schedule allocation. */
16
+ var STUDY_TRIALS = 4096;
17
+ /** Caps a declared scenario horizon before execution. */
18
+ var STUDY_GOALS = 4096;
19
+ /** Restricts identifiers to portable path-safe names. */
20
+ var STUDY_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
21
+ /** Lists every measured request role in report order. */
22
+ var STUDY_ROLES = Object.freeze([
23
+ "agent",
24
+ "judge",
25
+ "summary",
26
+ "metadata",
27
+ "tool"
28
+ ]);
29
+ /** Lists every ceiling a run can stop at in report order. */
30
+ var STUDY_LAYERS = Object.freeze([
31
+ "scope",
32
+ "window",
33
+ "custody",
34
+ "meter",
35
+ "budget",
36
+ "model"
37
+ ]);
38
+ /** Lists every operational ending in report order. */
39
+ var STUDY_CAUSES = Object.freeze([
40
+ "capacity",
41
+ "infrastructure",
42
+ "deadline",
43
+ "interrupted",
44
+ "content"
45
+ ]);
46
+ //#endregion
47
+ //#region src/core/helpers.ts
48
+ /**
49
+ * Copies the own entries of a record that hold a value, in their original order.
50
+ * @param value - The record whose undefined entries are absent declarations
51
+ * @returns A new record without the undefined entries
52
+ * @example
53
+ * ```ts
54
+ * omitStudyAbsent({ context: 512, recap: undefined }) // { context: 512 }
55
+ * ```
56
+ */
57
+ function omitStudyAbsent(value) {
58
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0));
59
+ }
60
+ /**
61
+ * Omits every undefined optional declaration so the profile has one JSON form.
62
+ * @param profile - The validated profile whose optional leaves may be undefined
63
+ * @returns The profile fields with absent qualification, settings, provider, judge and recap removed
64
+ * @example
65
+ * ```ts
66
+ * normalizeStudyProfile(profile) // no `recap` key when the room declares none
67
+ * ```
68
+ */
69
+ function normalizeStudyProfile(profile) {
70
+ const { provider, qualification, settings, room, ...required } = profile;
71
+ return {
72
+ ...required,
73
+ room: omitStudyAbsent(room),
74
+ ...provider === void 0 ? {} : { provider: {
75
+ ...omitStudyAbsent(provider),
76
+ digest: omitStudyAbsent(provider.digest)
77
+ } },
78
+ ...qualification === void 0 ? {} : { qualification },
79
+ ...settings === void 0 ? {} : { settings }
80
+ };
81
+ }
82
+ /**
83
+ * Projects a stop onto JSON with every unreported reading as null.
84
+ * @param stop - The ceiling that stopped a run
85
+ * @returns The stop's layer, id, and readings, with an undefined `max` or `consumed` as null
86
+ * @example
87
+ * ```ts
88
+ * studyStopToJSON({ layer: 'model', id: 'num_predict', max: 2048, consumed: undefined })
89
+ * // { layer: 'model', id: 'num_predict', max: 2048, consumed: null }
90
+ * ```
91
+ */
92
+ function studyStopToJSON(stop) {
93
+ return {
94
+ layer: stop.layer,
95
+ id: stop.id,
96
+ max: stop.max ?? null,
97
+ consumed: stop.consumed ?? null
98
+ };
99
+ }
100
+ /**
101
+ * Matches exact own enumerable data keys without evaluating accessors.
102
+ * @param value - The candidate record
103
+ * @param required - Required keys
104
+ * @param optional - Allowed optional keys
105
+ * @returns True if the record has exactly the allowed data keys; false otherwise
106
+ * @example Check exact keys
107
+ * ```ts
108
+ * import { matchesStudyKeys } from '@orkestrel/study'
109
+ *
110
+ * matchesStudyKeys({ id: 'one' }, ['id']) // true
111
+ * ```
112
+ */
113
+ function matchesStudyKeys(value, required, optional = []) {
114
+ return (0, _orkestrel_contract.holds)(() => {
115
+ if (!(0, _orkestrel_contract.isRecord)(value)) return false;
116
+ const keys = Reflect.ownKeys(value);
117
+ return required.every((key) => Object.hasOwn(value, key)) && keys.every((key) => {
118
+ if (typeof key !== "string" || !required.includes(key) && !optional.includes(key)) return false;
119
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
120
+ return descriptor !== void 0 && descriptor.enumerable === true && Object.hasOwn(descriptor, "value");
121
+ });
122
+ });
123
+ }
124
+ /**
125
+ * Builds a bounded schedule from explicit repetition rows and declared scenarios.
126
+ * @param definition - The frozen population declaration
127
+ * @param scenarios - The complete scenario declarations
128
+ * @returns Owned trials in repetition, scenario and row-arm order
129
+ * @throws StudyError - Thrown when the population or scenario set is invalid
130
+ * @example
131
+ * ```ts
132
+ * buildStudySchedule(definition, scenarios)
133
+ * ```
134
+ */
135
+ function buildStudySchedule(definition, scenarios) {
136
+ if (!isStudyDefinition(definition) || !scenarios.every(isStudyScenario)) throw new StudyError("CONFIG", "Invalid study population");
137
+ const ids = new Set(scenarios.map((scenario) => scenario.id));
138
+ if (ids.size !== scenarios.length || ids.size !== definition.scenarios.length || !definition.scenarios.every((id) => ids.has(id))) throw new StudyError("CONFIG", "Scenario declarations must match the population exactly");
139
+ return Object.freeze([...definition.order.entries()].flatMap(([repetition, row]) => [...definition.scenarios.entries()].flatMap(([scenario, id]) => row.map((arm) => Object.freeze({
140
+ id: `r${repetition + 1}-s${scenario + 1}-a${definition.arms.indexOf(arm) + 1}`,
141
+ scenario: id,
142
+ arm,
143
+ repetition
144
+ })))));
145
+ }
146
+ /**
147
+ * Validates grading coverage and request room against the declared study inputs.
148
+ * @param definition - The population declaration
149
+ * @param scenarios - The complete scenario declarations
150
+ * @param rubric - The independently held grading declaration
151
+ * @param profile - The execution bounds and model room
152
+ * @returns Nothing when every cross-input invariant holds
153
+ * @throws StudyError - Thrown when any input or cross-reference is invalid
154
+ * @example
155
+ * ```ts
156
+ * validateStudyInputs(definition, scenarios, rubric, profile)
157
+ * ```
158
+ */
159
+ function validateStudyInputs(definition, scenarios, rubric, profile) {
160
+ buildStudySchedule(definition, scenarios);
161
+ if (!isStudyRubric(rubric) || !isStudyProfile(profile)) throw new StudyError("CONFIG", "Invalid rubric or profile");
162
+ if (profile.bounds.request.tokens > profile.room.context - profile.room.safety || profile.room.output > profile.bounds.request.tokens) throw new StudyError("CONFIG", "Request allowance does not fit the model room");
163
+ for (const criterion of rubric.criteria) {
164
+ const scenario = scenarios.find((entry) => entry.id === criterion.scenario);
165
+ if (scenario === void 0 || !scenario.goals.some((goal) => goal.id === criterion.goal)) throw new StudyError("CONFIG", "Criterion references an undeclared goal");
166
+ if (definition.purpose === "mechanism" && criterion.method === "semantic") throw new StudyError("CONFIG", "Mechanism studies cannot establish semantic quality");
167
+ }
168
+ const covered = new Set(rubric.criteria.map((criterion) => (0, _orkestrel_contract.canonicalStringify)([criterion.scenario, criterion.goal]) ?? ""));
169
+ for (const scenario of scenarios) for (const goal of scenario.goals) if (!covered.has((0, _orkestrel_contract.canonicalStringify)([scenario.id, goal.id]) ?? "")) throw new StudyError("CONFIG", "Every declared goal needs a criterion");
170
+ }
171
+ /**
172
+ * Computes arm intervals over the complete declared criterion horizon.
173
+ * @param manifest - The sealed population and schedule
174
+ * @param rubric - The criterion declaration
175
+ * @param grading - Judgments bound to the complete scheduled attempt set
176
+ * @returns Whole-horizon scores in declared arm order
177
+ * @throws StudyError - Thrown when schedule, attempts or judgments are incompatible
178
+ * @example
179
+ * ```ts
180
+ * computeStudyScores(manifest, rubric, grading)
181
+ * ```
182
+ */
183
+ function computeStudyScores(manifest, rubric, grading) {
184
+ if (!isStudyRubric(rubric) || !isStudyGrading(grading)) throw new StudyError("EVIDENCE", "Invalid rubric or grading");
185
+ const expected = buildStudySchedule(manifest.definition, manifest.scenarios);
186
+ if ((0, _orkestrel_contract.canonicalStringify)(expected) !== (0, _orkestrel_contract.canonicalStringify)(manifest.schedule)) throw new StudyError("EVIDENCE", "Manifest schedule differs from the declared population");
187
+ const trials = new Map(expected.map((trial) => [trial.id, trial]));
188
+ if (grading.attempts.length !== expected.length || !grading.attempts.every((id) => trials.has(id))) throw new StudyError("EVIDENCE", "Grading attempts differ from the declared schedule");
189
+ const criteria = new Map(rubric.criteria.map((criterion) => [criterion.id, criterion]));
190
+ for (const scenario of manifest.scenarios) for (const goal of scenario.goals) if (!rubric.criteria.some((criterion) => criterion.scenario === scenario.id && criterion.goal === goal.id)) throw new StudyError("EVIDENCE", "Rubric omits a declared goal");
191
+ for (const criterion of rubric.criteria) if (!manifest.scenarios.some((scenario) => scenario.id === criterion.scenario && scenario.goals.some((goal) => goal.id === criterion.goal)) || manifest.definition.purpose === "mechanism" && criterion.method === "semantic") throw new StudyError("EVIDENCE", "Criterion is incompatible with the study");
192
+ const keyed = grading.judgments.map((judgment) => ({
193
+ judgment,
194
+ key: (0, _orkestrel_contract.canonicalStringify)([judgment.trial, judgment.criterion]) ?? ""
195
+ }));
196
+ const firsts = new Map([...keyed.entries()].reverse().map(([index, { key }]) => [key, index]));
197
+ for (const [index, { judgment, key }] of keyed.entries()) {
198
+ const trial = trials.get(judgment.trial);
199
+ const criterion = criteria.get(judgment.criterion);
200
+ if (trial === void 0 || criterion === void 0 || criterion.scenario !== trial.scenario || firsts.get(key) !== index) throw new StudyError("EVIDENCE", "Duplicate or foreign trial criterion judgment");
201
+ if (criterion.method === "semantic" ? judgment.method !== "human" && judgment.method !== "model" : judgment.method !== criterion.method) throw new StudyError("EVIDENCE", "Judgment method differs from the criterion");
202
+ }
203
+ const judgments = new Map(keyed.map(({ key, judgment }) => [key, judgment]));
204
+ return Object.freeze(manifest.definition.arms.map((arm) => {
205
+ const pairs = expected.filter((trial) => trial.arm === arm).flatMap((trial) => rubric.criteria.filter((criterion) => criterion.scenario === trial.scenario).map((criterion) => ({
206
+ criterion,
207
+ judgment: judgments.get((0, _orkestrel_contract.canonicalStringify)([trial.id, criterion.id]) ?? "")
208
+ })));
209
+ const refuted = pairs.filter(({ judgment }) => judgment?.verdict === "unsuccessful");
210
+ const total = pairs.length;
211
+ const achieved = pairs.filter(({ judgment }) => judgment?.verdict === "achieved").length;
212
+ const unsuccessful = refuted.length;
213
+ const critical = refuted.filter(({ criterion }) => criterion.critical).length;
214
+ const unknown = total - achieved - unsuccessful;
215
+ return Object.freeze({
216
+ arm,
217
+ total,
218
+ achieved,
219
+ unsuccessful,
220
+ unknown,
221
+ critical,
222
+ lower: achieved / total,
223
+ upper: (achieved + unknown) / total,
224
+ coverage: (achieved + unsuccessful) / total
225
+ });
226
+ }));
227
+ }
228
+ //#endregion
229
+ //#region src/core/validators.ts
230
+ /** Checks whether a value names a measured request role. */
231
+ var isStudyRole = (0, _orkestrel_contract.literalOf)(STUDY_ROLES);
232
+ /** Checks whether a value names an operational ending. */
233
+ var isStudyCause = (0, _orkestrel_contract.literalOf)(STUDY_CAUSES);
234
+ /** Checks whether a value names a ceiling a run can stop at. */
235
+ var isStudyLayer = (0, _orkestrel_contract.literalOf)(STUDY_LAYERS);
236
+ /**
237
+ * Checks whether a value is the exact record of a ceiling that stopped a run.
238
+ * @remarks
239
+ * The guard accepts exact own data keys: `layer` and `id` are required and `max` and `consumed` are
240
+ * optional. `max` and `consumed` are each undefined or a finite number. Finite foreign readings,
241
+ * including negative and fractional values, retain the source's measurement unchanged.
242
+ * @param value - The candidate stop
243
+ * @returns True if the layer is known, the id is nonempty, and every reading is absent or finite; false otherwise
244
+ * @example
245
+ * ```ts
246
+ * isStudyStop({ layer: 'scope', id: 'Goal tokens', max: 100, consumed: 120 }) // true
247
+ * ```
248
+ */
249
+ function isStudyStop(value) {
250
+ return (0, _orkestrel_contract.holds)(() => (0, _orkestrel_contract.isRecord)(value) && matchesStudyKeys(value, ["layer", "id"], ["max", "consumed"]) && isStudyLayer(value.layer) && (0, _orkestrel_contract.isNonEmptyString)(value.id) && ["max", "consumed"].every((key) => value[key] === void 0 || (0, _orkestrel_contract.isFiniteNumber)(value[key])));
251
+ }
252
+ /**
253
+ * Checks whether an identifier is portable and bounded.
254
+ * @param value - The candidate identifier
255
+ * @returns True if it is a portable study identifier; false otherwise
256
+ * @example
257
+ * ```ts
258
+ * isStudyName('memory') // true
259
+ * ```
260
+ */
261
+ function isStudyName(value) {
262
+ return typeof value === "string" && value.length <= 128 && STUDY_NAME.test(value);
263
+ }
264
+ /**
265
+ * Checks whether all allowances are positive safe integers within timer bounds.
266
+ * @param value - The candidate limit
267
+ * @returns True if it defines finite positive allowances; false otherwise
268
+ * @example
269
+ * ```ts
270
+ * isStudyLimit({ duration: 1000, calls: 1, tokens: 100, bytes: 1024 }) // true
271
+ * ```
272
+ */
273
+ function isStudyLimit(value) {
274
+ return (0, _orkestrel_contract.holds)(() => {
275
+ if (!(0, _orkestrel_contract.isRecord)(value) || !matchesStudyKeys(value, [
276
+ "duration",
277
+ "calls",
278
+ "tokens",
279
+ "bytes"
280
+ ])) return false;
281
+ return [
282
+ "duration",
283
+ "calls",
284
+ "tokens",
285
+ "bytes"
286
+ ].every((key) => typeof value[key] === "number" && Number.isSafeInteger(value[key]) && value[key] > 0) && typeof value.duration === "number" && value.duration <= _orkestrel_timeout.MAX_TIMEOUT_MS;
287
+ });
288
+ }
289
+ /**
290
+ * Checks whether nested scopes admit no larger allowance than their parent.
291
+ * @param value - The candidate bounds
292
+ * @returns True if every nested allowance is ordered; false otherwise
293
+ * @example
294
+ * ```ts
295
+ * isStudyBounds({}) // false
296
+ * ```
297
+ */
298
+ function isStudyBounds(value) {
299
+ return (0, _orkestrel_contract.holds)(() => {
300
+ if (!(0, _orkestrel_contract.isRecord)(value) || !matchesStudyKeys(value, [
301
+ "request",
302
+ "goal",
303
+ "trial",
304
+ "series"
305
+ ]) || !isStudyLimit(value.request) || !isStudyLimit(value.goal) || !isStudyLimit(value.trial) || !isStudyLimit(value.series)) return false;
306
+ const limits = [
307
+ value.request,
308
+ value.goal,
309
+ value.trial,
310
+ value.series
311
+ ];
312
+ for (const [index, limit] of limits.entries()) {
313
+ const next = limits[index + 1];
314
+ if (next === void 0) continue;
315
+ if (limit.duration > next.duration || limit.calls > next.calls || limit.tokens > next.tokens || limit.bytes > next.bytes) return false;
316
+ }
317
+ return value.request.calls === 1;
318
+ });
319
+ }
320
+ /**
321
+ * Checks whether a goal has a bounded identifier and exact JSON input.
322
+ * @param value - The candidate goal
323
+ * @returns True if the goal is valid; false otherwise
324
+ * @example
325
+ * ```ts
326
+ * isStudyGoal({ id: 'write', input: { text: 'hello' } }) // true
327
+ * ```
328
+ */
329
+ function isStudyGoal(value) {
330
+ return (0, _orkestrel_contract.holds)(() => {
331
+ return (0, _orkestrel_contract.isRecord)(value) && matchesStudyKeys(value, ["id", "input"]) && isStudyName(value.id) && (0, _orkestrel_contract.isJSONValue)(value.input);
332
+ });
333
+ }
334
+ /**
335
+ * Checks whether a scenario declares a nonempty horizon with unique goal ids.
336
+ * @param value - The candidate scenario
337
+ * @returns True if the scenario has a valid horizon; false otherwise
338
+ * @example
339
+ * ```ts
340
+ * isStudyScenario({ id: 'shift', goals: [{ id: 'handoff', input: 'Prepare handoff' }] }) // true
341
+ * ```
342
+ */
343
+ function isStudyScenario(value) {
344
+ return (0, _orkestrel_contract.holds)(() => {
345
+ if (!(0, _orkestrel_contract.isRecord)(value) || !matchesStudyKeys(value, ["id", "goals"]) || !isStudyName(value.id) || !(0, _orkestrel_contract.isArray)(value.goals)) return false;
346
+ return value.goals.length > 0 && value.goals.length <= 4096 && value.goals.every(isStudyGoal) && new Set(value.goals.map((goal) => goal.id)).size === value.goals.length && (0, _orkestrel_contract.isJSONValue)(value.goals);
347
+ });
348
+ }
349
+ /**
350
+ * Checks whether a study freezes a complete arm order for every repetition.
351
+ * @param value - The candidate definition
352
+ * @returns True if its population and repetition orders are valid; false otherwise
353
+ * @example
354
+ * ```ts
355
+ * isStudyDefinition({ name: 'tools' }) // false
356
+ * ```
357
+ */
358
+ function isStudyDefinition(value) {
359
+ return (0, _orkestrel_contract.holds)(() => {
360
+ if (!(0, _orkestrel_contract.isRecord)(value) || !(0, _orkestrel_contract.isJSONValue)(value) || !matchesStudyKeys(value, [
361
+ "name",
362
+ "version",
363
+ "question",
364
+ "purpose",
365
+ "driver",
366
+ "arms",
367
+ "scenarios",
368
+ "order",
369
+ "retries",
370
+ "rubric"
371
+ ]) || !isStudyName(value.name) || !isStudyName(value.driver) || !(0, _orkestrel_contract.isNonEmptyString)(value.version) || !(0, _orkestrel_contract.isNonEmptyString)(value.question) || value.purpose !== "mechanism" && value.purpose !== "quality" && value.purpose !== "capacity" || !(0, _orkestrel_contract.isArray)(value.arms) || value.arms.length === 0 || !value.arms.every(isStudyName) || new Set(value.arms).size !== value.arms.length || !(0, _orkestrel_contract.isArray)(value.scenarios) || value.scenarios.length === 0 || !value.scenarios.every(isStudyName) || new Set(value.scenarios).size !== value.scenarios.length || !(0, _orkestrel_contract.isArray)(value.order) || !(0, _orkestrel_contract.isJSONValue)(value.order) || value.order.length === 0 || value.retries !== 0 || !(0, _orkestrel_contract.isNonEmptyString)(value.rubric)) return false;
372
+ const arms = value.arms;
373
+ if (arms.length * value.scenarios.length * value.order.length > 4096) return false;
374
+ return value.order.every((order) => (0, _orkestrel_contract.isArray)(order) && order.length === arms.length && new Set(order).size === arms.length && order.every((arm) => typeof arm === "string" && arms.includes(arm)));
375
+ });
376
+ }
377
+ /**
378
+ * Checks whether generation room leaves positive context for input.
379
+ * @param value - The candidate room
380
+ * @returns True if input, output and safety allowances fit and any declared recap fits; false otherwise
381
+ * @example
382
+ * ```ts
383
+ * isStudyRoom({ context: 20480, output: 8192, safety: 512, recap: 2048, think: true }) // true
384
+ * isStudyRoom({ context: 20480, output: 8192, safety: 512, think: true }) // true
385
+ * ```
386
+ */
387
+ function isStudyRoom(value) {
388
+ return (0, _orkestrel_contract.holds)(() => {
389
+ if (!(0, _orkestrel_contract.isRecord)(value) || !matchesStudyKeys(value, [
390
+ "context",
391
+ "output",
392
+ "safety",
393
+ "think"
394
+ ], ["recap"]) || typeof value.think !== "boolean") return false;
395
+ if (![
396
+ "context",
397
+ "output",
398
+ "safety",
399
+ ...value.recap === void 0 ? [] : ["recap"]
400
+ ].every((key) => typeof value[key] === "number" && Number.isSafeInteger(value[key]) && value[key] > 0)) return false;
401
+ return typeof value.context === "number" && typeof value.output === "number" && typeof value.safety === "number" && value.output + value.safety < value.context && (value.recap === void 0 || typeof value.recap === "number" && value.recap + value.safety < value.context);
402
+ });
403
+ }
404
+ /**
405
+ * Checks whether a provider declaration names artifacts, an HTTP origin and models.
406
+ * @param value - The candidate provider declaration
407
+ * @returns True if the declaration has a supported origin, nonempty names, and a judge declared with its digest or not at all; false otherwise
408
+ * @example
409
+ * ```ts
410
+ * isStudyProvider({ entry: 'dist/index.js' }) // false
411
+ * ```
412
+ */
413
+ function isStudyProvider(value) {
414
+ return (0, _orkestrel_contract.holds)(() => {
415
+ if (!(0, _orkestrel_contract.isRecord)(value) || !matchesStudyKeys(value, [
416
+ "entry",
417
+ "url",
418
+ "model",
419
+ "digest"
420
+ ], ["judge"]) || ![
421
+ "entry",
422
+ "url",
423
+ "model"
424
+ ].every((key) => (0, _orkestrel_contract.isNonEmptyString)(value[key])) || typeof value.url !== "string" || !(0, _orkestrel_contract.isRecord)(value.digest) || !matchesStudyKeys(value.digest, ["model"], ["judge"]) || !isStudyDigest(value.digest.model) || value.judge === void 0 !== (value.digest.judge === void 0) || value.judge !== void 0 && (!(0, _orkestrel_contract.isNonEmptyString)(value.judge) || !isStudyDigest(value.digest.judge))) return false;
425
+ const url = new URL(value.url);
426
+ return ["http:", "https:"].includes(url.protocol) && url.username === "" && url.password === "" && url.search === "" && url.hash === "" && url.pathname === "/";
427
+ });
428
+ }
429
+ /**
430
+ * Checks whether a profile carries finite bounds and an optional explicit provider.
431
+ * @param value - The candidate profile
432
+ * @returns True if the profile is structurally valid; false otherwise
433
+ * @example
434
+ * ```ts
435
+ * isStudyProfile({ name: 'local' }) // false
436
+ * ```
437
+ */
438
+ function isStudyProfile(value) {
439
+ return (0, _orkestrel_contract.holds)(() => {
440
+ return (0, _orkestrel_contract.isRecord)(value) && matchesStudyKeys(value, [
441
+ "name",
442
+ "agent",
443
+ "subject",
444
+ "roots",
445
+ "bounds",
446
+ "room"
447
+ ], [
448
+ "provider",
449
+ "qualification",
450
+ "settings"
451
+ ]) && isStudyName(value.name) && (0, _orkestrel_contract.isNonEmptyString)(value.agent) && (0, _orkestrel_contract.isArray)(value.roots) && (0, _orkestrel_contract.isJSONValue)(value.roots) && value.roots.length > 0 && value.roots.every((root) => typeof root === "string" && root.trim().length > 0) && new Set(value.roots).size === value.roots.length && (0, _orkestrel_contract.isNonEmptyString)(value.subject) && isStudyBounds(value.bounds) && isStudyRoom(value.room) && (value.provider === void 0 || isStudyProvider(value.provider)) && (value.qualification === void 0 || (0, _orkestrel_contract.isNonEmptyString)(value.qualification)) && (value.settings === void 0 || (0, _orkestrel_contract.isRecord)(value.settings) && (0, _orkestrel_contract.isJSONValue)(value.settings));
452
+ });
453
+ }
454
+ /**
455
+ * Checks whether a byte identity is a lowercase SHA-256 digest.
456
+ * @param value - The candidate identity
457
+ * @returns True if it has exactly 64 hexadecimal digits; false otherwise
458
+ * @example
459
+ * ```ts
460
+ * isStudyDigest('a'.repeat(64)) // true
461
+ * ```
462
+ */
463
+ function isStudyDigest(value) {
464
+ return typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
465
+ }
466
+ /**
467
+ * Checks whether a timestamp is a canonical UTC millisecond instant.
468
+ * @param value - The candidate timestamp
469
+ * @returns True if it is a valid canonical timestamp; false otherwise
470
+ * @example
471
+ * ```ts
472
+ * isStudyTimestamp('2026-10-14T12:00:00.000Z') // true
473
+ * ```
474
+ */
475
+ function isStudyTimestamp(value) {
476
+ return (0, _orkestrel_contract.holds)(() => {
477
+ return typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value) && new Date(value).toISOString() === value;
478
+ });
479
+ }
480
+ /**
481
+ * Checks whether request usage contains nonnegative safe measurements.
482
+ * @param value - The candidate usage
483
+ * @returns True if the role and every known measurement are valid; false otherwise
484
+ * @example
485
+ * ```ts
486
+ * isStudyUsage({ role: 'tool', calls: 0, bytes: 0, duration: 0 }) // true
487
+ * ```
488
+ */
489
+ function isStudyUsage(value) {
490
+ return (0, _orkestrel_contract.holds)(() => {
491
+ return (0, _orkestrel_contract.isRecord)(value) && matchesStudyKeys(value, [
492
+ "role",
493
+ "calls",
494
+ "duration"
495
+ ], ["tokens", "bytes"]) && isStudyRole(value.role) && ["calls", "duration"].every((key) => typeof value[key] === "number" && Number.isSafeInteger(value[key]) && value[key] >= 0) && (value.bytes === void 0 || typeof value.bytes === "number" && Number.isSafeInteger(value.bytes) && value.bytes >= 0) && (value.tokens === void 0 || typeof value.tokens === "number" && Number.isSafeInteger(value.tokens) && value.tokens >= 0);
496
+ });
497
+ }
498
+ /**
499
+ * Checks a retained public product without awarding task achievement.
500
+ * @param value - The candidate product
501
+ * @returns True if the product carries JSON output and partial status; false otherwise
502
+ * @example
503
+ * ```ts
504
+ * isStudyProduct({ value: { answer: 1 }, partial: true }) // true
505
+ * ```
506
+ */
507
+ function isStudyProduct(value) {
508
+ return (0, _orkestrel_contract.holds)(() => (0, _orkestrel_contract.isRecord)(value) && typeof value.partial === "boolean" && (0, _orkestrel_contract.isJSONValue)(value.value));
509
+ }
510
+ /**
511
+ * Checks whether a criterion declares exact grading inputs and references.
512
+ * @param value - The candidate criterion
513
+ * @returns True if its structural grading declaration is valid; false otherwise
514
+ * @example
515
+ * ```ts
516
+ * isStudyCriterion({ id: 'saved', scenario: 'shift', goal: 'write', method: 'state', critical: true, assertion: true }) // true
517
+ * ```
518
+ */
519
+ function isStudyCriterion(value) {
520
+ return (0, _orkestrel_contract.holds)(() => {
521
+ return (0, _orkestrel_contract.isRecord)(value) && matchesStudyKeys(value, [
522
+ "id",
523
+ "scenario",
524
+ "goal",
525
+ "method",
526
+ "critical",
527
+ "assertion"
528
+ ]) && isStudyName(value.id) && isStudyName(value.scenario) && isStudyName(value.goal) && (value.method === "state" || value.method === "trace" || value.method === "semantic") && typeof value.critical === "boolean" && (0, _orkestrel_contract.isJSONValue)(value.assertion);
529
+ });
530
+ }
531
+ /**
532
+ * Checks whether a rubric declares nonempty criteria with unique identities.
533
+ * @param value - The candidate rubric
534
+ * @returns True if its version and criteria are valid; false otherwise
535
+ * @example
536
+ * ```ts
537
+ * isStudyRubric({ version: '1', criteria: [] }) // false
538
+ * ```
539
+ */
540
+ function isStudyRubric(value) {
541
+ return (0, _orkestrel_contract.holds)(() => {
542
+ return (0, _orkestrel_contract.isRecord)(value) && matchesStudyKeys(value, ["version", "criteria"]) && typeof value.version === "string" && value.version.trim().length > 0 && (0, _orkestrel_contract.isArray)(value.criteria) && value.criteria.length > 0 && value.criteria.every(isStudyCriterion) && new Set(value.criteria.map((criterion) => criterion.id)).size === value.criteria.length && (0, _orkestrel_contract.isJSONValue)(value.criteria);
543
+ });
544
+ }
545
+ /**
546
+ * Checks whether a judgment carries a supported verdict and evidence references.
547
+ * @param value - The candidate judgment
548
+ * @returns True if the judgment is attributable and structurally valid; false otherwise
549
+ * @example
550
+ * ```ts
551
+ * isStudyJudgment({ trial: 'r1-s1-a1', criterion: 'saved', verdict: 'unknown', method: 'state', reason: 'No evidence', references: [] }) // true
552
+ * ```
553
+ */
554
+ function isStudyJudgment(value) {
555
+ return (0, _orkestrel_contract.holds)(() => {
556
+ return (0, _orkestrel_contract.isRecord)(value) && matchesStudyKeys(value, [
557
+ "trial",
558
+ "criterion",
559
+ "verdict",
560
+ "method",
561
+ "reason",
562
+ "references"
563
+ ]) && isStudyName(value.trial) && isStudyName(value.criterion) && (value.verdict === "achieved" || value.verdict === "unsuccessful" || value.verdict === "unknown") && (value.method === "state" || value.method === "trace" || value.method === "human" || value.method === "model") && typeof value.reason === "string" && value.reason.trim().length > 0 && (0, _orkestrel_contract.isArray)(value.references) && (0, _orkestrel_contract.isJSONValue)(value.references) && value.references.every((reference) => typeof reference === "string" && reference.trim().length > 0) && new Set(value.references).size === value.references.length && (value.verdict === "unknown" || value.references.length > 0);
564
+ });
565
+ }
566
+ /**
567
+ * Checks whether imported semantic labels have accountable packet provenance.
568
+ * @param value - The candidate labels
569
+ * @returns True if provenance, usage and semantic judgments are valid; false otherwise
570
+ * @example
571
+ * ```ts
572
+ * isStudyLabeling({}) // false
573
+ * ```
574
+ */
575
+ function isStudyLabeling(value) {
576
+ return (0, _orkestrel_contract.holds)(() => {
577
+ return (0, _orkestrel_contract.isRecord)(value) && matchesStudyKeys(value, [
578
+ "packet",
579
+ "labeler",
580
+ "version",
581
+ "created",
582
+ "usage",
583
+ "judgments"
584
+ ]) && isStudyDigest(value.packet) && typeof value.labeler === "string" && value.labeler.trim().length > 0 && typeof value.version === "string" && value.version.trim().length > 0 && isStudyTimestamp(value.created) && (0, _orkestrel_contract.isArray)(value.usage) && Reflect.ownKeys(value.usage).length === value.usage.length + 1 && Array.from(value.usage).every(isStudyUsage) && (0, _orkestrel_contract.isArray)(value.judgments) && value.judgments.every(isStudyJudgment) && value.judgments.every((judgment) => judgment.method === "human" || judgment.method === "model") && new Set(value.judgments.map((judgment) => (0, _orkestrel_contract.canonicalStringify)([judgment.trial, judgment.criterion]))).size === value.judgments.length && (0, _orkestrel_contract.isJSONValue)(value.judgments);
585
+ });
586
+ }
587
+ /**
588
+ * Checks whether a value names a supported study error code.
589
+ * @param value - The candidate code
590
+ * @returns True if it is a declared study error code; false otherwise
591
+ * @example
592
+ * ```ts
593
+ * isStudyErrorCode('CONFIG') // true
594
+ * ```
595
+ */
596
+ function isStudyErrorCode(value) {
597
+ return value === "CONFIG" || value === "EVIDENCE" || value === "CUSTODY" || value === "CAPACITY" || value === "FAULT" || value === "DEADLINE";
598
+ }
599
+ /**
600
+ * Checks whether grading binds accountable judgments to unique attempt identities.
601
+ * @param value - The candidate grading
602
+ * @returns True if its identities, attempts and judgments are valid; false otherwise
603
+ * @example
604
+ * ```ts
605
+ * isStudyGrading({}) // false
606
+ * ```
607
+ */
608
+ function isStudyGrading(value) {
609
+ return (0, _orkestrel_contract.holds)(() => {
610
+ return (0, _orkestrel_contract.isRecord)(value) && matchesStudyKeys(value, [
611
+ "result",
612
+ "rubric",
613
+ "grader",
614
+ "instrument",
615
+ "attempts",
616
+ "judgments"
617
+ ], ["labels", "packet"]) && isStudyDigest(value.result) && isStudyDigest(value.rubric) && isStudyDigest(value.instrument) && typeof value.grader === "string" && value.grader.trim().length > 0 && (value.labels === void 0 || isStudyDigest(value.labels)) && (value.packet === void 0 || isStudyDigest(value.packet)) && (0, _orkestrel_contract.isArray)(value.attempts) && (0, _orkestrel_contract.isJSONValue)(value.attempts) && value.attempts.every(isStudyName) && new Set(value.attempts).size === value.attempts.length && (0, _orkestrel_contract.isArray)(value.judgments) && value.judgments.every(isStudyJudgment) && new Set(value.judgments.map((judgment) => (0, _orkestrel_contract.canonicalStringify)([judgment.trial, judgment.criterion]))).size === value.judgments.length && (0, _orkestrel_contract.isJSONValue)(value.judgments);
618
+ });
619
+ }
620
+ //#endregion
621
+ //#region src/core/errors.ts
622
+ /** Reports a study contract or operational failure with a stable code. */
623
+ var StudyError = class extends Error {
624
+ code;
625
+ failure;
626
+ /**
627
+ * Records the failing boundary and optional operational attribution.
628
+ * @param code - The machine-readable boundary
629
+ * @param message - The specific failure
630
+ * @param failure - The optional operational reading
631
+ */
632
+ constructor(code, message, failure) {
633
+ super(message);
634
+ Object.defineProperty(this, STUDY_ERROR_BRAND, {
635
+ value: this,
636
+ configurable: true
637
+ });
638
+ this.name = "StudyError";
639
+ this.code = code;
640
+ this.failure = failure;
641
+ }
642
+ };
643
+ /**
644
+ * Narrows a caught value to an attributable study error.
645
+ * @remarks
646
+ * Recognition combines the native `Error` base, a subclass prototype, the fixed name, a declared
647
+ * study code, and an own {@link STUDY_ERROR_BRAND} descriptor whose value is the error itself.
648
+ * The global key is recognized across package, ESM, CommonJS and captured module copies; it is
649
+ * not unforgeable provenance. A transparent proxy is refused because its forwarded descriptor
650
+ * stores the target, and an unbranded copy, an inherited brand, or a property-only lookalike
651
+ * stays outside the type. Hostile property access returns false instead of throwing.
652
+ * @param value - The caught value
653
+ * @returns True if the value is a study error; false otherwise
654
+ * @example
655
+ * ```ts
656
+ * isStudyError(new StudyError('CONFIG', 'missing definition')) // true
657
+ * ```
658
+ */
659
+ function isStudyError(value) {
660
+ return (0, _orkestrel_contract.isError)(value) && (0, _orkestrel_contract.holds)(() => Object.getPrototypeOf(value) !== Error.prototype && value.name === "StudyError" && Object.getOwnPropertyDescriptor(value, STUDY_ERROR_BRAND)?.value === value && "code" in value && isStudyErrorCode(value.code));
661
+ }
662
+ //#endregion
663
+ //#region src/core/parsers.ts
664
+ /**
665
+ * Parses a foreign reading into a number a stop can retain.
666
+ * @param value - The unknown reading a source reports
667
+ * @returns The value when it is a finite number; undefined otherwise
668
+ * @example
669
+ * ```ts
670
+ * parseStudyReading(2048) // 2048
671
+ * parseStudyReading(Number.NaN) // undefined
672
+ * ```
673
+ */
674
+ function parseStudyReading(value) {
675
+ return (0, _orkestrel_contract.isFiniteNumber)(value) ? value : void 0;
676
+ }
677
+ /**
678
+ * Parses a definition into an independent frozen validated snapshot.
679
+ * @param value - The unknown configuration
680
+ * @returns The owned study definition
681
+ * @throws StudyError - Thrown when configuration is invalid or cannot be owned
682
+ * @example
683
+ * ```ts
684
+ * parseStudyDefinition(configuration)
685
+ * ```
686
+ */
687
+ function parseStudyDefinition(value) {
688
+ try {
689
+ if (!isStudyDefinition(value)) throw new StudyError("CONFIG", "Invalid study definition");
690
+ const snapshot = (0, _orkestrel_contract.cloneJSONValue)(value);
691
+ if (isStudyDefinition(snapshot)) return snapshot;
692
+ } catch {
693
+ throw new StudyError("CONFIG", "Invalid or unreadable study definition");
694
+ }
695
+ throw new StudyError("CONFIG", "Invalid study definition snapshot");
696
+ }
697
+ /**
698
+ * Parses a scenario into an independent frozen validated snapshot.
699
+ * @param value - The unknown configuration
700
+ * @returns The owned scenario and goal inputs
701
+ * @throws StudyError - Thrown when configuration is invalid or cannot be owned
702
+ * @example
703
+ * ```ts
704
+ * parseStudyScenario({ id: 'shift', goals: [{ id: 'write', input: {} }] })
705
+ * ```
706
+ */
707
+ function parseStudyScenario(value) {
708
+ try {
709
+ if (!isStudyScenario(value)) throw new StudyError("CONFIG", "Invalid study scenario");
710
+ const snapshot = (0, _orkestrel_contract.cloneJSONValue)(value);
711
+ if (isStudyScenario(snapshot)) return snapshot;
712
+ } catch {
713
+ throw new StudyError("CONFIG", "Invalid or unreadable study scenario");
714
+ }
715
+ throw new StudyError("CONFIG", "Invalid study scenario snapshot");
716
+ }
717
+ /**
718
+ * Parses a profile into an independent frozen validated snapshot.
719
+ * @param value - The unknown configuration
720
+ * @returns The owned profile with absent optional settings preserved
721
+ * @throws StudyError - Thrown when configuration is invalid or cannot be owned
722
+ * @example
723
+ * ```ts
724
+ * parseStudyProfile(configuration)
725
+ * ```
726
+ */
727
+ function parseStudyProfile(value) {
728
+ try {
729
+ if (!isStudyProfile(value)) throw new StudyError("CONFIG", "Invalid study profile");
730
+ const snapshot = (0, _orkestrel_contract.cloneJSONValue)(normalizeStudyProfile(value));
731
+ if (isStudyProfile(snapshot)) return snapshot;
732
+ } catch {
733
+ throw new StudyError("CONFIG", "Invalid or unreadable study profile");
734
+ }
735
+ throw new StudyError("CONFIG", "Invalid study profile snapshot");
736
+ }
737
+ /**
738
+ * Parses a rubric into an independent frozen validated snapshot.
739
+ * @param value - The unknown grading declaration
740
+ * @returns The owned rubric and assertion inputs
741
+ * @throws StudyError - Thrown when configuration is invalid or cannot be owned
742
+ * @example
743
+ * ```ts
744
+ * parseStudyRubric(configuration)
745
+ * ```
746
+ */
747
+ function parseStudyRubric(value) {
748
+ try {
749
+ if (!isStudyRubric(value)) throw new StudyError("CONFIG", "Invalid study rubric");
750
+ const snapshot = (0, _orkestrel_contract.cloneJSONValue)(value);
751
+ if (isStudyRubric(snapshot)) return snapshot;
752
+ } catch {
753
+ throw new StudyError("CONFIG", "Invalid or unreadable study rubric");
754
+ }
755
+ throw new StudyError("CONFIG", "Invalid study rubric snapshot");
756
+ }
757
+ /**
758
+ * Parses grading into an independent frozen validated evidence snapshot.
759
+ * @param value - The unknown grading evidence
760
+ * @returns The owned grading identity and judgments
761
+ * @throws StudyError - Thrown when evidence is invalid or cannot be owned
762
+ * @example
763
+ * ```ts
764
+ * parseStudyGrading(evidence)
765
+ * ```
766
+ */
767
+ function parseStudyGrading(value) {
768
+ try {
769
+ if (!isStudyGrading(value)) throw new StudyError("EVIDENCE", "Invalid study grading");
770
+ const { labels, packet, ...required } = value;
771
+ const snapshot = (0, _orkestrel_contract.cloneJSONValue)({
772
+ ...required,
773
+ ...labels === void 0 ? {} : { labels },
774
+ ...packet === void 0 ? {} : { packet }
775
+ });
776
+ if (isStudyGrading(snapshot)) return snapshot;
777
+ } catch {
778
+ throw new StudyError("EVIDENCE", "Invalid or unreadable study grading");
779
+ }
780
+ throw new StudyError("EVIDENCE", "Invalid study grading snapshot");
781
+ }
782
+ /**
783
+ * Parses semantic labels into an independent frozen validated evidence snapshot.
784
+ * @param value - The unknown imported labels
785
+ * @returns The owned packet provenance, usage and judgments
786
+ * @throws StudyError - Thrown when evidence is invalid or cannot be owned
787
+ * @example
788
+ * ```ts
789
+ * parseStudyLabeling(evidence)
790
+ * ```
791
+ */
792
+ function parseStudyLabeling(value) {
793
+ try {
794
+ if (!isStudyLabeling(value)) throw new StudyError("EVIDENCE", "Invalid study labels");
795
+ const snapshot = (0, _orkestrel_contract.cloneJSONValue)({
796
+ ...value,
797
+ usage: value.usage.map(({ tokens, bytes, ...usage }) => ({
798
+ ...usage,
799
+ ...tokens === void 0 ? {} : { tokens },
800
+ ...bytes === void 0 ? {} : { bytes }
801
+ }))
802
+ });
803
+ if (isStudyLabeling(snapshot)) return snapshot;
804
+ } catch {
805
+ throw new StudyError("EVIDENCE", "Invalid or unreadable study labels");
806
+ }
807
+ throw new StudyError("EVIDENCE", "Invalid study labels snapshot");
808
+ }
809
+ //#endregion
810
+ //#region src/core/engines/helpers.ts
811
+ /** Converts an operational reading to its throwable boundary.
812
+ * @param failure - The retained operational reading.
813
+ * @returns An error preserving the reading's cause and responsibility.
814
+ */
815
+ function failureToStudyError(failure) {
816
+ return new StudyError(failure.cause === "capacity" ? "CAPACITY" : failure.cause === "deadline" ? "DEADLINE" : "FAULT", failure.message, failure);
817
+ }
818
+ /** Reads an operational error without inventing a task verdict.
819
+ * @remarks
820
+ * A branded `BudgetError` from any copy of the budget package reads as a `budget` stop, because the
821
+ * error alone does not prove which budget object raised it; the Agent record names a `meter` stop.
822
+ * An unbranded lookalike reads as an infrastructure failure.
823
+ * @param error - The caught error.
824
+ * @returns Existing attribution, the capacity a branded budget error names, the cause a bare
825
+ * capacity or deadline code names, or an infrastructure failure.
826
+ */
827
+ function readStudyFailure(error) {
828
+ if (isStudyError(error)) {
829
+ const { failure, code, message } = error;
830
+ if (failure !== void 0) return failure;
831
+ if (code === "CAPACITY") return {
832
+ cause: "capacity",
833
+ message,
834
+ role: void 0,
835
+ stop: void 0
836
+ };
837
+ if (code === "DEADLINE") return {
838
+ cause: "deadline",
839
+ message,
840
+ role: void 0,
841
+ stop: void 0
842
+ };
843
+ }
844
+ if ((0, _orkestrel_budget.isBudgetError)(error)) {
845
+ const reading = (0, _orkestrel_contract.attempt)(() => {
846
+ const context = error.context;
847
+ return {
848
+ id: context.id,
849
+ max: context.max,
850
+ consumed: context.consumed,
851
+ message: error.message
852
+ };
853
+ });
854
+ if (reading.success) return {
855
+ cause: "capacity",
856
+ message: reading.value.message,
857
+ role: void 0,
858
+ stop: {
859
+ layer: "budget",
860
+ id: (0, _orkestrel_contract.isNonEmptyString)(reading.value.id) ? reading.value.id : "Agent budget",
861
+ max: parseStudyReading(reading.value.max),
862
+ consumed: parseStudyReading(reading.value.consumed)
863
+ }
864
+ };
865
+ }
866
+ return {
867
+ cause: "infrastructure",
868
+ message: (0, _orkestrel_contract.isError)(error) ? error.message : "Study operation rejected without an Error",
869
+ role: void 0,
870
+ stop: void 0
871
+ };
872
+ }
873
+ /**
874
+ * Computes the stop of a request whose actual usage crossed the ceiling it was admitted under.
875
+ * @param charge - The request's admitted ceilings
876
+ * @param usage - The request's measured usage
877
+ * @returns The `scope` stop for the first quantity, tokens then bytes, whose known usage exceeds its admitted ceiling; undefined when none does
878
+ * @example
879
+ * ```ts
880
+ * computeStudyAdmittedStop({ role: 'agent', tokens: 10, bytes: 100 }, usage) // { layer: 'scope', id: 'Admitted tokens', max: 10, consumed: 12 }
881
+ * ```
882
+ */
883
+ function computeStudyAdmittedStop(charge, usage) {
884
+ if (usage.tokens !== void 0 && usage.tokens > charge.tokens) return {
885
+ layer: "scope",
886
+ id: "Admitted tokens",
887
+ max: charge.tokens,
888
+ consumed: usage.tokens
889
+ };
890
+ if (usage.bytes !== void 0 && usage.bytes > charge.bytes) return {
891
+ layer: "scope",
892
+ id: "Admitted bytes",
893
+ max: charge.bytes,
894
+ consumed: usage.bytes
895
+ };
896
+ }
897
+ /**
898
+ * Computes the stop of a product the output allowances cannot hold.
899
+ * @param bytes - The encoded size of the product's value
900
+ * @param limit - The goal's byte allowance
901
+ * @param outputs - The trial and series output budgets, in the order they refuse
902
+ * @returns The `Goal bytes` stop when the goal allowance refuses, else the stop of the first budget whose remaining room is below the product, with its tally including the refused product; undefined when every allowance holds it
903
+ * @example
904
+ * ```ts
905
+ * computeStudyOutputStop(2048, 1024, []) // { layer: 'scope', id: 'Goal bytes', max: 1024, consumed: 2048 }
906
+ * ```
907
+ */
908
+ function computeStudyOutputStop(bytes, limit, outputs) {
909
+ if (bytes > limit) return {
910
+ layer: "scope",
911
+ id: "Goal bytes",
912
+ max: limit,
913
+ consumed: bytes
914
+ };
915
+ const refusal = outputs.find((budget) => bytes > budget.remaining);
916
+ return refusal === void 0 ? void 0 : {
917
+ layer: "scope",
918
+ id: refusal.id,
919
+ max: refusal.max,
920
+ consumed: refusal.consumed + bytes
921
+ };
922
+ }
923
+ /**
924
+ * Records an error that escaped admitted work as the failure of its ticket.
925
+ * @param ticket - The admitted request whose work escaped
926
+ * @param error - The caught value, read through `readStudyFailure`
927
+ * @param role - The responsibility that replaces any role the reading carries; Default: the carried role, else the ticket's admitted role
928
+ * @remarks
929
+ * A ticket that already settled or whose signal aborted is left untouched, because its owner
930
+ * already holds the failure. A remote ticket's aborted signal does not mean it settled locally,
931
+ * so the parent's ownership is respected rather than inferred as local settlement. A refusal
932
+ * thrown by the ticket's own settlement propagates.
933
+ * @throws Thrown when the ticket's settlement refuses the failure.
934
+ * @example Fail an escaped request
935
+ * ```ts
936
+ * import type { StudyTicket } from '@orkestrel/study'
937
+ * import { failStudyTicket } from '@orkestrel/study'
938
+ *
939
+ * declare const ticket: StudyTicket
940
+ *
941
+ * failStudyTicket(ticket, new Error('Provider refused'), 'tool')
942
+ * ```
943
+ */
944
+ function failStudyTicket(ticket, error, role) {
945
+ if (ticket.settled || ticket.signal.aborted) return;
946
+ const failure = readStudyFailure(error);
947
+ ticket.fail(role === void 0 ? failure : {
948
+ ...failure,
949
+ role
950
+ });
951
+ }
952
+ //#endregion
953
+ //#region src/core/engines/StudyControl.ts
954
+ /** Retains the first operational failure while bounding asynchronous waits. */
955
+ var StudyControl = class {
956
+ #abort;
957
+ #listeners = new _orkestrel_abort.Abort();
958
+ #failure;
959
+ /** Links cancellation to the caller without assigning it a task verdict.
960
+ * @param signal - Optional parent cancellation.
961
+ */
962
+ constructor(signal) {
963
+ this.#abort = new _orkestrel_abort.Abort(signal === void 0 ? void 0 : { signal });
964
+ if (this.#abort.aborted) this.#interrupt();
965
+ else this.#abort.signal.addEventListener("abort", () => this.#interrupt(), {
966
+ once: true,
967
+ signal: this.#listeners.signal
968
+ });
969
+ }
970
+ get signal() {
971
+ return this.#abort.signal;
972
+ }
973
+ get failure() {
974
+ return this.#failure;
975
+ }
976
+ /** Latches an operational failure and cancels all linked work.
977
+ * @param failure - The first attribution to preserve.
978
+ */
979
+ fail(failure) {
980
+ if (this.#failure !== void 0) return;
981
+ this.#failure = Object.freeze({
982
+ ...failure,
983
+ stop: failure.stop === void 0 ? void 0 : Object.freeze({ ...failure.stop })
984
+ });
985
+ this.#abort.abort(failureToStudyError(this.#failure));
986
+ }
987
+ /** Races work against cancellation and removes its listener after either ending.
988
+ * @param work - Already-started work whose rejection remains observed after cancellation.
989
+ * @returns The work's result if it settles before cancellation.
990
+ * @throws Thrown with the retained operational attribution when cancelled.
991
+ */
992
+ wait(work) {
993
+ const listeners = new _orkestrel_abort.Abort();
994
+ return new Promise((resolve, reject) => {
995
+ Promise.resolve(work).then(resolve, reject);
996
+ if (this.#abort.aborted) reject(this.#reason());
997
+ else this.#abort.signal.addEventListener("abort", () => reject(this.#reason()), {
998
+ once: true,
999
+ signal: listeners.signal
1000
+ });
1001
+ }).finally(() => listeners.abort());
1002
+ }
1003
+ /** Removes the lifecycle listener without changing the retained failure. */
1004
+ close() {
1005
+ this.#listeners.abort();
1006
+ }
1007
+ #reason() {
1008
+ return failureToStudyError(this.#failure ?? {
1009
+ cause: "interrupted",
1010
+ message: "Study interrupted",
1011
+ role: void 0,
1012
+ stop: void 0
1013
+ });
1014
+ }
1015
+ #interrupt() {
1016
+ if (this.#failure === void 0) this.fail({
1017
+ cause: "interrupted",
1018
+ message: "Study interrupted by parent cancellation",
1019
+ role: void 0,
1020
+ stop: void 0
1021
+ });
1022
+ }
1023
+ };
1024
+ //#endregion
1025
+ //#region src/core/engines/StudyScope.ts
1026
+ /** Reserves finite request ceilings around cumulative actual budgets and one deadline. */
1027
+ var StudyScope = class {
1028
+ #options;
1029
+ #calls;
1030
+ #tokens;
1031
+ #bytes;
1032
+ #timeout;
1033
+ #listeners = new _orkestrel_abort.Abort();
1034
+ #pending = /* @__PURE__ */ new Map();
1035
+ #started = performance.now();
1036
+ #closed = false;
1037
+ /** Starts a timed scope with independent counters.
1038
+ * @param options - Finite limit, shared failure owner, and diagnostic label.
1039
+ */
1040
+ constructor(options) {
1041
+ if (!isStudyLimit(options.limit)) throw new StudyError("CONFIG", "Invalid study scope limit");
1042
+ this.#options = {
1043
+ ...options,
1044
+ limit: { ...options.limit }
1045
+ };
1046
+ this.#calls = new _orkestrel_budget.Budget({
1047
+ max: options.limit.calls,
1048
+ consumer: (value) => value
1049
+ });
1050
+ this.#tokens = new _orkestrel_budget.Budget({
1051
+ max: options.limit.tokens,
1052
+ consumer: (value) => value
1053
+ });
1054
+ this.#bytes = new _orkestrel_budget.Budget({
1055
+ max: options.limit.bytes,
1056
+ consumer: (value) => value
1057
+ });
1058
+ this.#timeout = new _orkestrel_timeout.Timeout({ ms: options.limit.duration });
1059
+ this.#timeout.signal.addEventListener("abort", () => this.#expire(), {
1060
+ once: true,
1061
+ signal: this.#listeners.signal
1062
+ });
1063
+ this.#timeout.start();
1064
+ }
1065
+ /** Checks cumulative consumption and every pending ceiling before admission.
1066
+ * @param charge - One prospective request's ceilings.
1067
+ * @throws Thrown when this scope cannot admit the request.
1068
+ */
1069
+ check(charge) {
1070
+ this.#checkTime();
1071
+ if (this.#closed) throw new StudyError("FAULT", "Study scope is closed");
1072
+ const prior = this.#options.control.failure;
1073
+ if (prior !== void 0) throw failureToStudyError(prior);
1074
+ if (charge === void 0) return;
1075
+ const pending = [...this.#pending.values()];
1076
+ const tokens = pending.reduce((total, entry) => total + entry.tokens, 0);
1077
+ const bytes = pending.reduce((total, entry) => total + entry.bytes, 0);
1078
+ const { label, limit } = this.#options;
1079
+ const refusal = [
1080
+ {
1081
+ id: `${label} calls`,
1082
+ refused: this.#calls.remaining - this.#pending.size < 1,
1083
+ max: limit.calls,
1084
+ consumed: this.#calls.consumed + this.#pending.size + 1
1085
+ },
1086
+ {
1087
+ id: `${label} tokens`,
1088
+ refused: this.#tokens.remaining - tokens < charge.tokens,
1089
+ max: limit.tokens,
1090
+ consumed: this.#tokens.consumed + tokens + charge.tokens
1091
+ },
1092
+ {
1093
+ id: `${label} bytes`,
1094
+ refused: this.#bytes.remaining - bytes < charge.bytes,
1095
+ max: limit.bytes,
1096
+ consumed: this.#bytes.consumed + bytes + charge.bytes
1097
+ }
1098
+ ].find((entry) => entry.refused);
1099
+ if (refusal !== void 0) {
1100
+ const failure = {
1101
+ cause: "capacity",
1102
+ message: `${label} allowance cannot admit the request`,
1103
+ role: charge.role,
1104
+ stop: {
1105
+ layer: "scope",
1106
+ id: refusal.id,
1107
+ max: refusal.max,
1108
+ consumed: refusal.consumed
1109
+ }
1110
+ };
1111
+ this.#options.control.fail(failure);
1112
+ throw failureToStudyError(failure);
1113
+ }
1114
+ }
1115
+ /** Reserves one request after the enclosing meter checked all scopes.
1116
+ * @param id - The request's unique reservation identity.
1117
+ * @param charge - Its admitted ceilings.
1118
+ */
1119
+ reserve(id, charge) {
1120
+ if (this.#pending.has(id)) throw new StudyError("FAULT", "Duplicate study reservation");
1121
+ this.#pending.set(id, { ...charge });
1122
+ }
1123
+ /** Commits known charges while retaining ceilings for missing measurements.
1124
+ * @param id - The pending reservation identity.
1125
+ * @param usage - The request's retained public measurements.
1126
+ */
1127
+ settle(id, usage) {
1128
+ const charge = this.#pending.get(id);
1129
+ if (charge === void 0) throw new StudyError("FAULT", "Study reservation is not pending");
1130
+ this.#pending.delete(id);
1131
+ this.#calls.consume(1);
1132
+ this.#tokens.consume(Math.min(charge.tokens, usage.tokens ?? charge.tokens));
1133
+ this.#bytes.consume(Math.min(charge.bytes, usage.bytes ?? charge.bytes));
1134
+ }
1135
+ /** Checks deadline attribution before clearing the timer. */
1136
+ close() {
1137
+ if (this.#closed) return;
1138
+ this.#checkTime();
1139
+ this.#closed = true;
1140
+ this.#listeners.abort();
1141
+ this.#timeout.clear();
1142
+ }
1143
+ #checkTime() {
1144
+ if (!this.#closed && (this.#timeout.expired || performance.now() - this.#started >= this.#options.limit.duration)) this.#expire();
1145
+ }
1146
+ #expire() {
1147
+ this.#options.control.fail({
1148
+ cause: "deadline",
1149
+ message: `${this.#options.label} deadline expired`,
1150
+ role: void 0,
1151
+ stop: {
1152
+ layer: "scope",
1153
+ id: `${this.#options.label} duration`,
1154
+ max: this.#options.limit.duration,
1155
+ consumed: Math.ceil(performance.now() - this.#started)
1156
+ }
1157
+ });
1158
+ }
1159
+ };
1160
+ //#endregion
1161
+ //#region src/core/engines/StudyDeadline.ts
1162
+ /** Bounds each independent operation with a fresh failure owner and deadline. */
1163
+ var StudyDeadline = class {
1164
+ #options;
1165
+ /** Retains the deadline without starting a timer.
1166
+ * @param options - Finite duration in milliseconds and diagnostic label.
1167
+ */
1168
+ constructor(options) {
1169
+ this.#options = { ...options };
1170
+ }
1171
+ /** Waits for work under a fresh failure owner and releases its timer and listener.
1172
+ * @param work - Already-started work whose late rejection remains observed.
1173
+ * @returns The work's result when it settles before the deadline.
1174
+ * @throws Thrown for an invalid duration, the work's own rejection, or the labelled deadline.
1175
+ */
1176
+ async wait(work) {
1177
+ const control = new StudyControl();
1178
+ const scope = this.#open(control, work);
1179
+ try {
1180
+ const result = await control.wait(work);
1181
+ scope.check();
1182
+ return result;
1183
+ } finally {
1184
+ scope.close();
1185
+ control.close();
1186
+ }
1187
+ }
1188
+ #open(control, work) {
1189
+ try {
1190
+ return new StudyScope({
1191
+ limit: {
1192
+ duration: this.#options.duration,
1193
+ calls: 1,
1194
+ tokens: 1,
1195
+ bytes: 1
1196
+ },
1197
+ control,
1198
+ label: this.#options.label
1199
+ });
1200
+ } catch (error) {
1201
+ Promise.resolve(work).catch(() => void 0);
1202
+ control.close();
1203
+ throw error;
1204
+ }
1205
+ }
1206
+ };
1207
+ //#endregion
1208
+ //#region src/core/engines/StudyRequest.ts
1209
+ /** Settles an admitted request once and propagates operational failure to its owner. */
1210
+ var StudyRequest = class {
1211
+ #options;
1212
+ #timeout;
1213
+ #signal;
1214
+ #listeners = new _orkestrel_abort.Abort();
1215
+ #started = performance.now();
1216
+ #settled = false;
1217
+ /** Starts the request deadline after its enclosing scopes reserve capacity.
1218
+ * @param options - Admitted ceilings, request deadline, and settlement callback.
1219
+ */
1220
+ constructor(options) {
1221
+ this.#options = {
1222
+ ...options,
1223
+ charge: { ...options.charge }
1224
+ };
1225
+ this.#timeout = new _orkestrel_timeout.Timeout({ ms: options.duration });
1226
+ this.#signal = (0, _orkestrel_abort.linkSignal)(this.#timeout.signal, options.control.signal);
1227
+ this.#signal.addEventListener("abort", () => this.#abort(), {
1228
+ once: true,
1229
+ signal: this.#listeners.signal
1230
+ });
1231
+ this.#timeout.start();
1232
+ if (this.#signal.aborted) this.#abort();
1233
+ }
1234
+ get signal() {
1235
+ return this.#signal;
1236
+ }
1237
+ get settled() {
1238
+ return this.#settled;
1239
+ }
1240
+ /** Retains actual measurements and refuses invalid or excessive charges.
1241
+ * @param usage - Measurements attributed to exactly this request.
1242
+ * @throws Thrown when settlement is late, repeated, invalid, or beyond admission.
1243
+ */
1244
+ finish(usage) {
1245
+ this.#checkPending();
1246
+ if (!isStudyUsage(usage) || usage.role !== this.#options.charge.role || usage.calls !== 1) {
1247
+ const failure = {
1248
+ cause: "infrastructure",
1249
+ message: "Request usage is invalid or misattributed",
1250
+ role: this.#options.charge.role,
1251
+ stop: void 0
1252
+ };
1253
+ this.fail(failure);
1254
+ throw failureToStudyError(failure);
1255
+ }
1256
+ const elapsed = performance.now() - this.#started;
1257
+ const admitted = computeStudyAdmittedStop(this.#options.charge, usage);
1258
+ const failure = this.#timeout.expired || elapsed >= this.#options.duration || usage.duration > this.#options.duration ? {
1259
+ cause: "deadline",
1260
+ message: "Request deadline expired",
1261
+ role: usage.role,
1262
+ stop: {
1263
+ layer: "scope",
1264
+ id: "Request duration",
1265
+ max: this.#options.duration,
1266
+ consumed: Math.ceil(Math.max(elapsed, usage.duration))
1267
+ }
1268
+ } : admitted !== void 0 ? {
1269
+ cause: "capacity",
1270
+ message: "Request usage exceeded its admitted ceiling",
1271
+ role: usage.role,
1272
+ stop: admitted
1273
+ } : void 0;
1274
+ this.#complete(usage);
1275
+ if (failure !== void 0) {
1276
+ this.#options.control.fail(failure);
1277
+ throw failureToStudyError(failure);
1278
+ }
1279
+ }
1280
+ /** Retains unknown cost conservatively and latches the first operational failure.
1281
+ * @param failure - The operational request failure.
1282
+ * @throws Thrown when this request was already settled.
1283
+ */
1284
+ fail(failure) {
1285
+ this.#checkPending();
1286
+ this.#complete({
1287
+ role: this.#options.charge.role,
1288
+ calls: 1,
1289
+ tokens: void 0,
1290
+ bytes: void 0,
1291
+ duration: Math.ceil(performance.now() - this.#started)
1292
+ });
1293
+ this.#options.control.fail({
1294
+ ...failure,
1295
+ role: failure.role ?? this.#options.charge.role
1296
+ });
1297
+ }
1298
+ #complete(usage) {
1299
+ this.#settled = true;
1300
+ this.#listeners.abort();
1301
+ this.#timeout.clear();
1302
+ this.#options.settle(Object.freeze({ ...usage }));
1303
+ }
1304
+ #checkPending() {
1305
+ if (this.#settled) {
1306
+ this.#options.control.fail({
1307
+ cause: "infrastructure",
1308
+ message: "Request settlement is late or repeated",
1309
+ role: this.#options.charge.role,
1310
+ stop: void 0
1311
+ });
1312
+ throw new StudyError("FAULT", "Request settlement is late or repeated", this.#options.control.failure);
1313
+ }
1314
+ }
1315
+ #abort() {
1316
+ if (this.#settled) return;
1317
+ const expired = this.#timeout.expired;
1318
+ this.fail(this.#options.control.failure ?? {
1319
+ cause: expired ? "deadline" : "interrupted",
1320
+ message: expired ? "Request deadline expired" : "Request interrupted",
1321
+ role: this.#options.charge.role,
1322
+ stop: expired ? {
1323
+ layer: "scope",
1324
+ id: "Request duration",
1325
+ max: this.#options.duration,
1326
+ consumed: Math.ceil(performance.now() - this.#started)
1327
+ } : void 0
1328
+ });
1329
+ }
1330
+ };
1331
+ //#endregion
1332
+ //#region src/core/engines/StudyMeter.ts
1333
+ /** Admits request ceilings across every enclosing scope before dispatch. */
1334
+ var StudyMeter = class {
1335
+ #options;
1336
+ #pending = /* @__PURE__ */ new Set();
1337
+ #usage = [];
1338
+ #closed = false;
1339
+ /** Holds the goal's shared admission scopes.
1340
+ * @param options - Request bound, enclosing scopes, and shared failure owner.
1341
+ */
1342
+ constructor(options) {
1343
+ if (!isStudyLimit(options.request) || options.request.calls !== 1 || options.scopes.length === 0) throw new StudyError("CONFIG", "Invalid request admission bounds");
1344
+ this.#options = {
1345
+ ...options,
1346
+ request: { ...options.request },
1347
+ scopes: [...options.scopes]
1348
+ };
1349
+ }
1350
+ get signal() {
1351
+ return this.#options.control.signal;
1352
+ }
1353
+ get usage() {
1354
+ return Object.freeze([...this.#usage]);
1355
+ }
1356
+ /** Reserves one request atomically across all enclosing allowances.
1357
+ * @param charge - Safe integer token and byte ceilings with the request's role.
1358
+ * @returns A request ticket that must settle before the goal completes.
1359
+ * @throws Thrown before dispatch if the request exceeds available capacity.
1360
+ */
1361
+ admit(charge) {
1362
+ if (this.#closed) throw new StudyError("FAULT", "Study meter is closed");
1363
+ if (this.#options.control.failure !== void 0) throw failureToStudyError(this.#options.control.failure);
1364
+ if (!isStudyRole(charge.role) || !Number.isSafeInteger(charge.tokens) || charge.tokens < 0 || !Number.isSafeInteger(charge.bytes) || charge.bytes < 0) {
1365
+ const failure = {
1366
+ cause: "infrastructure",
1367
+ message: "Request admission requires safe nonnegative ceilings",
1368
+ role: void 0,
1369
+ stop: void 0
1370
+ };
1371
+ this.#options.control.fail(failure);
1372
+ throw failureToStudyError(failure);
1373
+ }
1374
+ const { request } = this.#options;
1375
+ if (charge.tokens > request.tokens || charge.bytes > request.bytes) {
1376
+ const tokens = charge.tokens > request.tokens;
1377
+ const failure = {
1378
+ cause: "capacity",
1379
+ message: "Request ceiling exceeds the request allowance",
1380
+ role: charge.role,
1381
+ stop: {
1382
+ layer: "scope",
1383
+ id: tokens ? "Request tokens" : "Request bytes",
1384
+ max: tokens ? request.tokens : request.bytes,
1385
+ consumed: tokens ? charge.tokens : charge.bytes
1386
+ }
1387
+ };
1388
+ this.#options.control.fail(failure);
1389
+ throw failureToStudyError(failure);
1390
+ }
1391
+ for (const scope of this.#options.scopes) scope.check(charge);
1392
+ const id = Symbol("request");
1393
+ for (const scope of this.#options.scopes) scope.reserve(id, charge);
1394
+ this.#pending.add(id);
1395
+ return new StudyRequest({
1396
+ charge,
1397
+ duration: this.#options.request.duration,
1398
+ control: this.#options.control,
1399
+ settle: (usage) => {
1400
+ for (const scope of this.#options.scopes) scope.settle(id, usage);
1401
+ this.#pending.delete(id);
1402
+ this.#usage = [...this.#usage, usage];
1403
+ }
1404
+ });
1405
+ }
1406
+ /** Refuses unfinished requests before closing a goal's admission boundary. */
1407
+ close() {
1408
+ if (this.#closed) return;
1409
+ this.#closed = true;
1410
+ if (this.#pending.size > 0) this.#options.control.fail({
1411
+ cause: "infrastructure",
1412
+ message: "Goal completed with unsettled requests",
1413
+ role: void 0,
1414
+ stop: void 0
1415
+ });
1416
+ }
1417
+ };
1418
+ //#endregion
1419
+ //#region src/core/engines/StudyTrialLease.ts
1420
+ /** Holds one trial's evidence custody, admission scope and driver session from opening to cleanup. */
1421
+ var StudyTrialLease = class {
1422
+ #trial;
1423
+ #options;
1424
+ #control;
1425
+ #series;
1426
+ #deadline;
1427
+ #scope;
1428
+ #evidence;
1429
+ #opening;
1430
+ #session;
1431
+ /** Binds one scheduled trial to the series' owned inputs, failure owner, series scope and cleanup deadline.
1432
+ * @param trial - The scheduled trial.
1433
+ * @param options - The series' owned manifest, driver and store.
1434
+ * @param control - The series failure owner.
1435
+ * @param series - The series admission scope.
1436
+ * @param deadline - The custody and cleanup deadline.
1437
+ */
1438
+ constructor(trial, options, control, series, deadline) {
1439
+ this.#trial = trial;
1440
+ this.#options = options;
1441
+ this.#control = control;
1442
+ this.#series = series;
1443
+ this.#deadline = deadline;
1444
+ }
1445
+ /** Reports the trial scope once opened; undefined when the trial inherited a failure. */
1446
+ get scope() {
1447
+ return this.#scope;
1448
+ }
1449
+ /** Reports the trial's evidence sink once custody started. */
1450
+ get evidence() {
1451
+ return this.#evidence;
1452
+ }
1453
+ /** Reports the driver session once it opened. */
1454
+ get session() {
1455
+ return this.#session;
1456
+ }
1457
+ /** Starts evidence custody and, unless a failure is latched, opens the trial scope and driver session.
1458
+ * @returns Nothing after the session opened, or after custody alone started under a latched failure.
1459
+ * @throws StudyError - Thrown with code `CUSTODY` when custody refuses the trial; thrown for a series or trial limit or an opening failure.
1460
+ */
1461
+ async open() {
1462
+ const control = this.#control;
1463
+ if (control.failure !== void 0) {
1464
+ this.#evidence = await this.#start();
1465
+ return;
1466
+ }
1467
+ this.#series.check();
1468
+ const scope = new StudyScope({
1469
+ limit: this.#options.manifest.bounds.trial,
1470
+ control,
1471
+ label: "Trial"
1472
+ });
1473
+ this.#scope = scope;
1474
+ this.#evidence = await this.#start();
1475
+ this.#series.check();
1476
+ scope.check();
1477
+ const opening = this.#launch();
1478
+ this.#opening = opening;
1479
+ this.#session = await control.wait(opening);
1480
+ }
1481
+ /** Closes the opened session, or a session that opened late, then the trial scope.
1482
+ * @returns The cleanup failure, or undefined when cleanup succeeded or repeated the latched failure.
1483
+ */
1484
+ async close() {
1485
+ const cleanup = await this.#release();
1486
+ this.#scope?.close();
1487
+ return cleanup;
1488
+ }
1489
+ async #release() {
1490
+ const session = this.#session;
1491
+ const opening = this.#opening;
1492
+ if (session !== void 0) try {
1493
+ await this.#deadline.wait(session.close());
1494
+ return;
1495
+ } catch (error) {
1496
+ const cleanup = readStudyFailure(error);
1497
+ this.#control.fail(cleanup);
1498
+ return cleanup;
1499
+ }
1500
+ if (opening === void 0) return void 0;
1501
+ try {
1502
+ const late = await this.#deadline.wait(opening);
1503
+ await this.#deadline.wait(late.close());
1504
+ return;
1505
+ } catch (error) {
1506
+ const late = readStudyFailure(error);
1507
+ return late.message !== this.#control.failure?.message ? late : void 0;
1508
+ }
1509
+ }
1510
+ async #launch() {
1511
+ const control = this.#control;
1512
+ const session = await this.#options.driver.open(this.#trial, control.signal);
1513
+ if (control.failure !== void 0) {
1514
+ await this.#deadline.wait(session.close());
1515
+ throw failureToStudyError(control.failure);
1516
+ }
1517
+ return session;
1518
+ }
1519
+ async #start() {
1520
+ const control = this.#control;
1521
+ try {
1522
+ const pending = this.#options.store.start(this.#trial);
1523
+ return control.failure === void 0 ? await control.wait(pending) : await this.#deadline.wait(pending);
1524
+ } catch (error) {
1525
+ control.fail(readStudyFailure(error));
1526
+ const failure = control.failure ?? readStudyFailure(error);
1527
+ throw new StudyError("CUSTODY", failure.message, failure);
1528
+ }
1529
+ }
1530
+ };
1531
+ //#endregion
1532
+ //#region src/core/engines/StudySeries.ts
1533
+ /** Executes a frozen serial study schedule with finite admission and sticky failures. */
1534
+ var StudySeries = class {
1535
+ #options;
1536
+ #executed = false;
1537
+ /** Owns the declared inputs while retaining the concrete driver and custody store.
1538
+ * @param options - Frozen manifest, concrete adapters, and parent cancellation.
1539
+ */
1540
+ constructor(options) {
1541
+ this.#options = {
1542
+ ...options,
1543
+ manifest: structuredClone(options.manifest)
1544
+ };
1545
+ }
1546
+ /** Runs every declared trial once and retains explicit unexecuted observations after failure.
1547
+ * Custody rejection leaves the run unsealed; callers must seal only a fulfilled execution.
1548
+ * @returns Ordered terminal attempts without task success labels.
1549
+ * @throws Thrown for invalid configuration or failed or timed out custody operations.
1550
+ */
1551
+ async execute() {
1552
+ if (this.#executed) throw new StudyError("CONFIG", "Study series can execute only once");
1553
+ this.#executed = true;
1554
+ const manifest = this.#options.manifest;
1555
+ const expected = buildStudySchedule(manifest.definition, manifest.scenarios);
1556
+ if (!isStudyBounds(manifest.bounds) || (0, _orkestrel_contract.canonicalStringify)(expected) !== (0, _orkestrel_contract.canonicalStringify)(manifest.schedule)) throw new StudyError("CONFIG", "Study manifest schedule or bounds are invalid");
1557
+ const control = new StudyControl(this.#options.signal);
1558
+ const scope = new StudyScope({
1559
+ limit: manifest.bounds.series,
1560
+ control,
1561
+ label: "Series"
1562
+ });
1563
+ const deadline = new StudyDeadline({
1564
+ duration: manifest.bounds.request.duration,
1565
+ label: "Custody or cleanup"
1566
+ });
1567
+ const output = new _orkestrel_budget.Budget({
1568
+ id: "Series output",
1569
+ max: manifest.bounds.series.bytes,
1570
+ consumer: (bytes) => bytes
1571
+ });
1572
+ const attempts = [];
1573
+ try {
1574
+ for (const trial of manifest.schedule) attempts.push(await this.#executeTrial(trial, control, scope, output, deadline));
1575
+ } finally {
1576
+ scope.close();
1577
+ control.close();
1578
+ }
1579
+ return Object.freeze(attempts);
1580
+ }
1581
+ async #executeTrial(trial, control, series, output, deadline) {
1582
+ const started = performance.now();
1583
+ const scenario = this.#options.manifest.scenarios.find((entry) => entry.id === trial.scenario);
1584
+ if (scenario === void 0) throw new StudyError("CONFIG", "Scheduled scenario is absent");
1585
+ const prior = control.failure;
1586
+ const lease = new StudyTrialLease(trial, this.#options, control, series, deadline);
1587
+ const executed = await this.#executeGoals(scenario, lease, control, series, output);
1588
+ const cleanup = await this.#release(lease, control, series);
1589
+ const failure = control.failure;
1590
+ const observations = [...executed, ...scenario.goals.slice(executed.length).map((goal) => {
1591
+ const unexecuted = failure === void 0 ? {
1592
+ cause: "infrastructure",
1593
+ message: "Goal unexecuted because the trial did not open",
1594
+ role: void 0,
1595
+ stop: void 0
1596
+ } : {
1597
+ ...failure,
1598
+ message: `Goal unexecuted: ${failure.message}`
1599
+ };
1600
+ return Object.freeze({
1601
+ goal: goal.id,
1602
+ product: void 0,
1603
+ failure: unexecuted,
1604
+ usage: Object.freeze([]),
1605
+ duration: 0,
1606
+ executed: false
1607
+ });
1608
+ })];
1609
+ const attempt = Object.freeze({
1610
+ trial,
1611
+ observations: Object.freeze(observations),
1612
+ failure: cleanup !== void 0 && failure !== void 0 && (prior !== void 0 || failure.message !== cleanup.message) ? {
1613
+ ...failure,
1614
+ message: `${failure.message}; cleanup: ${cleanup.message}`
1615
+ } : failure,
1616
+ duration: Math.ceil(performance.now() - started),
1617
+ executed: prior === void 0
1618
+ });
1619
+ try {
1620
+ await deadline.wait(this.#options.store.finish(attempt));
1621
+ if (attempt.failure === void 0) series.check();
1622
+ } catch (error) {
1623
+ control.fail(readStudyFailure(error));
1624
+ const custody = control.failure ?? readStudyFailure(error);
1625
+ throw new StudyError("CUSTODY", custody.message, custody);
1626
+ }
1627
+ return attempt;
1628
+ }
1629
+ async #executeGoals(scenario, lease, control, series, output) {
1630
+ const observations = [];
1631
+ try {
1632
+ await lease.open();
1633
+ const trialOutput = new _orkestrel_budget.Budget({
1634
+ id: "Trial output",
1635
+ max: this.#options.manifest.bounds.trial.bytes,
1636
+ consumer: (bytes) => bytes
1637
+ });
1638
+ for (const goal of scenario.goals) {
1639
+ const { session, scope, evidence } = lease;
1640
+ if (control.failure !== void 0 || session === void 0 || scope === void 0 || evidence === void 0) break;
1641
+ series.check();
1642
+ scope.check();
1643
+ observations.push(await this.#executeGoal(goal, session, evidence, control, [scope, series], [trialOutput, output]));
1644
+ }
1645
+ } catch (error) {
1646
+ if (isStudyError(error) && error.code === "CUSTODY") {
1647
+ await this.#release(lease, control, series);
1648
+ throw error;
1649
+ }
1650
+ control.fail(readStudyFailure(error));
1651
+ }
1652
+ return observations;
1653
+ }
1654
+ async #release(lease, control, series) {
1655
+ const cleanup = await lease.close();
1656
+ try {
1657
+ series.check();
1658
+ } catch (error) {
1659
+ control.fail(readStudyFailure(error));
1660
+ }
1661
+ return cleanup;
1662
+ }
1663
+ async #executeGoal(goal, session, evidence, control, parents, outputs) {
1664
+ const started = performance.now();
1665
+ const bounds = this.#options.manifest.bounds;
1666
+ const scope = new StudyScope({
1667
+ limit: bounds.goal,
1668
+ control,
1669
+ label: "Goal"
1670
+ });
1671
+ const meter = new StudyMeter({
1672
+ request: bounds.request,
1673
+ scopes: [scope, ...parents],
1674
+ control
1675
+ });
1676
+ const product = await this.#produce(goal, session, evidence, control, scope, meter, parents, outputs);
1677
+ return Object.freeze({
1678
+ goal: goal.id,
1679
+ product,
1680
+ failure: control.failure,
1681
+ usage: meter.usage,
1682
+ duration: Math.ceil(performance.now() - started),
1683
+ executed: true
1684
+ });
1685
+ }
1686
+ async #produce(goal, session, evidence, control, scope, meter, parents, outputs) {
1687
+ const bounds = this.#options.manifest.bounds;
1688
+ try {
1689
+ const value = await control.wait(session.execute(goal, {
1690
+ signal: control.signal,
1691
+ meter,
1692
+ evidence
1693
+ }));
1694
+ if (!isStudyProduct(value)) throw new StudyError("FAULT", "Driver returned no valid study product");
1695
+ const candidate = Object.freeze({
1696
+ value: (0, _orkestrel_contract.cloneJSONValue)(value.value),
1697
+ partial: value.partial
1698
+ });
1699
+ const bytes = new TextEncoder().encode(JSON.stringify(candidate.value)).byteLength;
1700
+ const stop = computeStudyOutputStop(bytes, bounds.goal.bytes, outputs);
1701
+ const product = stop === void 0 ? candidate : void 0;
1702
+ try {
1703
+ for (const parent of parents) parent.check();
1704
+ scope.check();
1705
+ if (stop !== void 0) control.fail({
1706
+ cause: "capacity",
1707
+ message: "Study product exceeded its output allowance",
1708
+ role: void 0,
1709
+ stop
1710
+ });
1711
+ else for (const budget of outputs) budget.consume(bytes);
1712
+ } catch (error) {
1713
+ control.fail(readStudyFailure(error));
1714
+ }
1715
+ return product;
1716
+ } catch (error) {
1717
+ control.fail(readStudyFailure(error));
1718
+ return;
1719
+ } finally {
1720
+ meter.close();
1721
+ scope.close();
1722
+ }
1723
+ }
1724
+ };
1725
+ //#endregion
1726
+ //#region src/core/agents/helpers.ts
1727
+ /**
1728
+ * Prices a runtime estimate through an explicit gauge.
1729
+ * @param gauge - The declared scale and overhead
1730
+ * @param estimate - The runtime's estimate of one complete request
1731
+ * @returns The projected prompt tokens, rounded up
1732
+ */
1733
+ function projectStudyAgentRequest(gauge, estimate) {
1734
+ return Math.ceil(gauge.overhead + gauge.scale * estimate);
1735
+ }
1736
+ /**
1737
+ * Checks that a successful provider call reported a usable actual prompt count.
1738
+ * @remarks
1739
+ * The check compares nothing with a forecast; room enforcement stays with the transport.
1740
+ * @param usage - The usage a successful provider call reported
1741
+ * @param role - The responsibility whose request was dispatched; the failure retains it
1742
+ * @returns Nothing when the prompt count is finite and positive
1743
+ * @throws StudyError - Thrown with code `FAULT` when the prompt count is missing, not finite, or not positive
1744
+ */
1745
+ function validateStudyAgentUsage(usage, role) {
1746
+ const prompt = usage?.prompt;
1747
+ if (typeof prompt !== "number" || !Number.isFinite(prompt) || prompt <= 0) {
1748
+ const message = "Gauged request returned no usable prompt count";
1749
+ throw new StudyError("FAULT", message, {
1750
+ cause: "infrastructure",
1751
+ message,
1752
+ role,
1753
+ stop: void 0
1754
+ });
1755
+ }
1756
+ }
1757
+ /**
1758
+ * Translates only a nominal Agent window refusal into the attributable capacity failure.
1759
+ * @remarks
1760
+ * The failure's stop is the `window` layer with the id `Agent window`; its `max` is the window and
1761
+ * its `consumed` the measured request, each read from the error's context when it is a finite
1762
+ * number.
1763
+ * @param error - The caught or reported value
1764
+ * @param runtime - The admitted Agent namespace owning the nominal guard
1765
+ * @returns A capacity StudyError for an Agent `WINDOW` error; every other value with its identity
1766
+ */
1767
+ function translateStudyAgentError(error, runtime) {
1768
+ if (!runtime.isAgentError(error) || error.code !== "WINDOW") return error;
1769
+ const context = error.context;
1770
+ return new StudyError("CAPACITY", error.message, {
1771
+ cause: "capacity",
1772
+ message: error.message,
1773
+ role: "agent",
1774
+ stop: {
1775
+ layer: "window",
1776
+ id: "Agent window",
1777
+ max: parseStudyReading(context?.max),
1778
+ consumed: parseStudyReading(context?.consumed)
1779
+ }
1780
+ });
1781
+ }
1782
+ /**
1783
+ * Translates an Agent run's stop record into the attributable capacity failure of the layer that stopped it.
1784
+ * @remarks
1785
+ * The record is foreign data from the admitted runtime, so the helper reads it once, each member
1786
+ * once, inside one contained boundary, and validates only the members it dereferences. A `meter`
1787
+ * or `budget` stop always leaves the run partial; a `model` stop is a complete answer, so a
1788
+ * consumer whose role admits a `length` finish keeps it. The consumer throws the returned error
1789
+ * when its policy refuses the stop. A `model` stop reports no cap because the Agent does not see
1790
+ * one; its `consumed` is the completion the stopped call reported, when finite.
1791
+ * @param stop - The `stop` member of an Agent or Ledger result
1792
+ * @returns Undefined when `stop` is undefined; a `CAPACITY` StudyError with role `agent` and the Agent layer for a meter, budget, or model stop; a `FAULT` StudyError with role `agent` for a malformed record
1793
+ * @example
1794
+ * ```ts
1795
+ * translateStudyAgentStop({ layer: 'meter', id: 'meter', max: 2000, consumed: 2001 })
1796
+ * // a CAPACITY StudyError whose failure.stop is { layer: 'meter', id: 'meter', max: 2000, consumed: 2001 }
1797
+ * ```
1798
+ */
1799
+ function translateStudyAgentStop(stop) {
1800
+ if (stop === void 0) return void 0;
1801
+ const reading = (0, _orkestrel_contract.attempt)(() => {
1802
+ if (!(0, _orkestrel_contract.isObject)(stop)) return void 0;
1803
+ const layer = Reflect.get(stop, "layer");
1804
+ const id = Reflect.get(stop, "id");
1805
+ if (!(0, _orkestrel_contract.isNonEmptyString)(id)) return void 0;
1806
+ if (layer === "meter" || layer === "budget") {
1807
+ const max = Reflect.get(stop, "max");
1808
+ const consumed = Reflect.get(stop, "consumed");
1809
+ const limit = parseStudyReading(max);
1810
+ const used = parseStudyReading(consumed);
1811
+ return limit === void 0 || used === void 0 ? void 0 : {
1812
+ layer,
1813
+ id,
1814
+ max: limit,
1815
+ consumed: used
1816
+ };
1817
+ }
1818
+ if (layer === "model") {
1819
+ const usage = Reflect.get(stop, "usage");
1820
+ return {
1821
+ layer,
1822
+ id,
1823
+ max: void 0,
1824
+ consumed: (0, _orkestrel_contract.isObject)(usage) ? parseStudyReading(Reflect.get(usage, "completion")) : void 0
1825
+ };
1826
+ }
1827
+ });
1828
+ const parsed = reading.success ? reading.value : void 0;
1829
+ if (parsed === void 0) {
1830
+ const message = "Agent stop record is malformed";
1831
+ return new StudyError("FAULT", message, {
1832
+ cause: "infrastructure",
1833
+ message,
1834
+ role: "agent",
1835
+ stop: void 0
1836
+ });
1837
+ }
1838
+ const message = parsed.layer === "meter" ? "Agent meter allowance reached its ceiling" : parsed.layer === "budget" ? "Agent budget reached its ceiling" : "Agent model reached its own token limit";
1839
+ return new StudyError("CAPACITY", message, {
1840
+ cause: "capacity",
1841
+ message,
1842
+ role: "agent",
1843
+ stop: parsed
1844
+ });
1845
+ }
1846
+ /**
1847
+ * Projects a request's structural components onto plain JSON without storing a total.
1848
+ * @param measure - The runtime's disjoint per-message, tools and schema estimates
1849
+ * @returns The same components in request order
1850
+ */
1851
+ function buildStudyAgentParts(measure) {
1852
+ return {
1853
+ messages: measure.messages.map((message) => ({
1854
+ id: message.id,
1855
+ role: message.role,
1856
+ content: message.content,
1857
+ framing: message.framing,
1858
+ calls: message.calls,
1859
+ thinking: message.thinking,
1860
+ images: message.images
1861
+ })),
1862
+ tools: measure.tools,
1863
+ schema: measure.schema
1864
+ };
1865
+ }
1866
+ /**
1867
+ * Builds the evidence join of a wire request to its canonical dispatch.
1868
+ * @param dispatch - The measured dispatch, or undefined when the caller measured none
1869
+ * @returns The dispatch id and revision, each null when unknown
1870
+ */
1871
+ function buildStudyAgentDispatch(dispatch) {
1872
+ return {
1873
+ canonical: dispatch?.id ?? null,
1874
+ revision: dispatch?.revision ?? null
1875
+ };
1876
+ }
1877
+ //#endregion
1878
+ //#region src/core/agents/validators.ts
1879
+ /**
1880
+ * Checks whether a namespace exposes the Agent capabilities the instrumentation invokes.
1881
+ * @remarks
1882
+ * The guard reads only `estimateRequest`, `measureRequest`, and `isAgentError`, so a namespace
1883
+ * without Ledger or conversation factories passes. A throwing accessor returns false.
1884
+ * @param value - The admitted namespace
1885
+ * @returns True if every required capability is a function; false otherwise
1886
+ */
1887
+ function isStudyAgentRuntime(value) {
1888
+ return (0, _orkestrel_contract.holds)(() => (0, _orkestrel_contract.isObject)(value) && "estimateRequest" in value && typeof value.estimateRequest === "function" && "measureRequest" in value && typeof value.measureRequest === "function" && "isAgentError" in value && typeof value.isAgentError === "function");
1889
+ }
1890
+ //#endregion
1891
+ //#region src/core/agents/StudyAgentObserver.ts
1892
+ /** Reads each Agent request's size before delegating it unchanged to the real provider. */
1893
+ var StudyAgentObserver = class {
1894
+ #options;
1895
+ /** Binds the real provider, the measuring runtime, the explicit gauge and usage policy, and the reading recorder.
1896
+ * @param options - Delegate, measurement seam, and policies.
1897
+ */
1898
+ constructor(options) {
1899
+ this.#options = { ...options };
1900
+ }
1901
+ /** Reports the delegate's trace label. */
1902
+ get id() {
1903
+ return this.#options.provider.id;
1904
+ }
1905
+ /** Reports the delegate's backend name. */
1906
+ get name() {
1907
+ return this.#options.provider.name;
1908
+ }
1909
+ /** Reports the delegate's thinking replay policy; an absent policy is the declared `none`. */
1910
+ get replay() {
1911
+ return this.#options.provider.replay ?? "none";
1912
+ }
1913
+ /** Records one reading, then awaits the real generation.
1914
+ * @param messages - The conversation sent.
1915
+ * @param signal - Bounds the request.
1916
+ * @param tools - The tools advertised this turn.
1917
+ * @param options - The per-call options.
1918
+ * @returns The real provider's result.
1919
+ */
1920
+ async generate(messages, signal, tools, options) {
1921
+ this.#measure(messages, tools, options);
1922
+ const result = await this.#options.provider.generate(messages, signal, tools, options);
1923
+ if (this.#options.enforced && !signal.aborted) validateStudyAgentUsage(result.usage, "agent");
1924
+ return result;
1925
+ }
1926
+ /** Records one reading, then relays the real stream.
1927
+ * @param messages - The conversation sent.
1928
+ * @param signal - Bounds the request.
1929
+ * @param tools - The tools advertised this turn.
1930
+ * @param options - The per-call options.
1931
+ * @returns The real deltas and result.
1932
+ */
1933
+ stream(messages, signal, tools, options) {
1934
+ this.#measure(messages, tools, options);
1935
+ return this.#relay(this.#options.provider.stream(messages, signal, tools, options), signal);
1936
+ }
1937
+ #measure(messages, tools, options) {
1938
+ const request = {
1939
+ messages,
1940
+ ...tools === void 0 ? {} : { tools },
1941
+ ...options === void 0 ? {} : { options }
1942
+ };
1943
+ const estimate = this.#options.runtime.estimateRequest(request);
1944
+ const gauge = this.#options.gauge;
1945
+ const projected = gauge === void 0 ? void 0 : projectStudyAgentRequest(gauge, estimate);
1946
+ this.#options.record({
1947
+ estimate,
1948
+ projected
1949
+ }, request);
1950
+ }
1951
+ async *#relay(source, signal) {
1952
+ const result = yield* source;
1953
+ if (this.#options.enforced && !signal.aborted) validateStudyAgentUsage(result.usage, "agent");
1954
+ return result;
1955
+ }
1956
+ };
1957
+ //#endregion
1958
+ //#region src/core/agents/StudyAgentJudge.ts
1959
+ /** Latches a real judge's failure before an enclosing runtime can treat it as absent. */
1960
+ var StudyAgentJudge = class {
1961
+ #judge;
1962
+ #latch;
1963
+ /** Binds a real public judge to the trial's failure owner.
1964
+ * @param judge - The admitted judge every question is delegated to.
1965
+ * @param latch - The owner that retains the first operational failure.
1966
+ */
1967
+ constructor(judge, latch) {
1968
+ this.#judge = judge;
1969
+ this.#latch = latch;
1970
+ }
1971
+ /** Reports the delegate's trace label. */
1972
+ get id() {
1973
+ return this.#judge.id;
1974
+ }
1975
+ /** Reports the delegate's backend name. */
1976
+ get name() {
1977
+ return this.#judge.name;
1978
+ }
1979
+ /** Reports the delegate's model identity. */
1980
+ get model() {
1981
+ return this.#judge.model;
1982
+ }
1983
+ /** Refuses dispatch after a retained failure and retains a thrown failure with its identity.
1984
+ * @param request - The real classification request.
1985
+ * @param signal - The caller's cancellation.
1986
+ * @returns The unmodified judge result.
1987
+ */
1988
+ async ask(request, signal) {
1989
+ this.#latch.check();
1990
+ try {
1991
+ return await this.#judge.ask(request, signal);
1992
+ } catch (error) {
1993
+ this.#latch.fail(error);
1994
+ throw error;
1995
+ }
1996
+ }
1997
+ };
1998
+ //#endregion
1999
+ exports.STUDY_CAUSES = STUDY_CAUSES;
2000
+ exports.STUDY_ERROR_BRAND = STUDY_ERROR_BRAND;
2001
+ exports.STUDY_GOALS = STUDY_GOALS;
2002
+ exports.STUDY_LAYERS = STUDY_LAYERS;
2003
+ exports.STUDY_NAME = STUDY_NAME;
2004
+ exports.STUDY_ROLES = STUDY_ROLES;
2005
+ exports.STUDY_TRIALS = STUDY_TRIALS;
2006
+ exports.StudyAgentJudge = StudyAgentJudge;
2007
+ exports.StudyAgentObserver = StudyAgentObserver;
2008
+ exports.StudyControl = StudyControl;
2009
+ exports.StudyDeadline = StudyDeadline;
2010
+ exports.StudyError = StudyError;
2011
+ exports.StudyMeter = StudyMeter;
2012
+ exports.StudyRequest = StudyRequest;
2013
+ exports.StudyScope = StudyScope;
2014
+ exports.StudySeries = StudySeries;
2015
+ exports.buildStudyAgentDispatch = buildStudyAgentDispatch;
2016
+ exports.buildStudyAgentParts = buildStudyAgentParts;
2017
+ exports.buildStudySchedule = buildStudySchedule;
2018
+ exports.computeStudyAdmittedStop = computeStudyAdmittedStop;
2019
+ exports.computeStudyOutputStop = computeStudyOutputStop;
2020
+ exports.computeStudyScores = computeStudyScores;
2021
+ exports.failStudyTicket = failStudyTicket;
2022
+ exports.failureToStudyError = failureToStudyError;
2023
+ exports.isStudyAgentRuntime = isStudyAgentRuntime;
2024
+ exports.isStudyBounds = isStudyBounds;
2025
+ exports.isStudyCause = isStudyCause;
2026
+ exports.isStudyCriterion = isStudyCriterion;
2027
+ exports.isStudyDefinition = isStudyDefinition;
2028
+ exports.isStudyDigest = isStudyDigest;
2029
+ exports.isStudyError = isStudyError;
2030
+ exports.isStudyErrorCode = isStudyErrorCode;
2031
+ exports.isStudyGoal = isStudyGoal;
2032
+ exports.isStudyGrading = isStudyGrading;
2033
+ exports.isStudyJudgment = isStudyJudgment;
2034
+ exports.isStudyLabeling = isStudyLabeling;
2035
+ exports.isStudyLayer = isStudyLayer;
2036
+ exports.isStudyLimit = isStudyLimit;
2037
+ exports.isStudyName = isStudyName;
2038
+ exports.isStudyProduct = isStudyProduct;
2039
+ exports.isStudyProfile = isStudyProfile;
2040
+ exports.isStudyProvider = isStudyProvider;
2041
+ exports.isStudyRole = isStudyRole;
2042
+ exports.isStudyRoom = isStudyRoom;
2043
+ exports.isStudyRubric = isStudyRubric;
2044
+ exports.isStudyScenario = isStudyScenario;
2045
+ exports.isStudyStop = isStudyStop;
2046
+ exports.isStudyTimestamp = isStudyTimestamp;
2047
+ exports.isStudyUsage = isStudyUsage;
2048
+ exports.matchesStudyKeys = matchesStudyKeys;
2049
+ exports.normalizeStudyProfile = normalizeStudyProfile;
2050
+ exports.omitStudyAbsent = omitStudyAbsent;
2051
+ exports.parseStudyDefinition = parseStudyDefinition;
2052
+ exports.parseStudyGrading = parseStudyGrading;
2053
+ exports.parseStudyLabeling = parseStudyLabeling;
2054
+ exports.parseStudyProfile = parseStudyProfile;
2055
+ exports.parseStudyReading = parseStudyReading;
2056
+ exports.parseStudyRubric = parseStudyRubric;
2057
+ exports.parseStudyScenario = parseStudyScenario;
2058
+ exports.projectStudyAgentRequest = projectStudyAgentRequest;
2059
+ exports.readStudyFailure = readStudyFailure;
2060
+ exports.studyStopToJSON = studyStopToJSON;
2061
+ exports.translateStudyAgentError = translateStudyAgentError;
2062
+ exports.translateStudyAgentStop = translateStudyAgentStop;
2063
+ exports.validateStudyAgentUsage = validateStudyAgentUsage;
2064
+ exports.validateStudyInputs = validateStudyInputs;
2065
+
2066
+ //# sourceMappingURL=index.cjs.map