@agentswf/lab 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +15 -2
  3. package/package.json +46 -4
  4. package/schema/lab-check.schema.json +64 -0
  5. package/schema/lab-config.schema.json +187 -0
  6. package/schema/lab-final.schema.json +48 -0
  7. package/schema/lab-good-record.schema.json +70 -0
  8. package/schema/lab-grade.schema.json +49 -0
  9. package/schema/lab-key.schema.json +124 -0
  10. package/schema/lab-label.schema.json +32 -0
  11. package/schema/lab-loop-report.schema.json +221 -0
  12. package/schema/lab-loop.schema.json +141 -0
  13. package/schema/lab-plan.schema.json +128 -0
  14. package/schema/lab-previous.schema.json +70 -0
  15. package/schema/lab-proposal.schema.json +52 -0
  16. package/schema/lab-report.schema.json +1128 -0
  17. package/schema/lab-run.schema.json +253 -0
  18. package/schema/lab-runs.schema.json +132 -0
  19. package/schema/lab-score.schema.json +319 -0
  20. package/schema/lab-spread.schema.json +110 -0
  21. package/schema/lab-trial.schema.json +543 -0
  22. package/schema/lab-try.schema.json +113 -0
  23. package/schema/local.json +155 -0
  24. package/src/cli.ts +9 -0
  25. package/src/env/capture.ts +48 -0
  26. package/src/env/compare.ts +201 -0
  27. package/src/env/facts.ts +51 -0
  28. package/src/env/fetch.ts +57 -0
  29. package/src/env/files.ts +228 -0
  30. package/src/env/grade-case.ts +80 -0
  31. package/src/env/grade-helper.ts +352 -0
  32. package/src/env/grader.ts +131 -0
  33. package/src/env/index.ts +727 -0
  34. package/src/env/mock.ts +374 -0
  35. package/src/env/routes.ts +90 -0
  36. package/src/env/sources.ts +19 -0
  37. package/src/env/state.ts +79 -0
  38. package/src/env/trial.ts +185 -0
  39. package/src/format/key.ts +168 -0
  40. package/src/format/loop.ts +179 -0
  41. package/src/format/output.ts +542 -0
  42. package/src/format/records.ts +443 -0
  43. package/src/format/schema-files.ts +64 -0
  44. package/src/format/settings.ts +559 -0
  45. package/src/format/trial-env.ts +67 -0
  46. package/src/format/trial-file.ts +134 -0
  47. package/src/help/awf-lab.txt +29 -0
  48. package/src/help/case.txt +39 -0
  49. package/src/help/config.txt +14 -0
  50. package/src/help/label.txt +12 -0
  51. package/src/help/loop.txt +44 -0
  52. package/src/help/report.txt +20 -0
  53. package/src/help/run.txt +61 -0
  54. package/src/help/runs.txt +11 -0
  55. package/src/help/score.txt +28 -0
  56. package/src/judge/criteria.workflow.ts +237 -0
  57. package/src/judge/version.ts +6 -0
  58. package/src/lab/answer.ts +47 -0
  59. package/src/lab/blame.ts +204 -0
  60. package/src/lab/box.ts +251 -0
  61. package/src/lab/capture-command.ts +302 -0
  62. package/src/lab/capture.ts +234 -0
  63. package/src/lab/check-command.ts +187 -0
  64. package/src/lab/cli.ts +325 -0
  65. package/src/lab/code-graders.ts +108 -0
  66. package/src/lab/columns.ts +138 -0
  67. package/src/lab/command-context.ts +436 -0
  68. package/src/lab/compare.ts +123 -0
  69. package/src/lab/config-command.ts +283 -0
  70. package/src/lab/criteria.ts +69 -0
  71. package/src/lab/dataset.ts +375 -0
  72. package/src/lab/eval-files.ts +196 -0
  73. package/src/lab/expect.ts +79 -0
  74. package/src/lab/facts.ts +59 -0
  75. package/src/lab/families.ts +32 -0
  76. package/src/lab/folders.ts +172 -0
  77. package/src/lab/git.ts +128 -0
  78. package/src/lab/good.ts +224 -0
  79. package/src/lab/grading-stub.txt +8 -0
  80. package/src/lab/grading.ts +332 -0
  81. package/src/lab/inspect.ts +227 -0
  82. package/src/lab/labels.ts +211 -0
  83. package/src/lab/loop-code.ts +255 -0
  84. package/src/lab/loop-command.ts +774 -0
  85. package/src/lab/loop-records.ts +144 -0
  86. package/src/lab/loop.ts +864 -0
  87. package/src/lab/marker.ts +23 -0
  88. package/src/lab/outcome.ts +196 -0
  89. package/src/lab/pooled.ts +106 -0
  90. package/src/lab/project-env.ts +39 -0
  91. package/src/lab/rates.ts +155 -0
  92. package/src/lab/reach.ts +111 -0
  93. package/src/lab/record-copies.ts +202 -0
  94. package/src/lab/refusal.ts +2 -0
  95. package/src/lab/report-command.ts +157 -0
  96. package/src/lab/report.ts +936 -0
  97. package/src/lab/reuse.ts +134 -0
  98. package/src/lab/run-command.ts +958 -0
  99. package/src/lab/run-logs.ts +89 -0
  100. package/src/lab/run-report.ts +286 -0
  101. package/src/lab/runs-command.ts +171 -0
  102. package/src/lab/runs.ts +172 -0
  103. package/src/lab/scaffold.ts +94 -0
  104. package/src/lab/score-command.ts +197 -0
  105. package/src/lab/score.ts +396 -0
  106. package/src/lab/store.ts +383 -0
  107. package/src/lab/target-stub.txt +18 -0
  108. package/src/lab/text.ts +29 -0
  109. package/src/lab/trial-settings.ts +105 -0
  110. package/src/lab/trial.ts +439 -0
  111. package/src/lab/usage.ts +274 -0
  112. package/src/lab/verdict.ts +161 -0
  113. package/src/lab/workflow-graders.ts +164 -0
  114. package/src/lab/workspace.ts +496 -0
  115. package/src/loop/propose.workflow.ts +84 -0
  116. package/src/shared/allowance.ts +185 -0
  117. package/src/shared/compare/index.ts +3 -0
  118. package/src/shared/compare/paired.ts +397 -0
  119. package/src/shared/compare/stats.ts +139 -0
  120. package/src/shared/compare/types.ts +75 -0
  121. package/src/shared/config.ts +15 -0
  122. package/src/shared/runner.ts +321 -0
  123. package/src/shared/validate.ts +181 -0
  124. package/src/shared/version.ts +41 -0
  125. package/src/write-schemas.ts +10 -0
@@ -0,0 +1,383 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ appendFileSync,
4
+ cpSync,
5
+ existsSync,
6
+ linkSync,
7
+ mkdirSync,
8
+ readdirSync,
9
+ readFileSync,
10
+ renameSync,
11
+ rmSync,
12
+ writeFileSync,
13
+ } from "node:fs";
14
+ import { dirname, join } from "node:path";
15
+ import type Type from "typebox";
16
+ import {
17
+ type RunRecord,
18
+ RunRecordSchema,
19
+ type ScoreRecord,
20
+ ScoreRecordSchema,
21
+ type TrialRecord,
22
+ TrialRecordSchema,
23
+ } from "../format/records";
24
+ import { type Checked, checkSchema, describeProblems } from "../shared/validate";
25
+
26
+ // The store: `{store}/runs/{id}/run.json`; a trial at `runs/{id}/trials/{case}/{column}-{trial}/`,
27
+ // with `trial.json`, `kept/`, `trial.jsonl` (its trial file) and `scores.jsonl` (every score,
28
+ // newest last); each built case once, at `inputs/{digest}/`; the workflows' runs under
29
+ // `{store}/awf-runs`.
30
+
31
+ export const RUN_FILE = "run.json";
32
+ export const TRIAL_FILE = "trial.json";
33
+ export const SCORES_FILE = "scores.jsonl";
34
+ /** In a run's trial folder in place of `trial.json`: the trial it reuses, where that one ran. */
35
+ export const REUSED_FILE = "reused.json";
36
+
37
+ export type TrialRef = { labRun: string; column: number; trial: number };
38
+
39
+ export const awfRunsOf = (store: string) => join(store, "awf-runs");
40
+ export const runDirOf = (store: string, id: string) => join(store, "runs", id);
41
+ export const trialDirOf = (
42
+ store: string,
43
+ id: string,
44
+ name: string,
45
+ column: number,
46
+ trial: number,
47
+ ) => join(runDirOf(store, id), "trials", name, `${column}-${trial}`);
48
+ /** A built case folder, kept once by its digest however many trials ran on it. */
49
+ export const inputDirOf = (store: string, digest: string) => join(store, "inputs", digest);
50
+
51
+ /** Keeps a built case folder under its digest, unless it is kept already; made whole, then moved. */
52
+ export function keepInput(store: string, digest: string, from: string): string {
53
+ const target = inputDirOf(store, digest);
54
+ if (existsSync(target)) return target;
55
+ const making = `${target}.${process.pid}-${randomUUID()}`;
56
+ mkdirSync(dirname(target), { recursive: true });
57
+ cpSync(from, making, { recursive: true, verbatimSymlinks: true });
58
+ try {
59
+ renameSync(making, target);
60
+ } catch (error) {
61
+ rmSync(making, { recursive: true, force: true });
62
+ if (!existsSync(target)) throw error;
63
+ }
64
+ return target;
65
+ }
66
+
67
+ /** An `awf run --id` unique among every workflow's runs in the store. */
68
+ export function newRunId(now: Date): string {
69
+ const stamp = now
70
+ .toISOString()
71
+ .replace(/[-:]/g, "")
72
+ .replace(/\.\d+Z$/, "Z");
73
+ return `${stamp}-${randomUUID().slice(0, 8)}`;
74
+ }
75
+
76
+ /**
77
+ * A trial's file, which its process appends to, in the lab's home: named by this process, so a
78
+ * later `run` sweeps what a dead one left.
79
+ */
80
+ export function trialFileOf(labHome: string): string {
81
+ return join(labHome, "trials", `${process.pid}-${randomUUID()}.jsonl`);
82
+ }
83
+
84
+ /** Removes trial files whose lab is gone; never one still owned, or not named by a process. */
85
+ export function clearStaleTrialFiles(labHome: string): number {
86
+ const dir = join(labHome, "trials");
87
+ if (!existsSync(dir)) return 0;
88
+ let removed = 0;
89
+ for (const name of readdirSync(dir)) {
90
+ const pid = /^([1-9][0-9]*)-/.exec(name)?.[1];
91
+ if (pid !== undefined && !alive(Number(pid))) {
92
+ rmSync(join(dir, name), { force: true });
93
+ removed++;
94
+ }
95
+ }
96
+ return removed;
97
+ }
98
+
99
+ export function alive(pid: number): boolean {
100
+ try {
101
+ process.kill(pid, 0);
102
+ return true;
103
+ } catch (error) {
104
+ return (error as NodeJS.ErrnoException).code === "EPERM";
105
+ }
106
+ }
107
+
108
+ /** The pid a lock file holds; undefined when it holds none this lab wrote. */
109
+ function lockHolder(file: string): number | undefined {
110
+ return lockOf(file)?.pid;
111
+ }
112
+
113
+ /** What a lock file holds: the pid, and the command, as `loop run desk`. */
114
+ function lockOf(file: string): { pid: number; command?: string } | undefined {
115
+ try {
116
+ const { pid, command } = JSON.parse(readFileSync(file, "utf8")) as {
117
+ pid?: unknown;
118
+ command?: unknown;
119
+ };
120
+ if (typeof pid !== "number") return undefined;
121
+ return { pid, ...(typeof command === "string" ? { command } : {}) };
122
+ } catch {
123
+ return undefined;
124
+ }
125
+ }
126
+
127
+ /**
128
+ * One `run`, `score`, `case capture` or `case pin` at a time on a store, under a lockfile in it, freed
129
+ * when its process is gone. It keeps a dataset's grade folders, which hold keys, from agents of its
130
+ * other runs; another project's labs keep their own store and run meanwhile. The lock is made whole, a file with this pid linked into
131
+ * place, so no lab ever reads it half written; a stale one is moved aside before it is removed,
132
+ * and only when it still holds the pid found dead. Returns the release, or who holds it: a pid,
133
+ * or `undefined` for a lock this lab can't read, which it never removes.
134
+ */
135
+ export function takeLock(
136
+ store: string,
137
+ command?: string,
138
+ ): { release: () => void } | { heldBy: number | undefined; command?: string } {
139
+ mkdirSync(store, { recursive: true });
140
+ const file = join(store, "lock");
141
+ const mine = join(store, `lock.${process.pid}-${randomUUID()}`);
142
+ writeFileSync(mine, JSON.stringify({ pid: process.pid, ...(command ? { command } : {}) }));
143
+ const held = () => {
144
+ const lock = lockOf(file);
145
+ return { heldBy: lock?.pid, ...(lock?.command ? { command: lock.command } : {}) };
146
+ };
147
+ try {
148
+ for (let attempt = 0; attempt < 3; attempt++) {
149
+ try {
150
+ linkSync(mine, file);
151
+ return {
152
+ release: () => {
153
+ if (lockHolder(file) === process.pid) rmSync(file, { force: true });
154
+ },
155
+ };
156
+ } catch (error) {
157
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
158
+ }
159
+ const pid = lockHolder(file);
160
+ if (pid === undefined || alive(pid)) return held();
161
+ const aside = join(store, `lock.stale-${randomUUID()}`);
162
+ try {
163
+ renameSync(file, aside);
164
+ } catch {
165
+ continue;
166
+ }
167
+ if (lockHolder(aside) === pid) rmSync(aside, { force: true });
168
+ else {
169
+ // Another lab took the lock between the read and the move: put its lock back.
170
+ try {
171
+ linkSync(aside, file);
172
+ } catch {}
173
+ rmSync(aside, { force: true });
174
+ return held();
175
+ }
176
+ }
177
+ throw new Error(`could not take the lock ${file}`);
178
+ } finally {
179
+ rmSync(mine, { force: true });
180
+ }
181
+ }
182
+
183
+ /**
184
+ * A new run's id, its folder claimed: the time and four random hex digits, unique across machines
185
+ * so records from two of them never clash, and ordered by time as text.
186
+ */
187
+ export function claimRun(store: string, now: Date): string {
188
+ mkdirSync(join(store, "runs"), { recursive: true });
189
+ // Claimed under the lock: a second run within a second takes the next second, so ids stay in
190
+ // the order the runs were made.
191
+ const last = runIds(store).at(-1);
192
+ let at = now.getTime() - (now.getTime() % 1000);
193
+ if (last && stampOf(at) <= last.slice(0, 15)) at = timeOf(last) + 1000;
194
+ const stamp = stampOf(at);
195
+ for (;;) {
196
+ const id = `${stamp}-${randomUUID().slice(0, 4)}`;
197
+ try {
198
+ mkdirSync(runDirOf(store, id));
199
+ return id;
200
+ } catch (error) {
201
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
202
+ }
203
+ }
204
+ }
205
+
206
+ const stampOf = (ms: number) =>
207
+ new Date(ms).toISOString().replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
208
+
209
+ /** The time an id was claimed at, to the second. */
210
+ function timeOf(id: string): number {
211
+ const [, y, mo, d, h, mi, se] = /^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})/.exec(id)!;
212
+ return Date.UTC(+y!, +mo! - 1, +d!, +h!, +mi!, +se!);
213
+ }
214
+
215
+ /** The store's run ids, oldest first. */
216
+ export function runIds(store: string): string[] {
217
+ const dir = join(store, "runs");
218
+ if (!existsSync(dir)) return [];
219
+ return readdirSync(dir)
220
+ .filter((name) => RUN_ID.test(name))
221
+ .sort();
222
+ }
223
+
224
+ export const RUN_ID = /^[0-9]{8}-[0-9]{6}-[0-9a-f]{4}$/;
225
+
226
+ /**
227
+ * The store's runs whose records read, each with its trials, oldest first unless `newest`; of one
228
+ * dataset when named, and made before the run id `before` when given. A run whose records don't
229
+ * read is left out: `runs` names it.
230
+ */
231
+ export function* readableRuns(
232
+ store: string,
233
+ options: {
234
+ dataset?: string;
235
+ newest?: boolean;
236
+ before?: string;
237
+ } = {},
238
+ ): Generator<{ run: RunRecord; trials: StoredTrial[] }> {
239
+ const { before } = options;
240
+ const ids = runIds(store).filter((id) => before === undefined || id < before);
241
+ for (const id of options.newest ? ids.reverse() : ids) {
242
+ let read: { run: RunRecord; trials: StoredTrial[] } | undefined;
243
+ try {
244
+ const run = readRunRecord(store, id);
245
+ if (!run || (options.dataset !== undefined && run.dataset !== options.dataset)) continue;
246
+ read = { run, trials: readTrials(store, id) };
247
+ } catch (error) {
248
+ if (error instanceof UnreadableRecord) continue;
249
+ throw error;
250
+ }
251
+ yield read;
252
+ }
253
+ }
254
+
255
+ /**
256
+ * When a run ran, for the grades it made: from its start to its finish. A run killed before it
257
+ * stamped one ends when the next run's id says it started, so a `score` made in between counts as
258
+ * its; with no next run, it is open.
259
+ */
260
+ export function runSpan(store: string, run: RunRecord): { started: string; finished?: string } {
261
+ if (run.finished !== undefined) return { started: run.started, finished: run.finished };
262
+ const next = runIds(store).find((id) => id > run.id);
263
+ return next
264
+ ? { started: run.started, finished: new Date(timeOf(next)).toISOString() }
265
+ : { started: run.started };
266
+ }
267
+
268
+ /**
269
+ * A record this lab can't read: one that fails its schema, or not JSON. History
270
+ * leaves its run out; any other error is the lab's.
271
+ */
272
+ export class UnreadableRecord extends Error {}
273
+
274
+ function checked<T>(file: string, result: Checked<T>): T {
275
+ if (!result.ok) throw new UnreadableRecord(describeProblems(file, result.problems));
276
+ return result.value;
277
+ }
278
+
279
+ /** A record read back, checked against its schema. */
280
+ function readRecord<T>(file: string, schema: Type.TSchema, value: unknown): T {
281
+ return checked(file, checkSchema(schema, value)) as T;
282
+ }
283
+
284
+ function readJson(file: string): unknown {
285
+ return parseJson(file, readFileSync(file, "utf8"));
286
+ }
287
+
288
+ function parseJson(file: string, text: string): unknown {
289
+ try {
290
+ return JSON.parse(text);
291
+ } catch (error) {
292
+ throw new UnreadableRecord(`${file} is not valid:\n ${(error as Error).message}`);
293
+ }
294
+ }
295
+
296
+ export function writeRun(store: string, run: RunRecord): void {
297
+ const file = join(runDirOf(store, run.id), RUN_FILE);
298
+ writeFileSync(
299
+ file,
300
+ `${JSON.stringify(checked(file, checkSchema(RunRecordSchema, run)), null, 2)}\n`,
301
+ );
302
+ }
303
+
304
+ export function readRunRecord(store: string, id: string): RunRecord | undefined {
305
+ const file = join(runDirOf(store, id), RUN_FILE);
306
+ if (!existsSync(file)) return undefined;
307
+ return readRecord<RunRecord>(file, RunRecordSchema, readJson(file));
308
+ }
309
+
310
+ export function writeTrial(dir: string, trial: TrialRecord): void {
311
+ mkdirSync(dir, { recursive: true });
312
+ const file = join(dir, TRIAL_FILE);
313
+ writeFileSync(
314
+ file,
315
+ `${JSON.stringify(checked(file, checkSchema(TrialRecordSchema, trial)), null, 2)}\n`,
316
+ );
317
+ }
318
+
319
+ export function appendScore(dir: string, score: ScoreRecord): void {
320
+ const file = join(dir, SCORES_FILE);
321
+ appendFileSync(file, `${JSON.stringify(checked(file, checkSchema(ScoreRecordSchema, score)))}\n`);
322
+ }
323
+
324
+ export type StoredTrial = { dir: string; record: TrialRecord; scores: ScoreRecord[] };
325
+
326
+ /** A run's trials, each with its scores, newest last. */
327
+ function readSlot(dir: string): Omit<StoredTrial, "dir"> | undefined {
328
+ const file = join(dir, TRIAL_FILE);
329
+ if (!existsSync(file)) return undefined;
330
+ const record = readRecord<TrialRecord>(file, TrialRecordSchema, readJson(file));
331
+ const scoresFile = join(dir, SCORES_FILE);
332
+ const scores = existsSync(scoresFile)
333
+ ? readFileSync(scoresFile, "utf8")
334
+ .split("\n")
335
+ .filter((line) => line.trim() !== "")
336
+ .map((line) =>
337
+ readRecord<ScoreRecord>(scoresFile, ScoreRecordSchema, parseJson(scoresFile, line)),
338
+ )
339
+ : [];
340
+ return { record: gradedRecord(record, scores), scores };
341
+ }
342
+
343
+ /**
344
+ * The trial as its grading left it: errored in `facts` while its newest score that read facts says
345
+ * grading couldn't start. Never written back: the trial record stays as the trial ended.
346
+ */
347
+ export function gradedRecord(record: TrialRecord, scores: readonly ScoreRecord[]): TrialRecord {
348
+ const newest = scores.findLast((score) => score.facts !== undefined || score.errored);
349
+ if (record.errored || !newest?.errored) return record;
350
+ return { ...record, errored: newest.errored };
351
+ }
352
+
353
+ /**
354
+ * A run's trials, each with its scores, newest last. A reused trial is read where it ran, so its
355
+ * grades are one list however many runs reuse it, and shown as this run's, marked `reused`.
356
+ */
357
+ export function readTrials(store: string, id: string): StoredTrial[] {
358
+ const root = join(runDirOf(store, id), "trials");
359
+ if (!existsSync(root)) return [];
360
+ const found: StoredTrial[] = [];
361
+ for (const name of readdirSync(root).sort()) {
362
+ for (const slot of readdirSync(join(root, name)).sort()) {
363
+ const dir = join(root, name, slot);
364
+ const pointer = join(dir, REUSED_FILE);
365
+ if (existsSync(pointer)) {
366
+ const ref = readJson(pointer) as TrialRef;
367
+ const at = trialDirOf(store, ref.labRun, name, ref.column, ref.trial);
368
+ const ran = readSlot(at);
369
+ if (!ran) continue; // the run it reuses is gone from this store
370
+ const [column, trial] = slot.split("-").map(Number) as [number, number];
371
+ found.push({
372
+ dir: at,
373
+ record: { ...ran.record, labRun: id, column, trial, reused: ref },
374
+ scores: ran.scores,
375
+ });
376
+ continue;
377
+ }
378
+ const ran = readSlot(dir);
379
+ if (ran) found.push({ dir, ...ran });
380
+ }
381
+ }
382
+ return found.sort((a, b) => a.record.trial - b.record.trial || a.record.column - b.record.column);
383
+ }
@@ -0,0 +1,18 @@
1
+ Fill in workflow and setup, then delete this line: run refuses the file until then.
2
+ import { defineTarget } from "@agentswf/lab";
3
+
4
+ export default defineTarget({
5
+ // Bump the minor, or add a -{tag}, for a change that should rerun the kept trials.
6
+ version: "1.0.0",
7
+ // The workflow as it ships, imported lazily so the mocks setup makes exist before it loads.
8
+ workflow: () => import("../../path/to/workflow"),
9
+ // The whole trial runs in the lab's sandbox, everything closed, unless sandbox says otherwise:
10
+ // sandbox: { by: "workflow" } runs the agents in the sandboxes the workflow opens instead, and
11
+ // sandbox.network opens what a trial may reach. limits: { setup, workflow, after } are 10m, 30m, 10m.
12
+
13
+ setup(trial) {
14
+ // Build the case's world from trial.readJson(...) and trial.readText(...), the case's input/, with trial.mock("name", module, { … }), trial.fake and trial.mockFetch.
15
+ // The run ends in a trial record, which grading.ts's facts reads.
16
+ return { argv: [] };
17
+ },
18
+ });
@@ -0,0 +1,29 @@
1
+ import type { Folder } from "../format/records";
2
+
3
+ // How the lab writes counts, money, time and folders, in every command's text.
4
+
5
+ export const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`;
6
+
7
+ export function seconds(ms: number): string {
8
+ return ms < 10_000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.round(ms / 1000)}s`;
9
+ }
10
+
11
+ export const usd = (n: number) => `$${n < 0.01 && n > 0 ? n.toFixed(4) : n.toFixed(2)}`;
12
+
13
+ export function median(values: readonly number[]): number | undefined {
14
+ if (values.length === 0) return undefined;
15
+ const sorted = [...values].sort((a, b) => a - b);
16
+ const mid = Math.floor(sorted.length / 2);
17
+ return sorted.length % 2 ? sorted[mid]! : (sorted[mid - 1]! + sorted[mid]!) / 2;
18
+ }
19
+
20
+ /** A folder of code: `this checkout`, or its path, with its branch, commit and changes. */
21
+ export function describeFolder(
22
+ folder: Pick<Folder, "branch" | "commit" | "dirty"> & { path?: string | undefined },
23
+ ): string {
24
+ const parts = [
25
+ folder.branch ? `branch ${folder.branch}` : "detached",
26
+ ...(folder.commit ? [`commit ${folder.commit.slice(0, 7)}`] : []),
27
+ ];
28
+ return `${folder.path ?? "this checkout"}, ${parts.join(", ")}${folder.dirty ? ", with uncommitted changes" : ""}`;
29
+ }
@@ -0,0 +1,105 @@
1
+ import {
2
+ LIMIT_PHASES,
3
+ type LimitPhase,
4
+ type Limits,
5
+ type ResolvedLimits,
6
+ type ResolvedSandbox,
7
+ type TargetFile,
8
+ } from "../format/settings";
9
+ import type { TrialSettings } from "../format/trial-env";
10
+ import type { DatasetInfo } from "./dataset";
11
+ import { Refusal } from "./refusal";
12
+
13
+ /**
14
+ * The hosts the engine reaches itself from the trial's process: its decision provider,
15
+ * `OPENROUTER_DECISIONS` in `engine/src/decisions/openrouter.ts`. One that falls behind refuses a
16
+ * decision, which errors the trial as the dataset's and names the host.
17
+ */
18
+ export const ENGINE_HOSTS = ["openrouter.ai"] as const;
19
+
20
+ /** Each phase's limit when neither `target.ts` nor `--limit` gives one. */
21
+ export const LIMIT_DEFAULTS: ResolvedLimits = { setup: "10m", workflow: "30m", after: "10m" };
22
+
23
+ /** What shapes a column's trials beyond its parameters: its sandbox and limits, resolved. */
24
+ export type ResolvedSettings = { sandbox: ResolvedSandbox; limits: ResolvedLimits };
25
+
26
+ const UNIT = { ms: 1, s: 1000, m: 60_000, h: 3_600_000 } as const;
27
+ const DURATION = /^[1-9][0-9]*(ms|s|m|h)$/;
28
+
29
+ /** `"30m"` in ms; the schema has already checked its shape. */
30
+ export function durationMs(text: string): number {
31
+ const match = /^(\d+)(ms|s|m|h)$/.exec(text);
32
+ if (!match) throw new Error(`not a duration: ${text}`);
33
+ return Number(match[1]) * UNIT[match[2] as keyof typeof UNIT];
34
+ }
35
+
36
+ /** `--limit {phase}={duration}`, each repeatable: a phase once, of setup, workflow and after. */
37
+ export function readLimits(given: readonly string[]): Limits {
38
+ const limits: Limits = {};
39
+ for (const each of given) {
40
+ const at = each.indexOf("=");
41
+ const phase = at > 0 ? each.slice(0, at) : "";
42
+ const duration = at > 0 ? each.slice(at + 1) : "";
43
+ if (phase === "run") {
44
+ throw new Refusal(
45
+ `--limit run is now --limit workflow: --limit workflow=${duration || "{duration}"}`,
46
+ );
47
+ }
48
+ if (!(LIMIT_PHASES as readonly string[]).includes(phase)) {
49
+ throw new Refusal(
50
+ `--limit ${each}: give {phase}={duration}, the phase ${LIMIT_PHASES.join(", ")}`,
51
+ );
52
+ }
53
+ if (!DURATION.test(duration)) {
54
+ throw new Refusal(`--limit ${each}: a duration is a number and a unit, such as 30m or 90s`);
55
+ }
56
+ if (limits[phase as LimitPhase] !== undefined) {
57
+ throw new Refusal(`--limit ${each}: ${phase} is given twice`);
58
+ }
59
+ limits[phase as LimitPhase] = duration;
60
+ }
61
+ return limits;
62
+ }
63
+
64
+ /** A `target.ts`'s sandbox and limits, every part given: `--limit` over the file over the defaults. */
65
+ export function resolveSettings(target: TargetFile, limits: Limits = {}): ResolvedSettings {
66
+ const given = target.sandbox ?? {};
67
+ const network = {
68
+ agents: [...(given.network?.agents ?? [])],
69
+ code: [...(given.network?.code ?? [])],
70
+ webSearch: given.network?.webSearch === true,
71
+ sockets: [...(given.network?.sockets ?? [])],
72
+ };
73
+ // A provider names the lab's sandbox, so with `by: "workflow"` it shapes nothing.
74
+ const sandbox: ResolvedSandbox =
75
+ given.by === "workflow"
76
+ ? { by: "workflow", network }
77
+ : { by: "lab", provider: given.provider ?? "srt", network };
78
+ return { sandbox, limits: { ...LIMIT_DEFAULTS, ...target.limits, ...limits } };
79
+ }
80
+
81
+ /** What the trial's process is told: the dataset, its limits in ms and the hosts its code may reach. */
82
+ export function trialSettingsOf(info: DatasetInfo, settings: ResolvedSettings): TrialSettings {
83
+ return {
84
+ dataset: info.name,
85
+ datasetDir: info.evalDir,
86
+ setupMs: durationMs(settings.limits.setup),
87
+ workflowMs: durationMs(settings.limits.workflow),
88
+ afterMs: durationMs(settings.limits.after),
89
+ codeHosts: [...new Set([...settings.sandbox.network.code, ...ENGINE_HOSTS])],
90
+ };
91
+ }
92
+
93
+ /**
94
+ * The limit of what the lab runs in your checkout's helper after a trial: code graders, `facts`,
95
+ * `compare` and `capture.ts`, under `target.ts`'s `limits.after`.
96
+ */
97
+ export function afterMsOf(info: DatasetInfo): number {
98
+ return durationMs(info.target.limits?.after ?? LIMIT_DEFAULTS.after);
99
+ }
100
+
101
+ /** `awf run --timeout`: a backstop the engine records as `timed-out`, past every phase's own. */
102
+ export function backstopOf(settings: TrialSettings): string {
103
+ const ms = settings.setupMs + settings.workflowMs + settings.afterMs + 60_000;
104
+ return `${Math.ceil(ms / 1000)}s`;
105
+ }