@parcha/agentrun-serve 0.1.0-beta.51 → 0.1.0-beta.52

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 (135) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +94 -13
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +13 -2
  5. package/dist/agent-delete.js +14 -5
  6. package/dist/agents-store.d.ts +5 -1
  7. package/dist/agents-store.js +10 -4
  8. package/dist/api-only.d.ts +4 -2
  9. package/dist/api-only.js +5 -3
  10. package/dist/archil-routes.d.ts +1 -0
  11. package/dist/archil-routes.js +28 -2
  12. package/dist/computer-setting.d.ts +8 -0
  13. package/dist/computer-setting.js +11 -0
  14. package/dist/computers.d.ts +6 -2
  15. package/dist/computers.js +2 -2
  16. package/dist/console/assets/index-B-D0EM3j.js +733 -0
  17. package/dist/console/assets/index-DlQepP2J.css +1 -0
  18. package/dist/console/index.html +2 -2
  19. package/dist/fal-price.d.ts +76 -0
  20. package/dist/fal-price.js +368 -0
  21. package/dist/learn/commit.d.ts +5 -0
  22. package/dist/learn/commit.js +4 -1
  23. package/dist/learn/compile.d.ts +13 -5
  24. package/dist/learn/compile.js +24 -7
  25. package/dist/learn/delete.d.ts +12 -6
  26. package/dist/learn/delete.js +17 -11
  27. package/dist/learn/folder.d.ts +11 -0
  28. package/dist/learn/folder.js +20 -3
  29. package/dist/learn/learning-of.d.ts +8 -0
  30. package/dist/learn/learning-of.js +8 -0
  31. package/dist/learn/learning.sh +14 -1
  32. package/dist/learn/promote.d.ts +51 -7
  33. package/dist/learn/promote.js +51 -8
  34. package/dist/learning-reset.d.ts +18 -0
  35. package/dist/learning-reset.js +115 -0
  36. package/dist/learning-routes.d.ts +1 -1
  37. package/dist/learning-words.d.ts +5 -0
  38. package/dist/learning-words.js +5 -0
  39. package/dist/learning.d.ts +8 -6
  40. package/dist/learning.js +5 -4
  41. package/dist/llms.txt +1 -0
  42. package/dist/mcp-gateway.d.ts +39 -2
  43. package/dist/mcp-gateway.js +41 -10
  44. package/dist/mcp-pin-first.js +1 -1
  45. package/dist/mcp-servers-store.d.ts +1 -0
  46. package/dist/mcp-servers-store.js +2 -1
  47. package/dist/media-duration.d.ts +2 -0
  48. package/dist/media-duration.js +136 -0
  49. package/dist/openapi.js +45 -12
  50. package/dist/provider.d.ts +8 -0
  51. package/dist/provider.js +14 -2
  52. package/dist/refusal-words.d.ts +0 -3
  53. package/dist/refusal-words.js +0 -3
  54. package/dist/request-metadata.d.ts +20 -0
  55. package/dist/request-metadata.js +24 -0
  56. package/dist/run-launch.d.ts +13 -4
  57. package/dist/run-launch.js +14 -3
  58. package/dist/run-learning-served.d.ts +2 -2
  59. package/dist/run-usage.d.ts +48 -4
  60. package/dist/run-usage.js +156 -39
  61. package/dist/run-view.d.ts +1 -1
  62. package/dist/run-view.js +3 -7
  63. package/dist/runner/adapter-loop.d.ts +3 -1
  64. package/dist/runner/adapter-loop.js +12 -9
  65. package/dist/runner/adapter-run-spec.d.ts +1 -1
  66. package/dist/runner/adapter-run-spec.js +13 -13
  67. package/dist/runner/audit.d.ts +8 -3
  68. package/dist/runner/audit.js +21 -6
  69. package/dist/runner/claim-secrets.d.ts +2 -1
  70. package/dist/runner/claim-secrets.js +5 -3
  71. package/dist/runner/cli-run-spec.d.ts +1 -1
  72. package/dist/runner/cli-run-spec.js +12 -11
  73. package/dist/runner/conformance/harness.js +4 -2
  74. package/dist/runner/dispatch.js +4 -2
  75. package/dist/runner/harness-loops.js +5 -2
  76. package/dist/runner/journal-kinds.d.ts +3 -0
  77. package/dist/runner/learning-end.d.ts +2 -1
  78. package/dist/runner/learning-end.js +47 -22
  79. package/dist/runner/mcp-claim.js +1 -1
  80. package/dist/runner/mcp-run.d.ts +9 -0
  81. package/dist/runner/mcp-run.js +16 -1
  82. package/dist/runner/model-route.js +7 -4
  83. package/dist/runner/promotion.d.ts +40 -21
  84. package/dist/runner/promotion.js +130 -59
  85. package/dist/runner/run-child-host.js +6 -4
  86. package/dist/runner/runner.js +15 -3
  87. package/dist/runner/sdk-loop.d.ts +2 -2
  88. package/dist/runner/sdk-loop.js +3 -3
  89. package/dist/runner/store-port.d.ts +3 -0
  90. package/dist/runner/workflow-spec.js +3 -3
  91. package/dist/runs-over-store.d.ts +5 -2
  92. package/dist/runs-over-store.js +14 -7
  93. package/dist/sdk/check.d.ts +6 -5
  94. package/dist/sdk/check.js +17 -16
  95. package/dist/sdk/runs.js +81 -65
  96. package/dist/server.js +84 -20
  97. package/dist/store/agent-body.d.ts +4 -0
  98. package/dist/store/agent-body.js +4 -1
  99. package/dist/store/index.d.ts +1 -1
  100. package/dist/store/journal/storage.d.ts +2 -0
  101. package/dist/store/journal/storage.js +2 -1
  102. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  103. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  104. package/dist/store/schema.d.ts +14 -1
  105. package/dist/store/schema.js +42 -4
  106. package/dist/store/sqlite/run-launch.d.ts +22 -0
  107. package/dist/store/sqlite/run-launch.js +72 -7
  108. package/dist/store/sqlite/run-patch.d.ts +2 -1
  109. package/dist/store/sqlite/run-patch.js +4 -3
  110. package/dist/store/sqlite/store.js +141 -29
  111. package/dist/store/store-schema.js +2 -2
  112. package/dist/store/store.d.ts +67 -4
  113. package/dist/store-reads/learning.d.ts +12 -8
  114. package/dist/store-reads/learning.js +33 -24
  115. package/dist/store-reads/loop.d.ts +4 -3
  116. package/dist/store-reads/loop.js +7 -5
  117. package/dist/template-eval.js +4 -4
  118. package/dist/templates.d.ts +3 -0
  119. package/dist/templates.js +7 -5
  120. package/dist/timeline/labels.js +1 -1
  121. package/dist/tools.js +1 -1
  122. package/dist/uploads-archil.js +2 -1
  123. package/dist/uploads.d.ts +0 -3
  124. package/dist/uploads.js +2 -11
  125. package/dist/validate.js +5 -1
  126. package/dist/web-save.d.ts +3 -0
  127. package/dist/web-save.js +17 -2
  128. package/dist/workspace/archil-exec.js +1 -1
  129. package/dist/workspace/archil.js +1 -1
  130. package/dist/workspace/revision-skills.js +24 -11
  131. package/dist/workspace/synced-folder.d.ts +3 -3
  132. package/dist/workspace/synced-folder.js +7 -6
  133. package/package.json +10 -10
  134. package/dist/console/assets/index-Bt1B51b7.js +0 -733
  135. package/dist/console/assets/index-sVftE9Ht.css +0 -1
@@ -14,7 +14,7 @@ import { dirname, join } from "node:path";
14
14
  import { stopRunWith } from "../paid-calls.js";
15
15
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
16
16
  import { defineExtension, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
17
- import { checkRaise, followUpOf, freeModelRequestsOf, parkOf, planCapModel } from "@parcha/agentrun-kernel/kernel/cap";
17
+ import { checkRaise, followUpOf, freeRequestLimitOf, parkOf, planCapModel } from "@parcha/agentrun-kernel/kernel/cap";
18
18
  import { inspectWorkflow } from "@parcha/agentrun-dsl";
19
19
  import { factsOf } from "../harness-table.js";
20
20
  import { decisionProvidersIn } from "../decisions.js";
@@ -24,7 +24,6 @@ import { llmTiers, nodeTiers, thinkingLevel, TIERS, tierModelOf, workflowNodes }
24
24
  import { firstMessage, inputMessage, messageText } from "../run-manifest.js";
25
25
  import { learningStartOf, seedFailed } from "../run-launch.js";
26
26
  import { isWebHostTool } from "../tool-list.js";
27
- import { ASKED_BECAUSE } from "../refusal-words.js";
28
27
  import { deniedText, noApproverText, runGate } from "../tool-gate.js";
29
28
  import { DECISION_PROVIDER_KEYS, loadToolSettings, recheckPlane, TOOL_PLANE_ENV } from "../tool-plane.js";
30
29
  import { readApprovers } from "../server-approvers.js";
@@ -53,7 +52,7 @@ import { durableWait } from "../workflow/pi-versions.js";
53
52
  import { claimModelEnv, claimModelKey, claimSecrets, claimSpendOff, holdRunKey, keyedAtClaim, hostDecisionKeys, learnedDecisionKeys, savedModelKeys, tierModelKeys, withoutModelKeys } from "./claim-secrets.js";
54
53
  import { compareEndOfRun, GRADER, withGrader } from "./compare-end.js";
55
54
  import { agreeOnOf } from "../learning-setting.js";
56
- import { catalogSessionNames, mcpWhereHeld } from "./mcp-run.js";
55
+ import { catalogSessionNames, mcpWhereHeld, mediaForClaim } from "./mcp-run.js";
57
56
  import { held as runnerSeam, heldOrThrow, heldSignInReads } from "./held.js";
58
57
  import { hostLifecycle } from "./adapter-loop.js";
59
58
  import { RUNNER_HARNESSES } from "./adapters/index.js";
@@ -132,13 +131,14 @@ const isSubagentRoute = (key) => key.startsWith(SUBAGENT_ROUTE);
132
131
  * holds (savedModelKeys) as a subagent's tier does, held by the run's redactor, on the route's env alone. A run with its
133
132
  * own model key carries that key, and no saved key is read. Undefined when there is no fast model, the revision names
134
133
  * agree_on, or no route can be made (logged: the pair is then compared whole). */
135
- export async function graderRouteOf(body, keyed, runKey, claimed, cut, log, deps, holds = [cut]) {
134
+ export async function graderRouteOf(body, keyed, runKey, claimed, cut, log, deps, holds = [cut], claim) {
136
135
  if (agreeOnOf(body.learning)?.length)
137
136
  return undefined;
138
137
  const savedKeys = keyed ? {} : await savedModelKeys({ store: deps.store, sealKey: deps.sealKey, env: deps.env });
139
138
  for (const redact of new Set(holds))
140
139
  holdClaimed(redact, savedKeys);
141
- const env = claimModelEnv(deps.env, { ...savedKeys, ...claimed }, runKey);
140
+ // The claim's run, turn and attempt on its grader's requests too (request-metadata.ts): they spend on the run's cap.
141
+ const env = claimModelEnv(deps.env, { ...savedKeys, ...claimed }, runKey, claim);
142
142
  if (body.modelTiers?.fast === undefined && tierModelOf(env, "fast") === undefined)
143
143
  return undefined;
144
144
  try {
@@ -204,7 +204,7 @@ export async function adapterRunGate(store, claim, revision, root, shell, option
204
204
  const asksOf = decision === "allow" && host && options.ran ? toolOf(call.tool)?.asks : undefined;
205
205
  const because = asksOf ? await askedOne(call, asksOf, host, options.ran) : undefined;
206
206
  if (because !== undefined)
207
- return approvers ? { ask: { [ASKED_BECAUSE]: because } } : { deny: noApproverText(gate.askedAs(call.tool, call.args), options.replayed ? "unknown" : "no", because) };
207
+ return approvers ? { ask: {}, because } : { deny: noApproverText(gate.askedAs(call.tool, call.args), options.replayed ? "unknown" : "no", because) };
208
208
  // A learned workflow's MCP nodes are the run's own MCP calls, held to the same settings: one set to deny refuses the
209
209
  // whole call in the gate's words before any node runs, nothing sent; the actions set to ask are put to a person on the
210
210
  // call's one card, up front, each with its arguments' shape (learnedAskShown), and the person's allow passes the
@@ -344,7 +344,7 @@ async function adapterSpec(launch, run, deps, claim, holds, runner) {
344
344
  // words before the session opens. The seal key is the runner's own (deps.sealKey), not re-read from the environment.
345
345
  // A credential the claim opens mid-run (a GitHub App token, a saved or per_run server's) joins the run's redactor.
346
346
  const hold = (values) => cut.hold(values);
347
- const mcp = await mcpWhereHeld({ claim, store: deps.store, sealKey: deps.sealKey, grants: granted, harness: run.harness, work: () => ws.workspace, launchInput: launch.input, hold, githubAppAccess: (store, key, input) => githubAppAccess(store, key, input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub: launch.inputOrigin?.kind === "trigger" && launch.inputOrigin.source === "github", hold, ...(launch.repo !== undefined ? { repo: launch.repo } : {}) }), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}), ...reach });
347
+ const mcp = await mcpWhereHeld({ claim, store: deps.store, sealKey: deps.sealKey, grants: granted, harness: run.harness, work: () => ws.workspace, launchInput: launch.input, hold, githubAppAccess: (store, key, input) => githubAppAccess(store, key, input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub: launch.inputOrigin?.kind === "trigger" && launch.inputOrigin.source === "github", hold, ...(launch.repo !== undefined ? { repo: launch.repo } : {}) }), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}), ...reach, capped: () => launch.maxCostUsd !== undefined, media: mediaForClaim(deps.env, deps.evalFakes?.(runRow.agentId)?.web, deps.saveSlots) });
348
348
  // The claim's MCP goes to the loop, which lets it go; a build that throws lets it go itself.
349
349
  holds.hold({ passed: mcp });
350
350
  // The run's computer, from the one shared claim-time function (the CLI spec takes the same): none for a runner place, a
@@ -397,7 +397,7 @@ async function adapterSpec(launch, run, deps, claim, holds, runner) {
397
397
  holdClaimed(cut, toolEnv);
398
398
  // The route reads its model's key from the runner's environment, else the one the claim opened from the store: a key
399
399
  // saved in Settings → Model keys runs the next run with no restart (withModelKeys). A run with its own key: that key.
400
- const modelEnv = claimModelEnv(deps.env, toolEnv, runKey);
400
+ const modelEnv = claimModelEnv(deps.env, toolEnv, runKey, claim);
401
401
  const route = await deps.routeOf(modelAskOf(launch.model, body.model), modelEnv, "default", PI_WIRES, undefined, cut);
402
402
  await planBeforeRun(modelEnv, route.provider.plan ? { provider: PLAN_PROVIDER } : undefined);
403
403
  // The run's models of other tiers, for its learned workflows' nodes of a tier (learnedTierRoutes, filled once the seed's
@@ -429,7 +429,7 @@ async function adapterSpec(launch, run, deps, claim, holds, runner) {
429
429
  // A run with its own model key: its subagents' models carry that key too, and no saved key is read.
430
430
  const savedKeys = keyed ? {} : await savedModelKeys({ store: deps.store, sealKey: deps.sealKey, env: deps.env });
431
431
  holdClaimed(cut, savedKeys);
432
- const tierEnv = claimModelEnv(deps.env, { ...savedKeys, ...toolEnv }, runKey);
432
+ const tierEnv = claimModelEnv(deps.env, { ...savedKeys, ...toolEnv }, runKey, claim);
433
433
  for (const tier of SUBAGENT_TIERS) {
434
434
  if (body.modelTiers?.[tier] === undefined && tierModelOf(tierEnv, tier) === undefined)
435
435
  continue;
@@ -498,8 +498,8 @@ async function adapterSpec(launch, run, deps, claim, holds, runner) {
498
498
  },
499
499
  // What its audit's shadow took beside it, read by every gate with its own sessions (none: it starts none).
500
500
  ...(besideOf ? { beside: besideOf } : {}),
501
- // The most requests on free models it makes, capped or not (AGENTRUN_FREE_MODEL_REQUESTS).
502
- freeRequests: freeModelRequestsOf(deps.env),
501
+ // The most requests on free models it makes, capped or not (AGENTRUN_FREE_MODEL_REQUESTS, or the agent's lower max_requests).
502
+ freeRequests: freeRequestLimitOf(deps.env, body.maxRequests),
503
503
  };
504
504
  // The run's cap figure and what a refusal does to it (parkOf, with the kernel's raise rule): present only when the run
505
505
  // has a cap. A park names the cap the loop holds the run to then (a raise's, else this one).
@@ -554,7 +554,7 @@ async function adapterSpec(launch, run, deps, claim, holds, runner) {
554
554
  // A run with its own model key: its learned nodes' tiers carry that key too, and no saved key is read.
555
555
  const tierKeys = keyed ? {} : await tierModelKeys({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, learnedTiers(workflows));
556
556
  holdClaimed(cut, tierKeys);
557
- const tierEnv = claimModelEnv(deps.env, { ...toolEnv, ...tierKeys }, runKey);
557
+ const tierEnv = claimModelEnv(deps.env, { ...toolEnv, ...tierKeys }, runKey, claim);
558
558
  for (const [tier, routed] of await learnedTierRoutes(workflows, tierEnv, (tier) => deps.routeOf(undefined, tierEnv, tier, PI_WIRES, undefined, cut))) {
559
559
  if ("why" in routed)
560
560
  tierUnreachable.set(tier, routed.why);
@@ -567,7 +567,7 @@ async function adapterSpec(launch, run, deps, claim, holds, runner) {
567
567
  }
568
568
  // A replay run's or a shadow's grader (runner/compare-end.ts), on a route of its own beside the session's, on the
569
569
  // session's booking under the run's one cap. None: the pair is compared whole, in words saying so.
570
- const graderRoute = launch.replay || launch.audit ? await graderRouteOf(body, keyed, runKey, toolEnv, cut, log, deps) : undefined;
570
+ const graderRoute = launch.replay || launch.audit ? await graderRouteOf(body, keyed, runKey, toolEnv, cut, log, deps, [cut], claim) : undefined;
571
571
  if (graderRoute)
572
572
  tierRoutes.set(GRADER, graderRoute);
573
573
  // The tool host's install lifecycle: what a binding registers to run in each conversation's creating commit, once the
@@ -37,7 +37,7 @@ export declare function agreeOnOfRevision(store: Pick<Store, "agents">, revision
37
37
  export declare function auditedAnswerOf(deps: Pick<AuditDeps, "store" | "context" | "folder">, shadowRun: string): Promise<string | null>;
38
38
  /** How many of the newest stop_window runs `workflow` at `digest` served were not auditable (auditableLaunch: a trigger
39
39
  * started them): what the promotions read counts beside the audit line. */
40
- export declare function notAuditableOf(store: Pick<Store, "runs">, agentId: string, workflow: string, digest: string, loop: Pick<AuditLoop, "stop_window">): Promise<number>;
40
+ export declare function notAuditableOf(store: Pick<Store, "runs" | "settings">, agentId: string, workflow: string, digest: string, loop: Pick<AuditLoop, "stop_window">): Promise<number>;
41
41
  /** The words a shadow run ends failed with where it would wait on a person (AdapterRunSpec.neverWaits: an approval, a
42
42
  * raise of its cap, which is what its served run's cap left, a question), what it would wait on after them: its row is
43
43
  * `parked`, with no verdict. */
@@ -58,7 +58,9 @@ export declare function withAudit(step: EndOfRunTurn | undefined, deps: AuditDep
58
58
  * spend past the served run's cap; with less than a run's smallest cap left (or a spend not known), no shadow is started
59
59
  * and its row says `skipped: "no allowance"`. Its started line is appended first: a shadow is created only once the
60
60
  * ledger names it (settlement finds it there, never in a window of runs), and one whose line could not be written is
61
- * never created. Idempotent: one line and one shadow per run. */
61
+ * never created. Idempotent: one line and one shadow per run. A run the agent's learning reads no more starts none, as
62
+ * it adds no grade row (gradeRow): one before its learning's reset (sinceReset), ended again after it by a follow-up,
63
+ * or one on a named disk (learn/learning-of.ts). */
62
64
  export declare function startAudit(deps: AuditDeps & {
63
65
  readonly runId: string;
64
66
  readonly launch: RunLaunch;
@@ -71,5 +73,8 @@ export declare function startAudit(deps: AuditDeps & {
71
73
  export declare function settleAudits(deps: AuditDeps): Promise<void>;
72
74
  /** The row an owner's grade of served run `run` writes (source grade, agreed = the grade, counted for the digest's
73
75
  * promotion now), then the hold rule: only for a run the workflow answered alone (its answer is the workflow's).
74
- * Nothing else: no round, no compile by itself. */
76
+ * Nothing else: no round, no compile by itself. A run before the agent's learning reset (sinceReset) adds no row: its
77
+ * grade is kept, but a promotion of the same digest after the reset is never held by what came before it. A run on a
78
+ * named disk adds none either (learn/learning-of.ts): the hold rule would copy its answers into the promotion's
79
+ * disagreements, and the agent's compile reads those. */
75
80
  export declare function gradeRow(deps: AuditDeps, run: RunRow, correct: boolean): Promise<void>;
@@ -34,7 +34,7 @@ import { FINAL_STATES, StoreConstraint } from "../store/store.js";
34
34
  import { openRunMcpAuth, sealRunMcpAuth } from "../store/seal.js";
35
35
  import { isObject } from "../validate.js";
36
36
  import { auditableLaunch, auditChange, auditEveryOf, auditDrawn, auditsOffWords, auditWriterOf, holdOf, ledgerOf, lineKey, openAudits, rowsOf, shadowRunId } from "../learn/audit.js";
37
- import { lastRunsOf } from "../learn/compile.js";
37
+ import { lastRunsOf, sinceReset } from "../learn/compile.js";
38
38
  import { readLearning, writeLearning } from "../learn/folder.js";
39
39
  import { CHECK_TEXT_MAX, compareAnswers, comparedOf, promotionOf, promotionsOf, promotionStartOf, recordPromotion, servingOf } from "../learn/promote.js";
40
40
  import { excerptShown } from "../learn/secrets.js";
@@ -79,9 +79,13 @@ export async function auditedAnswerOf(deps, shadowRun) {
79
79
  const open = openAudits(await readLedger(deps)).find((line) => line.shadow_run === shadowRun);
80
80
  return open ? auditedAnswer(deps, open) : null;
81
81
  }
82
- /** The served runs of `workflow` (at `digest` when given) that `keep` keeps too, the newest `n` of them (lastRunsOf: the
83
- * shadows and the agent's own runs among them never push one out of the read). */
84
- const servedRuns = (store, agentId, n, workflow, digest, keep = () => true) => lastRunsOf(store, agentId, n, (row) => served(row) && metricsOf(row).workflow === workflow && (digest === undefined || metricsOf(row).workflow_digest === digest) && keep(row));
82
+ /** The served runs of `workflow` (at `digest` when given) that `keep` keeps too, since the agent's learning's reset
83
+ * (sinceReset), the newest `n` of them (lastRunsOf: the shadows and the agent's own runs among them never push one out
84
+ * of the read). */
85
+ const servedRuns = async (store, agentId, n, workflow, digest, keep = () => true) => {
86
+ const since = await sinceReset(store, agentId);
87
+ return lastRunsOf(store, agentId, n, (row) => served(row) && metricsOf(row).workflow === workflow && (digest === undefined || metricsOf(row).workflow_digest === digest) && keep(row) && since(row));
88
+ };
85
89
  /** How many of the newest stop_window runs `workflow` at `digest` served were not auditable (auditableLaunch: a trigger
86
90
  * started them): what the promotions read counts beside the audit line. */
87
91
  export async function notAuditableOf(store, agentId, workflow, digest, loop) {
@@ -134,7 +138,9 @@ async function auditAtEnd(deps, runId) {
134
138
  * spend past the served run's cap; with less than a run's smallest cap left (or a spend not known), no shadow is started
135
139
  * and its row says `skipped: "no allowance"`. Its started line is appended first: a shadow is created only once the
136
140
  * ledger names it (settlement finds it there, never in a window of runs), and one whose line could not be written is
137
- * never created. Idempotent: one line and one shadow per run. */
141
+ * never created. Idempotent: one line and one shadow per run. A run the agent's learning reads no more starts none, as
142
+ * it adds no grade row (gradeRow): one before its learning's reset (sinceReset), ended again after it by a follow-up,
143
+ * or one on a named disk (learn/learning-of.ts). */
138
144
  export async function startAudit(deps, serve) {
139
145
  const { store, agentId, runId, launch, log } = deps;
140
146
  if (!serve || serve.replay || launch.replay || launch.audit || !launch.learning || !auditableLaunch(launch))
@@ -145,6 +151,10 @@ export async function startAudit(deps, serve) {
145
151
  if (off)
146
152
  return void log(`workflow-first: ${off}`);
147
153
  try {
154
+ // The run is there at its end (its end commits after this step).
155
+ const row = await store.runs.get(runId);
156
+ if (row && ((row.disk ?? null) !== null || !(await sinceReset(store, agentId))(row)))
157
+ return;
148
158
  // Read after the claim pinned the revision's MCP tools (mcp-claim.ts pinFirst): the pin a revision saved without one
149
159
  // takes at its first run is what its tools are classed by.
150
160
  const revision = await store.agents.revision(deps.revisionId);
@@ -268,11 +278,16 @@ export async function settleAudits(deps) {
268
278
  }
269
279
  /** The row an owner's grade of served run `run` writes (source grade, agreed = the grade, counted for the digest's
270
280
  * promotion now), then the hold rule: only for a run the workflow answered alone (its answer is the workflow's).
271
- * Nothing else: no round, no compile by itself. */
281
+ * Nothing else: no round, no compile by itself. A run before the agent's learning reset (sinceReset) adds no row: its
282
+ * grade is kept, but a promotion of the same digest after the reset is never held by what came before it. A run on a
283
+ * named disk adds none either (learn/learning-of.ts): the hold rule would copy its answers into the promotion's
284
+ * disagreements, and the agent's compile reads those. */
272
285
  export async function gradeRow(deps, run, correct) {
273
286
  const m = metricsOf(run);
274
287
  if (m.path !== "workflow" || typeof m.workflow !== "string" || typeof m.workflow_digest !== "string")
275
288
  return;
289
+ if ((run.disk ?? null) !== null || !(await sinceReset(deps.store, deps.agentId))(run))
290
+ return;
276
291
  const promoted = promotionStartOf(await promotionsOf(deps.store.settings, deps.agentId), m.workflow, m.workflow_digest);
277
292
  // The answer graded: the run's newest now, kept by its row's id (as a shadow's audit keeps its turn).
278
293
  const turn = turnOf((await answerRowOf(deps.store, run.id, deps.context))?.id);
@@ -6,6 +6,7 @@ import type { Revision } from "../agent-rows.js";
6
6
  import type { HeldRedact } from "./redact.js";
7
7
  import { type HeldModelKey } from "../run-model-key.js";
8
8
  import { type RunModelKey } from "../store/seal.js";
9
+ import { type Claim } from "../store/store.js";
9
10
  /** What claimSecrets reads the keys from: the one store (its sealed keys) and the runner's seal key, and the runner's base
10
11
  * environment (its own, with no server secret in it: those are the store's). */
11
12
  export interface ClaimSecretsDeps {
@@ -109,7 +110,7 @@ export declare function claimSpendOff(deps: ClaimSecretsDeps, runKey: ClaimModel
109
110
  /** The env a claimed run's model routes read: the run's own key alone where the claim opened one (withRunModelKey); else
110
111
  * the runner's environment with the keys `opened` for it (withModelKeys), whose gateway variables read the run's key
111
112
  * once a message hands it one (withRunModelKeyLater). */
112
- export declare function claimModelEnv(env: NodeJS.ProcessEnv, opened: NodeJS.ProcessEnv, runKey: ClaimModelKey | undefined): NodeJS.ProcessEnv;
113
+ export declare function claimModelEnv(env: NodeJS.ProcessEnv, opened: NodeJS.ProcessEnv, runKey: ClaimModelKey | undefined, claim?: Pick<Claim, "runId" | "turn" | "attempt">): NodeJS.ProcessEnv;
113
114
  /** `toolEnv` with no model key in it, for a run that holds its own: a tool's environment never carries a model key the
114
115
  * run's model routes do not send. The decision providers' keys stay (DECISION_KEY_NAMES): a keyed workflow's judge,
115
116
  * pick, sift, route and ask nodes run on them as any run's do. */
@@ -18,6 +18,7 @@ import { savedGatewayIn } from "../model-gateway.js";
18
18
  import { noServerKeyWords, runKeyEndedFor, runModelOrigin, withRunModelKey, withRunModelKeyLater } from "../run-model-key.js";
19
19
  import { openRunLaunch } from "../store/seal.js";
20
20
  import { StoreLaunchMissing } from "../store/store.js";
21
+ import { withRequestMetadata } from "../request-metadata.js";
21
22
  /** Every server secret a run might be handed (runs.ts RUN_SECRETS is the tool and model keys; the decision keys go beside
22
23
  * them). Read from the store into a working environment, then scoped to the run below. */
23
24
  const CANDIDATES = [...new Set([...RUN_SECRETS, ...DECISION_KEYS])];
@@ -285,10 +286,11 @@ export async function claimSpendOff(deps, runKey) {
285
286
  /** The env a claimed run's model routes read: the run's own key alone where the claim opened one (withRunModelKey); else
286
287
  * the runner's environment with the keys `opened` for it (withModelKeys), whose gateway variables read the run's key
287
288
  * once a message hands it one (withRunModelKeyLater). */
288
- export function claimModelEnv(env, opened, runKey) {
289
+ export function claimModelEnv(env, opened, runKey, claim) {
290
+ // The claim's run, turn and attempt, which each request on serve's gateway names (request-metadata.ts).
289
291
  if (!runKey)
290
- return withModelKeys(env, opened);
291
- return keyedAtClaim(runKey) ? withRunModelKey(env, runKey) : withRunModelKeyLater(withModelKeys(env, opened), runKey);
292
+ return withRequestMetadata(withModelKeys(env, opened), claim);
293
+ return withRequestMetadata(keyedAtClaim(runKey) ? withRunModelKey(env, runKey) : withRunModelKeyLater(withModelKeys(env, opened), runKey), claim);
292
294
  }
293
295
  /** The decision providers' own keys (decisions.ts: Jev's TypeSafe key, OpenRouter's, Parallel's): some are also pi-ai
294
296
  * provider names, but a run's model key never replaces them, so withoutModelKeys keeps them. */
@@ -51,7 +51,7 @@ export declare function cliCapModel(entry: HarnessEntry & {
51
51
  * run whose plane resolves it to native gets the harness's own search (#2458), this run's alone; whatever the runner's
52
52
  * own environment says of a plane is never the run's. Whether each search runs is the tool's setting at that search
53
53
  * (SessionIO.permission, the gate), never this plane, which is frozen when the run is made. */
54
- export declare function cliRunEnv(env: NodeJS.ProcessEnv | undefined, data: string, claimed?: NodeJS.ProcessEnv, plane?: RunLaunch["plane"], runKey?: ClaimModelKey): NodeJS.ProcessEnv;
54
+ export declare function cliRunEnv(env: NodeJS.ProcessEnv | undefined, data: string, claimed?: NodeJS.ProcessEnv, plane?: RunLaunch["plane"], runKey?: ClaimModelKey, claim?: Pick<Claim, "runId" | "turn" | "attempt">): NodeJS.ProcessEnv;
55
55
  /** `tools` in the order the agent grants them (`granted`, catalog names; a tool is listed by its catalog name's wire
56
56
  * name), as main listed a CLI run's tools to its harness: each granted tool where its grant is, and a tool the grant
57
57
  * does not name (one a granted tool or the run's computer brings beside it) right after the tool listed before it. Ties
@@ -18,7 +18,7 @@ import { stopRunWith } from "../paid-calls.js";
18
18
  import { dirname, join } from "node:path";
19
19
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
20
20
  import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
21
- import { checkRaise, followUpOf, freeModelRequestsOf, parkOf, planCapModel } from "@parcha/agentrun-kernel/kernel/cap";
21
+ import { checkRaise, followUpOf, freeRequestLimitOf, parkOf, planCapModel } from "@parcha/agentrun-kernel/kernel/cap";
22
22
  import { PLAN_LIMIT_WORDS } from "@parcha/agentrun-kernel";
23
23
  import { modelWire } from "../wires.js";
24
24
  import { confineOf, noNewPrivsPrefix, standsIn, thinkingFor } from "../adapters.js";
@@ -57,7 +57,7 @@ import { hostToolOf } from "../host-tools.js";
57
57
  import { ASK_TOOL, askPerson } from "../tools.js";
58
58
  import { fakedPlane } from "../web-fake.js";
59
59
  import { claimModelEnv, claimModelKey, claimSecrets, claimSpendOff, holdRunKey, keyedAtClaim, hostDecisionKeys, learnedDecisionKeys, tierModelKeys, withoutModelKeys } from "./claim-secrets.js";
60
- import { mcpWhereHeld } from "./mcp-run.js";
60
+ import { mcpWhereHeld, mediaForClaim } from "./mcp-run.js";
61
61
  import { held as runnerSeam, heldSignInReads } from "./held.js";
62
62
  import { DECISION_PROVIDER_KEYS, TOOL_PLANE_ENV } from "../tool-plane.js";
63
63
  import { decisionProvidersIn } from "../decisions.js";
@@ -146,9 +146,10 @@ export async function cliCapModel(entry, env, ref) {
146
146
  * run whose plane resolves it to native gets the harness's own search (#2458), this run's alone; whatever the runner's
147
147
  * own environment says of a plane is never the run's. Whether each search runs is the tool's setting at that search
148
148
  * (SessionIO.permission, the gate), never this plane, which is frozen when the run is made. */
149
- export function cliRunEnv(env, data, claimed = {}, plane, runKey) {
150
- // A run with its own model key: that key alone, in the variables its route sends (claimModelEnv, never enumerable).
151
- const out = claimModelEnv(env ?? {}, claimed, runKey);
149
+ export function cliRunEnv(env, data, claimed = {}, plane, runKey, claim) {
150
+ // A run with its own model key: that key alone, in the variables its route sends (claimModelEnv, never enumerable), and
151
+ // the claim's request metadata beside it (request-metadata.ts, never enumerable either).
152
+ const out = claimModelEnv(env ?? {}, claimed, runKey, claim);
152
153
  Object.defineProperty(out, DATA_ENV, { value: data, enumerable: true, writable: true, configurable: true });
153
154
  delete out[TOOL_PLANE_ENV];
154
155
  if (plane && Object.keys(plane).length)
@@ -330,7 +331,7 @@ async function cliSpec(launch, run, deps, claim, holds) {
330
331
  // A credential the claim opens mid-run (a GitHub App token, a saved or per_run server's) joins the run's redactors.
331
332
  const hold = (values) => { for (const redact of [...(run.redact ? [heldRedactor(run.redact)] : []), cut])
332
333
  redact.hold(values); };
333
- const mcp = await mcpWhereHeld({ claim, store: deps.store, sealKey: deps.sealKey, grants: granted, harness: run.harness, work: () => runFolder(deps.data, runRow.agentId, claim.runId), launchInput: launch.input, hold, githubAppAccess: (store, key, input) => githubAppAccess(store, key, input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub: launch.inputOrigin?.kind === "trigger" && launch.inputOrigin.source === "github", hold, ...(launch.repo !== undefined ? { repo: launch.repo } : {}) }), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}), ...reach });
334
+ const mcp = await mcpWhereHeld({ claim, store: deps.store, sealKey: deps.sealKey, grants: granted, harness: run.harness, work: () => runFolder(deps.data, runRow.agentId, claim.runId), launchInput: launch.input, hold, githubAppAccess: (store, key, input) => githubAppAccess(store, key, input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub: launch.inputOrigin?.kind === "trigger" && launch.inputOrigin.source === "github", hold, ...(launch.repo !== undefined ? { repo: launch.repo } : {}) }), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}), ...reach, capped: () => launch.maxCostUsd !== undefined, media: mediaForClaim(deps.env, web, deps.saveSlots) });
334
335
  // The claim's MCP goes to the loop, which lets it go; a build that throws lets it go itself.
335
336
  holds.hold({ passed: mcp });
336
337
  // The run's mode is the server's: Mode 2 where its Archil settings are saved (archil-settings.ts), the run's folder then
@@ -452,7 +453,7 @@ async function cliSpec(launch, run, deps, claim, holds) {
452
453
  // carries only where it is, and its CLI says it is signed in before the run starts. A run that brought its own key
453
454
  // runs on that key, and a run in a sandbox place on the model keys.
454
455
  const login = keyed ? undefined : await loginForRun(deps.store.settings, deps.data, deps.env ?? {}, name, launch.place);
455
- const env = withClaudeLogin(cliRunEnv(deps.env, deps.data, claimed, launch.plane, runKey), login);
456
+ const env = withClaudeLogin(cliRunEnv(deps.env, deps.data, claimed, launch.plane, runKey, claim), login);
456
457
  const chosen = await modelsOf(entry, env, modelAskOf(launch.model, body.model));
457
458
  await planBeforeRun(env, chosen.model);
458
459
  if (login && entry.priceModel(env, chosen.model).provider === CLAUDE_LOGIN_PROVIDER) {
@@ -533,8 +534,8 @@ async function cliSpec(launch, run, deps, claim, holds) {
533
534
  },
534
535
  // What its audit's shadow took beside it, read by every gate with its own sessions (none: it starts none).
535
536
  ...(besideOf ? { beside: besideOf } : {}),
536
- // The most requests on free models it makes, capped or not (AGENTRUN_FREE_MODEL_REQUESTS).
537
- freeRequests: freeModelRequestsOf(deps.env),
537
+ // The most requests on free models it makes, capped or not (AGENTRUN_FREE_MODEL_REQUESTS, or the agent's lower max_requests).
538
+ freeRequests: freeRequestLimitOf(deps.env, body.maxRequests),
538
539
  };
539
540
  const cap = capUsd === undefined
540
541
  ? undefined
@@ -596,7 +597,7 @@ async function cliSpec(launch, run, deps, claim, holds) {
596
597
  const audits = { store: deps.store, agentId: runRow.agentId, revisionId: runRow.revisionId, context, log, folder: learningFolder, shown, sealKey: deps.sealKey, spendOff };
597
598
  // A replay run's or a shadow's grader (runner/compare-end.ts), on a proxy of its own beside the CLI session's, as pi's
598
599
  // is (adapter-run-spec.ts graderRouteOf), reached through the session's port while it is up. None: compared whole.
599
- const graderRoute = launch.replay || launch.audit ? await graderRouteOf(body, keyed, runKey, claimed, cut, log, deps, [held, cut]) : undefined;
600
+ const graderRoute = launch.replay || launch.audit ? await graderRouteOf(body, keyed, runKey, claimed, cut, log, deps, [held, cut], claim) : undefined;
600
601
  if (graderRoute)
601
602
  tierRoutes.set(GRADER, graderRoute);
602
603
  // Each step writes the store or reads another run (runner/learned-first.ts): in a run's own process its runner takes
@@ -643,7 +644,7 @@ async function cliSpec(launch, run, deps, claim, holds) {
643
644
  const tierKeys = keyed ? {} : await tierModelKeys({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, learnedTiers(workflows));
644
645
  for (const redact of new Set([held, cut]))
645
646
  holdClaimed(redact, tierKeys);
646
- const modelEnv = claimModelEnv(deps.env, { ...claimed, ...tierKeys }, runKey);
647
+ const modelEnv = claimModelEnv(deps.env, { ...claimed, ...tierKeys }, runKey, claim);
647
648
  const tiers = new Map();
648
649
  for (const [tier, routed] of await learnedTierRoutes(workflows, modelEnv, (tier) => deps.routeOf(undefined, modelEnv, tier, PI_WIRES, undefined, cut))) {
649
650
  if ("why" in routed)
@@ -1059,7 +1059,9 @@ const CASES = [
1059
1059
  await w.ended("parked");
1060
1060
  const callId = await w.askedCall();
1061
1061
  // Both sent before either is awaited (on Postgres, each on its own pooled connection). Whichever is written first, the
1062
- // store's one-answer index refuses the other: no order is imposed, so the case holds for either winner.
1062
+ // store refuses the other: no order is imposed, so the case holds for either winner. The other meets the one-answer
1063
+ // index (AnswerTaken) or, when the winner's answer already ended the run, the run's end (RunFinal): which one is
1064
+ // timing, so either stands, and the index itself is approval-double-click's (its call held so the run cannot end).
1063
1065
  const settled = await Promise.allSettled([
1064
1066
  sendCommand(w.server, RUN, { kind: "approve", body: { approval: callId } }),
1065
1067
  sendCommand(w.server, RUN, { kind: "deny", body: { approval: callId } }),
@@ -1067,7 +1069,7 @@ const CASES = [
1067
1069
  const won = settled.filter((r) => r.status === "fulfilled");
1068
1070
  const lost = settled.filter((r) => r.status === "rejected");
1069
1071
  assert.equal(won.length, 1, `one answer is written, not both: ${JSON.stringify(settled.map((r) => r.status))}`);
1070
- assert.ok(lost[0]?.reason instanceof AnswerTaken, `the other is refused by the store as answered already (AnswerTaken), never a bare constraint: ${String(lost[0]?.reason)}`);
1072
+ assert.ok(lost[0]?.reason instanceof AnswerTaken || lost[0]?.reason instanceof RunFinal, `the other is refused by the store, answered already (AnswerTaken) or the run ended on the winner (RunFinal), never a bare constraint: ${String(lost[0]?.reason)}`);
1071
1073
  await w.ended("ended");
1072
1074
  const winner = won[0].value;
1073
1075
  assert.equal(ran.asked, winner.kind === "approve" ? 1 : 0, "the run acted on the answer written, never the other");
@@ -8,7 +8,7 @@
8
8
  // through the inner loop the moment it is chosen. A launch whose harness this runner does not run, or whose body cannot
9
9
  // be read, fails the run in words (the dispatch's start() throws, which the runner records as the run failing).
10
10
  import { harnessOfBody } from "../harness.js";
11
- import { readLaunchBody } from "../run-launch.js";
11
+ import { launchOnItsDisk, readLaunchBody } from "../run-launch.js";
12
12
  /** A launch naming a harness this runner does not run. */
13
13
  export class UnknownHarness extends Error {
14
14
  harness;
@@ -58,7 +58,9 @@ function dispatchLoop(deps, loopDeps) {
58
58
  const innerDeps = { ...loopDeps, delivered: Promise.all([loopDeps.delivered ?? Promise.resolve(), earlyReplayed]).then(() => undefined) };
59
59
  async function begin(claim) {
60
60
  const row = await deps.launchOf(claim.runId);
61
- const launch = readLaunchBody(row.body);
61
+ // The launch as this run runs it: on a named disk, with nothing learned on another disk (launchOnItsDisk).
62
+ const read = readLaunchBody(row.body);
63
+ const launch = read && launchOnItsDisk(read);
62
64
  if (!launch)
63
65
  throw new LaunchUnreadable(claim.runId);
64
66
  const harness = harnessOfBody(row.body);
@@ -19,6 +19,7 @@ import { resolveHarness } from "./adapters/index.js";
19
19
  import { adapterRunSpecFromLaunch, PI_WIRES } from "./adapter-run-spec.js";
20
20
  import { createAdapterLoop } from "./adapter-loop.js";
21
21
  import { savedModelKeys, withModelKeys } from "./claim-secrets.js";
22
+ import { withRequestMetadata } from "../request-metadata.js";
22
23
  import { noServerKeyFor } from "../run-model-key.js";
23
24
  import { createDispatchLoop } from "./dispatch.js";
24
25
  import { cliRunSpecFromLaunch } from "./cli-run-spec.js";
@@ -73,11 +74,13 @@ async function loopOn(deps, harness, launch, runId) {
73
74
  // A backend SDK run's compile turn is asked on the runner's one model route, on the agent's own model (its learning
74
75
  // start's), its key from the runner's environment, else the one saved in Settings → Model keys, read at each ask.
75
76
  if (launch.sdk || launch.cli_learning)
76
- return createSdkLoop(launch, deps, async () => {
77
+ return createSdkLoop(launch, deps, async (claim) => {
77
78
  if (launch.cli_learning)
78
79
  throw new Error("Connected CLI capture has no workflow execution bridge.");
79
80
  const base = deps.env ?? process.env;
80
- const env = withModelKeys(base, await savedModelKeys({ store: deps.store, sealKey: deps.sealKey, env: base }));
81
+ // Its requests on serve's gateway name the claim's run, turn and attempt, as every other request of a claim does
82
+ // (request-metadata.ts): withModelKeys makes the env this ask's own.
83
+ const env = withRequestMetadata(withModelKeys(base, await savedModelKeys({ store: deps.store, sealKey: deps.sealKey, env: base })), claim);
81
84
  // It runs after its backend reported the run complete, on no run's key: on a server that holds no gateway key it is
82
85
  // skipped in words (run-model-key.ts noServerKeyFor), nothing sent.
83
86
  const off = noServerKeyFor(env, "An SDK run's compile turn");
@@ -260,6 +260,9 @@ export interface AskData {
260
260
  readonly tool: string;
261
261
  /** The call's input as the gate saw it; null when it had none. */
262
262
  readonly args?: unknown;
263
+ /** Why a call its setting allows asks a person anyway (a tool's own ask, tools.ts ToolEntry.asks): the gate's alone,
264
+ * never one of the call's arguments. */
265
+ readonly because?: string;
263
266
  /** When it was asked (ISO), from the loop's clock; a re-ask on a resume keeps the first. */
264
267
  readonly requestedAt?: string;
265
268
  /** Its approval price (a catalog tool's, the spec's mcp priceOf); null when it has none. */
@@ -136,7 +136,8 @@ export declare function checkDraftOf(deps: LearningEndDeps, input: {
136
136
  * its reason (DRAFT_FAILED) naming the failed checks. A first compile's earns the one recompile, as a check's hold
137
137
  * does (the agent's next due run compiles once more: learn/compile.ts newCompileAttempt); a recompile's (a revision of
138
138
  * a held workflow, or a new one after a first compile's failed drafts) stops (compileStoppedOf, heldNamesOf): nothing
139
- * compiles it again. One record per run (its digest is the run's), written once: a claim that ends the run again
139
+ * compiles it again. A revision of a connected agent's hold on give-backs is no recompile (runner/promotion.ts
140
+ * reviseAttemptOf). One record per run (its digest is the run's), written once: a claim that ends the run again
140
141
  * writes none. */
141
142
  export declare function recordDraftFailed(deps: Pick<LearningEndDeps, "store" | "log">, input: {
142
143
  runId: string;
@@ -17,7 +17,9 @@
17
17
  // keeps sealed (store-secrets.ts storeSecrets), the runner's secrets, the keys its claim handed it, and the sign-in
18
18
  // pointers its row says it was handed, read back from the store (handed-values.ts handedValuesOf). A run whose
19
19
  // pointers can't be read back learns nothing (the hook drops it, saying why), never over a shorter list.
20
- // A run whose seed could not be read keeps that drop.
20
+ // A run whose seed could not be read keeps that drop. A run whose seed was read at or before a reset of its agent's
21
+ // learning learns nothing at all, dropped at its entry with reason `reset`. Every read of the agent's runs here reads
22
+ // only those after the reset (learn/compile.ts sinceReset).
21
23
  import { createHash } from "node:crypto";
22
24
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
23
25
  import { isMessageRow } from "../timeline/index.js";
@@ -25,10 +27,11 @@ import { correctionRefused, learningCommit } from "../learn/commit.js";
25
27
  import { CAPS, checkDraft, problemWords, unstorable } from "../learn/index.js";
26
28
  import { repickSiteOf } from "../learn/check.js";
27
29
  import { repickLabelOf, repickRewrite } from "../learn/repick.js";
28
- import { folderAt, readLearning, readSnapshot, runMergeOf, snapshotAt, textsAt } from "../learn/folder.js";
29
- import { completedRun, compileStoppedOf, lastOwnRuns, compileDue, compilePrompt, compileReference, COMPILE_TRACES, DRAFT_FAILED, heldNamesOf, newCompileAttempt } from "../learn/compile.js";
30
+ import { folderAt, holdsCommit, readLearning, readSnapshot, runMergeOf, snapshotAt, textsAt } from "../learn/folder.js";
31
+ import { completedRun, compileStoppedOf, lastOwnRuns, sinceReset, compileDue, compilePrompt, compileReference, COMPILE_TRACES, DRAFT_FAILED, draftFailedOf, heldNamesOf, newCompileAttempt } from "../learn/compile.js";
32
+ import { reviseAttemptOf } from "./promotion.js";
30
33
  import { loopOf, repickOf } from "../learning-setting.js";
31
- import { CHECK_TEXT_MAX, promotionOf, promotionsOf, recordPromotion } from "../learn/promote.js";
34
+ import { CHECK_TEXT_MAX, promotionOf, promotionsOf, recordPromotion, resetAtOf } from "../learn/promote.js";
32
35
  import { draftDecisionProviders, draftDryRun, draftFiles, draftMcpTools, unpricedCalls, WORKFLOWS_DIR } from "../learn/workflow-draft.js";
33
36
  import { DECISION_PROVIDER_KEYS } from "../tool-plane.js";
34
37
  import { handedValuesOf } from "../handed-values.js";
@@ -36,7 +39,7 @@ import { excerptShown, MIN_SECRET, redactSecrets } from "../learn/secrets.js";
36
39
  import { LEARNED_WORKFLOW_TOOL } from "../learned-workflow.js";
37
40
  import { META_TOOLS } from "../meta-tool-names.js";
38
41
  import { holdsSecret, LEARNING_LABEL, secretsShown } from "../learning.js";
39
- import { said, STOPPED } from "../learning-words.js";
42
+ import { said, seedStopped } from "../learning-words.js";
40
43
  import { learningStartOf, readLaunchBody, seedFailed } from "../run-launch.js";
41
44
  import { FINAL_STATES } from "../store/store.js";
42
45
  import { shadowRunId } from "../learn/audit.js";
@@ -64,7 +67,7 @@ export function learningEndOfRun(launch, deps) {
64
67
  if (held())
65
68
  return heldEndOfRun();
66
69
  const env = deps.env ?? process.env;
67
- const hookFor = (seed, round) => createReflectHook({
70
+ const hookFor = (seed, round, mustHold) => createReflectHook({
68
71
  round,
69
72
  // A run its cap stopped has no room left, and one whose spend is unknown under a cap cannot be kept within it. The cap
70
73
  // is the run's now (capNowOf: its newest raise's, else its launch's), the one its requests were admitted under. Its
@@ -130,7 +133,7 @@ export function learningEndOfRun(launch, deps) {
130
133
  commit: async ({ runId, agentId, round: at, draft, correction, refuse }) => {
131
134
  const reason = draft ? `Compiled the job as workflow ${draft.name}${correction !== undefined ? ", with its owner's correction" : ""}.` : "Its owner's correction.";
132
135
  const done = await commitDirect({ folder: () => deps.learningFolder(agentId), log: deps.log ?? (() => undefined) }, {
133
- runId, round: at, reason, seed, files: draft ? draft.files.map((file) => ({ ...file })) : [],
136
+ runId, round: at, reason, seed, ...(mustHold ? { mustHold } : {}), files: draft ? draft.files.map((file) => ({ ...file })) : [],
134
137
  ...(draft?.held?.length ? { held: [...draft.held] } : {}), ...(draft?.bases ? { bases: draft.bases } : {}),
135
138
  ...(correction !== undefined ? { correction, refuseValues: refuse } : {}),
136
139
  });
@@ -142,15 +145,26 @@ export function learningEndOfRun(launch, deps) {
142
145
  // Why, as its start recorded it: a folder that could not be read, or a start that could not be made from it; a
143
146
  // start that records none names no reason.
144
147
  if (seedFailed(start)) {
145
- const failed = start.seedFailed;
146
- const why = failed === "unreadable" ? STOPPED.unreadable : failed === "not_copied" ? STOPPED.notCopied : STOPPED.noSeed;
148
+ const why = seedStopped(start.seedFailed);
147
149
  // Every end of it: the first's drop stands for a later one (the store keeps one a round, so it adds nothing new).
148
150
  return { also: [{ table: "learning_proposals", row: { turn: null, proposal: { state: "dropped", reason: "seed_failed", detail: said.stopped(why) } } }] };
149
151
  }
152
+ // The one check at the entry of a run's learning end, before any merge, look-back, compile, draft check or record: a
153
+ // run whose seed was read at or before a reset of its agent's learning (its watermark, learn/promote.ts resetAtOf; a
154
+ // start that records no time is read as before it) learns nothing, whole. Its corrections and compile would land on
155
+ // what the reset left. Read by time alone: a Mode 2 run's end writes the folder on its disk, which never held the
156
+ // seed the server read from its own folder, so a commit missing here says nothing of a reset.
157
+ const reset = await resetAtOf(deps.store.settings, input.agentId);
158
+ if (reset !== undefined && !(start.seededAt !== undefined && start.seededAt > reset)) {
159
+ return { also: [{ table: "learning_proposals", row: { turn: null, proposal: { state: "dropped", reason: "reset", detail: said.reset } } }] };
160
+ }
161
+ // The second wall, once the agent's learning was reset: a seed this folder holds now is one its merge must still
162
+ // find (commit.ts mustHold), so a reset after this check refuses the merge whole in the script.
163
+ const mustHold = reset !== undefined && (await withFolder(deps, input.agentId, (folder) => holdsCommit(folder.workspace, start.seed))) ? start.seed : undefined;
150
164
  // Which end of the run this is: the round after the newest it kept (a follow-up opened the run again after it), else
151
165
  // its first. A replayed end reads the same round: its rows are written only with the end that closes it.
152
166
  const prior = await deps.store.learning.proposal(input.runId);
153
- return hookFor(start.seed, prior ? prior.round + 1 : 1)(input);
167
+ return hookFor(start.seed, prior ? prior.round + 1 : 1, mustHold)(input);
154
168
  };
155
169
  }
156
170
  /** What every cap gate of run `runId` reads as spent beside it on its behalf (adapter-loop.ts RunCapConfig.beside): its
@@ -464,20 +478,23 @@ const workflowText = (doc) => {
464
478
  const text = `${JSON.stringify(doc, null, 2)}\n`;
465
479
  return Buffer.byteLength(text) <= CAPS.file ? text : `${JSON.stringify(doc)}\n`;
466
480
  };
481
+ /** The digest of the failed-draft record run `runId`'s compile keeps (recordDraftFailed): one per run. */
482
+ const draftFailedDigest = (runId) => createHash("sha256").update(`draft-failed\n${runId}`).digest("hex").slice(0, 16);
467
483
  /** Compile once: run `runId`'s compile turn whose drafts all failed their checks is the compile's attempt, kept as a
468
484
  * promotion record of the shape a check's stop has (runner/promotion.ts stopUnchecked): a hold with nothing checked,
469
485
  * its reason (DRAFT_FAILED) naming the failed checks. A first compile's earns the one recompile, as a check's hold
470
486
  * does (the agent's next due run compiles once more: learn/compile.ts newCompileAttempt); a recompile's (a revision of
471
487
  * a held workflow, or a new one after a first compile's failed drafts) stops (compileStoppedOf, heldNamesOf): nothing
472
- * compiles it again. One record per run (its digest is the run's), written once: a claim that ends the run again
488
+ * compiles it again. A revision of a connected agent's hold on give-backs is no recompile (runner/promotion.ts
489
+ * reviseAttemptOf). One record per run (its digest is the run's), written once: a claim that ends the run again
473
490
  * writes none. */
474
491
  export async function recordDraftFailed(deps, input) {
475
492
  try {
476
493
  const records = await promotionsOf(deps.store.settings, input.agentId);
477
- const attempt = input.compile.mode === "revise" ? 2 : newCompileAttempt(records);
494
+ const attempt = input.compile.mode === "revise" ? reviseAttemptOf(records, input.compile.held) : newCompileAttempt(records);
478
495
  const { compile_after, agree_min, alone_min } = await loopOfRun(deps.store, input.runId);
479
496
  const workflow = input.compile.mode === "revise" ? input.compile.workflow : input.workflow;
480
- const digest = createHash("sha256").update(`draft-failed\n${input.runId}`).digest("hex").slice(0, 16);
497
+ const digest = draftFailedDigest(input.runId);
481
498
  const failed = input.errors.join("; ").slice(0, CHECK_TEXT_MAX) || "no draft passed";
482
499
  const reason = `${DRAFT_FAILED}: ${failed}. ${attempt === 2 ? "It was the recompile, so it stops: nothing compiles again until its owner acts" : "It is not promoted; the next due run compiles it once more"}`;
483
500
  const check = { compile_after, agree_min, alone_min, attempt, n: 0, agreed: 0, alone: 0, of: [], ...(attempt === 2 ? { stopped: true } : {}) };
@@ -530,19 +547,23 @@ export function traceFrom(timeline, refuse) {
530
547
  * session, also carries the owner's standing corrections it was laid with (`corrections`, its # Learned section), as an
531
548
  * in-session compile reads them in its session. Undefined when it compiles nothing, or when the folder can't be read. */
532
549
  export async function compileAskOf(deps, input) {
550
+ const { agentId } = input;
533
551
  // A revision is asked only of a workflow its promotion holds, once per hold. The workflows whose newest revision other
534
552
  // than their champion (learn/promote.ts championOf: it serves while that one is held) is held: the run's own may be one.
535
- const records = await promotionsOf(deps.store.settings, input.agentId).catch(() => []);
553
+ const records = await promotionsOf(deps.store.settings, agentId).catch(() => []);
536
554
  const heldNames = heldNamesOf(records);
537
555
  // The loop's numbers on the agent's definition (the revision this run runs): the first compile waits for compile_after
538
556
  // completed agent runs, the ending one counted.
539
557
  const { compile_after: compileAfter } = await loopOfRun(deps.store, input.runId);
540
- // The agent's latest runs, newest first: those after the ending one in the list started before it.
541
- const listed = await deps.store.runs.list({ agentId: input.agentId, limit: Math.max(200, 2 * compileAfter) });
558
+ // The agent's latest runs, newest first: those after the ending one in the list started before it, and after its
559
+ // learning's reset (sinceReset): a run before the reset is never a compile's trace. None on a named disk: it learns
560
+ // nothing (learn/learning-of.ts).
561
+ const listed = await deps.store.runs.list({ agentId, disk: null, limit: Math.max(200, 2 * compileAfter) });
542
562
  const at = listed.findIndex((run) => run.id === input.runId);
543
- const earlier = (at < 0 ? listed : listed.slice(at + 1)).filter((run) => run.agentId === input.agentId);
563
+ const since = await sinceReset(deps.store, agentId);
564
+ const earlier = (at < 0 ? listed : listed.slice(at + 1)).filter((run) => run.agentId === agentId && since(run));
544
565
  const done = earlier.filter(completedRun);
545
- const byHand = (await lastOwnRuns(deps.store, input.agentId, compileAfter, input.runId)).length;
566
+ const byHand = (await lastOwnRuns(deps.store, agentId, compileAfter, input.runId)).length;
546
567
  const dueWith = (workflows) => compileDue({ completed: input.outcome === "completed", runs: byHand + (input.outcome === "completed" ? 1 : 0), workflows, compileAfter });
547
568
  const compiledOf = (kept) => kept?.proposal?.compiled;
548
569
  // Compile once: a recompile whose drafts failed their checks stopped the agent's new compiles (recordDraftFailed).
@@ -617,10 +638,14 @@ export async function compileAskOf(deps, input) {
617
638
  if (read.held) {
618
639
  // Once per hold: a run since it that compiled this workflow asked already, whatever came of it (its revision is on its
619
640
  // way to a replay, or its draft failed its checks), however many runs ago. Read from the agent's kept learning since
620
- // the hold, never a window of its last runs; one that can't be read asks nothing.
621
- const since = Date.parse(read.held.at);
622
- const kept = await deps.store.learning.proposals(input.agentId, { limit: HELD_ASKED_READ }).catch(() => undefined);
623
- if (!kept || kept.some((one) => !(one.createdAt < since) && compiledOf(one)?.workflow === read.held.workflow))
641
+ // the hold, never a window of its last runs; one that can't be read asks nothing. A draft that failed since, not stopped
642
+ // (only a revise of a connected agent's hold on give-backs: reviseAttemptOf), asks once more: counted from it, its own
643
+ // run's kept learning (written after its record, at the run's end) not counted.
644
+ const failed = records.findLast((one) => one.workflow === read.held.workflow && draftFailedOf(one) && !one.check?.stopped && !(one.at < read.held.at));
645
+ const since = Date.parse(failed?.at ?? read.held.at);
646
+ const kept = await deps.store.learning.proposals(agentId, { limit: HELD_ASKED_READ }).catch(() => undefined);
647
+ const asked = (one) => !(one.createdAt < since) && compiledOf(one)?.workflow === read.held.workflow && draftFailedDigest(one.runId) !== failed?.digest;
648
+ if (!kept || kept.some(asked))
624
649
  return sayLeftOut(), undefined;
625
650
  const { workflow, digest, reason, check, audit } = read.held;
626
651
  // A check's or an audit's disagreements are the agent's own inputs and answers: cut of the run's secrets as a trace is