@parcha/agentrun-serve 0.1.0-beta.42 → 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 (181) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/README.md +221 -31
  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/decisions.js +0 -4
  18. package/dist/errors.d.ts +1 -0
  19. package/dist/errors.js +3 -0
  20. package/dist/harness-table.d.ts +51 -3
  21. package/dist/harness-table.js +101 -13
  22. package/dist/harness.d.ts +18 -1
  23. package/dist/harness.js +21 -9
  24. package/dist/host.d.ts +12 -10
  25. package/dist/host.js +18 -16
  26. package/dist/import-sources.js +25 -5
  27. package/dist/import-worker.d.ts +3 -0
  28. package/dist/import-worker.js +7 -5
  29. package/dist/import.d.ts +22 -1
  30. package/dist/import.js +141 -28
  31. package/dist/learn/audit.d.ts +123 -0
  32. package/dist/learn/audit.js +159 -0
  33. package/dist/learn/check.d.ts +3 -0
  34. package/dist/learn/check.js +1 -1
  35. package/dist/learn/compile.d.ts +50 -74
  36. package/dist/learn/compile.js +90 -124
  37. package/dist/learn/delete.d.ts +17 -0
  38. package/dist/learn/delete.js +44 -0
  39. package/dist/learn/folder.d.ts +9 -0
  40. package/dist/learn/folder.js +13 -2
  41. package/dist/learn/promote.d.ts +92 -200
  42. package/dist/learn/promote.js +65 -187
  43. package/dist/learn/replay-calls.d.ts +5 -0
  44. package/dist/learn/replay-calls.js +12 -1
  45. package/dist/learn/secrets.d.ts +8 -0
  46. package/dist/learn/secrets.js +12 -0
  47. package/dist/learn/skills.d.ts +4 -0
  48. package/dist/learn/skills.js +19 -5
  49. package/dist/learn/workflow-nodes.d.ts +23 -3
  50. package/dist/learn/workflow-nodes.js +30 -12
  51. package/dist/learned-nodes.d.ts +9 -34
  52. package/dist/learned-nodes.js +11 -23
  53. package/dist/learned-workflow.d.ts +6 -8
  54. package/dist/learned-workflow.js +18 -57
  55. package/dist/learning-batch.d.ts +13 -5
  56. package/dist/learning-batch.js +34 -8
  57. package/dist/learning-cost.d.ts +111 -4
  58. package/dist/learning-cost.js +120 -3
  59. package/dist/learning-evals.d.ts +2 -0
  60. package/dist/learning-evals.js +4 -3
  61. package/dist/learning-routes.d.ts +8 -0
  62. package/dist/learning-routes.js +18 -1
  63. package/dist/learning-setting.d.ts +16 -1
  64. package/dist/learning-setting.js +34 -2
  65. package/dist/learning.d.ts +1 -1
  66. package/dist/listen-first.d.ts +30 -0
  67. package/dist/listen-first.js +115 -0
  68. package/dist/llms.txt +2 -1
  69. package/dist/mcp-servers-store.d.ts +12 -12
  70. package/dist/model.d.ts +8 -4
  71. package/dist/model.js +16 -8
  72. package/dist/openapi.js +203 -87
  73. package/dist/owner.d.ts +8 -0
  74. package/dist/owner.js +11 -0
  75. package/dist/paid-calls.d.ts +6 -0
  76. package/dist/paid-calls.js +11 -1
  77. package/dist/place.d.ts +8 -3
  78. package/dist/place.js +13 -9
  79. package/dist/provider.js +15 -1
  80. package/dist/run-launch.d.ts +6 -3
  81. package/dist/run-launch.js +2 -0
  82. package/dist/run-learning-served.d.ts +1 -1
  83. package/dist/run-model-key.d.ts +64 -0
  84. package/dist/run-model-key.js +147 -0
  85. package/dist/runner/adapter-loop.d.ts +10 -0
  86. package/dist/runner/adapter-loop.js +26 -4
  87. package/dist/runner/adapter-run-spec.d.ts +6 -3
  88. package/dist/runner/adapter-run-spec.js +83 -25
  89. package/dist/runner/adapters/index.d.ts +4 -2
  90. package/dist/runner/adapters/index.js +13 -4
  91. package/dist/runner/audit.d.ts +68 -0
  92. package/dist/runner/audit.js +349 -0
  93. package/dist/runner/beside.d.ts +2 -1
  94. package/dist/runner/beside.js +6 -3
  95. package/dist/runner/claim-secrets.d.ts +49 -0
  96. package/dist/runner/claim-secrets.js +110 -1
  97. package/dist/runner/cli-run-spec.d.ts +2 -1
  98. package/dist/runner/cli-run-spec.js +44 -15
  99. package/dist/runner/commands.d.ts +3 -6
  100. package/dist/runner/feedback-round.d.ts +3 -2
  101. package/dist/runner/feedback-round.js +8 -7
  102. package/dist/runner/harness-loops.js +31 -23
  103. package/dist/runner/journal-kinds.d.ts +5 -7
  104. package/dist/runner/journal-kinds.js +0 -7
  105. package/dist/runner/learning-dispatch.d.ts +0 -16
  106. package/dist/runner/learning-dispatch.js +4 -47
  107. package/dist/runner/learning-end.d.ts +55 -13
  108. package/dist/runner/learning-end.js +128 -44
  109. package/dist/runner/learning-factory.d.ts +1 -1
  110. package/dist/runner/learning-factory.js +1 -4
  111. package/dist/runner/learning-loop.d.ts +2 -38
  112. package/dist/runner/learning-loop.js +8 -116
  113. package/dist/runner/loop-contract.d.ts +6 -0
  114. package/dist/runner/loop-contract.js +4 -0
  115. package/dist/runner/loop.js +6 -2
  116. package/dist/runner/main.d.ts +1 -0
  117. package/dist/runner/main.js +25 -8
  118. package/dist/runner/memory-claim.d.ts +9 -6
  119. package/dist/runner/memory-claim.js +12 -9
  120. package/dist/runner/promotion.d.ts +55 -54
  121. package/dist/runner/promotion.js +232 -585
  122. package/dist/runner/reflect-hook.d.ts +14 -0
  123. package/dist/runner/reflect-hook.js +28 -3
  124. package/dist/runner/runner.js +57 -4
  125. package/dist/runner/store-secrets.js +9 -5
  126. package/dist/runner/workflow-first.d.ts +6 -5
  127. package/dist/runner/workflow-first.js +17 -12
  128. package/dist/runner/workflow-spec.js +10 -2
  129. package/dist/runs-over-store.d.ts +5 -4
  130. package/dist/runs-over-store.js +13 -3
  131. package/dist/sdk/workflows.d.ts +1 -1
  132. package/dist/server.d.ts +64 -50
  133. package/dist/server.js +516 -134
  134. package/dist/store/index.d.ts +2 -2
  135. package/dist/store/index.js +1 -1
  136. package/dist/store/seal.d.ts +20 -2
  137. package/dist/store/seal.js +24 -8
  138. package/dist/store/sqlite/run-launch.d.ts +4 -1
  139. package/dist/store/sqlite/run-launch.js +12 -0
  140. package/dist/store/sqlite/store.d.ts +3 -2
  141. package/dist/store/sqlite/store.js +119 -16
  142. package/dist/store/store.d.ts +41 -3
  143. package/dist/store-reads/analytics.js +11 -1
  144. package/dist/store-reads/learning.d.ts +57 -7
  145. package/dist/store-reads/learning.js +194 -28
  146. package/dist/store-reads/loop.d.ts +4 -39
  147. package/dist/store-reads/loop.js +10 -79
  148. package/dist/store-reads/stats.js +13 -3
  149. package/dist/store-view.d.ts +5 -1
  150. package/dist/store-view.js +12 -1
  151. package/dist/telemetry.d.ts +59 -0
  152. package/dist/telemetry.js +153 -0
  153. package/dist/tool-keys-store.d.ts +1 -1
  154. package/dist/tool-keys.d.ts +2 -2
  155. package/dist/tool-plane.d.ts +12 -12
  156. package/dist/tools.d.ts +11 -11
  157. package/dist/tools.js +18 -5
  158. package/dist/trigger-adapter.d.ts +3 -0
  159. package/dist/trigger-adapters.d.ts +4 -0
  160. package/dist/trigger-adapters.js +13 -0
  161. package/dist/trigger-composio.d.ts +58 -1
  162. package/dist/trigger-composio.js +160 -6
  163. package/dist/triggers.d.ts +4 -0
  164. package/dist/triggers.js +22 -3
  165. package/dist/validate.d.ts +11 -7
  166. package/dist/validate.js +8 -7
  167. package/dist/workspace/computer-for-claim.d.ts +15 -5
  168. package/dist/workspace/computer-for-claim.js +228 -32
  169. package/dist/workspace/resolve-computer.d.ts +8 -2
  170. package/dist/workspace/resolve-computer.js +1 -1
  171. package/dist/workspace/run-tools.d.ts +1 -1
  172. package/dist/workspace/run-tools.js +14 -3
  173. package/package.json +10 -9
  174. package/dist/console/assets/index-C3gNPz58.css +0 -1
  175. package/dist/console/assets/index-DYJ_wj27.js +0 -711
  176. package/dist/learn/general.d.ts +0 -69
  177. package/dist/learn/general.js +0 -75
  178. package/dist/learn/refit.d.ts +0 -48
  179. package/dist/learn/refit.js +0 -264
  180. package/dist/runner/step-guard.d.ts +0 -62
  181. package/dist/runner/step-guard.js +0 -93
@@ -1,14 +1,15 @@
1
1
  // Setup's import of this machine's sessions, on a worker thread: node:sqlite's wait for a busy store and the parsing of
2
2
  // every session line happen here, so neither holds up a request the server answers. `plan` counts what an import would
3
- // take; `import` takes it. The message "stop" ends either between two files or two sessions; what is written stays, and
3
+ // take, and names its projects for the owner to choose from; `import` takes it, only the projects chosen when some were
4
+ // (`projects`). The message "stop" ends either between two files or two sessions; what is written stays, and
4
5
  // the next import goes on from there. Its one message back is its answer.
5
6
  // Before anything loads node:sqlite, as in the server's own thread: its ExperimentalWarning is not the server's to print.
6
7
  import "./quiet-sqlite-warning.js";
7
8
  import { parentPort, workerData } from "node:worker_threads";
8
- import { ownSecrets, planImport, runImport } from "./import.js";
9
+ import { candidatesOf, ownSecrets, planImport, runImport, sessionsOf } from "./import.js";
9
10
  import { importStoreProxy } from "./import-proxy.js";
10
11
  import { toolKeysOverStore } from "./tool-keys-store.js";
11
- const { task, data, home, temp, secrets = {} } = workerData;
12
+ const { task, data, home, temp, secrets = {}, projects } = workerData;
12
13
  const stop = new AbortController();
13
14
  parentPort.on("message", (message) => void (message === "stop" && stop.abort()));
14
15
  // The port does not keep the thread alive on its own: the task does (the proxy references it only while it waits for the
@@ -25,7 +26,7 @@ const answer = async () => {
25
26
  // A count keeps no transcript: no key scan (a whole history read through secretlint at every start).
26
27
  const plan = await planImport({ ...options, keys: false });
27
28
  // Sessions as the import takes them: a session written in several files (a resumed thread) is one run.
28
- return stop.signal.aborted ? { stopped: true } : { projects: plan.projects.length, sessions: plan.projects.reduce((n, p) => n + new Set(p.sessions.map((s) => `${s.source}:${s.id}`)).size, 0) };
29
+ return stop.signal.aborted ? { stopped: true } : { projects: plan.projects.length, sessions: plan.projects.reduce((n, p) => n + sessionsOf(p.sessions).length, 0), candidates: candidatesOf(plan, env) };
29
30
  }
30
31
  // No store of its own: the worker reaches the server's one open store over the port. The server holds the exclusive owner
31
32
  // lock, so a second opener here would be refused; every read and write the import needs crosses the port instead.
@@ -35,7 +36,8 @@ const answer = async () => {
35
36
  const keys = toolKeysOverStore(store, env, () => { });
36
37
  await keys.load();
37
38
  // The secrets this server made and keeps, read from the store as the import starts: cut by their values too.
38
- const taking = { ...options, stored: keys.values(), own: await ownSecrets(store, data, env) };
39
+ // The owner's choice, when the setup named projects: nothing of another project is read for keys or written.
40
+ const taking = { ...options, stored: keys.values(), own: await ownSecrets(store, data, env), ...(projects ? { only: projects } : {}) };
39
41
  const report = await runImport(store, await planImport(taking, store), taking);
40
42
  const took = { agents: report.agents.filter((a) => a.runs > 0).map((a) => a.id), runs: report.agents.reduce((n, a) => n + a.runs, 0), skipped: report.skipped.length };
41
43
  return stop.signal.aborted ? { took, stopped: true } : { took };
package/dist/import.d.ts CHANGED
@@ -39,6 +39,11 @@ export declare const IMPORT_ASKED = ".import-at-setup";
39
39
  export declare const LIVE_MS: number;
40
40
  /** The most of one session file read. */
41
41
  export declare const MAX_SESSION_BYTES: number;
42
+ /** The most of one run read together: its session's files and its subagents'. A run is held in memory whole while its
43
+ * keys are found and it is written, so one over this is left out whole (never cut short), whatever the history's size. */
44
+ export declare const MAX_RUN_BYTES: number;
45
+ /** The most projects a count names for the owner to choose from: the latest active. */
46
+ export declare const MAX_CANDIDATES = 500;
42
47
  /** The most of one instructions or skill file read, and of one agent's skill files together. */
43
48
  export declare const MAX_FILE_BYTES: number;
44
49
  export declare const MAX_SKILL_BYTES: number;
@@ -72,6 +77,19 @@ export type ImportOptions = {
72
77
  keys?: boolean;
73
78
  /** Read each session's turns while planning, and measure it (`Plan.found`): what a dry run's summary counts. */
74
79
  measure?: boolean;
80
+ /** The owner's choice: only the projects of these agent ids (`agentIdOf`, as a count's candidates name them) are
81
+ * planned, so only they are read for keys and written. Absent: every project. */
82
+ only?: readonly string[];
83
+ };
84
+ /** A project a count found, for the owner to choose: the agent it would become (`id`), its folder, how many sessions
85
+ * an import would take from it, by which tools, and when the latest of them ended. */
86
+ export type ImportCandidate = {
87
+ id: string;
88
+ name: string;
89
+ path: string;
90
+ sessions: number;
91
+ sources: Source[];
92
+ last_active: string | null;
75
93
  };
76
94
  /** Why a session file or a project's file is left out, by kind, as the left-out counts group them (leftOutLines). */
77
95
  export type LeftOut = "gone" | "temp" | "live" | "large" | "unread" | "no-project" | "no-words" | "copies" | "vanished" | "file";
@@ -122,11 +140,14 @@ export type ImportReport = {
122
140
  * known format secretlint found. */
123
141
  secretsRemoved?: number;
124
142
  };
143
+ /** The projects of `plan` for the owner to choose from, the latest active first (then by folder), at most MAX_CANDIDATES.
144
+ * With `env`, the values of its keys are cut from a name and a folder as the import cuts them. */
145
+ export declare function candidatesOf(plan: Pick<Plan, "projects">, env?: NodeJS.ProcessEnv): ImportCandidate[];
125
146
  export declare const agentIdOf: (cwd: string) => string;
126
147
  /** What an import would take: the sessions under `home`, by project, with what it leaves out and why. Keeps no turns
127
148
  * (with `measure`, only until each session is measured), and reads no file `store`'s imports already read whole and
128
149
  * that has not changed since. */
129
- export declare function planImport({ home, sources, all, deleted, now, temp: tempDir, measure, env, stored, own, signal, keys: scan, onKeys }: ImportOptions, store?: ImportStore): Promise<Plan>;
150
+ export declare function planImport({ home, sources, all, deleted, now, temp: tempDir, measure, env, stored, own, signal, keys: scan, onKeys, only }: ImportOptions, store?: ImportStore): Promise<Plan>;
130
151
  /** The subagents tied to no session: each one's tokens and tool calls, for a summary's totals, each response once. */
131
152
  export declare function untiedFound(plan: Plan): Promise<Found[]>;
132
153
  /** The sessions `files` write, as the import takes them: one per source and session id, however many files write it
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));
@@ -0,0 +1,123 @@
1
+ import type { Workspace } from "../workspace/index.js";
2
+ import type { AuditLoop } from "../learning-setting.js";
3
+ import type { RunLaunch } from "../run-launch.js";
4
+ import { AUDITS_FILE, type FolderChange, type FolderRead } from "./folder.js";
5
+ import { type PromotionRecord } from "./promote.js";
6
+ export { AUDITS_FILE };
7
+ /** The newest rows the ledger keeps: twice the widest window a definition may set (AUDIT_MAX), and a file well under the
8
+ * folder's file cap (a line is a few hundred bytes); with them, the started lines of theirs, and every open one. */
9
+ export declare const AUDITS_KEPT = 2000;
10
+ /** What every shadow run's id starts with: its served run's id follows (shadowRunId). No server-minted id starts so. */
11
+ export declare const SHADOW_PREFIX = "audit.";
12
+ /** One finished audit. `run`: the served run; `shadow_run`: its shadow (null for a grade's row, or one never started);
13
+ * `workflow` at `digest` served it, under the promotion begun at `promoted_at` (learn/promote.ts promotionStartOf: the
14
+ * one serving when its shadow started, or at the grade; null: none); `agreed`: whether the two answers say the same (a
15
+ * grade's: the grade), null when either answer is missing (a shadow that failed, parked or never ran: no evidence either
16
+ * way, never counted by the hold rule); the two runs' costs (null unknown). `turn`: the served run's answer the audit is
17
+ * of, the id of its answer row (its newest final answer when the audit began, or at the grade): a follow-up's later
18
+ * answer is never the one compared; absent when it had none. `skipped`: a drawn run whose cap left its shadow no
19
+ * allowance (less than a run's smallest cap): no shadow was started. `parked`: its shadow came to wait on a person (an
20
+ * approval, a question, a raise of its cap: what the served run's cap left) and ended there, so it has no answer. */
21
+ export interface AuditRow {
22
+ readonly run: string;
23
+ readonly shadow_run: string | null;
24
+ readonly workflow: string;
25
+ readonly digest: string;
26
+ readonly promoted_at: string | null;
27
+ readonly source: "shadow" | "grade";
28
+ readonly agreed: boolean | null;
29
+ readonly served_cost: number | null;
30
+ readonly shadow_cost: number | null;
31
+ readonly turn?: string;
32
+ readonly skipped?: "no allowance";
33
+ readonly parked?: true;
34
+ readonly at: string;
35
+ }
36
+ /** A shadow audit begun (runner/audit.ts startAudit), written before its shadow run is created: open until a row of
37
+ * source `shadow` for the same `run` is written. `turn`: the served run's answer row it audits (AuditRow.turn). */
38
+ export interface AuditStarted {
39
+ readonly source: "started";
40
+ readonly run: string;
41
+ readonly shadow_run: string;
42
+ readonly workflow: string;
43
+ readonly digest: string;
44
+ readonly promoted_at: string | null;
45
+ readonly turn?: string;
46
+ readonly at: string;
47
+ }
48
+ /** One line of the ledger, in the order written. */
49
+ export type LedgerLine = AuditRow | AuditStarted;
50
+ /** The rows of `lines` (the finished audits), oldest first. */
51
+ export declare const rowsOf: (lines: readonly LedgerLine[]) => AuditRow[];
52
+ /** The started lines of `lines` with no result row yet: the audits settlement still owes, oldest first. */
53
+ export declare function openAudits(lines: readonly LedgerLine[]): AuditStarted[];
54
+ /** Whether served run `runId` is audited at 1 in `k`: the first 8 hex digits of sha256("audit:" + its id), read as a
55
+ * number, are a multiple of k. A function of the id and k alone, so a claim taken again draws the same. */
56
+ export declare const auditDrawn: (runId: string, k: number) => boolean;
57
+ /** The k a served run is drawn at: `audit_every`, or `audit_every_later` once its revision served `audit_later_after`. */
58
+ export declare const auditEveryOf: (loop: AuditLoop, served: number) => number;
59
+ /** The shadow run's id for served run `runId`: one per served run, ever (a second create is the store's constraint). */
60
+ export declare const shadowRunId: (runId: string) => string;
61
+ /** Whether `runId` is a shadow run's. */
62
+ export declare const isShadowRun: (runId: string) => boolean;
63
+ /** The first tool agent revision `revision` can call (its grants, and what its computer brings) that is not read-only by
64
+ * the rule a check's replay skips a write by (learn/replay-calls.ts toolClassOf: an MCP tool by its pinned annotations,
65
+ * readOnlyHint, a built-in by READ_TOOLS); undefined when every one only reads. An agent that can call one is never
66
+ * audited: its shadow, a second run of the agent on the same input, could do that write again. */
67
+ export declare function auditWriterOf(revision: {
68
+ readonly body: unknown;
69
+ readonly mcpPin: unknown;
70
+ } | undefined): string | undefined;
71
+ /** What the promotions read says of an agent never audited (auditWriterOf names `tool`). */
72
+ export declare const auditsOffWords: (tool: string) => string;
73
+ /** Whether a served run's launch can be audited: started over the API (no trigger, no origin of its first message) with no
74
+ * uploaded files. A triggered run's context (a GitHub event's checkout, the thread it answers on) is never rebuilt for a
75
+ * shadow, which could answer there too: its served run is not auditable (its record's metrics.not_auditable). */
76
+ export declare const auditableLaunch: (launch: Pick<RunLaunch, "trigger" | "inputOrigin" | "files">) => boolean;
77
+ /** The lines of a ledger's text, in the order written; one out of shape is skipped. */
78
+ export declare function parseLedger(text: string): LedgerLine[];
79
+ /** The ledger's text for `lines`: from the AUDITS_KEPT-th newest row on, and every open started line before it. */
80
+ export declare function auditsText(lines: readonly LedgerLine[]): string;
81
+ /** The ledger's lines on the folder's main as `folder` reads it (none before the first). */
82
+ export declare function ledgerOf(folder: FolderRead): Promise<LedgerLine[]>;
83
+ /** The ledger's rows on the folder's main: its finished audits, oldest first. */
84
+ export declare const readAudits: (ws: Workspace) => Promise<AuditRow[]>;
85
+ /** A line's place in the ledger: one per served run and source (a started line's, its shadow's row, a grade's row). */
86
+ export declare const lineKey: (line: LedgerLine) => string;
87
+ /** The change that appends `lines` to the ledger `before` (none when each is there already: lineKey), with the lines it
88
+ * appends. */
89
+ export declare function auditChange(before: readonly LedgerLine[], lines: readonly LedgerLine[]): {
90
+ added: LedgerLine[];
91
+ change?: FolderChange;
92
+ };
93
+ /** The rows the hold rule counts for `workflow` at `digest` under the promotion begun at `promotedAt` (learn/promote.ts
94
+ * promotionStartOf; none counted for null): those with a verdict, the newest `hold_window` of them. */
95
+ export declare const windowOf: (rows: readonly AuditRow[], workflow: string, digest: string, promotedAt: string | null, loop: Pick<AuditLoop, "hold_window">) => AuditRow[];
96
+ /** The hold rule: the counted rows (windowOf) when at least `hold_disagree` of them disagree, else undefined. */
97
+ export declare function holdOf(rows: readonly AuditRow[], workflow: string, digest: string, promotedAt: string | null, loop: Pick<AuditLoop, "hold_window" | "hold_disagree">): {
98
+ rows: AuditRow[];
99
+ disagreed: AuditRow[];
100
+ } | undefined;
101
+ /** A workflow's audit line, as the promotions read shows it: the bar, and the counted rows and disagreements now. */
102
+ export type AuditLine = {
103
+ readonly window: number;
104
+ readonly disagree: number;
105
+ readonly rows: number;
106
+ readonly disagreed: number;
107
+ };
108
+ export declare function auditLineOf(rows: readonly AuditRow[], workflow: string, digest: string, promotedAt: string | null, loop: Pick<AuditLoop, "hold_window" | "hold_disagree">): AuditLine;
109
+ /** What the promotions read says of each learned workflow beside what serves (learn/promote.ts servingOf, in its order):
110
+ * `state` (`checking`, its newest record is a check at work; `serving`, a revision serves; `stopped`, its newest record
111
+ * is a hold that stops it; `held`, else), its newest decided check's numbers, and its audit line over the rows of the
112
+ * serving (else the newest) revision's newest promotion (the ones the hold rule counts). */
113
+ export type ServingLine = {
114
+ readonly state: "serving" | "checking" | "held" | "stopped";
115
+ readonly check: {
116
+ readonly n: number;
117
+ readonly agreed: number;
118
+ readonly alone: number;
119
+ readonly attempt: 1 | 2;
120
+ } | null;
121
+ readonly audit: AuditLine | null;
122
+ };
123
+ export declare function servingLinesOf(records: readonly PromotionRecord[], rows: readonly AuditRow[], loop: Pick<AuditLoop, "hold_window" | "hold_disagree">): ServingLine[];