@orkestrel/study 0.0.0-stage → 0.0.2

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