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