@parcha/agentrun-serve 0.1.0-beta.40 → 0.1.0-beta.42

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 (199) hide show
  1. package/CHANGELOG.md +130 -0
  2. package/NOTICE +2 -0
  3. package/README.md +149 -21
  4. package/dist/agent-rows.d.ts +1 -1
  5. package/dist/agents-store.js +3 -1
  6. package/dist/api-only.d.ts +3 -1
  7. package/dist/api-only.js +4 -2
  8. package/dist/api-token.d.ts +30 -0
  9. package/dist/api-token.js +89 -0
  10. package/dist/calendar/address.d.ts +49 -0
  11. package/dist/calendar/address.js +153 -0
  12. package/dist/calendar/fetch.d.ts +24 -0
  13. package/dist/calendar/fetch.js +146 -0
  14. package/dist/calendar/ics-faux.d.ts +39 -0
  15. package/dist/calendar/ics-faux.js +236 -0
  16. package/dist/calendar/labels.d.ts +3 -0
  17. package/dist/calendar/labels.js +61 -0
  18. package/dist/calendar/names.d.ts +52 -0
  19. package/dist/calendar/names.js +54 -0
  20. package/dist/calendar/parse.d.ts +108 -0
  21. package/dist/calendar/parse.js +625 -0
  22. package/dist/calendar/routes.d.ts +17 -0
  23. package/dist/calendar/routes.js +81 -0
  24. package/dist/calendar/tools.d.ts +23 -0
  25. package/dist/calendar/tools.js +124 -0
  26. package/dist/cli.js +22 -6
  27. package/dist/composio-made.d.ts +54 -0
  28. package/dist/composio-made.js +83 -0
  29. package/dist/composio-preset.d.ts +16 -8
  30. package/dist/composio-preset.js +106 -43
  31. package/dist/composio-triggers.d.ts +7 -2
  32. package/dist/composio-triggers.js +13 -7
  33. package/dist/computer-attach.d.ts +29 -11
  34. package/dist/computer-attach.js +141 -47
  35. package/dist/computer-keys.d.ts +4 -0
  36. package/dist/computer-keys.js +5 -0
  37. package/dist/computer-record.d.ts +55 -0
  38. package/dist/computer-record.js +315 -0
  39. package/dist/computer-setting.d.ts +1 -0
  40. package/dist/computer-setting.js +15 -2
  41. package/dist/computers.d.ts +11 -1
  42. package/dist/computers.js +23 -26
  43. package/dist/console/assets/{index-B8Zn1Iqn.css → index-C3gNPz58.css} +1 -1
  44. package/dist/console/assets/index-DYJ_wj27.js +711 -0
  45. package/dist/console/index.html +2 -2
  46. package/dist/decisions.js +9 -2
  47. package/dist/eval-feed.d.ts +26 -0
  48. package/dist/eval-feed.js +72 -0
  49. package/dist/eval-mailbox.d.ts +4 -1
  50. package/dist/eval-mailbox.js +11 -3
  51. package/dist/exa-keyless.d.ts +1 -1
  52. package/dist/exa-keyless.js +1 -1
  53. package/dist/feed/feed-faux.d.ts +62 -0
  54. package/dist/feed/feed-faux.js +123 -0
  55. package/dist/feed/fetch.d.ts +41 -0
  56. package/dist/feed/fetch.js +128 -0
  57. package/dist/feed/parse.d.ts +42 -0
  58. package/dist/feed/parse.js +291 -0
  59. package/dist/feed/pointer.d.ts +2 -0
  60. package/dist/feed/pointer.js +17 -0
  61. package/dist/file-types.js +1 -0
  62. package/dist/host-command.d.ts +3 -0
  63. package/dist/host-command.js +18 -0
  64. package/dist/host.d.ts +3 -0
  65. package/dist/host.js +3 -0
  66. package/dist/learn/check.d.ts +17 -1
  67. package/dist/learn/check.js +240 -5
  68. package/dist/learn/compile.d.ts +48 -27
  69. package/dist/learn/compile.js +134 -101
  70. package/dist/learn/promote.d.ts +61 -5
  71. package/dist/learn/promote.js +12 -2
  72. package/dist/learned-nodes.d.ts +21 -4
  73. package/dist/learned-nodes.js +21 -8
  74. package/dist/learned-workflow.d.ts +3 -3
  75. package/dist/learned-workflow.js +14 -5
  76. package/dist/learning-setting.d.ts +23 -0
  77. package/dist/learning-setting.js +51 -0
  78. package/dist/learning-words.d.ts +3 -0
  79. package/dist/learning-words.js +3 -0
  80. package/dist/learning.d.ts +3 -2
  81. package/dist/learning.js +5 -3
  82. package/dist/mcp-oauth.d.ts +23 -1
  83. package/dist/mcp-oauth.js +46 -5
  84. package/dist/mcp-pin-first.d.ts +4 -2
  85. package/dist/mcp-pin-first.js +4 -3
  86. package/dist/mcp-private-hosts.d.ts +13 -0
  87. package/dist/mcp-private-hosts.js +16 -0
  88. package/dist/mcp-servers-store.d.ts +58 -5
  89. package/dist/mcp-servers-store.js +136 -17
  90. package/dist/mcp.d.ts +2 -2
  91. package/dist/mcp.js +2 -2
  92. package/dist/observation/http.d.ts +4 -1
  93. package/dist/observation/http.js +5 -4
  94. package/dist/openapi.d.ts +1 -0
  95. package/dist/openapi.js +151 -21
  96. package/dist/print.d.ts +6 -3
  97. package/dist/print.js +4 -2
  98. package/dist/run-files.d.ts +6 -2
  99. package/dist/run-files.js +29 -7
  100. package/dist/run-labels.d.ts +23 -0
  101. package/dist/run-labels.js +79 -0
  102. package/dist/run-learning-served.d.ts +1 -1
  103. package/dist/run-reads-over-store.d.ts +5 -1
  104. package/dist/run-reads-over-store.js +8 -4
  105. package/dist/run-recordings.d.ts +20 -0
  106. package/dist/run-recordings.js +133 -0
  107. package/dist/run-secrets.js +12 -4
  108. package/dist/runner/adapter-loop.d.ts +1 -1
  109. package/dist/runner/adapter-loop.js +94 -16
  110. package/dist/runner/adapter-run-spec.d.ts +19 -0
  111. package/dist/runner/adapter-run-spec.js +57 -36
  112. package/dist/runner/beside.d.ts +6 -3
  113. package/dist/runner/beside.js +9 -7
  114. package/dist/runner/cli-run-spec.js +41 -32
  115. package/dist/runner/conformance/harness.js +69 -14
  116. package/dist/runner/conformance/subject.d.ts +4 -1
  117. package/dist/runner/feedback-round.d.ts +9 -25
  118. package/dist/runner/feedback-round.js +22 -40
  119. package/dist/runner/learning-end.d.ts +17 -7
  120. package/dist/runner/learning-end.js +79 -53
  121. package/dist/runner/main.d.ts +12 -1
  122. package/dist/runner/main.js +31 -4
  123. package/dist/runner/mcp-claim.d.ts +3 -0
  124. package/dist/runner/mcp-claim.js +1 -1
  125. package/dist/runner/mcp-run.d.ts +6 -2
  126. package/dist/runner/mcp-run.js +5 -3
  127. package/dist/runner/model-route.d.ts +4 -2
  128. package/dist/runner/model-route.js +8 -8
  129. package/dist/runner/promotion.d.ts +44 -4
  130. package/dist/runner/promotion.js +323 -21
  131. package/dist/runner/reflect-hook.d.ts +5 -0
  132. package/dist/runner/reflect-hook.js +22 -14
  133. package/dist/runner/store-secrets.js +3 -1
  134. package/dist/runner/workflow-first.d.ts +6 -11
  135. package/dist/runner/workflow-first.js +16 -20
  136. package/dist/runs-over-store.d.ts +1 -1
  137. package/dist/runs-over-store.js +5 -2
  138. package/dist/sdk/runs.d.ts +7 -1
  139. package/dist/sdk/runs.js +21 -7
  140. package/dist/secret-cut.js +3 -1
  141. package/dist/secrets.js +5 -3
  142. package/dist/server.d.ts +31 -5
  143. package/dist/server.js +240 -61
  144. package/dist/store/agent-body.d.ts +5 -3
  145. package/dist/store/agent-body.js +14 -10
  146. package/dist/store/dialect.d.ts +3 -0
  147. package/dist/store/dialect.js +1 -0
  148. package/dist/store/index.d.ts +1 -1
  149. package/dist/store/postgres/dialect.js +1 -0
  150. package/dist/store/postgres/migrations/0015_run_labels.sql +5 -0
  151. package/dist/store/postgres/migrations/0016_minted_tokens.sql +21 -0
  152. package/dist/store/schema.d.ts +9 -0
  153. package/dist/store/schema.js +26 -2
  154. package/dist/store/sqlite/connection.js +11 -3
  155. package/dist/store/sqlite/run-patch.d.ts +2 -1
  156. package/dist/store/sqlite/run-patch.js +3 -2
  157. package/dist/store/sqlite/store.js +64 -10
  158. package/dist/store/store.d.ts +38 -1
  159. package/dist/store-reads/journal.js +2 -1
  160. package/dist/store-reads/learning.d.ts +1 -1
  161. package/dist/store-reads/learning.js +6 -1
  162. package/dist/store-reads/loop.d.ts +1 -0
  163. package/dist/store-reads/loop.js +14 -4
  164. package/dist/store-reads/runs.d.ts +4 -3
  165. package/dist/store-reads/runs.js +3 -2
  166. package/dist/store-view.d.ts +5 -0
  167. package/dist/store-view.js +8 -2
  168. package/dist/template-eval.d.ts +11 -0
  169. package/dist/template-eval.js +177 -52
  170. package/dist/templates.d.ts +13 -1
  171. package/dist/templates.js +89 -18
  172. package/dist/timeline/computer.js +2 -1
  173. package/dist/timeline/origin.d.ts +1 -1
  174. package/dist/timeline/origin.js +2 -2
  175. package/dist/tool-list.js +1 -0
  176. package/dist/tools.d.ts +7 -0
  177. package/dist/tools.js +11 -0
  178. package/dist/trigger-adapter.d.ts +9 -4
  179. package/dist/trigger-adapters.js +2 -1
  180. package/dist/trigger-feed.d.ts +12 -0
  181. package/dist/trigger-feed.js +420 -0
  182. package/dist/triggers.d.ts +2 -1
  183. package/dist/triggers.js +23 -5
  184. package/dist/validate.js +7 -2
  185. package/dist/webhooks.js +9 -5
  186. package/dist/workspace/computer-deps.d.ts +5 -1
  187. package/dist/workspace/computer-deps.js +2 -2
  188. package/dist/workspace/computer-for-claim.d.ts +7 -0
  189. package/dist/workspace/computer-for-claim.js +12 -2
  190. package/dist/workspace/index.d.ts +1 -0
  191. package/dist/workspace/index.js +2 -0
  192. package/dist/workspace/paths.d.ts +4 -0
  193. package/dist/workspace/paths.js +9 -0
  194. package/dist/workspace/resolve-computer.d.ts +35 -4
  195. package/dist/workspace/resolve-computer.js +47 -9
  196. package/launcher/agentrun-serve +34 -22
  197. package/package.json +11 -9
  198. package/templates/README.md +38 -4
  199. package/dist/console/assets/index-Jbxjcmdp.js +0 -705
@@ -5,9 +5,11 @@
5
5
  // - whether it looks back (learning-run.ts reflectSkip): its cap and its spend so far, read as its view reads them;
6
6
  // - its prompt's facts: how many notes its seed held (launch seedNotes);
7
7
  // - the compile turn's facts (compileAskOf, learn/compile.ts): whether the job is due to be compiled (its notes, its
8
- // completed runs, no learned workflow yet), or a workflow that handed the run back or that the money rule stopped
9
- // wants a revision; its notes whole, its last runs' traces, the tools a workflow may name (draftTools) and the DSL's
10
- // own language for writing one;
8
+ // completed runs, no learned workflow yet), or a workflow its promotion holds wants a revision (once per hold); its
9
+ // notes whole, its last runs' traces, the tools a workflow may name (draftTools) and the DSL's own language for
10
+ // writing one;
11
+ // - whether it looks back at all (ownerSaid): a run of a job that compiles workflows is asked its look-back only when
12
+ // its owner gave feedback (a grade's words, or a message after its first); its compile turn, when due, is asked alone;
11
13
  // - what the person said in the run and a trigger's input (heard.ts Hearing over its entries, the end-of-run turn's
12
14
  // own left out), as learning-run.ts turnOf reads them;
13
15
  // - whether the job gave nothing new to look back on (onlyLearnedWorkflows over its timeline): a run whose only tool
@@ -29,7 +31,8 @@ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
29
31
  import { isMessageRow } from "../timeline/index.js";
30
32
  import { Hearing } from "../heard.js";
31
33
  import { readLearning, readSnapshot } from "../learn/folder.js";
32
- import { compileDue, compilePrompt, compileReference, COMPILE_AFTER_RUNS, COMPILE_QUIET_RUNS, COMPILE_TRACES, heldNamesOf } from "../learn/compile.js";
34
+ import { completedRun, lastOwnRuns, compileDue, compilePrompt, compileReference, COMPILE_QUIET_RUNS, COMPILE_TRACES, heldNamesOf } from "../learn/compile.js";
35
+ import { loopOf } from "../learning-setting.js";
33
36
  import { promotionOf, promotionsOf, scoreOf } from "../learn/promote.js";
34
37
  import { draftDecisionProviders } from "../learn/skills.js";
35
38
  import { DECISION_PROVIDER_KEYS } from "../tool-plane.js";
@@ -48,7 +51,7 @@ import { readApprovers } from "../server-approvers.js";
48
51
  import { runEntries, runReflect, runTimeline, withFeedback, withoutFeedbackRounds } from "../store-reads/journal.js";
49
52
  import { capNowOf } from "./journal-kinds.js";
50
53
  import { bookedCapSpend, bookedSpend } from "./metrics.js";
51
- import { fits, reviseOf, servedAnswerOf, servedOf, workflowDigest } from "./workflow-first.js";
54
+ import { fits, workflowDigest } from "./workflow-first.js";
52
55
  import { pendingFeedbackOf } from "./feedback-round.js";
53
56
  import { createReflectHook } from "./reflect-hook.js";
54
57
  import { sdkDraftTools } from "../sdk/workflows.js";
@@ -99,8 +102,15 @@ export function learningEndOfRun(launch, deps) {
99
102
  // new"), whatever the job did: said here, never left to the words' row counting as a message of the job's.
100
103
  nothingNew: async (runId) => !pendingFeedbackOf(await runEntries(deps.store, runId, BACKGROUND_CONTEXT)) && onlyLearnedWorkflows(await runTimeline(deps.store, runId, BACKGROUND_CONTEXT, { settled: false })),
101
104
  promptFacts: async () => ({ active: start.seedNotes ?? start.given.length }),
102
- // A notes run (`learning: "notes"`) compiles nothing.
103
- ...(start.notesOnly ? {} : { compileFacts: (input) => compileAskOf(deps, { ...input, input: launch.input, ...(start.seedNotes !== undefined ? { seedNotes: start.seedNotes } : {}), seedWorkflows: start.workflows?.length ?? 0 }) }),
105
+ // A notes run (`learning: "notes"`) compiles nothing, and looks back on every run. A run of a job that compiles
106
+ // workflows looks back only on its owner's feedback (ownerSaid).
107
+ ...(start.notesOnly ? {} : {
108
+ compileFacts: (input) => compileAskOf(deps, { ...input, input: launch.input, seedWorkflows: start.workflows?.length ?? 0 }),
109
+ ownerSaid: async (runId) => {
110
+ const [entries, rows] = await Promise.all([runEntries(deps.store, runId, BACKGROUND_CONTEXT), runTimeline(deps.store, runId, BACKGROUND_CONTEXT, { settled: false })]);
111
+ return ownerSaid(entries, rows);
112
+ },
113
+ }),
104
114
  asked: async (runId) => {
105
115
  const [entries, reflect] = await Promise.all([runEntries(deps.store, runId, BACKGROUND_CONTEXT), runReflect(deps.store, runId, BACKGROUND_CONTEXT)]);
106
116
  const hearing = new Hearing();
@@ -244,6 +254,17 @@ export function onlyLearnedWorkflows(rows) {
244
254
  const answered = new Set(results.filter(models).map((row) => row.tool_use_id));
245
255
  return calls.every((row) => answered.has(row.tool_use_id));
246
256
  }
257
+ /** Whether a run carries its owner's feedback, the only thing a run of a job that compiles workflows is looked back on
258
+ * for: a grade's words its end closes (a feedback round, feedback-round.ts pendingFeedbackOf over its root `entries`),
259
+ * or a person's message after its first in its timeline `rows` (a follow-up, or a word while it ran: traceFrom's
260
+ * feedback), the end-of-run turn's own, a grade's round's and a subagent's (a child conversation's rows carry its
261
+ * spawning call, parent_tool_use_id: its task prompt is the job's, not the owner's) rows left out. */
262
+ export function ownerSaid(entries, rows) {
263
+ if (pendingFeedbackOf(entries))
264
+ return true;
265
+ const messages = withoutFeedbackRounds(rows).filter((row) => row.agent_label !== LEARNING_LABEL && !row.parent_tool_use_id && isMessageRow(row));
266
+ return messages.slice(1).some((row) => row.kind === "user_message");
267
+ }
247
268
  /** The path a run took (learning-cost.ts RunPath), by its timeline `rows` as runTimeline labels them (its end-of-run
248
269
  * turn's rows, LEARNING_LABEL, are the learning's and left out): `workflow` when its job did only what
249
270
  * onlyLearnedWorkflows asks of a run with nothing new to look back on, `handed_back` when it called a learned workflow
@@ -336,8 +357,17 @@ async function describedOf(tools, store) {
336
357
  }
337
358
  /** The most of an agent's kept learning, newest first, read for a held workflow's ask since its hold (compileAskOf). */
338
359
  const HELD_ASKED_READ = 200;
339
- /** Whether a store run ended completed (its state `ended`, a plain completion). */
340
- const completedRun = (run) => run.state === "ended" && (run.outcome === null || run.outcome === "completed");
360
+ /** The loop's numbers (learning-setting.ts loopOf) of the revision run `runId` runs: its definition's `learning`. */
361
+ async function loopOfRun(store, runId) {
362
+ try {
363
+ const run = await store.runs.get(runId);
364
+ const revision = run ? await store.agents.revision(run.revisionId) : undefined;
365
+ return loopOf(revision?.body?.learning);
366
+ }
367
+ catch {
368
+ return loopOf(undefined);
369
+ }
370
+ }
341
371
  /** The most tool calls of one run a trace keeps, and the most of a call's input or a message it holds, in characters. */
342
372
  const TRACE_CALLS = 20;
343
373
  const TRACE_TEXT = 600;
@@ -363,36 +393,38 @@ export function traceFrom(timeline, refuse) {
363
393
  return { input: first ? cut(first.text ?? first.summary) : "", calls, answer: cut(answer), feedback: messages.slice(1).filter((row) => row.kind === "user_message").map((row) => cut(row.text ?? row.summary)) };
364
394
  }
365
395
  /** The compile turn's facts for run `runId` of agent `agentId` (learn/compile.ts): a revision of the learned workflow
366
- * that handed the run back or that the money rule stopped (workflow-first.ts servedOf, reviseOf), its text as main holds
367
- * it; or of the one that fits the run's input and whose promotion holds it at main's digest (runner/promotion.ts: its
368
- * replay on the agent's graded inputs, or its graded served runs, fell under the bar; its champion served the run, or the
369
- * agent did by hand), with the
370
- * hold's numbers, once per hold (none when any run since the hold compiled it, read from the agent's kept learning); else, when the job is due (compileDue: the run completed, the agent has no learned workflow active or waiting, none
371
- * of its last COMPILE_QUIET_RUNS runs compiled, and it keeps enough notes or has run enough), a new one. Either way the
396
+ * that fits the run's input and whose promotion holds it at main's digest (runner/promotion.ts: its replay on the
397
+ * agent's graded inputs, or its graded served runs, fell under the bar; its champion served the run, or the agent did by
398
+ * hand), its text as main holds it, with the hold's numbers, once per hold (none when any run since the hold compiled
399
+ * it, read from the agent's kept learning; a check's hold with the inputs it disagreed on, a stopped check's none);
400
+ * else, when the job is due (compileDue: the run completed, the agent has no learned workflow active or waiting, none
401
+ * of its last COMPILE_QUIET_RUNS runs compiled, and it has its definition's compile_after completed agent runs), a new
402
+ * one. Nothing else asks one: a hand-back, a wrong grade of a served answer and the money rule's
403
+ * stop are single runs, which the hold reads among many. Either way the
372
404
  * agent's active notes whole, the traces of its last COMPILE_TRACES completed runs before this one, the tools a call node
373
405
  * may run (draftTools) with what each takes and gives, its decision providers, the run's input (`input`, its fields for
374
406
  * the workflow's input schema), the agent's output schema when it has one (its final output's shape) and the DSL's
375
407
  * language with this host's addendum. Undefined when it compiles nothing, or
376
408
  * when the folder can't be read. */
377
409
  export async function compileAskOf(deps, input) {
378
- const entries = await runEntries(deps.store, input.runId, BACKGROUND_CONTEXT).catch(() => []);
379
- const served = servedOf(entries);
380
- const stopped = reviseOf(entries);
381
- // A wrong grade of the answer its workflow gave alone (a `revise` feedback round this end closes): that workflow.
382
- const fed = pendingFeedbackOf(entries);
383
- const gradedOf = fed?.round === "revise" && fed.workflow ? fed.workflow : undefined;
384
- let revising = served?.outcome === "handed_back" ? served.workflow : (stopped?.workflow ?? gradedOf);
410
+ // A revision is asked only of a workflow its promotion holds, once per hold. One run is one sample: a hand-back, a wrong
411
+ // grade of a served answer or the money rule's stop asks for none (with a 10-15% base error rate on both sides, one
412
+ // wrong answer says nothing about the workflow); the hold, read over many runs, does.
385
413
  // The workflows whose newest revision other than their champion (learn/promote.ts championOf: it serves while that one
386
414
  // is held) is held: the run's own may be one (its champion served it, or it went by hand).
387
- const records = revising ? [] : await promotionsOf(deps.store.settings, input.agentId).catch(() => []);
415
+ const records = await promotionsOf(deps.store.settings, input.agentId).catch(() => []);
388
416
  const heldNames = heldNamesOf(records);
417
+ // The loop's numbers on the agent's definition (the revision this run runs): the first compile waits for compile_after
418
+ // completed agent runs, the ending one counted.
419
+ const { compile_after: compileAfter } = await loopOfRun(deps.store, input.runId);
389
420
  // The agent's latest runs, newest first: those after the ending one in the list started before it.
390
- const listed = await deps.store.runs.list({ agentId: input.agentId, limit: 200 });
421
+ const listed = await deps.store.runs.list({ agentId: input.agentId, limit: Math.max(200, 2 * compileAfter + COMPILE_QUIET_RUNS) });
391
422
  const at = listed.findIndex((run) => run.id === input.runId);
392
423
  const earlier = (at < 0 ? listed : listed.slice(at + 1)).filter((run) => run.agentId === input.agentId);
393
424
  const done = earlier.filter(completedRun);
425
+ const byHand = (await lastOwnRuns(deps.store, input.agentId, compileAfter, input.runId)).length;
394
426
  let compiledLately = false;
395
- const dueWith = (notes, workflows) => compileDue({ completed: input.outcome === "completed", notes, runs: Math.min(done.length, COMPILE_AFTER_RUNS) + (input.outcome === "completed" ? 1 : 0), workflows, compiledLately });
427
+ const dueWith = (workflows) => compileDue({ completed: input.outcome === "completed", runs: byHand + (input.outcome === "completed" ? 1 : 0), workflows, compiledLately, compileAfter });
396
428
  const compiledOf = (kept) => kept?.proposal?.compiled;
397
429
  // Every learning round a run kept: its newest, and each before it (a follow-up opened the run again after it).
398
430
  const roundsOf = async (runId) => {
@@ -401,16 +433,14 @@ export async function compileAskOf(deps, input) {
401
433
  return [];
402
434
  return [newest, ...(await Promise.all(Array.from({ length: Math.max(0, newest.round - 1) }, (_, i) => deps.store.learning.proposal(runId, i + 1).catch(() => undefined))))];
403
435
  };
404
- if (!revising) {
405
- // A compile in any learning round of the agent's last runs (a draft still waiting for its grade, or one that failed)
406
- // asks none now: a follow-up's round keeps no compile of its own, so a run's earlier rounds are read too.
407
- const lately = (await Promise.all(earlier.slice(0, COMPILE_QUIET_RUNS).map((run) => roundsOf(run.id)))).flat();
408
- compiledLately = lately.some((kept) => compiledOf(kept) !== undefined);
409
- // First by what the run started from (its seed's notes and the workflows it was offered): a run not due by them
410
- // opens no folder, unless one of its workflows is held. Main is read below for the turn itself, and decides again.
411
- if (!heldNames.size && !dueWith(input.seedNotes ?? 0, input.seedWorkflows ?? 0))
412
- return undefined;
413
- }
436
+ // A compile in any learning round of the agent's last runs (a draft still waiting for its grade, or one that failed)
437
+ // asks no new one now: a follow-up's round keeps no compile of its own, so a run's earlier rounds are read too.
438
+ const lately = (await Promise.all(earlier.slice(0, COMPILE_QUIET_RUNS).map((run) => roundsOf(run.id)))).flat();
439
+ compiledLately = lately.some((kept) => compiledOf(kept) !== undefined);
440
+ // First by what the run started from (its seed's notes and the workflows it was offered): a run not due by them
441
+ // opens no folder, unless one of its workflows is held. Main is read below for the turn itself, and decides again.
442
+ if (!heldNames.size && !dueWith(input.seedWorkflows ?? 0))
443
+ return undefined;
414
444
  const dsl = await import("@parcha/agentrun-dsl");
415
445
  // Every text the turn is told passes the check a run's start makes (learning.ts holdsSecret, as chooseWorkflows reads a
416
446
  // learned workflow) over what the run must never learn (`refuse`): one that holds a secret is left out whole, never sent
@@ -432,13 +462,13 @@ export async function compileAskOf(deps, input) {
432
462
  leftOut.workflows.add(shown.name(name));
433
463
  return undefined;
434
464
  };
435
- let current = revising ? await textOf(revising) : undefined;
465
+ let current;
436
466
  let held;
437
- if (!revising && heldNames.size) {
467
+ if (heldNames.size) {
438
468
  // The one active workflow that fits the run's input (the one workflow-first would serve), held at main's digest.
439
469
  const active = [];
440
470
  for (const one of workflows)
441
- if (one.status === "active") {
471
+ if (one.status === "active" && heldNames.has(one.name)) {
442
472
  const text = await textOf(one.name);
443
473
  if (text !== undefined)
444
474
  active.push({ name: one.name, workflow: text });
@@ -449,7 +479,7 @@ export async function compileAskOf(deps, input) {
449
479
  [held, current] = [record, fitting[0].workflow];
450
480
  }
451
481
  // An agent with a learned workflow compiles nothing new: its notes' text is not read.
452
- if (!revising && !held && workflows.length)
482
+ if (!held && workflows.length)
453
483
  return { notes: [], workflows: workflows.length };
454
484
  const notes = [];
455
485
  for (const note of snapshot?.notes ?? []) {
@@ -476,9 +506,6 @@ export async function compileAskOf(deps, input) {
476
506
  if (parts.length)
477
507
  deps.log?.(`learning: run ${input.runId}: the compile turn left out what holds a secret: ${parts.join(", ")}`);
478
508
  };
479
- // A revision of a workflow main no longer holds (a person retired it), or whose text holds a secret, asks for none.
480
- if (revising && read.current === undefined)
481
- return sayLeftOut(), undefined;
482
509
  let held;
483
510
  if (read.held) {
484
511
  // Once per hold: a run since it that compiled this workflow asked already, whatever came of it (its revision is on its
@@ -488,11 +515,13 @@ export async function compileAskOf(deps, input) {
488
515
  const kept = await deps.store.learning.proposals(input.agentId, { limit: HELD_ASKED_READ }).catch(() => undefined);
489
516
  if (!kept || kept.some((one) => !(one.createdAt < since) && compiledOf(one)?.workflow === read.held.workflow))
490
517
  return sayLeftOut(), undefined;
491
- const { workflow, digest, source, reason, replay } = read.held;
492
- held = { workflow, digest, source, reason, ...(replay ? { replay: scoreOf(replay) } : {}) };
493
- revising = workflow;
518
+ const { workflow, digest, source, reason, replay, check } = read.held;
519
+ // A check's disagreements are the agent's own inputs and answers: cut of the run's secrets as a trace is (traceFrom).
520
+ const cut = (text) => redactSecrets(text, input.refuse, Number.POSITIVE_INFINITY);
521
+ const checked = check ? { ...check, ...(check.disagreements ? { disagreements: check.disagreements.map((one) => ({ ...one, input: cut(one.input), agent: one.agent === null ? null : cut(one.agent), ...(one.draft !== undefined ? { draft: cut(one.draft) } : {}), ...(one.escalated !== undefined ? { escalated: cut(one.escalated) } : {}) })) } : {}) } : undefined;
522
+ held = { workflow, digest, source, reason, ...(replay ? { replay: scoreOf(replay) } : {}), ...(checked ? { check: checked } : {}) };
494
523
  }
495
- if (!revising && !dueWith(read.notes.length, read.workflows))
524
+ if (!held && !dueWith(read.workflows))
496
525
  return sayLeftOut(), undefined;
497
526
  // An earlier run's trace is cut of each value it held (traceFrom); one that still holds a secret (a value in a call's
498
527
  // input spelled in JSON escapes, a shape the cut does not take) is left out whole.
@@ -507,19 +536,16 @@ export async function compileAskOf(deps, input) {
507
536
  const { tools, decisions, outputSchema, workflowAdapters, described: sdkCatalog } = await draftTools(deps, input.runId);
508
537
  const allowed = draftDecisionProviders(decisions);
509
538
  const judges = workflowAdapters !== undefined ? workflowAdapters.includes("runJudge") : allowed.length > 0;
510
- // Jev by default: a run that can call Jev (a decision provider its gate does not deny) asks every step for a guard it reads.
511
- const jev = workflowAdapters === undefined && allowed.includes("jev");
539
+ // No Jev by default: a draft's steps are asked for no Jev guard, whether or not the run can call Jev (per-step Jev guards
540
+ // gave no judgment that moved a served answer; a check in code does that job).
512
541
  const described = sdkCatalog ?? await describedOf(tools, deps.store);
513
542
  const object = input.input !== null && typeof input.input === "object" && !Array.isArray(input.input);
514
543
  leftOut.input = object && holds(input.input);
515
544
  const fields = object && !leftOut.input ? { input: input.input } : {};
516
545
  const bridge = workflowAdapters !== undefined ? { workflowAdapters } : {};
517
- const base = { ...bridge, reference: compileReference(dsl, { tools, judges, jev, ...bridge }), notes: read.notes, traces, tools, described, judges, jev, ...fields, ...(outputSchema !== undefined ? { outputSchema } : {}) };
518
- // A wrong grade of the answer its workflow gave alone: that answer and the grade's words, cut of the runner's secrets.
519
- const cut = (text) => redactSecrets(text, input.refuse, Number.POSITIVE_INFINITY);
520
- const graded = revising && gradedOf && fed ? { answer: cut(servedAnswerOf(entries)?.answer ?? ""), words: cut(fed.text) } : undefined;
546
+ const base = { ...bridge, reference: compileReference(dsl, { tools, judges, ...bridge }), notes: read.notes, traces, tools, described, judges, ...fields, ...(outputSchema !== undefined ? { outputSchema } : {}) };
521
547
  // A revision is of main's text as read here, whatever the run started from: that commit is its conflict base (`base`).
522
- const ask = !revising ? { mode: "new", ...base } : { mode: "revise", workflow: revising, current: read.current, ...(read.main ? { base: read.main } : {}), ...(served?.outcome === "handed_back" ? { handedBack: true } : stopped ? { revise: { workflow: stopped.workflow, served_usd: stopped.served_usd, by_hand_usd: stopped.by_hand_usd, runs: stopped.runs } } : graded ? { graded } : held ? { held } : {}), ...base };
548
+ const ask = !held ? { mode: "new", ...base } : { mode: "revise", workflow: held.workflow, current: read.current, ...(read.main ? { base: read.main } : {}), held, ...base };
523
549
  sayLeftOut();
524
550
  // Last, the prompt itself, whatever it is told now or later (a tool's description, the agent's output schema): one that
525
551
  // still holds a secret asks nothing.
@@ -68,7 +68,7 @@ export declare function runEnv(env?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
68
68
  * provider loader in place of the computer package's. Under --faux (the runs' environment names the faux model, as a
69
69
  * --faux server's and a `runner --faux` give it), --faux's computers are beside them, as the server's start check
70
70
  * reads them (server.ts computerReady): a run on the faux desktop is claimed, and its live view opened, the real way. */
71
- export declare const runnerComputers: (store: Store, env: KeyEnv, sealKey: Buffer, own?: Pick<ComputerDepsOptions, "kinds" | "load" | "dockerPaths" | "hostAddresses" | "hostWhy" | "hub">) => {
71
+ export declare const runnerComputers: (store: Store, env: KeyEnv, sealKey: Buffer, own?: Pick<ComputerDepsOptions, "kinds" | "load" | "dockerPaths" | "hostAddresses" | "hostWhy" | "hub" | "dial">) => {
72
72
  computerForClaim: typeof import("../workspace/computer-deps.js").claimComputer;
73
73
  computerDeps: ComputerDeps;
74
74
  factories: import("../computer-keys.js").ProviderFactories;
@@ -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";
@@ -70,9 +73,9 @@ export async function openRunnerStore(dataDir, env, warn, url) {
70
73
  }
71
74
  }
72
75
  /** The runner's own secrets, which a run never gets, not even in the runner's in-process environment: the server's
73
- * token and API key, the seal key (the runner holds it as its sealKey), and the store's connection (its URL holds a
76
+ * tokens (the token and the token list) and API key, the seal key (the runner holds it as its sealKey), and the store's connection (its URL holds a
74
77
  * database password). */
75
- const RUNNER_ONLY = (name) => name === "AGENTRUN_TOKEN" || name === "AGENTRUN_API_KEY" || name === SEAL_KEY_ENV || name.startsWith("AGENTRUN_STORE_");
78
+ const RUNNER_ONLY = (name) => name === "AGENTRUN_TOKEN" || name === "AGENTRUN_TOKENS" || name === "AGENTRUN_API_KEY" || name === SEAL_KEY_ENV || name.startsWith("AGENTRUN_STORE_");
76
79
  /** A run's environment as the runner hands its loops (AdapterSpecDeps.env): this process's, less the runner's own
77
80
  * secrets, with every other secret the launcher's pipe handed it (a model key, a tool key, a box key) readable by name
78
81
  * but not enumerable, as secrets.ts withSecrets makes them: code that reads one by name (the model route) finds it, and
@@ -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
138
  // A run's log lines (a learning run's skipped generality check, 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. */
@@ -34,6 +34,9 @@ export interface McpClaimOptions {
34
34
  /** Whether this runner may reach a loopback address (McpForClaimOptions.loopback): a refresh's request to a loopback
35
35
  * authorization server is sent only then. Absent, never. */
36
36
  loopback?: boolean;
37
+ /** The own addresses of the local-install server beside this runner (McpForClaimOptions.own): a loopback authorization
38
+ * server on one of their ports is refused, as the server refuses it. */
39
+ own?: readonly string[];
37
40
  /** For a github_app server (auth github_app, nothing sealed): the server's GitHub App mint and the run's repository
38
41
  * (runner/mcp-github.ts). None: such a server's calls are refused in words. */
39
42
  githubApp?: GithubAppAccess;
@@ -117,7 +117,7 @@ export async function mcpClaim(options) {
117
117
  if (!set.tokens.refresh_token)
118
118
  return { refused: true };
119
119
  const call = AbortSignal.timeout(callMs);
120
- const reach = { allowed: await privateOAuthHosts(store), loopback: options.loopback === true };
120
+ const reach = { allowed: await privateOAuthHosts(store), loopback: options.loopback === true, own: options.own ?? [] };
121
121
  for (let tried = 0; tried < tries && !call.aborted; tried++) {
122
122
  // Every try before this one provably never left: nothing is spent.
123
123
  if (stop.aborted)
@@ -35,9 +35,13 @@ 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
+ /** The own addresses of the local-install server beside this runner (AdapterSpecDeps.mcpOwn, Serve.own): a loopback
42
+ * URL on one of their ports is refused, as the server refuses it, so a run never reaches that server through an MCP
43
+ * server's address, its authorization server's or a pin's listing. */
44
+ readonly own?: readonly string[];
41
45
  /** For tests: the authorization servers' network, a refresh's bound, the gateway's upstream fetch and bounds, and the
42
46
  * timer a github_app token's refresh is armed on. */
43
47
  readonly network?: OAuthNetwork;
@@ -30,10 +30,11 @@ export async function mcpForClaim(options) {
30
30
  sealKey: options.sealKey,
31
31
  signal: held.signal,
32
32
  // A run whose revision has no pin (one made before the upgrade) pins it here, listing as a save does.
33
- pinListing: registryListing(options.store, options.sealKey, { loopback: options.loopback === true, ...(options.network ? { network: options.network } : {}), ...(githubApp ? { githubApp } : {}), ...(options.githubMcpOrigin ? { appOrigin: options.githubMcpOrigin } : {}) }),
33
+ pinListing: registryListing(options.store, options.sealKey, { loopback: options.loopback === true, own: options.own ?? [], ...(options.network ? { network: options.network } : {}), ...(githubApp ? { githubApp } : {}), ...(options.githubMcpOrigin ? { appOrigin: options.githubMcpOrigin } : {}) }),
34
34
  ...(options.bounds ? { bounds: options.bounds } : {}),
35
35
  ...(options.network ? { network: options.network } : {}),
36
36
  ...(options.loopback ? { loopback: true } : {}),
37
+ ...(options.own ? { own: options.own } : {}),
37
38
  ...(githubApp ? { githubApp } : {}),
38
39
  ...(options.githubMcpOrigin ? { githubMcpOrigin: options.githubMcpOrigin } : {}),
39
40
  ...(options.githubTimer ? { githubTimer: options.githubTimer } : {}),
@@ -57,9 +58,10 @@ export async function mcpForClaim(options) {
57
58
  // private-network hosts read now, and dialled at the address checked: a name that resolves somewhere private since the
58
59
  // save, or a host the owner no longer allows, is refused unsent. A URL on loopback is reached only by a runner told
59
60
  // so by the local-install server beside it, in its own process (options.loopback): never by what a store says, so
60
- // one host's local install never opens loopback for another host's runner on a shared store.
61
+ // one host's local install never opens loopback for another host's runner on a shared store; and never at that
62
+ // server's own ports (options.own).
61
63
  reach: async (url, signal) => {
62
- const at = await mcpServerAt(new URL(url), signal, network, { allowed: await privateOAuthHosts(options.store), loopback: options.loopback === true });
64
+ const at = await mcpServerAt(new URL(url), signal, network, { allowed: await privateOAuthHosts(options.store), loopback: options.loopback === true, own: options.own ?? [] });
63
65
  return "refused" in at ? { refused: at.refused } : { send: dialAt(network, at.address, options.fetch ?? fetch) };
64
66
  },
65
67
  beforeCall: step.beforeCall,
@@ -130,8 +130,10 @@ type PiMessage = {
130
130
  export declare function routeOf(model: string | PinnedModel | undefined, env?: NodeJS.ProcessEnv, tier?: Tier, wires?: readonly Wire[], upstream?: typeof fetch, redact?: Redact): Promise<ModelRoute>;
131
131
  /** A fetch that answers Anthropic Messages requests on `target`, through pi-ai's `models`. A provider's error text, which
132
132
  * pi records, goes through `redact` (the runner's one redactor): a provider that echoes its key leaves none there.
133
- * `upstream`: the route's own fetch, for a model that does not speak Messages (absent: the network). */
134
- export declare function messagesFetch(models: PiModels, target: PiModel, redact?: Redact, upstream?: typeof fetch): typeof fetch;
133
+ * `upstream`: the route's own fetch, for a model that does not speak Messages (absent: the network). A request pi-ai
134
+ * sends to OpenRouter carries AgentRun's app attribution unless `env` turns it off (kernel openrouter-attribution.ts),
135
+ * as one the model proxy sends there does; a request to any other provider carries none. */
136
+ export declare function messagesFetch(models: PiModels, target: PiModel, redact?: Redact, upstream?: typeof fetch, env?: NodeJS.ProcessEnv): typeof fetch;
135
137
  /** A text-tools re-ask's output limit: the most tokens it may answer with when what is left of the request's hold is
136
138
  * `leftUsd` (its first try's input as it was billed and its output limit `outputHeld`, less every try so far) and its
137
139
  * input, the prompt `last` was asked with, is priced uncached at the dearer of the input and cache-write prices, as the
@@ -15,7 +15,7 @@
15
15
  // the tier, as its provider bills it), and its cost is that catalog entry, tiers included, for the cap's judgement.
16
16
  import { randomUUID } from "node:crypto";
17
17
  import { calculateCost } from "@earendil-works/pi-ai";
18
- import { ROUTE_ORIGIN, streamErrorOf } from "@parcha/agentrun-kernel/host";
18
+ import { onOpenRouter, openRouterAttribution, ROUTE_ORIGIN, streamErrorOf } from "@parcha/agentrun-kernel/host";
19
19
  import { chooseModel, MODEL_PROVIDER, runModels } from "../model.js";
20
20
  import { providerFor } from "../provider.js";
21
21
  import { keepText, runnerSecrets, secretRedactor } from "./redact.js";
@@ -76,11 +76,8 @@ export async function routeOf(model, env = process.env, tier = "default", wires
76
76
  // proxy reads it on ROUTE_ORIGIN (statesUsageCost). A model that reasons is given to pi's session as one that asks its
77
77
  // thinking level by name (LEVELS_BY_NAME), which the translation hands to pi-ai (levelOf): the run's effort reaches the
78
78
  // model, mapped and clamped by its own catalog entry.
79
- return { ...route, ...(target.reasoning ? { like: { ...sees, ...LEVELS_BY_NAME } } : {}), provider: { api: "anthropic-messages", origin: ROUTE_ORIGIN, credential: () => "model-route" }, fetch: messagesFetch(models, target, redact ?? secretRedactor(runnerSecrets(env)), upstream) };
79
+ return { ...route, ...(target.reasoning ? { like: { ...sees, ...LEVELS_BY_NAME } } : {}), provider: { api: "anthropic-messages", origin: ROUTE_ORIGIN, credential: () => "model-route" }, fetch: messagesFetch(models, target, redact ?? secretRedactor(runnerSecrets(env)), upstream, env) };
80
80
  }
81
- /** OpenRouter's origin: every answer it gives states its cost in its usage (https://openrouter.ai/docs/use-cases/usage-accounting). */
82
- const OPENROUTER_HOST = "openrouter.ai";
83
- const onOpenRouter = (origin) => URL.canParse(origin) && new URL(origin).hostname === OPENROUTER_HOST;
84
81
  /** Whether pi-ai sends `target`'s requests to OpenRouter (pi-ai's own test, utils/openrouter-cost.js isOpenRouterModel). */
85
82
  const piOnOpenRouter = (target) => target.provider === "openrouter" || onOpenRouter(target.baseUrl ?? "");
86
83
  /** How much of an answer's text the error tap keeps: its end, where a stream's error event is. */
@@ -109,8 +106,11 @@ function tapped(upstream) {
109
106
  }
110
107
  /** A fetch that answers Anthropic Messages requests on `target`, through pi-ai's `models`. A provider's error text, which
111
108
  * pi records, goes through `redact` (the runner's one redactor): a provider that echoes its key leaves none there.
112
- * `upstream`: the route's own fetch, for a model that does not speak Messages (absent: the network). */
113
- export function messagesFetch(models, target, redact = keepText, upstream) {
109
+ * `upstream`: the route's own fetch, for a model that does not speak Messages (absent: the network). A request pi-ai
110
+ * sends to OpenRouter carries AgentRun's app attribution unless `env` turns it off (kernel openrouter-attribution.ts),
111
+ * as one the model proxy sends there does; a request to any other provider carries none. */
112
+ export function messagesFetch(models, target, redact = keepText, upstream, env = process.env) {
113
+ const attribution = piOnOpenRouter(target) ? openRouterAttribution(env) : {};
114
114
  // A tool call's id as Messages carries it (letters, digits, _ and -), and back to the provider's own on its result.
115
115
  const providerIds = new Map();
116
116
  const messagesId = (id) => {
@@ -129,7 +129,7 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
129
129
  const tap = piOnOpenRouter(target) ? tapped(upstream) : undefined;
130
130
  const sendWith = tap?.fetch ?? upstream;
131
131
  const level = levelOf(body);
132
- const streamOptions = { ...(body.max_tokens ? { maxTokens: body.max_tokens } : {}), ...(level ? { reasoning: level } : {}), ...(init.signal ? { signal: init.signal } : {}), ...(sendWith ? { fetch: sendWith } : {}) };
132
+ const streamOptions = { ...(body.max_tokens ? { maxTokens: body.max_tokens } : {}), ...(level ? { reasoning: level } : {}), ...(init.signal ? { signal: init.signal } : {}), ...(sendWith ? { fetch: sendWith } : {}), ...(Object.keys(attribution).length ? { headers: attribution } : {}) };
133
133
  const events = models.streamSimple(target, context, streamOptions);
134
134
  const encoder = new TextEncoder();
135
135
  const stream = new ReadableStream({
@@ -1,11 +1,12 @@
1
1
  import type { Context } from "@earendil-works/chord/context";
2
2
  import type { LearnedWorkflow } from "../learning.js";
3
+ import type { GuardRow } from "../learned-nodes.js";
3
4
  import { type RunLaunch } from "../run-launch.js";
4
5
  import { type Store } from "../store/store.js";
5
- import { type ReplayCalls } from "../learn/replay-calls.js";
6
+ import { type ReplayCalls, type Skipped } from "../learn/replay-calls.js";
6
7
  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";
8
+ import { type CheckBar, type PromotionRecord, type ReplayOutcomes, type ReplayScore } from "../learn/promote.js";
9
+ import { type FirstChoice, type Promoted, type ReplayOutcome } from "./workflow-first.js";
9
10
  import type { LearningFolder } from "../learn/folder.js";
10
11
  import type { Shown } from "../learning.js";
11
12
  /** A replay run still not ended this long after its replay started counts as failed (no evidence), and is cancelled once
@@ -49,6 +50,9 @@ export interface PromotionDeps {
49
50
  * (startReplay). Absent: a replay run is handed none (a per_run server's calls are refused unsent, the input failed). */
50
51
  readonly sealKey?: Buffer;
51
52
  readonly now?: () => number;
53
+ /** The host's secrets as a reader cuts them (learning.ts secretsShown): a check's texts are cut of them whole, before
54
+ * they are shortened (decideCheck). */
55
+ readonly shown: () => Promise<Shown>;
52
56
  }
53
57
  /** The claim's promotion ports: `folder`, the agent's learning folder where the run's place keeps it, a refit's revision
54
58
  * written on it as a merge from the claim's seed (a workflow.json changed on main since is a conflict, never written over),
@@ -56,7 +60,6 @@ export interface PromotionDeps {
56
60
  * the workflow an earlier claim of this run served (`kept`, from its journal: none on a first claim). */
57
61
  export declare function claimPromotion(deps: Omit<PromotionDeps, "commit" | "champion" | "kept"> & {
58
62
  readonly folder: () => LearningFolder;
59
- readonly shown: () => Promise<Shown>;
60
63
  }): PromotionDeps;
61
64
  /** A replay run's claim (launch.replay) of run `runId`, once its first choice is made: refused (ClaimRefused: the run ends
62
65
  * failed, no agent turn, nothing sent) unless its revision's record still says replaying and names it among its runs (it
@@ -70,6 +73,14 @@ export declare function replayClaimed(store: Pick<Store, "settings">, agentId: s
70
73
  * the laid one is not the digest it replays (the replay then fails, never scoring another revision). Any other run's,
71
74
  * as laid. */
72
75
  export declare function replayLaid(launch: RunLaunch, laid: readonly LearnedWorkflow[]): LearnedWorkflow[];
76
+ /** The learned workflows a run's learned_workflow tool runs, once its first choice is made: what serves, never a
77
+ * revision its promotion has not promoted. The one its first choice served or the money rule stopped (laidFor: its
78
+ * champion in place of the laid revision) as chosen; any other the records name, its champion (championOf: the laid
79
+ * text when that is the champion, else its text at its record's commit), and none while nothing of it serves (none
80
+ * promoted yet, or the champion held): a revision replaying, queued, held or never decided is never handed to the
81
+ * 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
82
+ * replay run's as laid (replayLaid). The records unread: only the chosen one, as the gate leaves a run to its agent. */
83
+ export declare function toolFlowsFor(deps: Pick<PromotionDeps, "store" | "agentId" | "champion" | "log">, launch: RunLaunch, laid: readonly LearnedWorkflow[], choice: FirstChoice): Promise<LearnedWorkflow[]>;
73
84
  /** The gate workflowFirstOf asks (its `promoted`), at every run's claim, a queued run's included: the workflow that serves
74
85
  * this run first. A run already executing keeps the revision an earlier claim of it served (keptFor). Else the laid
75
86
  * revision (`workflow` at `digest`, the folder's revision as the run's seed holds it) has its promotion moved on (decide:
@@ -77,6 +88,35 @@ export declare function replayLaid(launch: RunLaunch, laid: readonly LearnedWork
77
88
  * (championOf), the laid text when it is the champion, its own text read from its record's commit when not; undefined
78
89
  * when none serves (the agent takes the run). A digest's own record never says it serves. */
79
90
  export declare const promotionGate: (deps: PromotionDeps) => Promoted;
91
+ /** The words a stopped check's record starts with when it had nothing to check its draft on. */
92
+ export declare const NOTHING_TO_CHECK = "nothing to check it on";
93
+ /** One input a check ran its draft on: the agent's run (`of`) and its input, the agent's recorded answer, and what the
94
+ * draft did: its answer when it answered alone, why it handed the input back, or failed (or skipped a write). A
95
+ * reserved input whose replay run was never created, or never ended, by the check's deadline failed (`unstarted` for
96
+ * the first). */
97
+ type CheckRow = {
98
+ readonly of: string;
99
+ readonly input: string;
100
+ readonly agent: string | null;
101
+ readonly outcome: ReplayOutcome;
102
+ readonly answer: string | null;
103
+ readonly guards: readonly GuardRow[];
104
+ readonly escalated?: string;
105
+ readonly skipped?: Skipped;
106
+ readonly unstarted?: true;
107
+ };
108
+ /** Decides a check on its rows: each input it ran on (a skipped write is none) agreed when the draft answered it alone
109
+ * with the agent's recorded answer (learn/promote.ts sameAnswer), alone when it answered it with no escalate, no failed
110
+ * step, and no guard or recorded escalate that hands it back at the workflow's serving `thresholds` (handsBackAt). Promoted (source check) when it clears the bar (checkPasses); else held with the inputs it did not
111
+ * agree on, which the agent's next run's compile turn reads as data (its one recompile); a recompile's check that holds
112
+ * it too stops: nothing compiles again. No grade, refit, queue or second replay. Kept only while `still` holds of the
113
+ * digest's record (the one write: of two claims at once, one decides). */
114
+ export declare function decideCheck(deps: PromotionDeps, name: string, digest: string, bar: CheckBar, read: {
115
+ rows: readonly CheckRow[];
116
+ cost: number | null;
117
+ outcomes: ReplayOutcomes;
118
+ unstarted: number;
119
+ }, thresholds: ReadonlyMap<string, number>, still: (was: PromotionRecord | undefined) => boolean, extra: Partial<PromotionRecord>): Promise<import("../learn/promote.js").Recorded>;
80
120
  /** Why a replay a person asked for (askReplay) or read (replayView) was refused: `missing`, no such workflow, revision or
81
121
  * replay of the agent (404); `conflict`, the revision cannot replay now (409), in words that say why. */
82
122
  export declare class ReplayRefused extends Error {