@parcha/agentrun-serve 0.1.0-beta.43 → 0.1.0-beta.44

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 (141) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/README.md +213 -24
  3. package/dist/cli.js +42 -8
  4. package/dist/composio-preset.d.ts +4 -3
  5. package/dist/composio-preset.js +12 -4
  6. package/dist/composio-triggers.d.ts +20 -2
  7. package/dist/composio-triggers.js +183 -17
  8. package/dist/computer-lost.d.ts +11 -0
  9. package/dist/computer-lost.js +19 -0
  10. package/dist/computer-record.d.ts +10 -2
  11. package/dist/computer-record.js +50 -18
  12. package/dist/computer-setting.d.ts +1 -0
  13. package/dist/computer-setting.js +2 -2
  14. package/dist/console/assets/index-BUktRvS-.css +1 -0
  15. package/dist/console/assets/index-nB9kTfIN.js +711 -0
  16. package/dist/console/index.html +2 -2
  17. package/dist/errors.d.ts +1 -0
  18. package/dist/errors.js +3 -0
  19. package/dist/harness-table.d.ts +51 -3
  20. package/dist/harness-table.js +101 -13
  21. package/dist/harness.d.ts +18 -1
  22. package/dist/harness.js +21 -9
  23. package/dist/host.d.ts +12 -10
  24. package/dist/host.js +18 -16
  25. package/dist/import-worker.d.ts +3 -0
  26. package/dist/import-worker.js +7 -5
  27. package/dist/import.d.ts +22 -1
  28. package/dist/import.js +141 -28
  29. package/dist/learn/check.d.ts +3 -0
  30. package/dist/learn/check.js +1 -1
  31. package/dist/learn/compile.js +1 -1
  32. package/dist/learn/delete.d.ts +17 -0
  33. package/dist/learn/delete.js +44 -0
  34. package/dist/learn/promote.d.ts +7 -1
  35. package/dist/learn/promote.js +8 -4
  36. package/dist/learn/skills.d.ts +4 -0
  37. package/dist/learn/skills.js +17 -1
  38. package/dist/learn/workflow-nodes.d.ts +22 -1
  39. package/dist/learn/workflow-nodes.js +28 -9
  40. package/dist/learning-cost.d.ts +100 -0
  41. package/dist/learning-cost.js +116 -1
  42. package/dist/learning-evals.d.ts +2 -0
  43. package/dist/learning-evals.js +4 -3
  44. package/dist/learning-routes.d.ts +8 -0
  45. package/dist/learning-routes.js +17 -0
  46. package/dist/learning.d.ts +1 -1
  47. package/dist/listen-first.d.ts +30 -0
  48. package/dist/listen-first.js +115 -0
  49. package/dist/llms.txt +2 -1
  50. package/dist/mcp-servers-store.d.ts +12 -12
  51. package/dist/model.d.ts +8 -4
  52. package/dist/model.js +16 -8
  53. package/dist/openapi.js +115 -39
  54. package/dist/owner.d.ts +8 -0
  55. package/dist/owner.js +11 -0
  56. package/dist/paid-calls.d.ts +6 -0
  57. package/dist/paid-calls.js +11 -1
  58. package/dist/place.d.ts +8 -3
  59. package/dist/place.js +13 -9
  60. package/dist/provider.js +15 -1
  61. package/dist/run-learning-served.d.ts +1 -1
  62. package/dist/run-model-key.d.ts +64 -0
  63. package/dist/run-model-key.js +147 -0
  64. package/dist/runner/adapter-loop.d.ts +6 -0
  65. package/dist/runner/adapter-loop.js +9 -2
  66. package/dist/runner/adapter-run-spec.d.ts +6 -3
  67. package/dist/runner/adapter-run-spec.js +70 -23
  68. package/dist/runner/adapters/index.d.ts +4 -2
  69. package/dist/runner/adapters/index.js +13 -4
  70. package/dist/runner/audit.d.ts +4 -0
  71. package/dist/runner/audit.js +15 -4
  72. package/dist/runner/beside.d.ts +2 -1
  73. package/dist/runner/beside.js +5 -2
  74. package/dist/runner/claim-secrets.d.ts +49 -0
  75. package/dist/runner/claim-secrets.js +110 -1
  76. package/dist/runner/cli-run-spec.d.ts +2 -1
  77. package/dist/runner/cli-run-spec.js +32 -13
  78. package/dist/runner/commands.d.ts +3 -6
  79. package/dist/runner/feedback-round.d.ts +3 -2
  80. package/dist/runner/feedback-round.js +7 -3
  81. package/dist/runner/harness-loops.js +30 -8
  82. package/dist/runner/journal-kinds.d.ts +5 -0
  83. package/dist/runner/learning-end.d.ts +3 -0
  84. package/dist/runner/learning-end.js +4 -0
  85. package/dist/runner/loop-contract.d.ts +6 -0
  86. package/dist/runner/loop-contract.js +4 -0
  87. package/dist/runner/loop.js +6 -2
  88. package/dist/runner/main.d.ts +1 -0
  89. package/dist/runner/main.js +24 -7
  90. package/dist/runner/memory-claim.d.ts +9 -6
  91. package/dist/runner/memory-claim.js +12 -9
  92. package/dist/runner/promotion.d.ts +5 -0
  93. package/dist/runner/promotion.js +46 -7
  94. package/dist/runner/reflect-hook.d.ts +4 -0
  95. package/dist/runner/reflect-hook.js +22 -3
  96. package/dist/runner/runner.js +57 -4
  97. package/dist/runner/store-secrets.js +9 -5
  98. package/dist/runner/workflow-spec.js +10 -2
  99. package/dist/runs-over-store.d.ts +5 -4
  100. package/dist/runs-over-store.js +13 -3
  101. package/dist/sdk/workflows.d.ts +1 -1
  102. package/dist/server.d.ts +64 -50
  103. package/dist/server.js +457 -120
  104. package/dist/store/index.d.ts +2 -2
  105. package/dist/store/index.js +1 -1
  106. package/dist/store/seal.d.ts +20 -2
  107. package/dist/store/seal.js +24 -8
  108. package/dist/store/sqlite/run-launch.d.ts +4 -1
  109. package/dist/store/sqlite/run-launch.js +12 -0
  110. package/dist/store/sqlite/store.d.ts +3 -2
  111. package/dist/store/sqlite/store.js +118 -16
  112. package/dist/store/store.d.ts +38 -3
  113. package/dist/store-reads/analytics.js +11 -1
  114. package/dist/store-reads/learning.d.ts +41 -2
  115. package/dist/store-reads/learning.js +158 -5
  116. package/dist/store-reads/stats.js +13 -3
  117. package/dist/store-view.d.ts +5 -1
  118. package/dist/store-view.js +12 -11
  119. package/dist/telemetry.d.ts +59 -0
  120. package/dist/telemetry.js +153 -0
  121. package/dist/tool-keys-store.d.ts +1 -1
  122. package/dist/tool-keys.d.ts +2 -2
  123. package/dist/tool-plane.d.ts +12 -12
  124. package/dist/tools.d.ts +11 -11
  125. package/dist/tools.js +18 -5
  126. package/dist/trigger-adapter.d.ts +3 -0
  127. package/dist/trigger-adapters.d.ts +4 -0
  128. package/dist/trigger-adapters.js +13 -0
  129. package/dist/trigger-composio.d.ts +58 -1
  130. package/dist/trigger-composio.js +160 -6
  131. package/dist/triggers.d.ts +4 -0
  132. package/dist/triggers.js +22 -3
  133. package/dist/validate.d.ts +11 -7
  134. package/dist/validate.js +8 -7
  135. package/dist/workspace/computer-for-claim.d.ts +15 -5
  136. package/dist/workspace/computer-for-claim.js +228 -32
  137. package/dist/workspace/resolve-computer.d.ts +8 -2
  138. package/dist/workspace/resolve-computer.js +1 -1
  139. package/package.json +10 -9
  140. package/dist/console/assets/index-BrcDSBD8.css +0 -1
  141. package/dist/console/assets/index-Bz6IWncl.js +0 -711
package/dist/import.js CHANGED
@@ -170,6 +170,12 @@ async function remoteHistoryMetadata(file, source) {
170
170
  cwd ??= str(row.cwd);
171
171
  child ||= row.isSidechain === true;
172
172
  }
173
+ else if (source === 'pi') {
174
+ if (row.type === 'session') {
175
+ id = str(row.id) ?? id;
176
+ cwd = str(row.cwd) ?? cwd;
177
+ }
178
+ }
173
179
  else if (row.type === 'session_meta') {
174
180
  const payload = row.payload;
175
181
  if (!payload || typeof payload !== 'object' || Array.isArray(payload))
@@ -221,6 +227,11 @@ export const IMPORT_ASKED = ".import-at-setup";
221
227
  export const LIVE_MS = 10 * 60_000;
222
228
  /** The most of one session file read. */
223
229
  export const MAX_SESSION_BYTES = 256 * 1024 * 1024;
230
+ /** The most of one run read together: its session's files and its subagents'. A run is held in memory whole while its
231
+ * keys are found and it is written, so one over this is left out whole (never cut short), whatever the history's size. */
232
+ export const MAX_RUN_BYTES = MAX_SESSION_BYTES;
233
+ /** The most projects a count names for the owner to choose from: the latest active. */
234
+ export const MAX_CANDIDATES = 500;
224
235
  /** The most of one instructions or skill file read, and of one agent's skill files together. */
225
236
  export const MAX_FILE_BYTES = 256 * 1024;
226
237
  export const MAX_SKILL_BYTES = 1024 * 1024;
@@ -232,6 +243,24 @@ const INSTRUCTIONS = {
232
243
  pi: ["AGENTS.md", "CLAUDE.md"],
233
244
  };
234
245
  const hash = (text) => createHash("sha256").update(text).digest("hex");
246
+ /** A run's files and its subagents' are over MAX_RUN_BYTES together: the run is left out. */
247
+ class RunTooLarge extends Error {
248
+ }
249
+ const budgetOf = () => ({ left: MAX_RUN_BYTES });
250
+ const fits = (budget, bytes) => (budget.left -= bytes) >= 0;
251
+ const tooLarge = (listed) => ({ what: listed.file, why: `its files and its subagents' are over ${MAX_RUN_BYTES} bytes together`, kind: "large", session: `${listed.source}:${listed.id}` });
252
+ /** The projects of `plan` for the owner to choose from, the latest active first (then by folder), at most MAX_CANDIDATES.
253
+ * With `env`, the values of its keys are cut from a name and a folder as the import cuts them. */
254
+ export function candidatesOf(plan, env) {
255
+ const text = env ? secretCut(env, SECRET_NAMES).text : (value) => value;
256
+ return plan.projects
257
+ .map((project) => {
258
+ const last = project.sessions.reduce((latest, s) => ((s.endedAt ?? s.startedAt ?? "") > (latest ?? "") ? (s.endedAt ?? s.startedAt) : latest), undefined);
259
+ return { id: project.agentId, name: keptName(project, text), path: text(project.cwd), sessions: sessionsOf(project.sessions).length, sources: [...new Set(project.sessions.map((s) => s.source))].sort(), last_active: last ?? null };
260
+ })
261
+ .sort((a, b) => (b.last_active ?? "").localeCompare(a.last_active ?? "") || a.path.localeCompare(b.path))
262
+ .slice(0, MAX_CANDIDATES);
263
+ }
235
264
  /** A session's id as an import keeps it: as it is, unless it holds one of the keys the import cuts, the environment's or
236
265
  * one saved on the server (a session named after its file can), then `redacted-` and a hash of it, the same each time
237
266
  * and different for each id, so two such sessions stay two runs and a later import finds each one's. The plan and the
@@ -281,6 +310,8 @@ async function keysInSessions(sessions) {
281
310
  async function findKeys(plan, add, cut, held, signal) {
282
311
  const stamps = new Map();
283
312
  const texts = new Map();
313
+ // The runs over MAX_RUN_BYTES (`source:id`): read no further here, and left out by the write.
314
+ const large = new Set();
284
315
  for (const project of plan.projects) {
285
316
  if (signal?.aborted)
286
317
  break;
@@ -298,19 +329,35 @@ async function findKeys(plan, add, cut, held, signal) {
298
329
  // Its own count of records seen: the import's, shared across its files, is the write's to keep.
299
330
  const seen = new Set();
300
331
  const parts = [];
332
+ const budget = budgetOf();
333
+ let over = false;
301
334
  for (const { file } of files) {
302
335
  const stats = await stat(file).catch(() => null);
336
+ if (stats && !fits(budget, stats.size)) {
337
+ over = true;
338
+ break;
339
+ }
303
340
  const part = stats ? await readSession(file, listed.source, { seen }).catch(() => undefined) : undefined;
304
341
  if (!part || !stats)
305
342
  continue;
306
343
  stamps.set(file, stampOf(stats));
307
344
  parts.push(part);
308
345
  }
346
+ if (over) {
347
+ large.add(`${listed.source}:${listed.id}`);
348
+ continue;
349
+ }
309
350
  if (!parts.length)
310
351
  continue;
311
352
  add(await keysInSessions(parts));
312
353
  const session = merged(parts);
313
- const subagents = await readChildren(plan, { ...session, id: cut(session.id) === session.id ? session.id : redactedId(session.id) }, parts, seen);
354
+ const subagents = await readChildren(plan, { ...session, id: cut(session.id) === session.id ? session.id : redactedId(session.id) }, parts, seen, budget).catch((error) => {
355
+ if (!(error instanceof RunTooLarge))
356
+ throw error;
357
+ large.add(`${listed.source}:${listed.id}`);
358
+ });
359
+ if (!subagents)
360
+ continue;
314
361
  for (const child of subagents) {
315
362
  const stats = await stat(child.file).catch(() => null);
316
363
  if (stats)
@@ -319,7 +366,7 @@ async function findKeys(plan, add, cut, held, signal) {
319
366
  add(await keysInSessions(subagents));
320
367
  }
321
368
  }
322
- return { stamps, texts };
369
+ return { stamps, texts, large };
323
370
  }
324
371
  /** A project's own text for secretlint: its path, its instructions, and its skills' paths and text. */
325
372
  const projectText = (cwd, files) => [cwd, ...Object.values(files.instructions), ...Object.entries(files.skills).flat()].join("\n");
@@ -343,11 +390,14 @@ const clip = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…`
343
390
  /** What an import would take: the sessions under `home`, by project, with what it leaves out and why. Keeps no turns
344
391
  * (with `measure`, only until each session is measured), and reads no file `store`'s imports already read whole and
345
392
  * that has not changed since. */
346
- export async function planImport({ home, sources = SOURCES, all = false, deleted = false, now = Date.now(), temp: tempDir = tmpdir(), measure = false, env, stored, own = [], signal, keys: scan = true, onKeys }, store) {
393
+ export async function planImport({ home, sources = SOURCES, all = false, deleted = false, now = Date.now(), temp: tempDir = tmpdir(), measure = false, env, stored, own = [], signal, keys: scan = true, onKeys, only }, store) {
347
394
  // A session's id that holds a key (one named after its file can) is kept as a hash of it: every lookup of an earlier
348
395
  // import's run then goes by the id as kept.
349
396
  const idOf = keptId([env, stored ?? {}], own);
350
397
  const skipped = [];
398
+ // Each file left out here, with the project folder its read gave, if it was read that far: what `only` goes by.
399
+ const leftFrom = new Map();
400
+ const leave = (entry, source, cwd) => void (skipped.push(entry), leftFrom.set(entry, { source, cwd }));
351
401
  const seen = store ? await filesIn(store) : new Map();
352
402
  let already = 0;
353
403
  const held = [];
@@ -370,19 +420,15 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
370
420
  continue;
371
421
  }
372
422
  if (now - stats.mtimeMs < LIVE_MS) {
373
- skipped.push({
374
- what: file,
375
- why: "written in the last 10 minutes: it may still be running",
376
- kind: "live",
377
- });
423
+ leave({ what: file, why: "written in the last 10 minutes: it may still be running", kind: "live" }, source);
378
424
  continue;
379
425
  }
380
426
  if (stats.size > MAX_SESSION_BYTES) {
381
- skipped.push({ what: file, why: `over ${MAX_SESSION_BYTES} bytes`, kind: "large" });
427
+ leave({ what: file, why: `over ${MAX_SESSION_BYTES} bytes`, kind: "large" }, source);
382
428
  continue;
383
429
  }
384
430
  // One file this user cannot read, or one gone since its stat, is named and passed over: the rest still import.
385
- const session = await readSession(file, source, { turns: false }).catch((error) => void skipped.push(unread(file, error)));
431
+ const session = await readSession(file, source, { turns: false }).catch((error) => leave(unread(file, error), source));
386
432
  if (!session)
387
433
  continue;
388
434
  session.id = await idOf(session.id, scan);
@@ -395,28 +441,23 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
395
441
  continue;
396
442
  }
397
443
  if (!session.cwd) {
398
- skipped.push({ what: file, why: "no project directory in it", kind: "no-project" });
444
+ leave({ what: file, why: "no project directory in it", kind: "no-project" }, source);
399
445
  continue;
400
446
  }
401
447
  if (!all && session.users === 0 && !session.child) {
402
- skipped.push({ what: file, why: "no message of the person's", kind: "no-words", session: `${source}:${session.id}` });
448
+ leave({ what: file, why: "no message of the person's", kind: "no-words", session: `${source}:${session.id}` }, source, session.cwd);
403
449
  continue;
404
450
  }
405
451
  const cwd = session.cwd;
406
452
  if (!all) {
407
453
  // A temp folder first, gone or not: only --all brings it in, as the left-out line says.
408
454
  if (temps.some((temp) => cwd === temp || cwd.startsWith(temp + sep))) {
409
- skipped.push({
410
- what: file,
411
- why: `its project ${cwd} is a temp directory`,
412
- kind: "temp",
413
- session: `${source}:${session.id}`,
414
- });
455
+ leave({ what: file, why: `its project ${cwd} is a temp directory`, kind: "temp", session: `${source}:${session.id}` }, source, cwd);
415
456
  continue;
416
457
  }
417
458
  const there = await lstat(cwd).catch(() => null);
418
459
  if (!there?.isDirectory() && !deleted) {
419
- skipped.push({ what: file, why: `its project ${cwd} is gone`, kind: "gone", session: `${source}:${session.id}` });
460
+ leave({ what: file, why: `its project ${cwd} is gone`, kind: "gone", session: `${source}:${session.id}` }, source, cwd);
420
461
  continue;
421
462
  }
422
463
  }
@@ -440,7 +481,24 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
440
481
  child(of, file);
441
482
  }
442
483
  ownRuns(projects, rank);
443
- const plan = { projects: [...projects.values()].sort((a, b) => a.cwd.localeCompare(b.cwd)), skipped, already, held, children, untied };
484
+ // The owner's choice, once each session has its one project: a project not chosen is no part of the plan.
485
+ const chosen = only === undefined ? undefined : new Set(only);
486
+ // What is left out is said of the projects chosen alone, each file by the folder it names: as its read gave it, or,
487
+ // for a file left out unread (still written, over the cap, unreadable), as its first records say. A file that names
488
+ // no folder is no chosen project's.
489
+ if (chosen) {
490
+ const ofChosen = [];
491
+ for (const entry of skipped) {
492
+ // A stop ends these reads as it ends the listing's: the plan is the stopped one's, and is not used.
493
+ if (signal?.aborted)
494
+ break;
495
+ const { source, cwd = (await remoteHistoryMetadata(entry.what, source).catch(() => undefined))?.cwd } = leftFrom.get(entry);
496
+ if (cwd !== undefined && chosen.has(agentIdOf(cwd)))
497
+ ofChosen.push(entry);
498
+ }
499
+ skipped.splice(0, skipped.length, ...ofChosen);
500
+ }
501
+ const plan = { projects: [...projects.values()].filter((project) => !chosen || chosen.has(project.agentId)).sort((a, b) => a.cwd.localeCompare(b.cwd)), skipped, already, held, children, untied };
444
502
  if (!measure)
445
503
  return plan;
446
504
  const counting = secretCut(env, SECRET_NAMES);
@@ -449,7 +507,7 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
449
507
  const foundKeys = (keys) => (counting.add(keys), onKeys?.(keys));
450
508
  // This server's own secrets first, as the import takes them.
451
509
  foundKeys(own);
452
- await findKeys(plan, foundKeys, counting.text, (listed) => heldBy?.get(`${listed.source}:${listed.id}`) !== undefined, signal);
510
+ const { large } = await findKeys(plan, foundKeys, counting.text, (listed) => heldBy?.get(`${listed.source}:${listed.id}`) !== undefined, signal);
453
511
  // Measured in the import's own order, a record or response counted once across files, each session with its
454
512
  // subagents; a session the store holds already from its run, as the import counts it, not from its file now.
455
513
  for (const project of plan.projects) {
@@ -460,14 +518,31 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
460
518
  held.push(run);
461
519
  continue;
462
520
  }
521
+ // A run over MAX_RUN_BYTES is left out by the import, so by its dry run: said, and read no further.
522
+ if (large.has(`${files[0].source}:${files[0].id}`)) {
523
+ skipped.push(tooLarge(files[0]));
524
+ continue;
525
+ }
463
526
  // Each of its files read; those holding only copies add no records to it, but their subagents' folders are its
464
527
  // too, read through the same count (readChildren).
465
528
  const read = [];
529
+ const budget = budgetOf();
530
+ let over = false;
466
531
  for (const listed of files) {
532
+ const stats = await stat(listed.file).catch(() => null);
533
+ // Grown over the cap since the scan above: left out here as the import leaves it out, and read no further.
534
+ if (stats && !fits(budget, stats.size)) {
535
+ over = true;
536
+ break;
537
+ }
467
538
  const part = await readSession(listed.file, listed.source, { seen: seen(listed.source) }).catch(() => undefined);
468
539
  if (part)
469
540
  read.push(part);
470
541
  }
542
+ if (over) {
543
+ skipped.push(tooLarge(files[0]));
544
+ continue;
545
+ }
471
546
  const parts = read.filter((part) => !ownless(part));
472
547
  if (!parts.length)
473
548
  continue;
@@ -476,7 +551,13 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
476
551
  counting.json(session.turns);
477
552
  if (session.firstPrompt)
478
553
  counting.text(session.firstPrompt);
479
- const subagents = await readChildren(plan, session, read, seen(session.source));
554
+ const subagents = await readChildren(plan, session, read, seen(session.source), budget).catch((error) => {
555
+ if (!(error instanceof RunTooLarge))
556
+ throw error;
557
+ skipped.push(tooLarge(files[0]));
558
+ });
559
+ if (!subagents)
560
+ continue;
480
561
  found.push({ source: session.source, agent: project.agentId, ...measured(session, subagents) });
481
562
  }
482
563
  }
@@ -513,7 +594,13 @@ export async function untiedFound(plan) {
513
594
  const found = [];
514
595
  for (const parts of threads.values()) {
515
596
  const session = merged(parts);
516
- found.push({ source: session.source, agent: "", untied: true, metrics: metricsOf(session, await readChildren(plan, session, parts, counted(session.source))) });
597
+ // One whose own subagents are over the cap together counts for itself alone: the totals never hold more than a run.
598
+ const children = await readChildren(plan, session, parts, counted(session.source), budgetOf()).catch((error) => {
599
+ if (!(error instanceof RunTooLarge))
600
+ throw error;
601
+ return [];
602
+ });
603
+ found.push({ source: session.source, agent: "", untied: true, metrics: metricsOf(session, children) });
517
604
  }
518
605
  return found;
519
606
  }
@@ -635,9 +722,10 @@ async function seenIn(store, agentId) {
635
722
  return seen;
636
723
  }
637
724
  /** A run's subagents, theirs, and so on down, each file once, read with the import's `seen`: those beside each of its
638
- * files (Claude Code's), and those naming its thread (Codex's, whichever of its files they ran under). Each within the cap
639
- * and readable; another is passed over. */
640
- async function readChildren(plan, session, parts, seen) {
725
+ * files (Claude Code's), and those naming its thread (Codex's, whichever of its files they ran under). One gone or
726
+ * unreadable is passed over. All of them are held at once, so their sizes are taken from `budget` (what the run's own
727
+ * files left of MAX_RUN_BYTES) before each is read: RunTooLarge once it is spent, as one file over the cap alone spends it. */
728
+ async function readChildren(plan, session, parts, seen, budget) {
641
729
  const out = [];
642
730
  const visited = new Set();
643
731
  const under = async (owner) => {
@@ -646,8 +734,12 @@ async function readChildren(plan, session, parts, seen) {
646
734
  continue;
647
735
  visited.add(file);
648
736
  const stats = await stat(file).catch(() => null);
649
- if (!stats || stats.size > MAX_SESSION_BYTES)
737
+ if (!stats)
650
738
  continue;
739
+ // Every subagent read is held with the run: one more than the run's cap holds ends the read, and the run is left out.
740
+ // No subagent is passed over for its size: the run would be kept without its usage.
741
+ if (!fits(budget, stats.size))
742
+ throw new RunTooLarge();
651
743
  const child = await readSession(file, session.source, { seen }).catch(() => undefined);
652
744
  if (!child)
653
745
  continue;
@@ -1068,6 +1160,13 @@ export async function runImport(store, plan, options) {
1068
1160
  line.already += 1;
1069
1161
  continue;
1070
1162
  }
1163
+ // A run over MAX_RUN_BYTES (found so by the scan above, or grown so since) is left out whole, and said.
1164
+ if (known.large.has(`${listed.source}:${listed.id}`)) {
1165
+ report.skipped.push(tooLarge(listed));
1166
+ continue;
1167
+ }
1168
+ const budget = budgetOf();
1169
+ let over = false;
1071
1170
  // Each of its files, in order. The first's size and time before its read: a file that changes during it is read
1072
1171
  // again next time.
1073
1172
  const parts = [];
@@ -1080,6 +1179,10 @@ export async function runImport(store, plan, options) {
1080
1179
  let changed = false;
1081
1180
  for (const { file } of files) {
1082
1181
  const stats = await stat(file).catch(() => null);
1182
+ if (stats && !fits(budget, stats.size)) {
1183
+ over = true;
1184
+ break;
1185
+ }
1083
1186
  const part = stats ? await readSession(file, listed.source, { seen: seen(listed.source) }).catch((error) => void report.skipped.push(unread(file, error))) : void report.skipped.push({ what: file, why: "gone since it was listed", kind: "vanished" });
1084
1187
  if (!part || !stats)
1085
1188
  continue;
@@ -1096,6 +1199,10 @@ export async function runImport(store, plan, options) {
1096
1199
  if (scannedAs.get(file) !== stampOf(stats))
1097
1200
  changed = true;
1098
1201
  }
1202
+ if (over) {
1203
+ report.skipped.push(tooLarge(listed));
1204
+ continue;
1205
+ }
1099
1206
  if (!read)
1100
1207
  continue;
1101
1208
  const session = merged(parts);
@@ -1109,7 +1216,13 @@ export async function runImport(store, plan, options) {
1109
1216
  // holding a key counts among the keys removed.
1110
1217
  const keptAs = text(session.id) === session.id ? session.id : redactedId(session.id);
1111
1218
  session.id = keptAs;
1112
- const subagents = await readChildren(plan, session, searched, seen(listed.source));
1219
+ const subagents = await readChildren(plan, session, searched, seen(listed.source), budget).catch((error) => {
1220
+ if (!(error instanceof RunTooLarge))
1221
+ throw error;
1222
+ report.skipped.push(tooLarge(listed));
1223
+ });
1224
+ if (!subagents)
1225
+ continue;
1113
1226
  const moved = await Promise.all(subagents.map(async (child) => scannedAs.get(child.file) !== stampOf((await stat(child.file).catch(() => null)) ?? { size: -1, mtimeMs: -1 })));
1114
1227
  if (moved.some(Boolean))
1115
1228
  add(await keysInSessions(subagents));
@@ -101,6 +101,9 @@ export type ProposalCheck = {
101
101
  /** `problem` as it may be printed: its path and detail cut of `values` and of every shape learning refuses, a bank's
102
102
  * numbers too (redactLearned: a name refused for one never prints it), whole when over PRINT_MAX. */
103
103
  export declare const printable: (problem: Problem, values: readonly string[]) => Problem;
104
+ /** The model node kinds a tier routes (model.ts MODEL_NODES); a decision node (judge, pick, sift) goes to its decision
105
+ * provider, never a tier. */
106
+ export declare const TIERED_KINDS: ReadonlySet<string>;
104
107
  /** Why a draft's answer is not written on the agent's own model: each model node that writes the state key its
105
108
  * output.path reads (its answering step) and names tier "fast", one line each, in words the compile retry acts on. A
106
109
  * composed workflow node that writes it answers with its own workflow's answering step, held to the same; a map that
@@ -139,7 +139,7 @@ function decodedScanned(path, text, refused, add, deep = true) {
139
139
  }
140
140
  /** The model node kinds a tier routes (model.ts MODEL_NODES); a decision node (judge, pick, sift) goes to its decision
141
141
  * provider, never a tier. */
142
- const TIERED_KINDS = new Set(["agent", "decide", "extract", "report"]);
142
+ export const TIERED_KINDS = new Set(["agent", "decide", "extract", "report"]);
143
143
  const isNode = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && typeof value.node === "string";
144
144
  /** The state key a step writes (the DSL's writeKeyOf): a report's `report_markdown`, else its `as`, else an agent's,
145
145
  * decide's or extract's label. */
@@ -305,7 +305,7 @@ export function compilePrompt(ask) {
305
305
  : []),
306
306
  `Give \`${ask.workflow}\` again whole under its name, changed so it says what you said on these inputs: fix the step that gets them wrong, and hand back at an \`escalate\` step only a case its rules do not cover. This revision is checked once on your recent inputs and these; if audits hold it again, nothing compiles again.`,
307
307
  ]
308
- : [`Give \`${ask.workflow}\` again whole under its name, changed so its answers agree with the agent's own: fix the step that gets them wrong, or hand those cases back at an \`escalate\` step.`]),
308
+ : [`Give \`${ask.workflow}\` again whole under its name, changed so what held it holds no more: fix what its reason names. This revision is checked once on your recent inputs; if it falls short again, nothing compiles again.`]),
309
309
  OUTPUT_FORMAT,
310
310
  ];
311
311
  return [
@@ -0,0 +1,17 @@
1
+ import { type Store } from "../store/store.js";
2
+ import type { LearningFolder } from "./folder.js";
3
+ /** A delete refused: work of the agent's learning is still in flight (`runs`: a run of the agent not ended, its
4
+ * compile turn, a check's replay or an audit's shadow among them, or a learning run grading one). Nothing was removed. */
5
+ export declare class LearningInFlight extends Error {
6
+ readonly runs: readonly string[];
7
+ constructor(agentId: string, runs: readonly string[]);
8
+ }
9
+ /** Agent `agentId`'s learning deleted: every file of its learning folder (`folder`, learning.ts learningFolderOf: its
10
+ * notes, skills and workflows, its git history and snapshot, audits.jsonl), then the learning records the store keeps
11
+ * for it (its promotions, grades and eval records). Refused (LearningInFlight), with nothing removed, while a run of the
12
+ * agent has not ended or a learning run grades one. Idempotent: what is gone already is skipped, so a second call
13
+ * removes nothing. `files`: the folder's entries it removed; `records`: the store's records. `folder` is ended here. */
14
+ export declare function deleteLearning(store: Store, agentId: string, folder: LearningFolder): Promise<{
15
+ files: number;
16
+ records: number;
17
+ }>;
@@ -0,0 +1,44 @@
1
+ // An agent's learning, deleted: the learning half of an agent's delete. Its caller (DELETE /v2/agents/{id}) stops the
2
+ // agent's runs and learning work first, then calls deleteLearning, then deletes the agent's store rows, in that order:
3
+ // a call again after a crash finishes what a first one began, and no learning is left with no agent to own it.
4
+ import { isWorkspaceError } from "../workspace/workspace.js";
5
+ import { FINAL_STATES } from "../store/store.js";
6
+ import { evalsKey } from "../learning-evals.js";
7
+ import { gradesKey, promotionsKey } from "./promote.js";
8
+ /** A delete refused: work of the agent's learning is still in flight (`runs`: a run of the agent not ended, its
9
+ * compile turn, a check's replay or an audit's shadow among them, or a learning run grading one). Nothing was removed. */
10
+ export class LearningInFlight extends Error {
11
+ runs;
12
+ constructor(agentId, runs) {
13
+ super(`agent ${agentId}'s learning is at work in ${runs.slice(0, 5).join(", ")}${runs.length > 5 ? ` and ${runs.length - 5} more` : ""}: stop them, then delete`);
14
+ this.name = "LearningInFlight";
15
+ this.runs = runs;
16
+ }
17
+ }
18
+ /** Agent `agentId`'s learning deleted: every file of its learning folder (`folder`, learning.ts learningFolderOf: its
19
+ * notes, skills and workflows, its git history and snapshot, audits.jsonl), then the learning records the store keeps
20
+ * for it (its promotions, grades and eval records). Refused (LearningInFlight), with nothing removed, while a run of the
21
+ * agent has not ended or a learning run grades one. Idempotent: what is gone already is skipped, so a second call
22
+ * removes nothing. `files`: the folder's entries it removed; `records`: the store's records. `folder` is ended here. */
23
+ export async function deleteLearning(store, agentId, folder) {
24
+ try {
25
+ const open = (await store.runs.list({ agentId })).filter((run) => run.agentId === agentId && !FINAL_STATES.includes(run.state)).map((run) => run.id);
26
+ const grading = (await store.learning.grading(agentId)).map((one) => one.learningRunId ?? one.runId);
27
+ if (open.length || grading.length)
28
+ throw new LearningInFlight(agentId, [...open, ...grading]);
29
+ const entries = await folder.workspace.list("").catch((error) => (isWorkspaceError(error, "NOT_FOUND") ? [] : Promise.reject(error)));
30
+ for (const entry of entries)
31
+ await folder.workspace.remove(entry.name, { recursive: true, force: true });
32
+ let records = 0;
33
+ for (const key of [promotionsKey(agentId), gradesKey(agentId), evalsKey(agentId)]) {
34
+ if ((await store.settings.get(key)) === undefined)
35
+ continue;
36
+ await store.settings.remove(key);
37
+ records += 1;
38
+ }
39
+ return { files: entries.length, records };
40
+ }
41
+ finally {
42
+ await folder.end();
43
+ }
44
+ }
@@ -224,6 +224,12 @@ export declare function promotionsShown(records: readonly PromotionRecord[], sho
224
224
  promotions: PromotionRecord[];
225
225
  serving: ReturnType<typeof servingOf>;
226
226
  };
227
+ /** `value` cut as the promotions read cuts its records (promotionsShown), at any depth and under any field: a workflow's
228
+ * name whole (`shown.name`), any other text of its part (`shown.text`). Numbers and the rest as they are. */
229
+ export declare function shownDeep(value: unknown, shown: {
230
+ readonly text: (text: string) => string;
231
+ readonly name: (name: string) => string;
232
+ }, key?: string): unknown;
227
233
  /** What a guarded promotion write did: `won`, whether this write kept its record (else `still` did not hold when it
228
234
  * wrote: another claim's decision came first); `record`, the newest record of its workflow at its digest after (the one
229
235
  * written when won, else the one there, undefined when none). A claim acts on a decision (starts replay runs, cancels)
@@ -251,7 +257,7 @@ export declare const sameAnswer: (a: string | null, b: string | null) => boolean
251
257
  export declare const gradeView: (grade: Grade) => {
252
258
  source: "feedback" | "eval";
253
259
  graded_at: string;
254
- path: "agent" | "workflow" | "handed_back" | "replay" | "audit";
260
+ path: "agent" | "workflow" | "replay" | "handed_back" | "audit";
255
261
  workflow: string | null;
256
262
  workflow_digest: string | null;
257
263
  feedback: "look_back" | null;
@@ -137,11 +137,15 @@ export function servingOf(records) {
137
137
  * (`shown.text`: a reason, a digest, a run id). Numbers and the rest as they are. A replaying record's `launch` (a run
138
138
  * launch: its notes, model and plane) never leaves: aggregates only. */
139
139
  export function promotionsShown(records, shown) {
140
- const cut = (value, key) => typeof value === "string" ? (key === "workflow" ? shown.name(value) : shown.text(value))
141
- : Array.isArray(value) ? value.map((one) => cut(one))
142
- : value !== null && typeof value === "object" ? Object.fromEntries(Object.entries(value).map(([field, one]) => [field, cut(one, field)]))
140
+ return { promotions: records.map(({ launch: _, ...one }) => shownDeep(one, shown)), serving: servingOf(records).map((one) => shownDeep(one, shown)) };
141
+ }
142
+ /** `value` cut as the promotions read cuts its records (promotionsShown), at any depth and under any field: a workflow's
143
+ * name whole (`shown.name`), any other text of its part (`shown.text`). Numbers and the rest as they are. */
144
+ export function shownDeep(value, shown, key) {
145
+ return typeof value === "string" ? (key === "workflow" ? shown.name(value) : shown.text(value))
146
+ : Array.isArray(value) ? value.map((one) => shownDeep(one, shown))
147
+ : value !== null && typeof value === "object" ? Object.fromEntries(Object.entries(value).map(([field, one]) => [field, shownDeep(one, shown, field)]))
143
148
  : value;
144
- return { promotions: records.map(({ launch: _, ...one }) => cut(one)), serving: servingOf(records).map((one) => cut(one)) };
145
149
  }
146
150
  /** Keeps `record` as the newest of its workflow at its digest, when `still` holds of the one there now (none: undefined)
147
151
  * and of every record kept (`items`: a check across revisions, one at a time, in the same guarded write): so of two
@@ -267,6 +267,10 @@ export declare const DECODED_DEPTH = 100;
267
267
  /** The most turns a learned workflow's model node runs (learned-workflow.ts hands its runner this cap): an agent node
268
268
  * that asks for more is refused at learn time and before a call, never when it comes up after earlier nodes spent. */
269
269
  export declare const LEARNED_MAX_TURNS = 8;
270
+ /** The first thing this release's workflow DSL refuses in a learned workflow's text on its own (`validateWorkflow`, no code
271
+ * run, no tool list: a refusal of the text, never of a host setting such as a tool gated, denied or missing), in the
272
+ * words a run's refusal gives it (draftProblems); undefined when the DSL takes it, or it is no JSON (no DSL issue). */
273
+ export declare function dslRefusalOf(dsl: DraftReader, text: string): string | undefined;
270
274
  /** Why `workflows/<name>/workflow.json` is not a draft the host can run; empty when it is. The DSL's own
271
275
  * `validateWorkflow` judges it, with `executeCode: false` so no code it holds is run (a code node is syntax-checked),
272
276
  * and with `tools`, so a node that names a tool outside them is its error: a harness's own tool (Bash, exec_command,
@@ -972,6 +972,22 @@ const issuesOf = (dsl, doc, tools) => {
972
972
  const valid = dsl.validateWorkflow(doc, { executeCode: false, ...(tools ? { tools } : {}) });
973
973
  return valid.ok ? [] : valid.issues;
974
974
  };
975
+ /** A DSL issue as a refusal says it: its code, where, and its words (cut at 200). */
976
+ const issueWords = (issue) => `${issue.code} at ${issue.path || "/"}: ${issue.message.slice(0, 200)}`;
977
+ /** The first thing this release's workflow DSL refuses in a learned workflow's text on its own (`validateWorkflow`, no code
978
+ * run, no tool list: a refusal of the text, never of a host setting such as a tool gated, denied or missing), in the
979
+ * words a run's refusal gives it (draftProblems); undefined when the DSL takes it, or it is no JSON (no DSL issue). */
980
+ export function dslRefusalOf(dsl, text) {
981
+ let doc;
982
+ try {
983
+ doc = JSON.parse(text);
984
+ }
985
+ catch {
986
+ return undefined;
987
+ }
988
+ const issue = issuesOf(dsl, doc)[0];
989
+ return issue ? issueWords(issue) : undefined;
990
+ }
975
991
  /** Why `workflows/<name>/workflow.json` is not a draft the host can run; empty when it is. The DSL's own
976
992
  * `validateWorkflow` judges it, with `executeCode: false` so no code it holds is run (a code node is syntax-checked),
977
993
  * and with `tools`, so a node that names a tool outside them is its error: a harness's own tool (Bash, exec_command,
@@ -993,7 +1009,7 @@ export function draftProblems(dsl, text, tools, gated = {}, deniedBy = {}, decis
993
1009
  const listed = tools ? [...tools, ...Object.keys(gated)] : undefined;
994
1010
  const issues = issuesOf(dsl, doc, listed);
995
1011
  if (issues.length)
996
- return issues.slice(0, 5).map((issue) => ({ rule: "workflow", detail: `the workflow DSL refuses it: ${issue.code} at ${issue.path || "/"}: ${issue.message.slice(0, 200)}` }));
1012
+ return issues.slice(0, 5).map((issue) => ({ rule: "workflow", detail: `the workflow DSL refuses it: ${issueWords(issue)}` }));
997
1013
  let out;
998
1014
  try {
999
1015
  // A label names one step (workflow-nodes.ts repeatedLabels): its events and escalation read by it.
@@ -1,13 +1,34 @@
1
1
  /** One node of a workflow document, with the prefix the DSL puts on its step's name when it runs: `parent/` for each
2
- * `workflow` node it sits in (scopeDepsToChild), so a nested step's label reads `parent/child`. */
2
+ * `workflow` node it sits in (scopeDepsToChild), so a nested step's label reads `parent/child`, and its place in the
3
+ * document (`path`: a chain's step by its index, any other child by the field that holds it, dot-joined; "" the root). */
3
4
  export type WorkflowNodeAt = {
4
5
  readonly node: Record<string, unknown>;
5
6
  readonly prefix: string;
7
+ readonly path: string;
6
8
  };
7
9
  /** Every node of `doc` (a parsed workflow.json), in document order: its root, a chain's steps, a parallel's branches, a
8
10
  * map's and a loop's body, a route's branches' bodies, a nested workflow's root, as the DSL's inspection visits them.
9
11
  * Walked with a stack of its own, never the call stack, so no draft's nesting can throw here. */
10
12
  export declare function workflowNodes(doc: unknown): WorkflowNodeAt[];
13
+ /** A check a node runs in code: on `when` (it runs only when the predicate holds) or `until` (a loop's stop). */
14
+ export type NodeCheck = {
15
+ readonly on: "when" | "until";
16
+ readonly predicate: unknown;
17
+ };
18
+ /** A node of a learned workflow as a person reads it (GET /agents/{id}/learning/promotions `serving[].champion.nodes`):
19
+ * where it is (`path`, as workflowNodes gives it; "root" for a root that is no chain), its kind and label (its kind
20
+ * when it has none), the tier its model step runs on (`fast`, or `agent` for the agent's own model; null for a node
21
+ * that calls no model tier), and its checks in code. */
22
+ export type WorkflowNode = {
23
+ readonly path: string;
24
+ readonly kind: string;
25
+ readonly label: string;
26
+ readonly tier: "fast" | "agent" | null;
27
+ readonly checks: readonly NodeCheck[];
28
+ };
29
+ /** Every node of workflow document `doc` (the one walk above), a chain left out (its steps are the nodes). Read off the
30
+ * document alone: nothing is run, and a document out of shape gives what of it is in shape. */
31
+ export declare function workflowNodesOf(doc: unknown): WorkflowNode[];
11
32
  /** The labels of `doc` that name more than one node, each once, in document order, as the DSL names a step when it runs
12
33
  * (`parent/child` in a child workflow). A label names one step: its events and its escalation read by it, and the durable runner refuses a workflow
13
34
  * that repeats one (DUPLICATE_LABEL). */
@@ -1,30 +1,49 @@
1
1
  // The one walk over a learned workflow's nodes (learn/skills.ts callNodes): only the
2
2
  // workflow's node positions, never an object in a call's args, a schema or any other data, however it is shaped.
3
+ import { TIERED_KINDS } from "./check.js";
4
+ const join = (path, key) => (path ? `${path}.${key}` : key);
3
5
  const asNode = (value) => (value && typeof value === "object" && !Array.isArray(value) ? value : undefined);
4
6
  /** Every node of `doc` (a parsed workflow.json), in document order: its root, a chain's steps, a parallel's branches, a
5
7
  * map's and a loop's body, a route's branches' bodies, a nested workflow's root, as the DSL's inspection visits them.
6
8
  * Walked with a stack of its own, never the call stack, so no draft's nesting can throw here. */
7
9
  export function workflowNodes(doc) {
8
10
  const out = [];
9
- const stack = [{ value: asNode(doc)?.root, prefix: "" }];
11
+ const stack = [{ value: asNode(doc)?.root, prefix: "", path: "" }];
10
12
  while (stack.length) {
11
- const { value, prefix } = stack.pop();
13
+ const { value, prefix, path } = stack.pop();
12
14
  const node = asNode(value);
13
15
  if (!node)
14
16
  continue;
15
- out.push({ node, prefix });
16
- const children = node.node === "chain" && Array.isArray(node.steps) ? node.steps
17
- : node.node === "parallel" && Array.isArray(node.branches) ? node.branches
18
- : (node.node === "map" || node.node === "loop") ? [node.body]
19
- : node.node === "route" && asNode(node.branches) ? Object.values(node.branches).map((branch) => asNode(branch)?.body)
20
- : node.node === "workflow" ? [asNode(node.workflow)?.root]
17
+ out.push({ node, prefix, path });
18
+ const children = node.node === "chain" && Array.isArray(node.steps) ? node.steps.map((step, i) => [String(i), step])
19
+ : node.node === "parallel" && Array.isArray(node.branches) ? node.branches.map((branch, i) => [`branches.${i}`, branch])
20
+ : (node.node === "map" || node.node === "loop") ? [["body", node.body]]
21
+ : node.node === "route" && asNode(node.branches) ? Object.entries(node.branches).map(([key, branch]) => [`branches.${key}.body`, asNode(branch)?.body])
22
+ : node.node === "workflow" ? [["workflow.root", asNode(node.workflow)?.root]]
21
23
  : [];
22
24
  const inner = node.node === "workflow" && typeof node.label === "string" ? `${prefix}${node.label}/` : prefix;
23
25
  for (let i = children.length - 1; i >= 0; i--)
24
- stack.push({ value: children[i], prefix: inner });
26
+ stack.push({ value: children[i][1], prefix: inner, path: join(path, children[i][0]) });
25
27
  }
26
28
  return out;
27
29
  }
30
+ const CHECK_KEYS = ["when", "until"];
31
+ /** Every node of workflow document `doc` (the one walk above), a chain left out (its steps are the nodes). Read off the
32
+ * document alone: nothing is run, and a document out of shape gives what of it is in shape. */
33
+ export function workflowNodesOf(doc) {
34
+ return workflowNodes(doc).flatMap(({ node, path }) => {
35
+ const kind = typeof node.node === "string" ? node.node : "?";
36
+ if (kind === "chain")
37
+ return [];
38
+ return [{
39
+ path: path || "root",
40
+ kind,
41
+ label: typeof node.label === "string" ? node.label : kind,
42
+ tier: TIERED_KINDS.has(kind) ? (node.tier === "fast" ? "fast" : "agent") : null,
43
+ checks: CHECK_KEYS.filter((key) => asNode(node[key])).map((key) => ({ on: key, predicate: node[key] })),
44
+ }];
45
+ });
46
+ }
28
47
  /** The labels of `doc` that name more than one node, each once, in document order, as the DSL names a step when it runs
29
48
  * (`parent/child` in a child workflow). A label names one step: its events and its escalation read by it, and the durable runner refuses a workflow
30
49
  * that repeats one (DUPLICATE_LABEL). */