@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
@@ -13,7 +13,6 @@
13
13
  // merge's call merges once.
14
14
  import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
15
15
  import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
16
- import { GENERAL_NO_BUDGET, GENERAL_THRESHOLD, ONE_CASE } from "../learn/general.js";
17
16
  import { CONTRADICTED_REASON, CONTRADICTED_TWICE_REASON, CONTRADICTION_ASK, gradedItems, gradePrompt, parseVerdict, UNREADABLE_REASON } from "../learn/grade.js";
18
17
  import { mergedNote, parseNoteFile, ruleOf } from "../learn/notes.js";
19
18
  import { learnedPlace } from "../learn/skills.js";
@@ -41,18 +40,6 @@ export class GradeOverCap extends Error {
41
40
  this.name = "GradeOverCap";
42
41
  }
43
42
  }
44
- /** A generality check its learning run's cap refused before any of its requests left (learning-dispatch.ts general: its
45
- * worst case over the cap left): nothing of it was sent or spent, and it is skipped as `unchecked` "no_budget"
46
- * (GENERAL_NO_BUDGET), said so, the grader then judged against the cap on its own. `forGood`: no room could ever send it
47
- * (its provider's price unknown here), not only none now. */
48
- export class GeneralOverCap extends Error {
49
- forGood;
50
- constructor(message, forGood) {
51
- super(message);
52
- this.forGood = forGood;
53
- this.name = "GeneralOverCap";
54
- }
55
- }
56
43
  const ROOT = ROOT_CONVERSATION_ID;
57
44
  /** The graded item a proposal's file is judged as (grade.ts itemOf): a draft's README.md with its workflow.json, every
58
45
  * other file as itself. */
@@ -352,106 +339,12 @@ export function createLearningLoop(learning) {
352
339
  // added, either unknown (null) once any ask's is, and an ask that fails spent what nobody knows.
353
340
  let usd = 0;
354
341
  let tokens = { input: 0, cache_read: 0, cache_write: 0, output: 0 };
355
- // What the generality pre-check's Jev requests spent (its kept dollars, null once unknown), outside the
356
- // grader's records, and the most they may have spent (`beside`: those dollars, else their worst case), which
357
- // each grader call's room under the cap leaves out. The grade ends with both: Jev's and the grader's.
358
- let checkUsd = 0;
359
- let beside = 0;
360
- const spent = () => (checkUsd === null || usd === null ? null : checkUsd + usd);
361
- // The generality pre-check: a note Jev scores under the bar rests on its one input, and is dropped before the
362
- // grader reads it, its why said with the grader's items. Jev down or not set up here: every note is graded.
363
- let screened = false;
364
- // Why the check could not run, kept on the grade's (or the drop's) entry: never a silent skip.
365
- let unchecked;
366
- if (grading.length && learning.general) {
367
- const threshold = learning.generalThreshold ?? GENERAL_THRESHOLD;
368
- const input = proposal.asked?.[0] ?? proposal.triggered?.[0]?.text;
369
- // The check is paid and Jev dedupes none, so it is made durable as the grade's ask is (learning-ask.ts
370
- // bookedAsk): marked sent before its requests leave, and its end kept before the grader starts. A restart
371
- // reuses a check that ended, paying nothing again; one an earlier attempt sent with no end after it was cut,
372
- // what it spent is unknown (null, as a cut grade request is booked before it is asked again), and it is
373
- // asked again with that unknown kept.
374
- let ended = [...entries].reverse().find((entry) => entry.kind === KINDS.learningGeneral)?.data;
375
- if (!ended) {
376
- const sentMarks = entries.filter((entry) => entry.kind === KINDS.learningGeneralSent);
377
- const cut = sentMarks.length > 0;
378
- if (cut)
379
- learning.log?.(`learning run ${claim.runId}: a generality check an earlier attempt sent was cut, so what it spent is unknown; it is asked again`);
380
- // Under a cap: the most the cut attempts' requests may have spent (each mark's worst case), and this one's.
381
- const cutHeld = sentMarks.reduce((sum, entry) => sum + (entry.data?.held ?? 0), 0);
382
- let sentHeld = 0;
383
- let checked;
384
- let failed;
385
- let overCap;
386
- try {
387
- checked = await learning.general(grading, { ...(source.instructions ? { job: source.instructions } : {}), ...(input !== undefined ? { input } : {}) }, AbortSignal.any([deps.signal, stopAsk.signal]), source.runId, async (held) => {
388
- sentHeld += held ?? 0;
389
- await append(KINDS.learningGeneralSent, { source: source.runId, ...(held !== undefined ? { held } : {}) });
390
- await deps.flush();
391
- }, cutHeld);
392
- }
393
- catch (error) {
394
- // Cut by a stop, a lost claim or a shutdown: what it sent spent what nobody knows. A stop row ends the run
395
- // stopped with that unknown; otherwise nothing more is written, and the next attempt finds it sent with no
396
- // end, books it unknown and asks again.
397
- if (stopped || deps.signal.aborted) {
398
- spend = null;
399
- return (await halted()) ?? { state: "interrupted" };
400
- }
401
- // No room under the run's cap for its worst case: nothing sent, skipped, said so (never silent), and the
402
- // grader judged against the cap on its own.
403
- if (error instanceof GeneralOverCap)
404
- overCap = error;
405
- else {
406
- // Its requests were sent and one failed: what they spent is unknown, never 0 (as an ask that fails is).
407
- // Its error is kept and logged cut of the runner's secrets (LoopDeps.redact).
408
- const message = error?.message ?? String(error);
409
- failed = deps.redact ? deps.redact(message) : message;
410
- learning.log?.(`learning run ${claim.runId}: the generality check could not run, so the grader reads every note: ${failed}`);
411
- }
412
- }
413
- const held = cutHeld + sentHeld;
414
- const bound = held > 0 ? { held } : {};
415
- if (checked)
416
- ended = { source: source.runId, scores: checked.scores, usd: cut ? null : checked.usd, ...bound };
417
- else if (overCap) {
418
- learning.log?.(`learning run ${claim.runId}: the generality check has no room under the cap (${overCap.message}), so the grader reads every note`);
419
- ended = { source: source.runId, unchecked: GENERAL_NO_BUDGET, usd: cut ? null : 0, ...bound };
420
- }
421
- else if (failed !== undefined)
422
- ended = { source: source.runId, unchecked: failed, usd: null, ...bound };
423
- else if (cut)
424
- ended = { source: source.runId, unchecked: "no Jev is set up on this host now", usd: null, ...bound };
425
- // Kept, durably, before the grader starts: a restart from here on asks Jev nothing.
426
- if (ended) {
427
- await append(KINDS.learningGeneral, ended);
428
- await deps.flush();
429
- }
430
- }
431
- if (ended) {
432
- checkUsd = ended.usd;
433
- beside = ended.usd ?? ended.held ?? 0;
434
- if (ended.unchecked !== undefined)
435
- unchecked = ended.unchecked;
436
- if (ended.scores) {
437
- screened = true;
438
- const scores = ended.scores;
439
- const below = grading.filter(({ file }) => typeof scores[file] === "number" && scores[file] < threshold);
440
- settledItems.push(...below.map(({ file }) => ({ file, keep: false, question: "General", why: ONE_CASE(scores[file], threshold) })));
441
- grading = grading.filter((note) => !below.includes(note));
442
- }
443
- }
444
- }
445
342
  // The notes the graded ones supersede, of those main gave: a dropped note's are not the grade's.
446
343
  const replacing = new Set(grading.flatMap((note) => { const parsed = parseNoteFile(note.file, note.text); return Array.isArray(parsed) ? [] : parsed.supersedes; }));
447
344
  const superseded = main.superseded.filter(({ file }) => replacing.has(file));
448
345
  if (!grading.length && !proposal.files?.length) {
449
- const verdict = { merge: false, reason: settledItems.some(({ question }) => question === "General") ? "No new note holds beyond the one input it came from, or each is named like one the agent holds now." : "Every new note is named like one the agent holds now.", items: settledItems };
450
- // A proposal the generality check emptied is recorded as a grade (its verdict, each item's why, what the check
451
- // spent) before it is dropped, so the run's learning reads why each note was left out.
452
- if (screened)
453
- await append(KINDS.learningGraded, { source: source.runId, verdict, usd: spent(), tokens, graded: main.graded });
454
- await append(KINDS.learningDropped, { source: source.runId, reason: "grader", detail: notKept(verdict, lostOf(proposal)), usd: spent(), tokens }, "ended");
346
+ const verdict = { merge: false, reason: "Every new note is named like one the agent holds now.", items: settledItems };
347
+ await append(KINDS.learningDropped, { source: source.runId, reason: "grader", detail: notKept(verdict, lostOf(proposal)), usd, tokens }, "ended");
455
348
  return { state: "ended" };
456
349
  }
457
350
  const items = gradedItems(grading, (proposal.files ?? []));
@@ -466,8 +359,7 @@ export function createLearningLoop(learning) {
466
359
  catch (error) {
467
360
  // A full native policy can fill the remaining prompt budget. Refuse the whole proposal visibly;
468
361
  // no grader was called and no standing instruction or proposal is silently omitted.
469
- // Keep what the generality pre-check already spent.
470
- await append(KINDS.learningDropped, { source: source.runId, reason: "checker", detail: error instanceof Error ? error.message : "The grading evidence exceeds the supported prompt budget.", usd: spent(), tokens, ...(unchecked !== undefined ? { unchecked } : {}) }, "ended");
362
+ await append(KINDS.learningDropped, { source: source.runId, reason: "checker", detail: error instanceof Error ? error.message : "The grading evidence exceeds the supported prompt budget.", usd, tokens }, "ended");
471
363
  return { state: "ended" };
472
364
  }
473
365
  /** The asks of this attempt that answered: the records holding more requests than these is an earlier attempt's. */
@@ -490,7 +382,7 @@ export function createLearningLoop(learning) {
490
382
  const timer = AbortSignal.timeout(GRADE_TIMEOUT_MS);
491
383
  let answer;
492
384
  try {
493
- answer = await learning.ask({ prompt: again ? `${prompt}\n\n${again}` : prompt, maxTokens: GRADE_MAX_TOKENS, ...(beside > 0 ? { beside } : {}) }, AbortSignal.any([deps.signal, timer, stopAsk.signal]), { journal: () => deps.journal(claim), flush: () => deps.flush() });
385
+ answer = await learning.ask({ prompt: again ? `${prompt}\n\n${again}` : prompt, maxTokens: GRADE_MAX_TOKENS }, AbortSignal.any([deps.signal, timer, stopAsk.signal]), { journal: () => deps.journal(claim), flush: () => deps.flush() });
494
386
  }
495
387
  catch (error) {
496
388
  // A call the cap refused was never sent: it spent nothing, and what the grade spent before it stands, as its
@@ -527,23 +419,23 @@ export function createLearningLoop(learning) {
527
419
  catch (error) {
528
420
  // What the asks spent (and the check before them): a cut one's unknown (null), kept on a stopped run's row as
529
421
  // on a dropped one's.
530
- spend = spent();
422
+ spend = usd;
531
423
  const end = await halted();
532
424
  if (end)
533
425
  return end;
534
426
  // No room under the run's cap for the grade (a call the cap refused): skipped, said so, with what it spent
535
427
  // before (an earlier ask's), never a failure and never past the cap.
536
428
  if (error instanceof GradeOverCap) {
537
- await append(KINDS.learningDropped, { source: source.runId, reason: "no_budget", detail: error.forGood ? said.gradeUncapped : said.noRoomToGrade, usd: spent(), tokens, ...(unchecked !== undefined ? { unchecked } : {}) }, "ended");
429
+ await append(KINDS.learningDropped, { source: source.runId, reason: "no_budget", detail: error.forGood ? said.gradeUncapped : said.noRoomToGrade, usd, tokens }, "ended");
538
430
  return { state: "ended" };
539
431
  }
540
- await append(KINDS.learningDropped, { source: source.runId, reason: "grade_failed", detail: said.stopped(STOPPED.noReview), usd: spent(), tokens, ...(unchecked !== undefined ? { unchecked } : {}) }, "ended");
432
+ await append(KINDS.learningDropped, { source: source.runId, reason: "grade_failed", detail: said.stopped(STOPPED.noReview), usd, tokens }, "ended");
541
433
  void error;
542
434
  return { state: "ended" };
543
435
  }
544
436
  if (settledItems.length)
545
437
  verdict = { ...verdict, items: [...verdict.items, ...settledItems] };
546
- graded = { source: source.runId, verdict, usd: spent(), tokens, graded: main.graded, ...(unchecked !== undefined ? { unchecked } : {}) };
438
+ graded = { source: source.runId, verdict, usd, tokens, graded: main.graded };
547
439
  spend = graded.usd;
548
440
  await append(KINDS.learningGraded, graded);
549
441
  // The verdict is durable before the merge, its side effect.
@@ -84,6 +84,17 @@ export declare function besideRunEnv(env: NodeJS.ProcessEnv, switches: NodeJS.Pr
84
84
  * journal, the seal key and the model route. `booted`: the seal key startRunnerProcess booted against the store (else
85
85
  * this process's, as it was handed or booted). Refused in words with no seal key. */
86
86
  export declare function runnerLoop(store: Store, dataDir: string, env?: NodeJS.ProcessEnv, booted?: Buffer): RunnerParts;
87
+ /** What a runner in its own process may reach on loopback, from its own environment alone, as a server takes its opt-in
88
+ * (cli.ts mcpLoopback): with AGENTRUN_MCP_ALLOW_LOOPBACK=1, an MCP server on this machine's loopback (the machine this
89
+ * process runs on, its container's in a container), never at `own`: the port a server listens on unless --port says
90
+ * otherwise (DEFAULT_PORT) and, when this environment names one on loopback, the port of its public address
91
+ * (AGENTRUN_PUBLIC_URL); runnerLoop adds, at each claim, the addresses the server kept in the store at its last start
92
+ * (serverOwn), so a run never reaches a server beside this runner through an MCP server's address, whatever its port.
93
+ * Undefined without it. The opt-in is never read from the store or the data directory: a runner never inherits
94
+ * another process's. */
95
+ export declare function runnerLoopback(env: NodeJS.ProcessEnv): {
96
+ readonly own: readonly string[];
97
+ } | undefined;
87
98
  /** A runner's loop factory with the run's computers it composed and the runs' environment: what the janitor sweeps with. */
88
99
  export type RunnerParts = {
89
100
  readonly createLoop: LoopFactory;
@@ -20,7 +20,7 @@ import { hostCommandRefusals } from "../computers.js";
20
20
  import { hostAddressesOnce } from "../docker-host-addresses.js";
21
21
  import { claimInstallsStopped } from "../harness-install.js";
22
22
  import { HARNESS_TABLE_ENV } from "../harness-table.js";
23
- import { maxRunsOf } from "../host.js";
23
+ import { DEFAULT_PORT, maxRunsOf } from "../host.js";
24
24
  import { FAUX_ENV, FAUX_PREFIX, withoutFaux } from "../model.js";
25
25
  import { durationMs, runLine } from "../print.js";
26
26
  import { bootSealKey } from "../seal-key.js";
@@ -29,7 +29,10 @@ import { migrationsIn, openStore, SchemaVersionUnknown, storePlace, storeTarget
29
29
  import { SCHEMA_VERSION } from "../store/schema.js";
30
30
  import { SEAL_KEY_ENV, sealKeyOf } from "../tool-keys.js";
31
31
  import { claimViewOpener } from "../computer-live.js";
32
- import { runnerLiveOf } from "../live-reach.js";
32
+ import { LOOPBACK as LIVE_LOOPBACK, runnerLiveOf } from "../live-reach.js";
33
+ import { LOOPBACK } from "../mcp-oauth.js";
34
+ import { serverOwn } from "../mcp-private-hosts.js";
35
+ import { MCP_ALLOW_LOOPBACK_ENV } from "../mcp-servers-store.js";
33
36
  import { envValue } from "../key-meta.js";
34
37
  import { fauxComputers } from "../faux-computers.js";
35
38
  import { computerDepsFrom } from "../workspace/computer-deps.js";
@@ -126,15 +129,39 @@ export function runnerLoop(store, dataDir, env = process.env, booted) {
126
129
  // mounts by where this process's Docker has the data directory (box-paths.ts), read once; a desktop's or a phone's live
127
130
  // view opened with it.
128
131
  const computers = runnerComputers(store, runs, sealKey, { dockerPaths: () => dockerPathsForRuns(runs, dataDir), hostAddresses: () => hostAddressesOnce(runs), hostWhy: hostCommandRefusals(PROVIDERS, process.env.PATH) });
132
+ const loopback = runnerLoopback(env);
133
+ if (loopback)
134
+ process.stderr.write(`agentrun-serve runner: ${MCP_ALLOW_LOOPBACK_ENV}=1: this runner's runs may reach an MCP server on this machine's loopback, never at ${loopback.own.join(" or ")} nor where its server listens\n`);
129
135
  const deps = {
130
136
  env: runs, data: dataDir, journal: (claim) => store.journal(claim), store, sealKey, routeOf,
131
137
  computerForClaim: computers.computerForClaim, computerDeps: computers.computerDeps,
132
- // A run's log lines (a learning run's skipped generality check, a sweep that failed) on the runner's stderr, as its
138
+ // A run's log lines (a sweep that failed) on the runner's stderr, as its
133
139
  // warnings are.
134
140
  log: (line) => void process.stderr.write(`agentrun-serve runner: ${line}\n`),
141
+ // An MCP server on loopback: reached only when this process's own operator set AGENTRUN_MCP_ALLOW_LOOPBACK=1
142
+ // (runnerLoopback), never at a server's own port on it.
143
+ // The server's own addresses, as it kept them in the store at its last start, are read at each claim beside these.
144
+ ...(loopback ? { mcpLoopback: true, mcpOwn: loopback.own, mcpOwnOf: () => serverOwn(store) } : {}),
135
145
  };
136
146
  return { createLoop: createDispatchLoop({ launchOf: (runId) => store.runs.launch(runId), resolve: resolveRunnerLoop(deps) }), computers: computers.computerDeps, env: runs };
137
147
  }
148
+ /** What a runner in its own process may reach on loopback, from its own environment alone, as a server takes its opt-in
149
+ * (cli.ts mcpLoopback): with AGENTRUN_MCP_ALLOW_LOOPBACK=1, an MCP server on this machine's loopback (the machine this
150
+ * process runs on, its container's in a container), never at `own`: the port a server listens on unless --port says
151
+ * otherwise (DEFAULT_PORT) and, when this environment names one on loopback, the port of its public address
152
+ * (AGENTRUN_PUBLIC_URL); runnerLoop adds, at each claim, the addresses the server kept in the store at its last start
153
+ * (serverOwn), so a run never reaches a server beside this runner through an MCP server's address, whatever its port.
154
+ * Undefined without it. The opt-in is never read from the store or the data directory: a runner never inherits
155
+ * another process's. */
156
+ export function runnerLoopback(env) {
157
+ if (env[MCP_ALLOW_LOOPBACK_ENV] !== "1")
158
+ return undefined;
159
+ const own = [`http://${LIVE_LOOPBACK}:${DEFAULT_PORT}`];
160
+ const pub = URL.parse(env.AGENTRUN_PUBLIC_URL ?? "");
161
+ if (pub && LOOPBACK.test(pub.hostname))
162
+ own.push(pub.origin);
163
+ return { own };
164
+ }
138
165
  /** Where runner `name` writes its heartbeat in `dataDir`. */
139
166
  export const heartbeatFile = (dataDir, name) => join(dataDir, `runner-${name.replace(/[^A-Za-z0-9._:-]/g, "_")}.alive`);
140
167
  /** The runner's heartbeat writer: its file's time set to now, at most every half renew interval. */
@@ -35,8 +35,8 @@ export interface McpForClaimOptions {
35
35
  /** A test's fake GitHub MCP origin, handed to the claim step (mcpClaim's githubMcpOrigin): for tests only: no environment variable, flag or setting maps onto it; absent, GitHub's hosted MCP
36
36
  * (github.ts GITHUB_MCP_ORIGIN). */
37
37
  readonly githubMcpOrigin?: string;
38
- /** Whether this runner may reach an MCP server whose URL is on loopback (AdapterSpecDeps.mcpLoopback): only a runner
39
- * beside a local-install server is. Absent, never. */
38
+ /** Whether this runner may reach an MCP server whose URL is on loopback (AdapterSpecDeps.mcpLoopback): the runner
39
+ * beside a local-install server, or a runner in its own process whose own environment opts in. Absent, never. */
40
40
  readonly loopback?: boolean;
41
41
  /** The own addresses of the local-install server beside this runner (AdapterSpecDeps.mcpOwn, Serve.own): a loopback
42
42
  * URL on one of their ports is refused, as the server refuses it, so a run never reaches that server through an MCP
@@ -2,10 +2,10 @@ import type { Context } from "@earendil-works/chord/context";
2
2
  import type { LearnedWorkflow } from "../learning.js";
3
3
  import { type RunLaunch } from "../run-launch.js";
4
4
  import { type Store } from "../store/store.js";
5
- import { type ReplayCalls } from "../learn/replay-calls.js";
5
+ import { type ReplayCalls, type Skipped } from "../learn/replay-calls.js";
6
6
  import { type Json } from "../validate.js";
7
- import { type ReplayOutcomes, type ReplayScore } from "../learn/promote.js";
8
- import { type FirstChoice, type Promoted } from "./workflow-first.js";
7
+ import { type CheckBar, type PromotionRecord, type ReplayOutcomes, type ReplayScore } from "../learn/promote.js";
8
+ import { type FirstChoice, type Promoted, type ReplayOutcome } from "./workflow-first.js";
9
9
  import type { LearningFolder } from "../learn/folder.js";
10
10
  import type { Shown } from "../learning.js";
11
11
  /** A replay run still not ended this long after its replay started counts as failed (no evidence), and is cancelled once
@@ -17,26 +17,20 @@ export declare const REPLAY_LAUNCH_GRACE_MS: number;
17
17
  export interface PromotionDeps {
18
18
  readonly store: Store;
19
19
  readonly agentId: string;
20
- /** The run being claimed: never one of its own replay's inputs. Absent: no run is claimed (a person's replay, and its
20
+ /** The run being claimed: never one of its own check's inputs. Absent: no run is claimed (a person's replay, and its
21
21
  * read): no run served first to keep, none whose per_run MCP credentials a replay is handed. */
22
22
  readonly runId?: string;
23
23
  /** The revision the claimed run runs: its replay runs run it too. */
24
24
  readonly revisionId: string;
25
- /** The claimed run's launch: a replay run's is this one with the graded run's input. */
25
+ /** The claimed run's launch: a replay run's is this one with the agent run's input. */
26
26
  readonly launch: RunLaunch;
27
27
  readonly context: Context;
28
28
  readonly log: (line: string) => void;
29
- /** Writes a refit's new workflow text onto the agent's learning folder (a merge as `id`, from the claim's seed); the
30
- * learning commit it landed as, or null when it did not. Absent: no refit is written. */
31
- readonly commit?: (files: {
32
- path: string;
33
- text: string;
34
- }[], reason: string, id: string) => Promise<string | null>;
35
29
  /** The learned workflow `name` as the learning folder held it active at `commit` (a champion's text), or undefined when
36
30
  * it held none by that name. Absent: no champion serves. */
37
31
  readonly champion?: (name: string, commit: string) => Promise<LearnedWorkflow | undefined>;
38
32
  /** The digest of the learned workflow `name` the learning folder's main holds now (the newest revision), or undefined
39
- * when it holds none by that name. Absent: no revision queues behind another's replay. */
33
+ * when it holds none by that name. Absent: every revision is the newest. */
40
34
  readonly newest?: (name: string) => Promise<string | undefined>;
41
35
  /** The learned workflow an earlier claim of this run served first (its WORKFLOW_FIRST entry, answered or handed back:
42
36
  * workflow-first.ts servedOf), or undefined for a run no claim served yet: a run already executing keeps its revision
@@ -49,14 +43,15 @@ export interface PromotionDeps {
49
43
  * (startReplay). Absent: a replay run is handed none (a per_run server's calls are refused unsent, the input failed). */
50
44
  readonly sealKey?: Buffer;
51
45
  readonly now?: () => number;
46
+ /** The host's secrets as a reader cuts them (learning.ts secretsShown): a check's texts are cut of them whole, before
47
+ * they are shortened (decideCheck). */
48
+ readonly shown: () => Promise<Shown>;
52
49
  }
53
- /** The claim's promotion ports: `folder`, the agent's learning folder where the run's place keeps it, a refit's revision
54
- * written on it as a merge from the claim's seed (a workflow.json changed on main since is a conflict, never written over),
55
- * and a champion read from it at its record's commit, cut of the server's secrets (`shown`) as the claim's lay is; and
56
- * the workflow an earlier claim of this run served (`kept`, from its journal: none on a first claim). */
57
- export declare function claimPromotion(deps: Omit<PromotionDeps, "commit" | "champion" | "kept"> & {
50
+ /** The claim's promotion ports: `folder`, the agent's learning folder where the run's place keeps it, a champion read
51
+ * from it at its record's commit, cut of the server's secrets (`shown`) as the claim's lay is; and the workflow an earlier
52
+ * claim of this run served (`kept`, from its journal: none on a first claim). */
53
+ export declare function claimPromotion(deps: Omit<PromotionDeps, "champion" | "kept"> & {
58
54
  readonly folder: () => LearningFolder;
59
- readonly shown: () => Promise<Shown>;
60
55
  }): PromotionDeps;
61
56
  /** A replay run's claim (launch.replay) of run `runId`, once its first choice is made: refused (ClaimRefused: the run ends
62
57
  * failed, no agent turn, nothing sent) unless its revision's record still says replaying and names it among its runs (it
@@ -65,26 +60,61 @@ export declare function claimPromotion(deps: Omit<PromotionDeps, "commit" | "cha
65
60
  * replay's leftover once its revision replays again; one whose workflow is not laid at its digest (the seed could not be
66
61
  * read, the folder moved on) never falls to the agent's path. Any other run: nothing to check. */
67
62
  export declare function replayClaimed(store: Pick<Store, "settings">, agentId: string, runId: string, launch: RunLaunch, choice: FirstChoice): Promise<void>;
68
- /** The workflows a replay run's claim lays (`laid`, the seed lay's): the one it replays record-only (learn/promote.ts
69
- * recordOnly: every guard at the least threshold the DSL takes, so each step's p is read and none hands back on it), or none by that name when
70
- * the laid one is not the digest it replays (the replay then fails, never scoring another revision). Any other run's,
71
- * as laid. */
63
+ /** The workflows a replay run's claim lays (`laid`, the seed lay's): the one it replays, or none by that name when the
64
+ * laid one is not the digest it replays (the replay then fails, never scoring another revision). Any other run's, as laid. */
72
65
  export declare function replayLaid(launch: RunLaunch, laid: readonly LearnedWorkflow[]): LearnedWorkflow[];
73
66
  /** The learned workflows a run's learned_workflow tool runs, once its first choice is made: what serves, never a
74
67
  * revision its promotion has not promoted. The one its first choice served or the money rule stopped (laidFor: its
75
68
  * champion in place of the laid revision) as chosen; any other the records name, its champion (championOf: the laid
76
69
  * text when that is the champion, else its text at its record's commit), and none while nothing of it serves (none
77
- * promoted yet, or the champion held): a revision replaying, queued, held or never decided is never handed to the
78
- * agent to run in its place. One the records never named (no run's input fit it, so no claim asked) runs as laid. A
79
- * replay run's as laid (replayLaid). The records unread: only the chosen one, as the gate leaves a run to its agent. */
70
+ * promoted yet, or the champion held): a revision replaying, held or never decided is never handed to the agent to run
71
+ * in its place. One the records never named (no run's input fit it, so no claim asked) runs as laid. A replay run's as
72
+ * laid (replayLaid). The records unread: only the chosen one, as the gate leaves a run to its agent. */
80
73
  export declare function toolFlowsFor(deps: Pick<PromotionDeps, "store" | "agentId" | "champion" | "log">, launch: RunLaunch, laid: readonly LearnedWorkflow[], choice: FirstChoice): Promise<LearnedWorkflow[]>;
81
74
  /** The gate workflowFirstOf asks (its `promoted`), at every run's claim, a queued run's included: the workflow that serves
82
75
  * this run first. A run already executing keeps the revision an earlier claim of it served (keptFor). Else the laid
83
- * revision (`workflow` at `digest`, the folder's revision as the run's seed holds it) has its promotion moved on (decide:
84
- * a replay started, queued or settled, a dry-run promote), and then servingNow alone says who serves: the champion
85
- * (championOf), the laid text when it is the champion, its own text read from its record's commit when not; undefined
86
- * when none serves (the agent takes the run). A digest's own record never says it serves. */
76
+ * revision (`workflow` at `digest`, the folder's revision as the run's seed holds it) has its check moved on (decide:
77
+ * started, or settled once its runs ended), and then servingNow alone says who serves: the champion (championOf), the
78
+ * laid text when it is the champion, its own text read from its record's commit when not; undefined when none serves
79
+ * (the agent takes the run). A digest's own record never says it serves. */
87
80
  export declare const promotionGate: (deps: PromotionDeps) => Promoted;
81
+ /** The words a stopped check's record starts with when it had nothing to check its draft on. */
82
+ export declare const NOTHING_TO_CHECK = "nothing to check it on";
83
+ /** One input a check ran its draft on: the agent's run (`of`) and its input, the agent's recorded answer, and what the
84
+ * draft did: its answer when it answered alone, why it handed the input back, or failed (or skipped a write). A
85
+ * reserved input whose replay run was never created, or never ended, by the check's deadline failed (`unstarted` for
86
+ * the first). */
87
+ type CheckRow = {
88
+ readonly of: string;
89
+ readonly input: string;
90
+ readonly agent: string | null;
91
+ readonly outcome: ReplayOutcome;
92
+ readonly answer: string | null;
93
+ readonly escalated?: string;
94
+ readonly skipped?: Skipped;
95
+ readonly unstarted?: true;
96
+ };
97
+ /** Decides a check on its rows: each input it ran on (a skipped write is none) agreed when the draft answered it alone
98
+ * with the agent's recorded answer (learn/promote.ts sameAnswer), alone when it answered it with no escalate and no
99
+ * failed step. Promoted when it clears the bar (checkPasses); else held with the inputs it did not agree on, which the
100
+ * agent's next run's compile turn reads as data (its one recompile); a recompile's check that holds it too stops:
101
+ * nothing compiles again. No grade, refit, queue or second replay. Kept only while `still` holds of the digest's record
102
+ * (the one write: of two claims at once, one decides). */
103
+ export declare function decideCheck(deps: PromotionDeps, name: string, digest: string, bar: CheckBar, read: {
104
+ rows: readonly CheckRow[];
105
+ cost: number | null;
106
+ outcomes: ReplayOutcomes;
107
+ unstarted: number;
108
+ }, still: (was: PromotionRecord | undefined) => boolean, extra: Partial<PromotionRecord>): Promise<import("../learn/promote.js").Recorded>;
109
+ /** A run's final answer row, its text whole (its last final answer row that is not its end-of-run turn's), or null: none,
110
+ * or its record could not be read. `turn`: the row of that id instead (the answer an audit is of, runner/audit.ts), so an
111
+ * answer a follow-up gave since is never read for it. */
112
+ export declare function answerRowOf(store: PromotionDeps["store"], runId: string, context: Context, turn?: string): Promise<{
113
+ id: string;
114
+ text: string;
115
+ } | null>;
116
+ /** A run's final answer, whole (answerRowOf's text; `turn`: that row's), or null. */
117
+ export declare const answerOf: (store: PromotionDeps["store"], runId: string, context: Context, turn?: string) => Promise<string | null>;
88
118
  /** Why a replay a person asked for (askReplay) or read (replayView) was refused: `missing`, no such workflow, revision or
89
119
  * replay of the agent (404); `conflict`, the revision cannot replay now (409), in words that say why. */
90
120
  export declare class ReplayRefused extends Error {
@@ -93,7 +123,7 @@ export declare class ReplayRefused extends Error {
93
123
  }
94
124
  /** What a person's replay reads and writes through (POST and GET .../revisions/{digest}/replays): the claim's ports, with
95
125
  * no claimed run. `launchOf`: a run's launch of the agent on `input` as its start makes one now, and the revision it runs
96
- * on: a replay run's is this one with its graded run's input (startReplay), at the revision's learning commit. */
126
+ * on: a replay run's is this one with its agent run's input (startReplay), at the revision's learning commit. */
97
127
  export interface ReplayAsk {
98
128
  readonly store: Store;
99
129
  readonly agentId: string;
@@ -107,26 +137,24 @@ export interface ReplayAsk {
107
137
  }>;
108
138
  readonly now?: () => number;
109
139
  }
110
- /** A replay of `name` at `digest` a person asked for: the claim path's replay (reserve, startReplay), on `inputs`: `held`,
111
- * the graded runs its last replay or hold was decided on (else, with none, the agent's newest REPLAY_INPUTS), or a number,
112
- * the agent's newest that many (each a graded input the workflow fits); with either, the served runs graded wrong it was
113
- * held on (heldOn), which it promotes only once it answered on: the claim's picker (inputsFor). Its runs end as a claim's
114
- * do, and it is decided by the claim path's settle: at a claim that lays the revision, or at its read (replayView).
115
- * Refused (ReplayRefused): no such workflow or revision; one replaying already, or another revision of it replaying (one
116
- * at a time, never queued by a person: a queued revision is one a run's claim found newest); a promoted one (it serves already); fewer than REPLAY_MIN graded inputs it fits (a replay on fewer could
117
- * only hold it: settle scores none of it), refused before anything is reserved; an agent that does not learn here. The
118
- * replay's id and its inputs. */
140
+ /** A check of `name` at `digest` a person asked for: the claim path's check (reserve, startReplay), on `inputs`: `held`,
141
+ * the agent runs its last check ran on (else, with none, the agent's last compile_after completed runs), or a number,
142
+ * the agent's newest that many (each a completed run of its own the workflow fits). Its runs end as a claim's do, and it
143
+ * is decided by settleCheck: at a claim that lays the revision, or at its read (replayView). Refused (ReplayRefused): no
144
+ * such workflow or revision; one replaying already, or another revision of it replaying (one at a time); a promoted one
145
+ * (it serves already); no input it fits (nothing is reserved); an agent that does not learn here. The replay's id and
146
+ * its inputs. */
119
147
  export declare function askReplay(ask: ReplayAsk, name: string, digest: string, inputs: "held" | number): Promise<{
120
148
  replay: string;
121
149
  inputs: number;
122
150
  }>;
123
151
  /** A replay as its read answers it (GET .../replays/{replay_id}). `status`: `running` while its record says replaying,
124
152
  * `done` once promoted or held, `failed` when none of its runs started by its deadline (nothing was replayed; held, its
125
- * `reason` says so). A replay is never cancelled for a newer revision: that one queues behind it. `outcomes`: what its own runs did (outcomesOf), so far
126
- * while it runs, and once decided as its record kept them, whatever the agent's grades kept now; never the thresholds'
127
- * reading (a run answered under its guard's threshold stays answered: `score` hands it back). `score` and `cost_usd`
128
- * the decided record's, else the runs ended so far at the revision's serving thresholds, and null while a run's cost
129
- * is unknown (replayCost). */
153
+ * `reason` says so). `outcomes`: what its own runs did (outcomesOf), so far while it runs, and once decided as its
154
+ * record kept them. `score`: the decided check's numbers in the replay's shape with the agent's own answers as the label
155
+ * (`agree` the inputs the draft answered alone as the agent did, `agent_acc` 1, `wf_acc` those plus the ones handed back,
156
+ * a hand-back being the agent's answer, over the inputs it ran on), zero while it runs. `cost_usd` the decided record's,
157
+ * else the runs ended so far, and null while a run's cost is unknown (replayCost). */
130
158
  type ReplayView = {
131
159
  readonly replay: string;
132
160
  readonly workflow: string;
@@ -139,14 +167,14 @@ type ReplayView = {
139
167
  readonly decided?: "promote" | "hold";
140
168
  readonly reason?: string;
141
169
  };
142
- /** Reads replay `id` of `name` at `digest`, settling it first as a claim of its revision would (the claim path's settle)
143
- * once its runs ended or its deadline passed: it writes only the decision. A read never starts a run: a replay whose
144
- * launch was interrupted (reserved runs never created) reads running until its deadline, then is decided held, read as
145
- * failed, its reason saying none of its runs started and to start it again with POST. So a replay of a revision no claim
146
- * lays (an older, held one) is decided too, and never running forever. Once decided, it reads only its record. Refused
170
+ /** Reads replay `id` of `name` at `digest`, settling it first as a claim of its revision would (settleCheck) once its runs
171
+ * ended or its deadline passed: it writes only the decision. A read never starts a run: a replay whose launch was
172
+ * interrupted (reserved runs never created) reads running until its deadline, then is decided held, read as failed, its
173
+ * reason saying none of its runs started and to start it again with POST. So a replay of a revision no claim lays (an
174
+ * older, held one) is decided too, and never running forever. Once decided, it reads only its record. Refused
147
175
  * (missing) when the agent has no such replay. */
148
176
  export declare function replayView(ask: ReplayAsk, name: string, digest: string, id: string): Promise<ReplayView>;
149
- /** A replay run's call nodes (launch.replay; learn/replay-calls.ts): the graded run's recorded calls, read from its journal
177
+ /** A replay run's call nodes (launch.replay; learn/replay-calls.ts): the agent run's recorded calls, read from its journal
150
178
  * (a CLI's record shaped as pi's), and each tool classed by the claim's MCP pin (`runId`'s, its servers' annotations as
151
179
  * they listed them) or the built-in list. Undefined for any other run. A recording that cannot be read is an empty one:
152
180
  * every write is then skipped, never run. */