@agentswf/lab 0.0.0-stage → 0.3.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/case-check.schema.json +64 -0
  5. package/schema/case-config.schema.json +187 -0
  6. package/schema/case-final.schema.json +48 -0
  7. package/schema/case-good-record.schema.json +70 -0
  8. package/schema/case-grade.schema.json +49 -0
  9. package/schema/case-key.schema.json +117 -0
  10. package/schema/case-label.schema.json +32 -0
  11. package/schema/case-loop-report.schema.json +210 -0
  12. package/schema/case-loop.schema.json +141 -0
  13. package/schema/case-plan.schema.json +117 -0
  14. package/schema/case-previous.schema.json +70 -0
  15. package/schema/case-proposal.schema.json +52 -0
  16. package/schema/case-report.schema.json +892 -0
  17. package/schema/case-run.schema.json +253 -0
  18. package/schema/case-runs.schema.json +125 -0
  19. package/schema/case-score.schema.json +319 -0
  20. package/schema/case-spread.schema.json +110 -0
  21. package/schema/case-trial.schema.json +543 -0
  22. package/schema/case-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 +128 -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 +182 -0
  39. package/src/format/key.ts +144 -0
  40. package/src/format/loop.ts +178 -0
  41. package/src/format/output.ts +481 -0
  42. package/src/format/records.ts +440 -0
  43. package/src/format/schema-files.ts +64 -0
  44. package/src/format/settings.ts +552 -0
  45. package/src/format/trial-env.ts +64 -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 +38 -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 +60 -0
  54. package/src/help/runs.txt +10 -0
  55. package/src/help/score.txt +27 -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 +249 -0
  61. package/src/lab/capture-command.ts +298 -0
  62. package/src/lab/capture.ts +234 -0
  63. package/src/lab/check-command.ts +187 -0
  64. package/src/lab/cli.ts +324 -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 +278 -0
  70. package/src/lab/criteria.ts +69 -0
  71. package/src/lab/dataset.ts +356 -0
  72. package/src/lab/eval-files.ts +185 -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 +153 -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 +226 -0
  82. package/src/lab/labels.ts +206 -0
  83. package/src/lab/loop-code.ts +255 -0
  84. package/src/lab/loop-command.ts +770 -0
  85. package/src/lab/loop-records.ts +144 -0
  86. package/src/lab/loop.ts +859 -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 +150 -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 +156 -0
  96. package/src/lab/report.ts +838 -0
  97. package/src/lab/reuse.ts +126 -0
  98. package/src/lab/run-command.ts +853 -0
  99. package/src/lab/run-logs.ts +89 -0
  100. package/src/lab/run-report.ts +259 -0
  101. package/src/lab/runs-command.ts +163 -0
  102. package/src/lab/runs.ts +172 -0
  103. package/src/lab/scaffold.ts +91 -0
  104. package/src/lab/score-command.ts +189 -0
  105. package/src/lab/score.ts +396 -0
  106. package/src/lab/store.ts +383 -0
  107. package/src/lab/text.ts +29 -0
  108. package/src/lab/trial-settings.ts +100 -0
  109. package/src/lab/trial-stub.txt +18 -0
  110. package/src/lab/trial.ts +443 -0
  111. package/src/lab/usage.ts +273 -0
  112. package/src/lab/verdict.ts +161 -0
  113. package/src/lab/workflow-graders.ts +161 -0
  114. package/src/lab/workspace.ts +489 -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,443 @@
1
+ import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { runLogLine, type SandboxRecord } from "@agentswf/contract/records";
4
+ import {
5
+ type Errored,
6
+ type Params,
7
+ SCORE_KIND,
8
+ type ScoreRecord,
9
+ TRIAL_KIND,
10
+ type TrialRecord,
11
+ } from "../format/records";
12
+ import { TRIAL_ENV } from "../format/trial-env";
13
+ import { type AwfBin, loginRefused, type Runner, withoutCallingSession } from "../shared/runner";
14
+ import { blame, harnessStop, readTrialLines } from "./blame";
15
+ import { type BoxSpec, boxNetwork, boxReach, boxSpec, hiddenOf, writeBoxSpec } from "./box";
16
+ import { type CaseInfo, type DatasetInfo, folderDigest } from "./dataset";
17
+ import { type FactsReader, recordOf } from "./facts";
18
+ import {
19
+ buildCase,
20
+ keepFiles,
21
+ makeTrialFolders,
22
+ type Needle,
23
+ searchFolder,
24
+ searchText,
25
+ } from "./folders";
26
+ import { decidersOf, gradeTrial, type LabGrader } from "./grading";
27
+ import type { FolderSetup } from "./inspect";
28
+ import { checkReach, type OpenedAgent } from "./reach";
29
+ import { agentsOpenedOf, runFactsOf, turnsOf } from "./run-logs";
30
+ import {
31
+ appendScore,
32
+ awfRunsOf,
33
+ gradedRecord,
34
+ keepInput,
35
+ newRunId,
36
+ trialDirOf,
37
+ trialFileOf,
38
+ writeTrial,
39
+ } from "./store";
40
+ import { backstopOf, type ResolvedSettings, trialSettingsOf } from "./trial-settings";
41
+ import type { CaseWorkspace } from "./workspace";
42
+
43
+ export type TrialLab = {
44
+ workspace: CaseWorkspace;
45
+ dataset: DatasetInfo;
46
+ run: string;
47
+ runner: Runner;
48
+ /** Everything `awf logs` has for a trial's run, or why it couldn't be read whole. */
49
+ logs: (
50
+ awf: AwfBin,
51
+ runRoot: string,
52
+ ref: string,
53
+ env: Record<string, string | undefined>,
54
+ ) => Promise<{ text: string } | { unread: string }>;
55
+ /** What a run that printed no record is estimated at, read from its folder; absent, unpriced. */
56
+ estimate?: (
57
+ awf: AwfBin,
58
+ runRoot: string,
59
+ ref: string,
60
+ env: Record<string, string | undefined>,
61
+ ) => Promise<number | undefined>;
62
+ /** Where trial folders are made: the system's temporary folder. */
63
+ tmp: string;
64
+ /** The lab's environment, which every trial starts from. */
65
+ env: Readonly<Record<string, string | undefined>>;
66
+ graders: readonly LabGrader[];
67
+ /** `grading.ts`'s `facts`, run on the trial record once it ends. */
68
+ facts: FactsReader;
69
+ now: () => Date;
70
+ };
71
+
72
+ export type TrialDone = { record: TrialRecord; score?: ScoreRecord; dir: string };
73
+
74
+ /** What a column's trials run under: its `trial.ts`, parameters, version and settings. */
75
+ export type ColumnShape = {
76
+ /** The column's `trial.ts`: your checkout's, or the same file in a folder `--against` names. */
77
+ trialScript: string;
78
+ params: Params;
79
+ /** The column's version: its `trial.ts`'s, or the loop's id of its code. */
80
+ version: string;
81
+ /** Its `trial.ts`'s sandbox and limits, resolved, `--limit` over them. */
82
+ settings: ResolvedSettings;
83
+ /** The trial's reuse key, from its built case's digest; absent, never reused. */
84
+ reuseOf?: (input: string) => string | undefined;
85
+ };
86
+
87
+ /**
88
+ * One trial: the case folder built without the key, the marker looked for, the folder's own `awf`
89
+ * run on `trial.ts`, its ending blamed, its agents' reach checked, the marker looked for again, the
90
+ * facts graded; then both folders deleted.
91
+ */
92
+ export async function runTrial(
93
+ lab: TrialLab,
94
+ folder: FolderSetup,
95
+ info: CaseInfo,
96
+ column: number,
97
+ trial: number,
98
+ shape: ColumnShape,
99
+ ): Promise<TrialDone> {
100
+ const { workspace, dataset } = lab;
101
+ const { trialScript, params, version, settings: shaped } = shape;
102
+ const { sandbox } = shaped;
103
+ const started = Date.now();
104
+ const dir = trialDirOf(workspace.store, lab.run, info.name, column, trial);
105
+ rmSync(dir, { recursive: true, force: true });
106
+ mkdirSync(dir, { recursive: true });
107
+ const folders = makeTrialFolders(lab.tmp, lab.run);
108
+ // In the lab's box, everything the trial's process writes is in its own folder: the box denies
109
+ // the home folder, so `~/.awf/lab` too.
110
+ const boxed = sandbox.by === "lab";
111
+ const trialFile = boxed
112
+ ? join(folders.parent, "trial", "trial.jsonl")
113
+ : trialFileOf(workspace.labHome);
114
+ try {
115
+ buildCase(dataset.dataDir, info, folders.dir);
116
+ const input = folderDigest(folders.dir);
117
+ keepInput(workspace.store, input, folders.dir);
118
+ const reuse = shape.reuseOf?.(input);
119
+ const needle: Needle = { marker: info.key.marker, keyFiles: info.keyFiles };
120
+ const base: TrialRecord = {
121
+ kind: TRIAL_KIND,
122
+ run: lab.run,
123
+ dataset: dataset.name,
124
+ case: info.name,
125
+ column,
126
+ trial,
127
+ params,
128
+ version,
129
+ ...(reuse ? { reuse } : {}),
130
+ awf: { bin: folder.awf.bin, version: folder.version },
131
+ input,
132
+ sandbox,
133
+ limits: shaped.limits,
134
+ models: [],
135
+ at: lab.now().toISOString(),
136
+ ms: 0,
137
+ files: [],
138
+ unused: [],
139
+ refused: [],
140
+ leaked: false,
141
+ };
142
+ if (searchFolder(folders.dir, needle, "the case folder").length > 0) {
143
+ const record = { ...base, leaked: true, ms: Date.now() - started };
144
+ writeTrial(dir, record);
145
+ return { record, dir };
146
+ }
147
+
148
+ mkdirSync(dirname(trialFile), { recursive: true });
149
+ writeFileSync(trialFile, "");
150
+ const settings = trialSettingsOf(dataset, shaped);
151
+ const id = newRunId(lab.now());
152
+ const storeRuns = awfRunsOf(workspace.store);
153
+ const path = [folder.bin, lab.env.PATH].filter(Boolean).join(":");
154
+ // The box's run records are its own, copied into the store after: the box never reads it.
155
+ const runRoot = boxed ? join(folders.parent, "runs") : storeRuns;
156
+ const box: BoxSpec | undefined = boxed
157
+ ? boxSpec({
158
+ read: [folder.root, folders.dir],
159
+ write: [".", dirname(trialFile)],
160
+ hide: hiddenOf(folder.root, workspace, {
161
+ trial: { data: dataset.dataDir, dir: info.dir },
162
+ }),
163
+ network: boxNetwork(sandbox.network, settings.codeHosts),
164
+ webSearch: sandbox.network.webSearch,
165
+ sockets: sandbox.network.sockets,
166
+ })
167
+ : undefined;
168
+ const env: Record<string, string | undefined> = {
169
+ ...definedOf(withoutCallingSession(lab.env)),
170
+ PATH: path,
171
+ [TRIAL_ENV.case]: folders.dir,
172
+ [TRIAL_ENV.trial]: trialFile,
173
+ [TRIAL_ENV.scratch]: folders.scratch,
174
+ [TRIAL_ENV.root]: folder.root,
175
+ [TRIAL_ENV.settings]: JSON.stringify(settings),
176
+ [TRIAL_ENV.params]: JSON.stringify(params),
177
+ };
178
+ const result = await lab.runner({
179
+ workflow: trialScript,
180
+ cwd: folders.scratch,
181
+ timeout: backstopOf(settings),
182
+ argv: [],
183
+ runRoot,
184
+ id,
185
+ awf: folder.awf,
186
+ quiet: true,
187
+ env,
188
+ ...(box ? { in: writeBoxSpec(box, join(folders.parent, "box.json")) } : {}),
189
+ });
190
+ // The box's run records move into the store, where `awf logs` and history find them.
191
+ if (boxed && existsSync(runRoot)) cpSync(runRoot, storeRuns, { recursive: true });
192
+ // The lab's own failures to read what the trial left: its result says nothing of the workflow.
193
+ const unread: string[] = [];
194
+ if (result.unread) unread.push(result.unread);
195
+ const trialText = readFileSync(trialFile, "utf8");
196
+ writeFileSync(join(dir, "trial.jsonl"), trialText);
197
+ const { lines, bad } = readTrialLines(trialText);
198
+ if (bad > 0) unread.push(`${bad} line${bad === 1 ? "" : "s"} of the trial file fit no shape`);
199
+ const run = result.record;
200
+ const blamed = blame(lines, {
201
+ ...(run ? { outcome: run.outcome } : {}),
202
+ ...(run && run.outcome !== "completed" ? { reason: run.reason } : {}),
203
+ ...(run?.outcome === "completed" ? { value: run.value } : {}),
204
+ stderr: result.stderr,
205
+ loginRefused: run !== undefined && loginRefused(run),
206
+ });
207
+
208
+ const boxedDir = run?.artifacts?.startsWith(runRoot)
209
+ ? join(storeRuns, run.artifacts.slice(runRoot.length))
210
+ : undefined;
211
+ const runDir = boxed
212
+ ? (boxedDir ?? findRunDir(storeRuns, id))
213
+ : (run?.artifacts ?? findRunDir(runRoot, id));
214
+ const reach = box
215
+ ? boxReach(box, runDir ? readAgents(runDir).opened.map((a) => a.agent) : [])
216
+ : runDir
217
+ ? checkReach({
218
+ ...readAgents(runDir),
219
+ sandboxes: sandboxesOf(runDir, run?.sandboxes),
220
+ network: sandbox.network,
221
+ })
222
+ : undefined;
223
+
224
+ const gathered = blamed.gathered;
225
+ const files = gathered ? keepFiles(folders.scratch, gathered.files, join(dir, "kept")) : [];
226
+ const ref = run?.ref ?? (run ? `${run.workflow.name}/${run.runId}` : undefined);
227
+ const shown = JSON.stringify({
228
+ value: run?.outcome === "completed" ? run.value : null,
229
+ gathered: gathered ?? null,
230
+ });
231
+ const logs = ref ? await lab.logs(folder.awf, storeRuns, ref, env) : undefined;
232
+ if (logs && "unread" in logs) unread.push(logs.unread);
233
+ const turns = logs && "text" in logs ? turnsOf(logs.text) : undefined;
234
+ if (run && !runDir) unread.push(`no folder for run ${run.runId} under ${runRoot}`);
235
+ const leaks = [
236
+ ...searchFolder(folders.scratch, needle, "the scratch folder"),
237
+ ...searchText(shown, needle, "the result"),
238
+ ...(logs && "text" in logs ? searchText(logs.text, needle, "the run's logs") : []),
239
+ ...(runDir ? searchFolder(runDir, needle, "the run's records") : []),
240
+ ];
241
+
242
+ const errored: Errored | undefined =
243
+ (unread.length > 0
244
+ ? { by: "lab" as const, phase: "after" as const, reason: unread.join("; ") }
245
+ : undefined) ??
246
+ blamed.errored ??
247
+ (reach && !reach.ok
248
+ ? {
249
+ by: "dataset" as const,
250
+ phase: "after" as const,
251
+ code: "reach" as const,
252
+ reason: reach.problems[0]!,
253
+ }
254
+ : undefined) ??
255
+ harnessStop(blamed, turns ?? []);
256
+ const accounting = run?.accounting;
257
+ // A run cut short prints no record, though its agents ran: its folder still says what it is
258
+ // estimated at.
259
+ const lost =
260
+ !run && lab.estimate
261
+ ? await lab.estimate(folder.awf, boxed ? storeRuns : runRoot, id, env)
262
+ : undefined;
263
+ const estimate = accounting?.totals.estimate ?? lost;
264
+ const record: TrialRecord = {
265
+ ...base,
266
+ ...(blamed.workflow ? { workflow: blamed.workflow } : {}),
267
+ ...(run ? { runId: run.runId, runOutcome: run.outcome } : {}),
268
+ ...(run && run.outcome !== "completed" ? { runReason: run.reason } : {}),
269
+ models: accounting ? accounting.byModel.map((m) => m.model) : [],
270
+ ms: accounting?.wallMs ?? result.ms,
271
+ ...(estimate !== undefined ? { estimate } : {}),
272
+ ...(accounting
273
+ ? {
274
+ known: accounting.totals.known,
275
+ priced: accounting.totals.priced,
276
+ agents: accounting.totals.agents,
277
+ }
278
+ : {}),
279
+ ...(gathered ? { ...gathered, files } : { files }),
280
+ // Empty when the logs were no page; absent only on a trial kept before the lab read them.
281
+ runFacts:
282
+ turns && logs && "text" in logs ? runFactsOf(turns, agentsOpenedOf(logs.text) ?? []) : {},
283
+ ...stageTimes(run?.stages, Object.keys(gathered?.stubbedStages ?? {})),
284
+ unused: blamed.unused,
285
+ refused: blamed.refused,
286
+ leaked: leaks.length > 0,
287
+ ...(reach ? { reach } : {}),
288
+ ...(blamed.stopped !== undefined ? { stopped: blamed.stopped } : {}),
289
+ ...(blamed.workflowError !== undefined ? { workflowError: blamed.workflowError } : {}),
290
+ };
291
+
292
+ let score: ScoreRecord | undefined;
293
+ const gradable =
294
+ !record.leaked &&
295
+ !errored &&
296
+ !record.workflowError &&
297
+ record.stopped === undefined &&
298
+ gathered !== undefined;
299
+ // A draft's facts are read too, though it isn't graded: `capture` and the report show them.
300
+ // What stops grading is kept with the score, never the trial, so `score` grades it again.
301
+ const read = gradable ? (await lab.facts([recordOf(record)], folders.parent))[0] : undefined;
302
+ const at = lab.now().toISOString();
303
+ if (gradable && (!read || "problem" in read)) {
304
+ score = {
305
+ kind: SCORE_KIND,
306
+ at,
307
+ entries: [],
308
+ errored: {
309
+ by: "dataset",
310
+ phase: "facts",
311
+ code: read?.problem.code ?? "facts-missing",
312
+ reason: read?.problem.reason ?? "facts gave no answer",
313
+ },
314
+ };
315
+ } else if (read && "facts" in read) {
316
+ const graded = info.key.draft
317
+ ? { entries: [] }
318
+ : await gradeTrial({
319
+ info,
320
+ facts: read.facts,
321
+ ...(record.runFacts ? { runFacts: record.runFacts } : {}),
322
+ stages: record.stages ?? {},
323
+ result: record.result ?? null,
324
+ caseDir: folders.dir,
325
+ scratch: folders.scratch,
326
+ kept: join(dir, "kept"),
327
+ work: folders.parent,
328
+ env: definedOf(withoutCallingSession(lab.env)),
329
+ params,
330
+ expect: Object.keys(info.key.expect ?? {}).length > 0,
331
+ graders: lab.graders.filter((g) => !g.manual),
332
+ deciders: decidersOf(info.key, lab.graders),
333
+ });
334
+ score = {
335
+ kind: SCORE_KIND,
336
+ at,
337
+ facts: read.facts,
338
+ entries: "entries" in graded ? graded.entries : [],
339
+ ...("errored" in graded
340
+ ? {
341
+ errored: {
342
+ by: "dataset" as const,
343
+ phase: "facts" as const,
344
+ ...(graded.errored.code ? { code: graded.errored.code } : {}),
345
+ reason: graded.errored.reason,
346
+ },
347
+ }
348
+ : {}),
349
+ };
350
+ }
351
+ const final = { ...record, ...(errored ? { errored } : {}) };
352
+ writeTrial(dir, final);
353
+ if (score) appendScore(dir, score);
354
+ return { record: gradedRecord(final, score ? [score] : []), ...(score ? { score } : {}), dir };
355
+ } finally {
356
+ rmSync(folders.parent, { recursive: true, force: true });
357
+ rmSync(trialFile, { force: true });
358
+ }
359
+ }
360
+
361
+ /** How long each stage the run ran took; a stage stubbed or reused ran no work of its own. */
362
+ function stageTimes(
363
+ stages: readonly { stage: string; source: string; spanMs: number; provided?: true }[] | undefined,
364
+ given: readonly string[] = [],
365
+ ): { stageMs?: Record<string, number> } {
366
+ // A stage the case stubbed ran through the engine too, its work only handing the value back.
367
+ const ran = (stages ?? []).filter(
368
+ (s) => s.source === "ran" && !s.provided && !given.includes(s.stage),
369
+ );
370
+ if (ran.length === 0) return {};
371
+ return { stageMs: Object.fromEntries(ran.map((s) => [s.stage, s.spanMs])) };
372
+ }
373
+
374
+ export function definedOf(
375
+ env: Readonly<Record<string, string | undefined>>,
376
+ ): Record<string, string> {
377
+ return Object.fromEntries(
378
+ Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined),
379
+ );
380
+ }
381
+
382
+ function findRunDir(runRoot: string, id: string): string | undefined {
383
+ if (!existsSync(runRoot)) return undefined;
384
+ for (const path of new Bun.Glob(`*/${id}`).scanSync({ cwd: runRoot, onlyFiles: false })) {
385
+ return join(runRoot, path);
386
+ }
387
+ return undefined;
388
+ }
389
+
390
+ function jsonLines(file: string): object[] {
391
+ if (!existsSync(file)) return [];
392
+ return readFileSync(file, "utf8")
393
+ .split("\n")
394
+ .flatMap((line) => {
395
+ if (line.trim() === "") return [];
396
+ try {
397
+ const value = JSON.parse(line);
398
+ return value && typeof value === "object" ? [value as object] : [];
399
+ } catch {
400
+ return [];
401
+ }
402
+ });
403
+ }
404
+
405
+ /** The agents a run opened, and every agent its sessions and turns name. */
406
+ function readAgents(runDir: string): { opened: OpenedAgent[]; named: string[] } {
407
+ const opened: OpenedAgent[] = [];
408
+ const named: string[] = [];
409
+ for (const raw of jsonLines(join(runDir, "log.jsonl"))) {
410
+ const line = runLogLine(raw);
411
+ if (!line) continue;
412
+ if (line.kind === "agent-opened") {
413
+ if (line.caller) continue;
414
+ opened.push({
415
+ agent: line.agent,
416
+ harness: line.harness,
417
+ ...(line.sandbox ? { sandbox: line.sandbox } : {}),
418
+ ...(line.domains ? { domains: line.domains } : {}),
419
+ });
420
+ } else if (line.kind === "turn" || line.kind === "compact") {
421
+ named.push(line.agent);
422
+ }
423
+ }
424
+ for (const raw of jsonLines(join(runDir, "run.jsonl"))) {
425
+ const line = raw as { kind?: unknown; agent?: unknown };
426
+ if (line.kind === "session" && typeof line.agent === "string") named.push(line.agent);
427
+ }
428
+ return { opened, named };
429
+ }
430
+
431
+ /** The run record's sandboxes, and any its `sandbox-opened` lines have that it lacks. */
432
+ function sandboxesOf(
433
+ runDir: string,
434
+ recorded: readonly SandboxRecord[] | undefined,
435
+ ): Pick<SandboxRecord, "key" | "provider" | "spec">[] {
436
+ const byKey = new Map<string, Pick<SandboxRecord, "key" | "provider" | "spec">>();
437
+ for (const raw of jsonLines(join(runDir, "log.jsonl"))) {
438
+ const line = runLogLine(raw);
439
+ if (line?.kind === "sandbox-opened") byKey.set(line.key, line);
440
+ }
441
+ for (const sandbox of recorded ?? []) byKey.set(sandbox.key, sandbox);
442
+ return [...byKey.values()];
443
+ }