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

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 (164) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/NOTICE +2 -0
  3. package/README.md +85 -19
  4. package/dist/agent-rows.d.ts +1 -1
  5. package/dist/agents-store.js +3 -1
  6. package/dist/calendar/address.d.ts +49 -0
  7. package/dist/calendar/address.js +153 -0
  8. package/dist/calendar/fetch.d.ts +24 -0
  9. package/dist/calendar/fetch.js +146 -0
  10. package/dist/calendar/ics-faux.d.ts +39 -0
  11. package/dist/calendar/ics-faux.js +236 -0
  12. package/dist/calendar/labels.d.ts +3 -0
  13. package/dist/calendar/labels.js +61 -0
  14. package/dist/calendar/names.d.ts +52 -0
  15. package/dist/calendar/names.js +54 -0
  16. package/dist/calendar/parse.d.ts +108 -0
  17. package/dist/calendar/parse.js +625 -0
  18. package/dist/calendar/routes.d.ts +17 -0
  19. package/dist/calendar/routes.js +81 -0
  20. package/dist/calendar/tools.d.ts +23 -0
  21. package/dist/calendar/tools.js +124 -0
  22. package/dist/cli.js +3 -1
  23. package/dist/computer-record.d.ts +55 -0
  24. package/dist/computer-record.js +315 -0
  25. package/dist/computer-setting.d.ts +1 -0
  26. package/dist/computer-setting.js +15 -2
  27. package/dist/computers.js +2 -14
  28. package/dist/console/assets/index-BrcDSBD8.css +1 -0
  29. package/dist/console/assets/index-Bz6IWncl.js +711 -0
  30. package/dist/console/index.html +2 -2
  31. package/dist/decisions.js +0 -4
  32. package/dist/eval-feed.d.ts +2 -2
  33. package/dist/eval-feed.js +9 -5
  34. package/dist/feed/parse.d.ts +3 -2
  35. package/dist/feed/parse.js +9 -18
  36. package/dist/feed/pointer.d.ts +2 -0
  37. package/dist/feed/pointer.js +17 -0
  38. package/dist/file-types.js +1 -0
  39. package/dist/host-command.d.ts +3 -0
  40. package/dist/host-command.js +18 -0
  41. package/dist/host.d.ts +3 -0
  42. package/dist/host.js +3 -0
  43. package/dist/import-sources.js +25 -5
  44. package/dist/learn/audit.d.ts +123 -0
  45. package/dist/learn/audit.js +159 -0
  46. package/dist/learn/check.d.ts +14 -0
  47. package/dist/learn/check.js +194 -14
  48. package/dist/learn/compile.d.ts +75 -78
  49. package/dist/learn/compile.js +175 -176
  50. package/dist/learn/folder.d.ts +9 -0
  51. package/dist/learn/folder.js +13 -2
  52. package/dist/learn/promote.d.ts +138 -196
  53. package/dist/learn/promote.js +68 -184
  54. package/dist/learn/replay-calls.d.ts +5 -0
  55. package/dist/learn/replay-calls.js +12 -1
  56. package/dist/learn/secrets.d.ts +8 -0
  57. package/dist/learn/secrets.js +12 -0
  58. package/dist/learn/skills.js +2 -4
  59. package/dist/learn/workflow-nodes.d.ts +1 -2
  60. package/dist/learn/workflow-nodes.js +2 -3
  61. package/dist/learned-nodes.d.ts +9 -34
  62. package/dist/learned-nodes.js +11 -23
  63. package/dist/learned-workflow.d.ts +6 -8
  64. package/dist/learned-workflow.js +18 -57
  65. package/dist/learning-batch.d.ts +13 -5
  66. package/dist/learning-batch.js +34 -8
  67. package/dist/learning-cost.d.ts +11 -4
  68. package/dist/learning-cost.js +4 -2
  69. package/dist/learning-routes.js +1 -1
  70. package/dist/learning-setting.d.ts +38 -0
  71. package/dist/learning-setting.js +83 -0
  72. package/dist/learning-words.d.ts +3 -0
  73. package/dist/learning-words.js +3 -0
  74. package/dist/learning.d.ts +3 -2
  75. package/dist/learning.js +5 -3
  76. package/dist/mcp-oauth.d.ts +8 -0
  77. package/dist/mcp-oauth.js +7 -0
  78. package/dist/mcp-private-hosts.d.ts +13 -0
  79. package/dist/mcp-private-hosts.js +16 -0
  80. package/dist/openapi.d.ts +1 -0
  81. package/dist/openapi.js +195 -59
  82. package/dist/run-files.d.ts +6 -2
  83. package/dist/run-files.js +29 -7
  84. package/dist/run-launch.d.ts +6 -3
  85. package/dist/run-launch.js +2 -0
  86. package/dist/run-learning-served.d.ts +2 -2
  87. package/dist/run-reads-over-store.d.ts +5 -1
  88. package/dist/run-reads-over-store.js +8 -4
  89. package/dist/run-recordings.d.ts +20 -0
  90. package/dist/run-recordings.js +133 -0
  91. package/dist/runner/adapter-loop.d.ts +5 -1
  92. package/dist/runner/adapter-loop.js +20 -8
  93. package/dist/runner/adapter-run-spec.d.ts +16 -1
  94. package/dist/runner/adapter-run-spec.js +36 -11
  95. package/dist/runner/audit.d.ts +64 -0
  96. package/dist/runner/audit.js +338 -0
  97. package/dist/runner/beside.js +2 -2
  98. package/dist/runner/cli-run-spec.js +25 -12
  99. package/dist/runner/feedback-round.d.ts +9 -25
  100. package/dist/runner/feedback-round.js +19 -40
  101. package/dist/runner/harness-loops.js +1 -15
  102. package/dist/runner/journal-kinds.d.ts +0 -7
  103. package/dist/runner/journal-kinds.js +0 -7
  104. package/dist/runner/learning-dispatch.d.ts +0 -16
  105. package/dist/runner/learning-dispatch.js +4 -47
  106. package/dist/runner/learning-end.d.ts +62 -13
  107. package/dist/runner/learning-end.js +180 -74
  108. package/dist/runner/learning-factory.d.ts +1 -1
  109. package/dist/runner/learning-factory.js +1 -4
  110. package/dist/runner/learning-loop.d.ts +2 -38
  111. package/dist/runner/learning-loop.js +8 -116
  112. package/dist/runner/main.d.ts +11 -0
  113. package/dist/runner/main.js +30 -3
  114. package/dist/runner/mcp-run.d.ts +2 -2
  115. package/dist/runner/promotion.d.ts +78 -50
  116. package/dist/runner/promotion.js +371 -503
  117. package/dist/runner/reflect-hook.d.ts +15 -0
  118. package/dist/runner/reflect-hook.js +28 -14
  119. package/dist/runner/store-secrets.js +3 -1
  120. package/dist/runner/workflow-first.d.ts +6 -11
  121. package/dist/runner/workflow-first.js +24 -25
  122. package/dist/runs-over-store.d.ts +1 -1
  123. package/dist/sdk/runs.js +2 -1
  124. package/dist/secrets.js +2 -2
  125. package/dist/server.d.ts +4 -3
  126. package/dist/server.js +132 -26
  127. package/dist/store/agent-body.d.ts +5 -3
  128. package/dist/store/agent-body.js +14 -10
  129. package/dist/store/sqlite/store.js +1 -0
  130. package/dist/store/store.d.ts +3 -0
  131. package/dist/store-reads/learning.d.ts +18 -7
  132. package/dist/store-reads/learning.js +36 -23
  133. package/dist/store-reads/loop.d.ts +5 -39
  134. package/dist/store-reads/loop.js +21 -80
  135. package/dist/store-view.d.ts +5 -0
  136. package/dist/store-view.js +16 -2
  137. package/dist/template-eval.d.ts +7 -0
  138. package/dist/template-eval.js +54 -6
  139. package/dist/templates.d.ts +3 -1
  140. package/dist/templates.js +14 -1
  141. package/dist/timeline/computer.js +2 -1
  142. package/dist/tool-list.js +1 -0
  143. package/dist/tools.d.ts +7 -0
  144. package/dist/tools.js +11 -0
  145. package/dist/trigger-feed.js +67 -18
  146. package/dist/validate.js +7 -2
  147. package/dist/workspace/computer-for-claim.d.ts +7 -0
  148. package/dist/workspace/computer-for-claim.js +12 -2
  149. package/dist/workspace/paths.d.ts +4 -0
  150. package/dist/workspace/paths.js +9 -0
  151. package/dist/workspace/resolve-computer.d.ts +3 -1
  152. package/dist/workspace/run-tools.d.ts +1 -1
  153. package/dist/workspace/run-tools.js +14 -3
  154. package/launcher/agentrun-serve +31 -24
  155. package/package.json +10 -9
  156. package/templates/README.md +11 -2
  157. package/dist/console/assets/index-C3gNPz58.css +0 -1
  158. package/dist/console/assets/index-COGhx_2Z.js +0 -711
  159. package/dist/learn/general.d.ts +0 -69
  160. package/dist/learn/general.js +0 -75
  161. package/dist/learn/refit.d.ts +0 -48
  162. package/dist/learn/refit.js +0 -264
  163. package/dist/runner/step-guard.d.ts +0 -62
  164. package/dist/runner/step-guard.js +0 -93
package/dist/server.js CHANGED
@@ -41,7 +41,7 @@ import { chooseModel, EFFORTS, FAUX_ENV, FAUX_UPSTREAM_ENV, MODEL_NODES, modelSo
41
41
  import { DEFAULT_HARNESS, HARNESSES, harnessOfBody, harnessOffers } from "./harness.js";
42
42
  import { HARNESS_TABLE_ENV, harnessOf } from "./harness-table.js";
43
43
  import { HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./harness-install.js";
44
- import { healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
44
+ import { DEFAULT_PORT, healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
45
45
  import { IMPORT_ASKED } from "./import.js";
46
46
  import { answerStoreCall } from "./import-proxy.js";
47
47
  import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningFolderOf, learningOf, learnsOf, RUN_LEARNING_USE, seedOf } from "./learning.js";
@@ -84,8 +84,11 @@ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
84
84
  import { openStore, sealRunMcpAuth, StoreOwned, storeTarget } from "./store/index.js";
85
85
  import { answerOf, logged } from "./agents.js";
86
86
  import { keepGrade } from "./runner/feedback-round.js";
87
+ import { gradeRow, notAuditableOf } from "./runner/audit.js";
88
+ import { auditsOffWords, auditWriterOf, isShadowRun, readAudits, servingLinesOf } from "./learn/audit.js";
89
+ import { auditLoopOf, COMPILE_AFTER_MAX } from "./learning-setting.js";
87
90
  import { FINAL_STATES, RUN_CHANGES_PAGE } from "./store/store.js";
88
- import { GRADE_SOURCES, GRADES_KEPT, gradeView, LABEL_MAX, promotionsOf, promotionsShown } from "./learn/promote.js";
91
+ import { GRADE_SOURCES, gradeView, LABEL_MAX, promotionsOf, promotionsShown, servingOf } from "./learn/promote.js";
89
92
  import { runModelRef } from "./model.js";
90
93
  import { REDACTED } from "./secret-cut.js";
91
94
  // The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
@@ -106,7 +109,7 @@ import { DRAIN_TIMEOUT } from "./runner/beside.js";
106
109
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
107
110
  import { agentLoopOverStore } from "./store-reads/loop.js";
108
111
  import { printable } from "./learn/index.js";
109
- import { agentCostOverStore, agentLearningOverStore, allInOf, costRunOf, learningCountsOverStore, learningSpendOverStore, runLearningEnd } from "./store-reads/learning.js";
112
+ import { agentCostOverStore, agentLearningOverStore, allInOf, costRunOf, learningCountsOverStore, learningSpendOverStore, runLearningEnd, shadowSpendOf } from "./store-reads/learning.js";
110
113
  import { figuresOf, LearningBatches } from "./learning-batch.js";
111
114
  import { costCsv, learningCostQuery, RUN_PATHS } from "./learning-cost.js";
112
115
  import { evalOf, evalsOf, recordEval } from "./learning-evals.js";
@@ -117,12 +120,12 @@ import { signInsOverStore } from "./sign-ins-store.js";
117
120
  import { boundTool, MCP_AUTH_TYPES, marked, mcpAuthOf, nameOf as mcpNameOf } from "./mcp-probe.js";
118
121
  import { composioForget, composioNote, composioSave, composioTools } from "./composio-preset.js";
119
122
  import { ComposioTriggers } from "./composio-triggers.js";
120
- import { mcpServersOverStore } from "./mcp-servers-store.js";
123
+ import { loopbackWords, mcpServersOverStore } from "./mcp-servers-store.js";
121
124
  import { getMcpServer, listMcpServers } from "./mcp-store.js";
122
- import { privateHostsRoute } from "./mcp-private-hosts.js";
125
+ import { privateHostsRoute, saveServerOwn } from "./mcp-private-hosts.js";
123
126
  import { metaToolOf } from "./mcp-meta.js";
124
127
  import { mcpPinOf } from "./mcp-gateway.js";
125
- import { MCP_SETTINGS_PAGE, signInCookie, startedHere } from "./mcp-oauth.js";
128
+ import { LOOPBACK, MCP_SETTINGS_PAGE, signInCookie, startedHere } from "./mcp-oauth.js";
126
129
  import { WEBHOOK_EVENTS, WEBHOOK_FILE, waitMarkerOf, Webhooks } from "./webhooks.js";
127
130
  import { appPermissionWarnings } from "./template-github-permissions.js";
128
131
  import { templateApplied, templateTriggerSecret, templateWebhookSecrets, triggerMade, triggerRotated, webhookSaved, withTriggerSecret } from "./trigger-secrets-shown.js";
@@ -151,6 +154,8 @@ import { toolSettingsOverStore } from "./tool-settings-store.js";
151
154
  import { readApprovers, writeApprovers } from "./server-approvers.js";
152
155
  import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
153
156
  import { entryAt, listFiles, sendFile as sendWorkspaceFile, viewOf } from "./run-files.js";
157
+ import { recordingsOf, recordingsWorkspace } from "./run-recordings.js";
158
+ import { recordingsFolder } from "./workspace/paths.js";
154
159
  import { heldRoute, holdIssues, runComputerRead } from "./computer-held-routes.js";
155
160
  import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runComputerKind } from "./computer-routes.js";
156
161
  import { ATTACH_PATH, AttachHub, PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
@@ -161,6 +166,8 @@ import { freeModelRequestsOf } from "@parcha/agentrun-kernel/kernel/cap";
161
166
  import { archilRoute, createArchilRoutes, liveRunsOnDisk } from "./archil-routes.js";
162
167
  import { noAccount, openAccount } from "./email/account.js";
163
168
  import { emailRoute } from "./email/routes.js";
169
+ import { addressForms, openCalendar } from "./calendar/address.js";
170
+ import { calendarRoute } from "./calendar/routes.js";
164
171
  import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode } from "./archil-settings.js";
165
172
  import { computerOfPlace } from "./computer-setting.js";
166
173
  import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
@@ -171,7 +178,7 @@ import { keyReader } from "./key-meta.js";
171
178
  export const CONTRACT = "agentrun.v2/0";
172
179
  /** A process's flags for a worker of it: without --input-type and the code string given with -e, --eval, -p or --print. */
173
180
  const workerArgs = (args) => args.filter((arg, i) => !arg.startsWith("--input-type") && !/^(?:-e|--eval|-p|--print)(?:=|$)/.test(arg) && !/^(?:-e|--eval|-p|--print)$/.test(args[i - 1] ?? ""));
174
- export const DEFAULT_PORT = 7340;
181
+ export { DEFAULT_PORT };
175
182
  const VERSION = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8")).version;
176
183
  const IDEMPOTENCY_FILE = ".idempotency.json";
177
184
  /** A run's live viewer, under the run's path (browser-live.ts): its run id, the family's address (`computer`, one for every
@@ -334,6 +341,11 @@ export const ROUTES = [
334
341
  { method: "PUT", pattern: /^\/settings\/email$/, name: "saveEmailAccount" },
335
342
  { method: "DELETE", pattern: /^\/settings\/email$/, name: "deleteEmailAccount" },
336
343
  { method: "POST", pattern: /^\/settings\/email\/test$/, name: "testEmailAccount" },
344
+ // The server's calendar (calendar/routes.ts): the owner's session's alone, its address in no answer.
345
+ { method: "GET", pattern: /^\/settings\/calendar$/, name: "getCalendar" },
346
+ { method: "PUT", pattern: /^\/settings\/calendar$/, name: "saveCalendar" },
347
+ { method: "DELETE", pattern: /^\/settings\/calendar$/, name: "deleteCalendar" },
348
+ { method: "POST", pattern: /^\/settings\/calendar\/test$/, name: "testCalendar" },
337
349
  { method: "GET", pattern: /^\/settings\/chatgpt$/, name: "getChatGPTSignIn" },
338
350
  { method: "DELETE", pattern: /^\/settings\/chatgpt$/, name: "signOutChatGPT" },
339
351
  { method: "POST", pattern: /^\/settings\/chatgpt\/sign-in$/, name: "startChatGPTSignIn" },
@@ -392,6 +404,7 @@ export const ROUTES = [
392
404
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
393
405
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/cost$/, name: "getLearningCost" },
394
406
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/promotions$/, name: "listLearningPromotions" },
407
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/audits$/, name: "listLearningAudits" },
395
408
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "createLearningBatch" },
396
409
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "listLearningBatches" },
397
410
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches\/([^/]+)$/, name: "getLearningBatch" },
@@ -583,7 +596,7 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
583
596
  runs: { stop: true, cancel: true, kill: false, list: true, kinds: ["agentic", "workflow"], pause_workflow_runs: true, graph: true },
584
597
  messages: { steer: true, answer: true, follow_up: true, steer_workflow_runs: false },
585
598
  timeline: { long_poll: true, sse: true, live_rows: true, live_workflow_rows: false },
586
- files: { upload: true, read: true, range: false, during_run: true },
599
+ files: { upload: true, read: true, range: true, during_run: true },
587
600
  quotes: false,
588
601
  usage: { basis: "estimate", meters: ["tokens", "tools", "browser_time", "learning"] },
589
602
  efforts: [...EFFORTS],
@@ -1147,6 +1160,17 @@ async function startHolding(options, data, checked, stops) {
1147
1160
  };
1148
1161
  await heldEmailPassword();
1149
1162
  secretStores.add("email", () => [...emailPasswords]);
1163
+ // The calendar's iCal address (calendar/address.ts), in each of its forms, and each one saved since this server started:
1164
+ // the address reads the calendar, so it is cut from everything the server shows, as a password is.
1165
+ const calendarAddresses = new Set();
1166
+ const heldCalendar = async () => {
1167
+ const url = (await openCalendar(store, sealKey).catch(() => undefined))?.url;
1168
+ if (url)
1169
+ for (const form of addressForms(url))
1170
+ calendarAddresses.add(form);
1171
+ };
1172
+ await heldCalendar();
1173
+ secretStores.add("calendar", () => [...calendarAddresses]);
1150
1174
  // Each agent's saved sign-ins, over the one store (module A, sign-ins-store): the vendor's calls on the server's keys
1151
1175
  // (under faux, the vendor's fake alone), under this server's seal key. The store holds whether a sign-in is still held
1152
1176
  // (a live run's sign_in_handed) and who was handed it, so this takes no `holds`/`handedTo` callback — one store, one lock.
@@ -1331,8 +1355,9 @@ async function startHolding(options, data, checked, stops) {
1331
1355
  // Every round the run kept (a review follow-up opens a round of its own), in order: what each one learned and merged.
1332
1356
  const newest = await store.learning.proposal(runId);
1333
1357
  const ends = await Promise.all(Array.from({ length: newest?.round ?? 1 }, (_, i) => runLearningEnd(store, runId, i + 1)));
1334
- // A run still going names no path yet (its end writes it): the batch reads it as the agent's until then.
1335
- return figuresOf((await costRunOf(store, run, 0)) ?? { path: "agent", ...(await allInOf(store, run)) }, ends);
1358
+ // A run still going names no path yet (its end writes it): the batch reads it as the agent's until then. Its all-in
1359
+ // is not known while its audit's shadow run is queued or running (shadowSpendOf): the batch closes no row on it.
1360
+ return figuresOf((await costRunOf(store, run, 0)) ?? { path: "agent", ...(await allInOf(store, run)) }, ends, (await shadowSpendOf(store, runId)).open);
1336
1361
  },
1337
1362
  // A batch's reads are the learning routes' reads: the same cut, the same 403 when a sign-in can't be read here.
1338
1363
  shown: (agentId) => learningShown(agentId),
@@ -1351,9 +1376,23 @@ async function startHolding(options, data, checked, stops) {
1351
1376
  return [...serverSecrets(), ...pointers];
1352
1377
  };
1353
1378
  const learningShown = async (agentId) => secretsShown(await learningValues(agentId));
1379
+ // The agent's audit ledger on its learning folder's main (learn/audit.ts), oldest first.
1380
+ const auditsOfAgent = async (agentId) => {
1381
+ const { workspace, end } = learningFolderOf(data, agentId);
1382
+ try {
1383
+ return await readAudits(workspace);
1384
+ }
1385
+ finally {
1386
+ await end().catch(() => undefined);
1387
+ }
1388
+ };
1354
1389
  // What a run held for its owner's OK reads as it stands on its agent's learning folder's main (statusesOf).
1355
1390
  const statuses = (agentId) => statusesOf(data, agentId);
1356
1391
  const viewDepsFor = (origin) => ({ origin, serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)), statuses });
1392
+ // A run read as a whole (its own read, its archive) lists its recordings too, from its recordings folder on this machine
1393
+ // (run-recordings.ts), where the runner beside it wrote them; every other read of the view opens no file.
1394
+ const recordings = (agentId, runId, endedAt) => recordingsOf(recordingsFolder(data, agentId, runId), endedAt);
1395
+ const runReadDepsFor = (origin) => ({ ...viewDepsFor(origin), recordings });
1357
1396
  const ownOriginOf = () => options.publicUrl ?? url;
1358
1397
  // The run read routes (a run's files, its browser state, its workflow graph) over the one store (run-reads-over-store):
1359
1398
  // a run's files through the server's read-only Workspace of its folder (serverRunWorkspace, no runner claim), its view
@@ -1362,6 +1401,10 @@ async function startHolding(options, data, checked, stops) {
1362
1401
  // timeline route keeps its own stub (store-reads journal + SSE) until E2c's timeline lands.
1363
1402
  const runReadsDeps = {
1364
1403
  runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey, env: withSecrets(process.env, "own") }),
1404
+ recordings: async (_store, runId) => {
1405
+ const run = await store.runs.get(runId);
1406
+ return run ? recordingsWorkspace(recordingsFolder(data, run.agentId, runId)) : null;
1407
+ },
1365
1408
  env,
1366
1409
  runFacts: (_store, runId) => factsOverStore(store, runId, viewDepsFor(ownOriginOf())),
1367
1410
  withheld: (_store, runId) => withheldOverStore(store, runId, viewDepsFor(ownOriginOf())),
@@ -1753,7 +1796,7 @@ async function startHolding(options, data, checked, stops) {
1753
1796
  const learning = await learningOfAgent(entry);
1754
1797
  const native = nativeOf(entry.revision?.body);
1755
1798
  const nativeStatus = native?.remote ? await new RemoteConnectors(store).status(native) : undefined;
1756
- const runs = await listRunsOverStore(store, { agent: entry.agent.id }, ctx);
1799
+ const runs = (await listRunsOverStore(store, { agent: entry.agent.id }, ctx)).filter((run) => !isShadowRun(run.id));
1757
1800
  return {
1758
1801
  ...(nativeStatus ? { nativeStatus } : {}),
1759
1802
  signIns: await signIns.view(entry.agent.id),
@@ -1871,7 +1914,14 @@ async function startHolding(options, data, checked, stops) {
1871
1914
  if (!named || !mcpMeta.has(named.server))
1872
1915
  return [];
1873
1916
  const pinned = Object.hasOwn(pin, named.server) && pin[named.server].tools.some((one) => one.name === named.tool);
1874
- return pinned ? [] : [{ field: `definition.tools[${index}]`, reason: "not_an_option", message: `The MCP tool ${tool} was not pinned when this revision was saved: save the agent again to pin it.`, tool }];
1917
+ if (pinned)
1918
+ return [];
1919
+ // Its first run could not pin it (mcp-pin-first.ts) because this server refuses its server's address: a loopback
1920
+ // one on a server whose operator never said it is a local install. Saving again is refused the same way, so the
1921
+ // words say the cause, as the save's refusal does (mcp-servers-store.ts reached).
1922
+ const at = URL.parse(mcpMeta.get(named.server).url)?.hostname ?? "";
1923
+ const why = options.mcpLoopback !== true && LOOPBACK.test(at) ? `its server ${named.server} can't be listed here to pin it: ${loopbackWords(at)}` : "save the agent again to pin it.";
1924
+ return [{ field: `definition.tools[${index}]`, reason: "not_an_option", message: `The MCP tool ${tool} was not pinned when this revision was saved: ${why}`, tool }];
1875
1925
  });
1876
1926
  if (unpinned.length)
1877
1927
  throw new ApiError("agent_not_runnable", unpinned.map((one) => one.message).join(" "), { fields: unpinned.map(({ tool: _tool, ...issue }) => issue), details: { unbound: unpinned.map((one) => one.tool), missing: {} } });
@@ -2526,7 +2576,8 @@ async function startHolding(options, data, checked, stops) {
2526
2576
  // `label=<key>:<value>`, once: only the runs holding it (run-labels.ts), filtered in the store.
2527
2577
  const labels = labelFilter(url.searchParams.getAll("label"));
2528
2578
  const vd = viewDepsFor(origin);
2529
- let rows = (await listRunsOverStore(store, { ...filter, ...(labels ? { labels } : {}) }, ctx)).filter((row) => Boolean(row.archivedAt) === archived);
2579
+ // An audit's shadow run is no row of the list (learn/audit.ts): it is read by id, and its cost is its served run's.
2580
+ let rows = (await listRunsOverStore(store, { ...filter, ...(labels ? { labels } : {}) }, ctx)).filter((row) => Boolean(row.archivedAt) === archived && !isShadowRun(row.id));
2530
2581
  if (status !== null) {
2531
2582
  // The v2 status is the run view's (store-view over the journal), per row.
2532
2583
  const statuses = await Promise.all(rows.map((row) => viewOverStore(store, row.id, vd).then((v) => v?.status)));
@@ -3385,7 +3436,7 @@ async function startHolding(options, data, checked, stops) {
3385
3436
  return send(res, 200, await runsPage(url, { ...(agent ? { agent } : {}), ...(revision ? { revision } : {}) }, linkOrigin(req)));
3386
3437
  }
3387
3438
  case "getRun": {
3388
- const view = await viewOverStore(store, id, viewDepsFor(linkOrigin(req)));
3439
+ const view = await viewOverStore(store, id, runReadDepsFor(linkOrigin(req)));
3389
3440
  if (!view)
3390
3441
  throw new ApiError("not_found", `no run ${id}`);
3391
3442
  return send(res, 200, { ...view, ...(await runComputerOf(id, view)) });
@@ -3488,14 +3539,20 @@ async function startHolding(options, data, checked, stops) {
3488
3539
  const m = (isObject(row.metrics) ? row.metrics : {});
3489
3540
  if (m.path === "replay")
3490
3541
  throw invalid([{ field: "run_id", reason: "not_allowed", message: "A replay run is never graded: its answer is scored against the run it replays." }]);
3542
+ if (m.path === "audit" || isShadowRun(row.id))
3543
+ throw invalid([{ field: "run_id", reason: "not_allowed", message: "An audit's shadow run is never graded: grade the run it audits." }]);
3491
3544
  const path = RUN_PATHS.includes(m.path) ? m.path : "agent";
3492
3545
  const grade = {
3493
3546
  run: row.id, correct: body.correct, ...(body.expected !== undefined ? { expected: body.expected } : {}), source: body.source ?? "feedback", at: new Date().toISOString(), path,
3494
3547
  ...(typeof m.workflow === "string" ? { workflow: m.workflow } : {}), ...(typeof m.workflow_digest === "string" ? { digest: m.workflow_digest } : {}),
3495
3548
  ...(typeof m.workflow_promotion === "number" ? { promotion: m.workflow_promotion } : {}),
3496
3549
  };
3497
- // Kept with what it asks of the run's learning (runner/feedback-round.ts): nothing, a revision ask, or a look-back.
3550
+ // Kept with what it asks of the run's learning (runner/feedback-round.ts): nothing, or a look-back.
3498
3551
  const kept = gradeView(await keepGrade(store, row.agentId, grade, typeof body.label === "string" ? body.label : undefined));
3552
+ // A grade of a run its learned workflow answered alone is an audit row too (runner/audit.ts gradeRow): the hold rule
3553
+ // reads it with the shadows'. A row not written now is logged, never the grade refused.
3554
+ const said = (line) => log?.(logLine("audit", { run: row.id, said: line }));
3555
+ await gradeRow({ store, agentId: row.agentId, revisionId: row.revisionId, context: ctx, folder: () => learningFolderOf(data, row.agentId), shown: () => learningShown(row.agentId), log: said }, row, body.correct).catch((error) => said(`the grade wrote no audit row (${error?.message ?? error})`));
3499
3556
  // Its workflow's name cut as GET /runs/{id}/learning cuts it (learningShown); withheld whole when that cut can't be
3500
3557
  // read (the grade is kept by then: never a shorter cut, never a refusal of a grade it kept).
3501
3558
  const shown = await learningShown(row.agentId).catch(() => undefined);
@@ -3505,7 +3562,7 @@ async function startHolding(options, data, checked, stops) {
3505
3562
  case "unarchiveRun": {
3506
3563
  const run = await needRun(id);
3507
3564
  await archiveRun(store, run.id, found.name === "archiveRun");
3508
- return send(res, 200, await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))));
3565
+ return send(res, 200, await viewOverStore(store, run.id, runReadDepsFor(linkOrigin(req))));
3509
3566
  }
3510
3567
  case "getRunBrowser":
3511
3568
  case "getRunComputer": {
@@ -3801,6 +3858,24 @@ async function startHolding(options, data, checked, stops) {
3801
3858
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
3802
3859
  return send(res, 200, answer, { "cache-control": "no-store" });
3803
3860
  }
3861
+ // Never through `idempotent` either: its record keeps the body, and the body holds the calendar's address. A read
3862
+ // reaches loopback only on a local install (its fakes), and a private host only where the owner allows it.
3863
+ case "getCalendar":
3864
+ case "saveCalendar":
3865
+ case "deleteCalendar":
3866
+ case "testCalendar": {
3867
+ const body = found.name === "saveCalendar" || found.name === "testCalendar" ? await bodyOf(req) : undefined;
3868
+ if (found.name === "saveCalendar" && stopping.signal.aborted)
3869
+ throw new ApiError("unavailable", "The server is shutting down: the calendar was not saved.");
3870
+ // The MCP servers' network and reach (mcp-oauth.ts calendarAt is mcpServerAt's rule), and their stop with the server's.
3871
+ const outbound = await mcpServers.outboundReach();
3872
+ const answer = await calendarRoute({ store, sealKey, reach: async () => outbound.reach, network: outbound.network, signal: AbortSignal.any([outbound.signal, stopping.signal]) }, found.name, body);
3873
+ if (found.name === "saveCalendar")
3874
+ await heldCalendar();
3875
+ if (answer === undefined)
3876
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
3877
+ return send(res, 200, answer, { "cache-control": "no-store" });
3878
+ }
3804
3879
  // The ChatGPT sign-in (chatgpt-plan.ts): a step it refuses is 400 in its words; its token is in no answer.
3805
3880
  case "getChatGPTSignIn":
3806
3881
  await planNow();
@@ -3984,11 +4059,34 @@ async function startHolding(options, data, checked, stops) {
3984
4059
  return send(res, 200, { agent: id, ...cost });
3985
4060
  }
3986
4061
  case "listLearningPromotions": {
4062
+ const entry = await needAgent(id);
4063
+ // Each learned workflow's promotion records, oldest first (learn/promote.ts): its check's numbers and decisions,
4064
+ // its holds (a check's, an audit's). Every text in them cut as the other learning reads cut theirs
4065
+ // (promotionsShown: a reason as well as each workflow's name). Beside what serves, each one's state, its check's
4066
+ // numbers and its audit line (learn/audit.ts servingLinesOf), at the agent's numbers.
4067
+ const records = await promotionsOf(store.settings, id);
4068
+ const shown = await learningShown(id);
4069
+ const shownRead = promotionsShown(records, shown);
4070
+ // A ledger that can't be read now leaves each audit line at no rows, never the read refused.
4071
+ const loop = auditLoopOf(entry.revision?.body?.learning);
4072
+ const lines = servingLinesOf(records, await auditsOfAgent(id).catch(() => []), loop);
4073
+ // Why its runs are never audited, when the agent can call a tool that writes (learn/audit.ts auditWriterOf, the
4074
+ // rule startAudit reads); and how many of the serving revision's runs a trigger started (never audited).
4075
+ const writer = auditWriterOf(entry.revision ?? undefined);
4076
+ const auditsOff = writer === undefined ? null : shown.text(auditsOffWords(writer));
4077
+ const serving = await Promise.all(servingOf(records).map(async (one, i) => ({
4078
+ ...shownRead.serving[i], ...lines[i], audits_off: auditsOff,
4079
+ not_auditable: one.digest === null ? 0 : await notAuditableOf(store, id, one.workflow, one.digest, loop).catch(() => 0),
4080
+ })));
4081
+ return send(res, 200, { agent: id, promotions: shownRead.promotions, serving });
4082
+ }
4083
+ case "listLearningAudits": {
3987
4084
  await needAgent(id);
3988
- // Each learned workflow's promotion records, oldest first (learn/promote.ts): its replays' numbers and decisions,
3989
- // its refits, its holds. Aggregates only; every text in them cut as the other learning reads cut theirs
3990
- // (promotionsShown: a reason and a refit guard's label as well as each workflow's name).
3991
- return send(res, 200, { agent: id, ...promotionsShown(await promotionsOf(store.settings, id), await learningShown(id)) });
4085
+ // The audit ledger (learn/audit.ts audits.jsonl), oldest first: each workflow's name and every other text cut as the
4086
+ // promotions read cuts its own.
4087
+ const shown = await learningShown(id);
4088
+ const rows = await auditsOfAgent(id);
4089
+ return send(res, 200, { agent: id, audits: rows.map((row) => ({ ...row, workflow: shown.name(row.workflow), run: shown.text(row.run), shadow_run: row.shadow_run === null ? null : shown.text(row.shadow_run), digest: shown.text(row.digest) })) });
3992
4090
  }
3993
4091
  case "createLearningBatch": {
3994
4092
  await needAgent(id);
@@ -4022,7 +4120,7 @@ async function startHolding(options, data, checked, stops) {
4022
4120
  }
4023
4121
  case "getLearningLoop": {
4024
4122
  await needAgent(id);
4025
- // The loop's own record over the one store (store-reads/loop.ts): compile turns and guarded steps, aggregates only.
4123
+ // The loop's own record over the one store (store-reads/loop.ts): compile turns, aggregates only.
4026
4124
  // Names cut as the other learning reads cut them; a compile's error texts cut by its run's own cut as its run's
4027
4125
  // learning read cuts them (run-learning-served.ts), and left out when that run's handed values can't be read.
4028
4126
  const shown = await learningShown(id);
@@ -4037,8 +4135,7 @@ async function startHolding(options, data, checked, stops) {
4037
4135
  const said = (error) => shown.text(printable({ rule: "workflow", detail: error }, all).detail);
4038
4136
  return { ...one, workflow, from_notes: one.from_notes.map(shown.name), attempts: one.attempts.map(({ ok, errors }) => ({ ok, errors: errors.map(said) })), draft_errors: one.draft_errors.map(said), withheld: false };
4039
4137
  }));
4040
- const guards = read.guards.map((one) => ({ ...one, workflow: shown.name(one.workflow), node: shown.text(one.node) }));
4041
- return send(res, 200, { agent: id, compiles, guards });
4138
+ return send(res, 200, { agent: id, completed_runs: read.completed_runs, compiles });
4042
4139
  }
4043
4140
  case "listLearningNotes":
4044
4141
  case "listLearningLog":
@@ -4088,8 +4185,8 @@ async function startHolding(options, data, checked, stops) {
4088
4185
  if (extra.length)
4089
4186
  throw invalid(extra);
4090
4187
  const inputs = body.inputs === undefined ? "held" : body.inputs;
4091
- if (inputs !== "held" && !(typeof inputs === "number" && Number.isInteger(inputs) && inputs >= 1 && inputs <= GRADES_KEPT)) {
4092
- throw new ApiError("bad_request", `inputs is "held" (the graded inputs the revision was last decided on, the default) or a whole number from 1 to ${GRADES_KEPT}: that many of the agent's newest graded inputs.`);
4188
+ if (inputs !== "held" && !(typeof inputs === "number" && Number.isInteger(inputs) && inputs >= 1 && inputs <= COMPILE_AFTER_MAX)) {
4189
+ throw new ApiError("bad_request", `inputs is "held" (the runs the revision was last checked on, the default) or a whole number from 1 to ${COMPILE_AFTER_MAX}: that many of the agent's newest completed runs.`);
4093
4190
  }
4094
4191
  const [, , name, digest] = found.pattern.exec(path).map((part) => decodeURIComponent(part));
4095
4192
  const started = await replayAsked(() => askReplay(replayAskOf(entry), name, digest, inputs));
@@ -4435,6 +4532,14 @@ async function startHolding(options, data, checked, stops) {
4435
4532
  // listens: a hosted container listens on loopback behind its proxy too.
4436
4533
  const localInstall = options.mcpLoopback === true;
4437
4534
  mcpServers.attach(options.publicUrl ?? url, url, localInstall);
4535
+ // Its own addresses, kept in the store for a runner in its own process whose own opt-in lets it reach loopback: its runs
4536
+ // never reach this server's ports there either (mcp-private-hosts.ts saveServerOwn). It listens already: a write that
4537
+ // fails stops the start and lets go of the port, as the start's other stops let go of the store and the locks.
4538
+ await saveServerOwn(store, mcpServers.own).catch(async (error) => {
4539
+ server.closeAllConnections();
4540
+ await new Promise((done) => server.close(() => done()));
4541
+ throw error;
4542
+ });
4438
4543
  // A run's end and its wait are the outbound webhook's run.ended and run.needs_input (webhooks.ts). The runners write them
4439
4544
  // to the store and this server runs no run, so it follows the store's run-change feed (Store.runs.changedSince): every
4440
4545
  // run reaching a final state, or let go by its runner (parked, or running with none), once, in order, under a cursor
@@ -4479,7 +4584,8 @@ async function startHolding(options, data, checked, stops) {
4479
4584
  * is not done (a read that failed, or its notice not saved): it is read again. */
4480
4585
  const tellWait = async (row) => {
4481
4586
  const seen = `${row.state}\n${row.epoch}\n${row.runner ?? ""}\n${row.summary ?? ""}`;
4482
- if (readWaits.get(row.id) === seen)
4587
+ // An audit's shadow run waits on no one (runner/audit.ts AUDIT_PARKED): the park it ends at once is no one's to answer.
4588
+ if (readWaits.get(row.id) === seen || isShadowRun(row.id))
4483
4589
  return true;
4484
4590
  const view = await viewOverStore(store, row.id, viewDepsFor(ownOriginOf()));
4485
4591
  if (view?.status !== "input_required")
@@ -1,4 +1,5 @@
1
1
  import type { NativeBinding } from "../native/types.js";
2
+ import { type LearningSetting } from "../learning-setting.js";
2
3
  /** A revision's body the store refuses: its content is not one the store keeps. The server maps it to an input refusal. */
3
4
  export declare class AgentBodyInvalid extends Error {
4
5
  constructor(message: string);
@@ -30,7 +31,7 @@ export type RevisionPlace = {
30
31
  /** A revision's computer (computer-setting.ts): its kind and the provider that serves it, ids its host knows, and a
31
32
  * sandbox's GPUs, a type its provider names and how many; `place` is its v2 view. `image`: one the provider offers for
32
33
  * the kind, absent for its default. A desktop's or a phone's surface and exec: how the agent drives it, and whether it
33
- * may run programs on it. */
34
+ * may run programs on it, and whether each run records a video of its screen. */
34
35
  export type RevisionComputer = {
35
36
  kind: string;
36
37
  provider?: string;
@@ -42,6 +43,7 @@ export type RevisionComputer = {
42
43
  persistent?: boolean;
43
44
  surface?: "code" | "tools";
44
45
  exec?: boolean;
46
+ record?: boolean;
45
47
  };
46
48
  /** A revision's tool settings as its body keeps them: a map of a tool's key to its settings ({provider?, permission?,
47
49
  * pin?}), checked and made canonical by the caller (agents-store.ts, through tool-plane's settingsIssues +
@@ -73,7 +75,7 @@ export type AgenticBody = {
73
75
  harness?: string;
74
76
  place?: RevisionPlace;
75
77
  computer?: RevisionComputer;
76
- learning?: boolean | "notes";
78
+ learning?: LearningSetting;
77
79
  toolSettings?: ToolSettings;
78
80
  maxCostUsd?: number;
79
81
  approvals?: "ask" | "never";
@@ -108,7 +110,7 @@ export type RevisionBodyInput = {
108
110
  harness?: string;
109
111
  place?: unknown;
110
112
  computer?: unknown;
111
- learning?: boolean | "notes";
113
+ learning?: LearningSetting;
112
114
  toolSettings?: ToolSettings;
113
115
  maxCostUsd?: number;
114
116
  approvals?: "ask" | "never";
@@ -7,6 +7,7 @@
7
7
  // two equal pins are one revision.
8
8
  import { createHash } from "node:crypto";
9
9
  import { nativeBindingOf } from "../native/binding.js";
10
+ import { learningSettingIssue, learningSettingOf } from "../learning-setting.js";
10
11
  /** A revision's body the store refuses: its content is not one the store keeps. The server maps it to an input refusal. */
11
12
  export class AgentBodyInvalid extends Error {
12
13
  constructor(message) {
@@ -46,24 +47,24 @@ function placeOf(place) {
46
47
  /** A GPU type as a body keeps it: the vendor's own name ("T4", "A100-80GB", "RTX-PRO-6000"). */
47
48
  const GPU_TYPE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
48
49
  /** The keys a body's computer keeps. */
49
- const COMPUTER_KEYS = new Set(["kind", "provider", "image", "gpu", "persistent", "surface", "exec"]);
50
- /** A computer as a body keeps it: `{kind, provider?, image?, gpu?, persistent?, surface?, exec?}`, nothing else: kind
51
- * and provider ids, image a name with no spaces around it, gpu `{type, count}`, a GPU type name and a whole count from
52
- * 1, persistent and exec booleans, and surface code or tools. */
50
+ const COMPUTER_KEYS = new Set(["kind", "provider", "image", "gpu", "persistent", "surface", "exec", "record"]);
51
+ /** A computer as a body keeps it: `{kind, provider?, image?, gpu?, persistent?, surface?, exec?, record?}`, nothing
52
+ * else: kind and provider ids, image a name with no spaces around it, gpu `{type, count}`, a GPU type name and a whole
53
+ * count from 1, persistent, exec and record booleans, and surface code or tools. */
53
54
  function computerOf(computer) {
54
55
  const image = isObject(computer) ? computer.image : undefined;
55
56
  const named = (value) => typeof value === "string" && value !== "" && value === value.trim();
56
57
  const flag = (value) => value === undefined || typeof value === "boolean";
57
58
  const surface = isObject(computer) ? computer.surface : undefined;
58
- if (!isObject(computer) || !hostId(computer.kind) || (computer.provider !== undefined && !hostId(computer.provider)) || (image !== undefined && !named(image)) || !flag(computer.persistent) || !flag(computer.exec) || (surface !== undefined && surface !== "code" && surface !== "tools") || Object.keys(computer).some((key) => !COMPUTER_KEYS.has(key)))
59
- invalid("the computer is not {kind, provider?, image?, gpu?, persistent?, surface?, exec?}, kind and provider each an id (lowercase letters, digits and dashes), image a name, persistent a boolean, surface code or tools, exec a boolean");
59
+ if (!isObject(computer) || !hostId(computer.kind) || (computer.provider !== undefined && !hostId(computer.provider)) || (image !== undefined && !named(image)) || !flag(computer.persistent) || !flag(computer.exec) || !flag(computer.record) || (surface !== undefined && surface !== "code" && surface !== "tools") || Object.keys(computer).some((key) => !COMPUTER_KEYS.has(key)))
60
+ invalid("the computer is not {kind, provider?, image?, gpu?, persistent?, surface?, exec?, record?}, kind and provider each an id (lowercase letters, digits and dashes), image a name, persistent a boolean, surface code or tools, exec a boolean, record a boolean");
60
61
  const ok = computer;
61
62
  const gpu = ok.gpu;
62
63
  if (gpu !== undefined && (!isObject(gpu) || Object.keys(gpu).some((key) => key !== "type" && key !== "count") || typeof gpu.type !== "string" || !GPU_TYPE.test(gpu.type) || !Number.isSafeInteger(gpu.count) || gpu.count < 1)) {
63
64
  invalid("the computer's gpu is not {type, count}: a GPU type name (letters, digits, dots, underscores and dashes) and a whole count from 1");
64
65
  }
65
66
  const kept = gpu;
66
- return { kind: ok.kind, ...(ok.provider !== undefined ? { provider: ok.provider } : {}), ...(ok.image !== undefined ? { image: ok.image } : {}), ...(kept !== undefined ? { gpu: { type: kept.type, count: kept.count } } : {}), ...(ok.persistent !== undefined ? { persistent: ok.persistent } : {}), ...(ok.surface !== undefined ? { surface: ok.surface } : {}), ...(ok.exec !== undefined ? { exec: ok.exec } : {}) };
67
+ return { kind: ok.kind, ...(ok.provider !== undefined ? { provider: ok.provider } : {}), ...(ok.image !== undefined ? { image: ok.image } : {}), ...(kept !== undefined ? { gpu: { type: kept.type, count: kept.count } } : {}), ...(ok.persistent !== undefined ? { persistent: ok.persistent } : {}), ...(ok.surface !== undefined ? { surface: ok.surface } : {}), ...(ok.exec !== undefined ? { exec: ok.exec } : {}), ...(ok.record !== undefined ? { record: ok.record } : {}) };
67
68
  }
68
69
  /** The body of a new revision and the text of each skill it names (path to text), everything checked here, before any
69
70
  * write. The body keeps each skill path to its text's SHA-256; `skills` is the texts, for the revision's row. */
@@ -113,8 +114,11 @@ export function bodyOf(input) {
113
114
  for (const field of ["model", "thinking"])
114
115
  if (input[field] !== undefined && (typeof input[field] !== "string" || input[field] === ""))
115
116
  invalid(`the ${field} is not a non-empty string`);
116
- if (input.learning !== undefined && typeof input.learning !== "boolean" && input.learning !== "notes")
117
- invalid("learning is not true, false or \"notes\"");
117
+ if (input.learning !== undefined) {
118
+ const wrong = learningSettingIssue(input.learning);
119
+ if (wrong)
120
+ invalid(wrong);
121
+ }
118
122
  if (input.inputSchema !== undefined && !isObject(input.inputSchema))
119
123
  invalid("the inputSchema is not a JSON object");
120
124
  if (input.outputSchema !== undefined && !isObject(input.outputSchema))
@@ -138,7 +142,7 @@ export function bodyOf(input) {
138
142
  ...(input.thinking !== undefined ? { thinking: input.thinking } : {}),
139
143
  ...(input.prompts !== undefined ? { prompts: structuredClone(input.prompts) } : {}),
140
144
  ...host,
141
- ...(input.learning !== undefined ? { learning: input.learning } : {}),
145
+ ...(input.learning !== undefined ? { learning: learningSettingOf(input.learning) } : {}),
142
146
  // The JSON Schema each run's input meets (definition.input_schema), checked at every start (validate.ts inputSchemaOf).
143
147
  ...(input.inputSchema !== undefined ? { inputSchema: structuredClone(input.inputSchema) } : {}),
144
148
  // The JSON Schema its final answer's structured part meets (definition.output_schema): a completed run's result.output.
@@ -1167,6 +1167,7 @@ class SqliteStore {
1167
1167
  return row ? proposalOf(row) : undefined;
1168
1168
  },
1169
1169
  proposals: async (agentId, { limit = 100 } = {}) => (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? ORDER BY created_at DESC, run_id DESC, round DESC LIMIT ?`, agentId, limit)).map(proposalOf),
1170
+ grading: async (agentId) => (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? AND learning_run_id IN (SELECT id FROM runs WHERE state NOT IN (${FINAL})) ORDER BY created_at DESC, run_id DESC, round DESC`, agentId)).map(proposalOf),
1170
1171
  kept: async (agentId) => {
1171
1172
  const proposals = (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? ORDER BY run_id, round`, agentId)).map(proposalOf);
1172
1173
  const learningRuns = (await db.all(`SELECT ${RUN_COLUMNS} FROM runs WHERE id IN (SELECT learning_run_id FROM learning_proposals WHERE agent_id = ? AND learning_run_id IS NOT NULL)`, agentId)).map(runOf);
@@ -297,6 +297,9 @@ export interface Learning {
297
297
  proposals(agentId: string, options?: {
298
298
  limit?: number;
299
299
  }): Promise<LearningProposal[]>;
300
+ /** The agent's kept proposals whose learning run (its grade) has not ended: queued, running or parked. Every one of
301
+ * them, however many proposals were kept since, newest first. */
302
+ grading(agentId: string): Promise<LearningProposal[]>;
300
303
  /** Everything agent `agentId`'s runs' learning kept, in two reads whatever the number of its runs: every round of every
301
304
  * run's kept proposal (oldest round first within a run), and the rows of the learning runs they name (as runs.get
302
305
  * reads one; a learning run named and never written has none). An agent-wide read's, never a read a run. */
@@ -39,7 +39,8 @@ export type RunRecords = {
39
39
  /** Agent `agentId`'s runs' records read at once, whatever their number: its runs' launches (Store.runs.launches) and every
40
40
  * round its runs' learning kept with the learning runs they name (Store.learning.kept), two reads beside `listed` (its
41
41
  * runs, as runs.list read them). Each answers as the store's per-run read does: a run of `listed` with no launch row is
42
- * StoreLaunchMissing, one that kept no learning has no round. A run not of `listed` is read from the store. */
42
+ * StoreLaunchMissing, one that kept no learning has no round. A run not of `listed` is read from the store, but for an
43
+ * audit's shadow run: `listed` is every run of the agent, its shadows among them. */
43
44
  export declare function agentRecordsOf(store: Store, agentId: string, listed: readonly RunRecord[]): Promise<RunRecords>;
44
45
  /** Run `runId`'s learning end (its newest round's, or round `round`'s); null when the run kept no learning. Proposed while its learning run has not ended. `records`: where its rows are read (the store's per-run reads by default). */
45
46
  export declare function runLearningEnd(store: Store, runId: string, round?: number, records?: RunRecords): Promise<RunLearningEnd | null>;
@@ -104,10 +105,11 @@ export declare function agentCostOverStore(store: Store, agentId: string, limit?
104
105
  unknown_path_runs: number;
105
106
  workflows: ReturnType<typeof workflowCostsOf>;
106
107
  }>;
107
- /** The replay the serving promotion was decided on, as the cost summary says it: the champion (championOf) of the learned
108
- * workflow the newest run a learned workflow ran first on ran (`workflow` or `handed_back`), its record's `replay` numbers
109
- * and whether they cleared the bar (withinBar, promotion's own). Null when no run was served, nothing serves now (held,
110
- * or never promoted), or it was promoted with no replay (a dry run). */
108
+ /** The check the serving promotion was decided on, as the cost summary says it: the champion (championOf) of the learned
109
+ * workflow the newest run a learned workflow ran first on ran (`workflow` or `handed_back`), its record's check numbers
110
+ * (the share of the inputs it ran on that said what the agent said, against the agent's own 100%). `cleared`: it passed
111
+ * (a champion is promoted), with the agreement check it passed (`agreed` of `alone`, its bar `agree_min`). Null when no run was served, nothing serves now (held, or never promoted), or it was promoted
112
+ * on no input (a dry run). */
111
113
  export declare function servingReplayOf(records: readonly PromotionRecord[], runs: readonly CostRun[]): CostReplay | null;
112
114
  /** What run `runId`'s learning spent, as its cost per run counts it, over every round a follow-up opened (roundsOf): what
113
115
  * it kept as it answered (`looked`: answeredOf), and its grades' spend (`grade`): each round's learning run's cost once
@@ -130,6 +132,15 @@ type RunRecord = NonNullable<Awaited<ReturnType<Store["runs"]["get"]>>>;
130
132
  * never the newest round's alone), else its one round's (learningSpendOf). `total_usd` is the run's all-in cost, the one
131
133
  * the cost page shows and the money rule reads (pastRunsOverStore); null when any part is unknown. */
132
134
  export declare function allInOf(store: RunRecords, run: RunRecord): Promise<ReturnType<typeof runCostOf>>;
135
+ /** What run `runId`'s audit shadow run (runner/audit.ts) adds to its all-in cost: `open` while it is queued or running
136
+ * (its cost not known yet: `usd` null, never $0), else its cost once it ended, stopped or failed (null: unknown); 0 when
137
+ * none was started, and for a shadow itself. */
138
+ export declare function shadowSpendOf(store: {
139
+ readonly runs: Pick<RunRecords["runs"], "get">;
140
+ }, runId: string): Promise<{
141
+ open: boolean;
142
+ usd: number | null;
143
+ }>;
133
144
  /** One run of the cost series, as number `n` of it: its figures (allInOf) and its path (agentCostOverStore's loop body,
134
145
  * and a learning batch's row once the run's learning has settled). */
135
146
  export declare function costRunOf(store: RunRecords, run: RunRecord, n: number): Promise<CostRun>;
@@ -309,9 +320,9 @@ export declare function runLearningOverStore(store: Store, runId: string, shown:
309
320
  feedback_status: "running" | "ended" | "not_run" | null;
310
321
  source: "feedback" | "eval";
311
322
  graded_at: string;
312
- path: "agent" | "workflow" | "handed_back" | "replay";
323
+ path: "agent" | "workflow" | "handed_back" | "replay" | "audit";
313
324
  workflow_digest: string | null;
314
- feedback: "revise" | "look_back" | null;
325
+ feedback: "look_back" | null;
315
326
  run_id: string;
316
327
  correct: boolean;
317
328
  };