@parcha/agentrun-serve 0.1.0-beta.45 → 0.1.0-beta.47

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 (256) hide show
  1. package/CHANGELOG.md +180 -0
  2. package/NOTICE +4 -0
  3. package/README.md +283 -47
  4. package/dist/acp-package.d.ts +35 -6
  5. package/dist/acp-package.js +3 -3
  6. package/dist/adapter-facts.d.ts +5 -2
  7. package/dist/adapter-facts.js +6 -3
  8. package/dist/adapters.d.ts +7 -0
  9. package/dist/adapters.js +39 -0
  10. package/dist/agents-store.d.ts +5 -3
  11. package/dist/agents-store.js +13 -8
  12. package/dist/api-only.d.ts +7 -10
  13. package/dist/api-only.js +7 -10
  14. package/dist/archil-routes.js +2 -1
  15. package/dist/cap.js +12 -2
  16. package/dist/chatgpt-plan.js +2 -1
  17. package/dist/cli.js +119 -44
  18. package/dist/composio-made.d.ts +19 -2
  19. package/dist/composio-made.js +17 -5
  20. package/dist/composio-preset.d.ts +42 -7
  21. package/dist/composio-preset.js +106 -70
  22. package/dist/composio-triggers.d.ts +9 -4
  23. package/dist/composio-triggers.js +20 -13
  24. package/dist/computer-attach.d.ts +11 -10
  25. package/dist/computer-attach.js +13 -14
  26. package/dist/computer-commands.d.ts +3 -0
  27. package/dist/computer-commands.js +3 -2
  28. package/dist/computer-lost.d.ts +4 -0
  29. package/dist/computer-lost.js +8 -3
  30. package/dist/computer-setting.d.ts +2 -0
  31. package/dist/computer-setting.js +2 -0
  32. package/dist/computers.d.ts +9 -75
  33. package/dist/computers.js +20 -66
  34. package/dist/console/assets/index-BBFzAxLB.js +715 -0
  35. package/dist/console/assets/index-BRi-Rgq6.css +1 -0
  36. package/dist/console/index.html +2 -2
  37. package/dist/cost-heal.d.ts +13 -0
  38. package/dist/cost-heal.js +27 -0
  39. package/dist/dial-relay.d.ts +6 -2
  40. package/dist/dial-relay.js +9 -12
  41. package/dist/email/routes.js +2 -1
  42. package/dist/errors.d.ts +2 -0
  43. package/dist/errors.js +5 -0
  44. package/dist/exa-keyless.d.ts +1 -1
  45. package/dist/exa-keyless.js +1 -1
  46. package/dist/faux-computers.d.ts +2 -3
  47. package/dist/faux-computers.js +9 -31
  48. package/dist/github-connection.js +2 -1
  49. package/dist/harness-archive.d.ts +19 -2
  50. package/dist/harness-archive.js +49 -15
  51. package/dist/harness-check.d.ts +73 -0
  52. package/dist/harness-check.js +489 -0
  53. package/dist/harness-cursor.d.ts +45 -0
  54. package/dist/harness-cursor.js +121 -0
  55. package/dist/harness-recipe.d.ts +127 -0
  56. package/dist/harness-recipe.js +357 -0
  57. package/dist/harness-table.d.ts +12 -0
  58. package/dist/harness-table.js +62 -2
  59. package/dist/harness.d.ts +2 -0
  60. package/dist/harness.js +3 -2
  61. package/dist/host-check.d.ts +6 -0
  62. package/dist/host-check.js +14 -0
  63. package/dist/host.d.ts +10 -3
  64. package/dist/host.js +17 -3
  65. package/dist/import-sources.d.ts +2 -0
  66. package/dist/import-sources.js +2 -0
  67. package/dist/import-summary.d.ts +15 -5
  68. package/dist/import-summary.js +24 -8
  69. package/dist/import.d.ts +34 -4
  70. package/dist/import.js +134 -32
  71. package/dist/key-refusal.d.ts +1 -0
  72. package/dist/key-refusal.js +8 -3
  73. package/dist/key-words.d.ts +1 -1
  74. package/dist/key-words.js +4 -4
  75. package/dist/learn/check.d.ts +3 -0
  76. package/dist/learn/check.js +31 -20
  77. package/dist/learn/compile.js +11 -4
  78. package/dist/learn/promote.d.ts +77 -4
  79. package/dist/learn/promote.js +123 -2
  80. package/dist/learned-nodes.d.ts +4 -3
  81. package/dist/learned-workflow.js +4 -1
  82. package/dist/learning-cost.d.ts +6 -16
  83. package/dist/learning-cost.js +6 -12
  84. package/dist/learning-setting.d.ts +17 -6
  85. package/dist/learning-setting.js +41 -5
  86. package/dist/learning-words.d.ts +2 -0
  87. package/dist/learning-words.js +1 -1
  88. package/dist/listen-first.d.ts +10 -0
  89. package/dist/listen-first.js +25 -1
  90. package/dist/llms.txt +1 -1
  91. package/dist/mcp-gateway.d.ts +2 -1
  92. package/dist/mcp-gateway.js +31 -15
  93. package/dist/mcp-probe.d.ts +18 -6
  94. package/dist/mcp-probe.js +41 -8
  95. package/dist/mcp-secret-writes.d.ts +8 -0
  96. package/dist/mcp-secret-writes.js +104 -4
  97. package/dist/mcp-servers-store.d.ts +11 -5
  98. package/dist/mcp-servers-store.js +46 -20
  99. package/dist/model-form.d.ts +2 -1
  100. package/dist/model-form.js +22 -8
  101. package/dist/model-gateway.d.ts +113 -0
  102. package/dist/model-gateway.js +433 -0
  103. package/dist/model.d.ts +2 -1
  104. package/dist/model.js +9 -7
  105. package/dist/monid.js +1 -1
  106. package/dist/native/binding.d.ts +4 -0
  107. package/dist/native/binding.js +9 -0
  108. package/dist/native/cli.d.ts +3 -2
  109. package/dist/native/cli.js +6 -5
  110. package/dist/openapi.d.ts +2 -0
  111. package/dist/openapi.js +326 -41
  112. package/dist/owner.d.ts +4 -2
  113. package/dist/owner.js +10 -4
  114. package/dist/page.d.ts +8 -0
  115. package/dist/page.js +9 -1
  116. package/dist/port-models.js +17 -10
  117. package/dist/provider.d.ts +3 -3
  118. package/dist/provider.js +12 -3
  119. package/dist/public-address.d.ts +28 -0
  120. package/dist/public-address.js +62 -0
  121. package/dist/run-launch.d.ts +1 -1
  122. package/dist/run-launch.js +1 -1
  123. package/dist/run-secrets.d.ts +3 -2
  124. package/dist/run-secrets.js +6 -4
  125. package/dist/runner/adapter-loop.d.ts +10 -7
  126. package/dist/runner/adapter-loop.js +57 -22
  127. package/dist/runner/adapter-run-spec.d.ts +12 -0
  128. package/dist/runner/adapter-run-spec.js +40 -6
  129. package/dist/runner/adapters/index.js +16 -0
  130. package/dist/runner/adapters/pi.d.ts +5 -2
  131. package/dist/runner/adapters/pi.js +7 -4
  132. package/dist/runner/audit.d.ts +7 -0
  133. package/dist/runner/audit.js +24 -6
  134. package/dist/runner/claim-secrets.js +5 -1
  135. package/dist/runner/cli-run-spec.js +15 -7
  136. package/dist/runner/compare-end.d.ts +43 -0
  137. package/dist/runner/compare-end.js +95 -0
  138. package/dist/runner/computer-journal.d.ts +3 -0
  139. package/dist/runner/computer-journal.js +22 -2
  140. package/dist/runner/conformance/harness.js +19 -8
  141. package/dist/runner/conformance/subject.d.ts +6 -0
  142. package/dist/runner/harness-loops.d.ts +6 -1
  143. package/dist/runner/harness-loops.js +94 -54
  144. package/dist/runner/held.d.ts +5 -4
  145. package/dist/runner/journal-kinds.d.ts +4 -1
  146. package/dist/runner/journal-kinds.js +3 -0
  147. package/dist/runner/loop-contract.d.ts +10 -0
  148. package/dist/runner/main.d.ts +5 -5
  149. package/dist/runner/main.js +81 -11
  150. package/dist/runner/mcp-claim.js +40 -12
  151. package/dist/runner/metrics.d.ts +26 -0
  152. package/dist/runner/metrics.js +44 -1
  153. package/dist/runner/presence.d.ts +41 -0
  154. package/dist/runner/presence.js +89 -0
  155. package/dist/runner/promotion.d.ts +10 -3
  156. package/dist/runner/promotion.js +42 -21
  157. package/dist/runner/run-child-host.js +52 -14
  158. package/dist/runner/runner.d.ts +5 -0
  159. package/dist/runner/runner.js +8 -0
  160. package/dist/runner/store-port.d.ts +3 -0
  161. package/dist/runner/store-secrets.js +19 -7
  162. package/dist/runner/workflow-first.d.ts +5 -2
  163. package/dist/runner/workflow-first.js +6 -3
  164. package/dist/runs-over-store.d.ts +6 -2
  165. package/dist/runs-over-store.js +14 -4
  166. package/dist/sdk/runs.d.ts +1 -1
  167. package/dist/sdk/runs.js +6 -1
  168. package/dist/sdk/schema.js +1 -1
  169. package/dist/secret-writes.d.ts +16 -3
  170. package/dist/secret-writes.js +28 -3
  171. package/dist/server-secrets-store.js +5 -0
  172. package/dist/server.d.ts +31 -2
  173. package/dist/server.js +326 -53
  174. package/dist/sign-ins-secrets.js +4 -1
  175. package/dist/skills/agentrun-serve/SKILL.md +11 -0
  176. package/dist/slack-url.d.ts +5 -0
  177. package/dist/slack-url.js +11 -0
  178. package/dist/slack.d.ts +107 -0
  179. package/dist/slack.js +292 -0
  180. package/dist/start-switches.d.ts +28 -0
  181. package/dist/start-switches.js +37 -0
  182. package/dist/stats.d.ts +1 -1
  183. package/dist/stats.js +2 -1
  184. package/dist/stop-signals.d.ts +11 -0
  185. package/dist/stop-signals.js +22 -0
  186. package/dist/store/agent-body.d.ts +1 -1
  187. package/dist/store/agent-body.js +2 -2
  188. package/dist/store/index.d.ts +3 -3
  189. package/dist/store/index.js +1 -1
  190. package/dist/store/postgres/migrations/0020_runners.sql +18 -0
  191. package/dist/store/postgres/store.d.ts +1 -1
  192. package/dist/store/postgres/store.js +4 -2
  193. package/dist/store/schema.d.ts +13 -5
  194. package/dist/store/schema.js +20 -11
  195. package/dist/store/seal.d.ts +16 -4
  196. package/dist/store/sqlite/store.d.ts +1 -1
  197. package/dist/store/sqlite/store.js +106 -27
  198. package/dist/store/store.d.ts +75 -23
  199. package/dist/store/store.js +11 -0
  200. package/dist/store-reads/analytics.js +3 -2
  201. package/dist/store-reads/cap.d.ts +7 -0
  202. package/dist/store-reads/cap.js +11 -1
  203. package/dist/store-reads/journal.js +27 -1
  204. package/dist/store-reads/learning.d.ts +23 -2
  205. package/dist/store-reads/learning.js +29 -8
  206. package/dist/store-reads/runs.d.ts +9 -0
  207. package/dist/store-reads/runs.js +19 -6
  208. package/dist/store-reads/stats.d.ts +4 -1
  209. package/dist/store-reads/stats.js +15 -6
  210. package/dist/store-view.d.ts +123 -14
  211. package/dist/store-view.js +154 -21
  212. package/dist/telemetry.d.ts +7 -7
  213. package/dist/telemetry.js +38 -15
  214. package/dist/templates.d.ts +6 -3
  215. package/dist/templates.js +38 -3
  216. package/dist/timeline/timeline.js +18 -0
  217. package/dist/tool-keys-store.js +2 -2
  218. package/dist/tool-keys.js +2 -1
  219. package/dist/tool-plane.js +2 -2
  220. package/dist/trigger-adapter.d.ts +3 -4
  221. package/dist/trigger-adapter.js +2 -2
  222. package/dist/trigger-composio.js +3 -3
  223. package/dist/trigger-email.js +0 -2
  224. package/dist/trigger-feed.js +0 -2
  225. package/dist/trigger-schedule.js +3 -0
  226. package/dist/trigger-secrets-shown.d.ts +6 -3
  227. package/dist/trigger-secrets-shown.js +22 -13
  228. package/dist/trigger-targets.d.ts +1 -1
  229. package/dist/trigger-targets.js +19 -8
  230. package/dist/triggers.d.ts +7 -3
  231. package/dist/triggers.js +2 -1
  232. package/dist/webhooks.d.ts +85 -9
  233. package/dist/webhooks.js +129 -46
  234. package/dist/wires.d.ts +6 -1
  235. package/dist/wires.js +5 -0
  236. package/dist/workspace/attach.d.ts +3 -2
  237. package/dist/workspace/attach.js +2 -1
  238. package/dist/workspace/attached-computers.d.ts +6 -8
  239. package/dist/workspace/attached-computers.js +27 -24
  240. package/dist/workspace/computer-deps.d.ts +2 -3
  241. package/dist/workspace/computer-deps.js +3 -6
  242. package/dist/workspace/computer-for-claim.js +72 -96
  243. package/dist/workspace/computer-kept.d.ts +0 -7
  244. package/dist/workspace/computer-kept.js +0 -17
  245. package/dist/workspace/resolve-computer.d.ts +18 -14
  246. package/dist/workspace/resolve-computer.js +47 -60
  247. package/dist/workspace/synced-folder.d.ts +20 -15
  248. package/dist/workspace/synced-folder.js +33 -43
  249. package/launcher/agentrun-serve +4 -1
  250. package/package.json +10 -10
  251. package/skills/agentrun-serve/SKILL.md +11 -0
  252. package/templates/README.md +1 -1
  253. package/templates/inbound-lead/agent.md +2 -1
  254. package/templates/kyb/agent.md +2 -1
  255. package/dist/console/assets/index-3O2Yl6hZ.js +0 -701
  256. package/dist/console/assets/index-DaFsZuzQ.css +0 -1
package/dist/import.js CHANGED
@@ -14,9 +14,10 @@ import { BACKGROUND_CONTEXT as ctx } from "@earendil-works/chord/context";
14
14
  import { AssistantEntry, ROOT_CONVERSATION_ID, ToolResultEntry, UserEntry } from "@earendil-works/pi-durable";
15
15
  import { REQUEST_COST, runMetricsOf } from "./timeline/index.js";
16
16
  import { defaultData } from "./files.js";
17
- import { childFiles, HARNESS_OF, mostEffortOf, readSession, SOURCES, sessionFiles } from "./import-sources.js";
17
+ import { childFiles, HARNESS_OF, mostEffortOf, readSession, SOURCE_NAMES, SOURCES, sessionFiles } from "./import-sources.js";
18
18
  import { hoursOf, summaryLines } from "./import-summary.js";
19
- import { catalogPrices } from "./model.js";
19
+ import { stopOnce } from "./stop-signals.js";
20
+ import { catalogPrices, providerModels } from "./model.js";
20
21
  import { logLine } from "./print.js";
21
22
  import { launchBody } from "./run-launch.js";
22
23
  import { DEFAULT_PORT } from "./server.js";
@@ -307,7 +308,7 @@ async function keysInSessions(sessions) {
307
308
  * and each run the import would write (its sessions, then its subagents, which the reader holds to MAX_SESSION_BYTES),
308
309
  * read through secretlint once, findings only, into `add`. Each file's size and time as read, and each project's text
309
310
  * as read, are kept: a write reads a run (or a project's text) through secretlint again only if it changed since. */
310
- async function findKeys(plan, add, cut, held, signal) {
311
+ async function findKeys(plan, add, cut, held, signal, onProgress) {
311
312
  const stamps = new Map();
312
313
  const texts = new Map();
313
314
  // The runs over MAX_RUN_BYTES (`source:id`): read no further here, and left out by the write.
@@ -319,6 +320,9 @@ async function findKeys(plan, add, cut, held, signal) {
319
320
  texts.set(project.agentId, hash(own));
320
321
  add(await secretsIn(own));
321
322
  }
323
+ const toRead = onProgress ? plan.projects.flatMap((p) => byRun(p.sessions)).filter((files) => !held(files[0])).length : 0;
324
+ let readSoFar = 0;
325
+ onProgress?.("keys", 0, toRead);
322
326
  for (const project of plan.projects) {
323
327
  for (const files of byRun(project.sessions)) {
324
328
  if (signal?.aborted)
@@ -326,6 +330,9 @@ async function findKeys(plan, add, cut, held, signal) {
326
330
  const listed = files[0];
327
331
  if (held(listed))
328
332
  continue;
333
+ onProgress?.("keys", readSoFar++, toRead);
334
+ if (signal?.aborted)
335
+ break;
329
336
  // Its own count of records seen: the import's, shared across its files, is the write's to keep.
330
337
  const seen = new Set();
331
338
  const parts = [];
@@ -406,13 +413,16 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
406
413
  const child = (owner, file) => void children.set(owner, [...(children.get(owner) ?? []), file]);
407
414
  const untied = [];
408
415
  const projects = new Map();
416
+ let stopped = false;
409
417
  // Each listed session's place in the import's order (inOrder).
410
418
  const rank = new Map();
411
419
  const temps = [...new Set([tempDir, await realpath(tempDir).catch(() => tempDir)])];
412
420
  for (const source of sources) {
413
421
  for (const { file, stats } of await inOrder(await sessionFiles(home, source), source)) {
414
- if (signal?.aborted)
422
+ if (signal?.aborted) {
423
+ stopped = true;
415
424
  break;
425
+ }
416
426
  const known = seen.get(hash(file));
417
427
  if (sameFile(known, stats)) {
418
428
  already += 1;
@@ -498,7 +508,7 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
498
508
  }
499
509
  skipped.splice(0, skipped.length, ...ofChosen);
500
510
  }
501
- const plan = { projects: [...projects.values()].filter((project) => !chosen || chosen.has(project.agentId)).sort((a, b) => a.cwd.localeCompare(b.cwd)), skipped, already, held, children, untied };
511
+ const plan = { projects: [...projects.values()].filter((project) => !chosen || chosen.has(project.agentId)).sort((a, b) => a.cwd.localeCompare(b.cwd)), skipped, already, held, children, untied, ...(stopped ? { stopped: true } : {}) };
502
512
  if (!measure)
503
513
  return plan;
504
514
  const counting = secretCut(env, SECRET_NAMES);
@@ -1044,19 +1054,26 @@ async function estimateOf(entries, catalog) {
1044
1054
  }
1045
1055
  return Math.round(total * 1e6) / 1e6;
1046
1056
  }
1057
+ /** What an imported agent is told when its project has no CLAUDE.md or AGENTS.md (or the harness's own file): an agentic
1058
+ * revision with no instructions is refused every run (runnable.ts), so an import never writes one. */
1059
+ export const importedInstructions = (project, source) => `You work on the project ${project}. Your past runs are its ${SOURCE_NAMES[source]} sessions, imported. Read the project's files before you change them, and say what you changed.`;
1047
1060
  /** The revision of `source`'s harness this agent keeps already (one per source, by its note), or a new one to write: its
1048
1061
  * id, and the `NewRevision` the caller stores (through agents.create for the agent's first, agents.addRevision for the
1049
- * rest). The body is built and checked here (bodyOf), its instructions and skills cut. */
1050
- async function revisionFor(store, agentId, source, files, model, cut) {
1062
+ * rest). The body is built and checked here (bodyOf), its instructions and skills cut. `model`: the harness's latest
1063
+ * session's, kept only when a model catalog here lists it. A coding app's own model (Codex's gpt-6.1-codex) is listed by
1064
+ * none and runs here on no key: pinned, every run of the agent is refused. Left out, the agent runs on this server's
1065
+ * default for its harness, and each imported run still names the model it ran on. `project`: its name as kept (keptName). */
1066
+ async function revisionFor(store, agentId, source, files, model, project, cut) {
1051
1067
  const note = `imported from ${source}`;
1052
1068
  const held = (await store.agents.revisions(agentId)).find((r) => r.note === note);
1053
1069
  if (held)
1054
1070
  return { id: held.id };
1055
1071
  const harness = HARNESS_OF[source];
1056
- const instructions = INSTRUCTIONS[harness].map((name) => files.instructions[name]).find((text) => text !== undefined) ?? "";
1072
+ const own = INSTRUCTIONS[harness].map((name) => files.instructions[name]).find((text) => text !== undefined);
1073
+ const instructions = own?.trim() ? cut(own) : importedInstructions(project, source);
1057
1074
  const { body, skills } = bodyOf({
1058
1075
  kind: "agentic",
1059
- instructions: cut(instructions),
1076
+ instructions,
1060
1077
  skills: keptSkills(files.skills, cut),
1061
1078
  tools: [],
1062
1079
  ...(model ? { model } : {}),
@@ -1103,17 +1120,29 @@ export async function runImport(store, plan, options) {
1103
1120
  const add = (keys) => (cut.add(keys), options.onKeys?.(keys));
1104
1121
  // This server's own secrets, then every key the import finds.
1105
1122
  add(options.own ?? []);
1106
- const report = { agents: [], skipped: [...plan.skipped], already: plan.already };
1123
+ const report = { agents: [], skipped: [...plan.skipped], already: plan.already, ...(plan.stopped ? { stopped: true } : {}) };
1107
1124
  let prices;
1108
1125
  const catalog = () => (prices ??= catalogPrices());
1109
1126
  const held = await importedIn(store);
1127
+ // Whether a model catalog here lists a session's model ("provider/model id"), keys aside: one none lists is no model to pin.
1128
+ let models;
1129
+ const inCatalog = async (ref) => {
1130
+ const at = ref.indexOf("/");
1131
+ return at > 0 && (await (models ??= providerModels(options.env))).getModel(ref.slice(0, at), ref.slice(at + 1)) !== undefined;
1132
+ };
1110
1133
  // Every key of the import is known before anything of it is written.
1111
- const known = await findKeys(plan, add, text, (listed) => held.get(`${listed.source}:${listed.id}`) !== undefined, options.signal);
1134
+ const known = await findKeys(plan, add, text, (listed) => held.get(`${listed.source}:${listed.id}`) !== undefined, options.signal, options.onProgress);
1135
+ const toTake = options.onProgress ? plan.projects.reduce((n, p) => n + byRun(p.sessions).length, 0) : 0;
1136
+ let written = 0;
1137
+ if (!options.signal?.aborted)
1138
+ options.onProgress?.("write", 0, toTake);
1112
1139
  const scannedAs = known.stamps;
1113
1140
  const epoch0 = new Date(0).toISOString();
1114
1141
  for (const project of plan.projects) {
1115
- if (options.signal?.aborted)
1142
+ if (options.signal?.aborted) {
1143
+ report.stopped = true;
1116
1144
  break;
1145
+ }
1117
1146
  const existing = await store.agents.get(project.agentId);
1118
1147
  const created = !existing;
1119
1148
  const files = await projectFiles(project.cwd, report.skipped);
@@ -1123,20 +1152,25 @@ export async function runImport(store, plan, options) {
1123
1152
  add(await secretsIn(textNow));
1124
1153
  const byStart = [...project.sessions].sort((a, b) => (a.startedAt ?? "").localeCompare(b.startedAt ?? ""));
1125
1154
  const latest = byStart.at(-1);
1126
- // The latest session's harness names the agent's current revision; its model, each harness's latest. The latest source
1127
- // is last in the order, so it is the last revision written — created with the agent, or added current.
1155
+ const name = keptName(project, text);
1156
+ // The latest session's harness names the agent's current revision; its model, each harness's latest a catalog lists. The
1157
+ // latest source is last in the order, so it is the last revision written — created with the agent, or added current.
1128
1158
  const order = [...new Set(project.sessions.map((s) => s.source))].sort((a, b) => (a === latest.source ? 1 : 0) - (b === latest.source ? 1 : 0));
1129
1159
  const revisions = new Map();
1130
1160
  const toWrite = [];
1131
1161
  for (const source of order) {
1132
- const resolved = await revisionFor(store, project.agentId, source, files, byStart.findLast((s) => s.source === source && s.model)?.model, text);
1162
+ const model = byStart.findLast((s) => s.source === source && s.model)?.model;
1163
+ const pinned = model && (await inCatalog(model)) ? model : undefined;
1164
+ const resolved = await revisionFor(store, project.agentId, source, files, pinned, name, text);
1165
+ if (resolved.create && model && !pinned)
1166
+ (report.modelsLeftOut ??= []).push({ cwd: project.cwd, source, model });
1133
1167
  revisions.set(source, resolved.id);
1134
1168
  if (resolved.create)
1135
1169
  toWrite.push(resolved.create);
1136
1170
  }
1137
1171
  if (created) {
1138
1172
  // The agent and its first revision in one commit, the rest added; the latest is last, so the current one.
1139
- await store.agents.create({ id: project.agentId, name: keptName(project, text), description: text(project.cwd) }, toWrite[0]);
1173
+ await store.agents.create({ id: project.agentId, name, description: text(project.cwd) }, toWrite[0]);
1140
1174
  for (const revision of toWrite.slice(1))
1141
1175
  await store.agents.addRevision({ agentId: project.agentId, ...revision });
1142
1176
  }
@@ -1152,8 +1186,11 @@ export async function runImport(store, plan, options) {
1152
1186
  // A record or response counted once across the import's files, those its runs here hold already included.
1153
1187
  const seen = await seenIn(store, project.agentId);
1154
1188
  for (const files of byRun(project.sessions)) {
1155
- if (options.signal?.aborted)
1189
+ options.onProgress?.("write", written++, toTake);
1190
+ if (options.signal?.aborted) {
1191
+ report.stopped = true;
1156
1192
  break;
1193
+ }
1157
1194
  const listed = files[0];
1158
1195
  // A run the store holds already is left as it is: importRun is atomic, so a held run is a whole run.
1159
1196
  if (held.get(`${listed.source}:${listed.id}`) !== undefined) {
@@ -1306,10 +1343,27 @@ export async function describePlan(plan, store, { verbose = false } = {}) {
1306
1343
  });
1307
1344
  return [...lines, ...(plan.already ? [`already imported, unchanged: ${plan.already} session files`] : []), ...(verbose ? plan.skipped.map((s) => `skipped ${s.what}: ${s.why}`) : [])];
1308
1345
  }
1309
- /** `agentrun-serve import ARGS`: its exit code. */
1310
- export async function importCommand(args, usage, { home = homedir(),
1346
+ /** `agentrun-serve import ARGS`: its exit code. The first Ctrl+C (or SIGTERM) once it writes stops it between two
1347
+ * sessions: each is written whole (importRun is atomic), what is written stays, and the next import picks up the rest.
1348
+ * Its listeners stay until everything it says is printed, since its lines are held until the end; a Ctrl+C it took is
1349
+ * in the code (130) whenever it came. */
1350
+ export async function importCommand(args, usage, deps = {}) {
1351
+ const progress = deps.progress ?? terminalProgress();
1352
+ const stops = stopOnce(() => {
1353
+ progress.done();
1354
+ console.error("agentrun-serve import: stopping; a session being saved is finished first, what is saved stays, and the summary follows (Ctrl+C again to quit now)");
1355
+ });
1356
+ try {
1357
+ const code = await importWith(args, usage, { ...deps, progress }, stops);
1358
+ return code === 0 && stops.signal.aborted ? 130 : code;
1359
+ }
1360
+ finally {
1361
+ stops.unhook();
1362
+ }
1363
+ }
1364
+ async function importWith(args, usage, { home = homedir(),
1311
1365
  // The folder whose projects are left out as temporary (the OS's temp directory).
1312
- temp = tmpdir(), env, out = console.log, } = {}) {
1366
+ temp = tmpdir(), env, out = console.log, progress, }, stops) {
1313
1367
  // The server's own secrets, kept sealed in the store, open only under the server's seal key: it is
1314
1368
  // booted the one way the server and runner boot it (seal-key.ts bootSealKey) once the store is open (keyed below), and
1315
1369
  // checked against it. The key handed over wins (this process's, else a caller's own environment's: a test's), else the
@@ -1377,8 +1431,8 @@ temp = tmpdir(), env, out = console.log, } = {}) {
1377
1431
  console.error(`${error.message}\n\n${usage}`);
1378
1432
  return 2;
1379
1433
  }
1380
- const port = values.port === undefined ? DEFAULT_PORT : Number(values.port);
1381
- if (!Number.isInteger(port) || port < 0 || port > 65_535) {
1434
+ const port = values.port === undefined ? undefined : Number(values.port);
1435
+ if (port !== undefined && (!Number.isInteger(port) || port < 0 || port > 65_535)) {
1382
1436
  console.error(`--port takes a port number\n\n${usage}`);
1383
1437
  return 2;
1384
1438
  }
@@ -1454,7 +1508,7 @@ temp = tmpdir(), env, out = console.log, } = {}) {
1454
1508
  out(`${plan.secretsFound} secret${plan.secretsFound === 1 ? "" : "s"} would be removed`);
1455
1509
  for (const line of leftOutLines(plan.skipped))
1456
1510
  out(line);
1457
- for (const line of summaryLines(found, open, { dryRun: true }))
1511
+ for (const line of summaryLines(found, open))
1458
1512
  out(line);
1459
1513
  return 0;
1460
1514
  }
@@ -1469,7 +1523,7 @@ temp = tmpdir(), env, out = console.log, } = {}) {
1469
1523
  }
1470
1524
  catch (error) {
1471
1525
  if (error instanceof StoreFromEarlierVersion || error instanceof StoreOwned) {
1472
- warnings.push(`agentrun-serve import: ${error.message}`);
1526
+ warnings.push(`agentrun-serve import: ${error.message}${error instanceof StoreOwned ? `\n${STOP_SERVER_FIRST}` : ""}`);
1473
1527
  return 1;
1474
1528
  }
1475
1529
  throw error;
@@ -1483,9 +1537,22 @@ temp = tmpdir(), env, out = console.log, } = {}) {
1483
1537
  return 1;
1484
1538
  throw error;
1485
1539
  }
1486
- const options = await optionsFrom(store);
1487
- const plan = await planImport(options, store);
1488
- const report = await runImport(store, plan, options);
1540
+ stops.hook();
1541
+ let plan;
1542
+ let report;
1543
+ try {
1544
+ const options = {
1545
+ ...(await optionsFrom(store)),
1546
+ signal: stops.signal,
1547
+ onProgress: (step, done, total) => progress.show(`${step === "keys" ? "Checking sessions for keys" : "Importing sessions"}: ${done.toLocaleString("en-US")} of ${total.toLocaleString("en-US")}`),
1548
+ };
1549
+ progress.show("Looking for sessions…");
1550
+ plan = await planImport(options, store);
1551
+ report = await runImport(store, plan, options);
1552
+ }
1553
+ finally {
1554
+ progress.done();
1555
+ }
1489
1556
  for (const agent of report.agents)
1490
1557
  out(`${agent.cwd} ${agent.created ? "new agent" : "agent held"} ${agent.id} imported ${agent.runs}${agent.already ? `, already imported ${agent.already}` : ""}`);
1491
1558
  if (report.already)
@@ -1493,14 +1560,18 @@ temp = tmpdir(), env, out = console.log, } = {}) {
1493
1560
  if (values.verbose)
1494
1561
  for (const s of report.skipped)
1495
1562
  out(`skipped ${s.what}: ${s.why}`);
1496
- out(`${report.agents.length} agents, ${report.agents.reduce((n, a) => n + a.runs, 0)} runs imported into ${dir}`);
1563
+ const taken = report.agents.reduce((n, a) => n + a.runs, 0);
1564
+ out(`${report.agents.length} agents, ${taken} runs imported into ${dir}`);
1497
1565
  out(`${report.secretsRemoved ?? 0} secret${report.secretsRemoved === 1 ? "" : "s"} removed`);
1498
1566
  for (const line of leftOutLines(report.skipped))
1499
1567
  out(line);
1568
+ for (const { cwd, source, model } of report.modelsLeftOut ?? [])
1569
+ out(`model not kept: ${cwd} (${source}) ran on ${model}, which no model catalog here lists; its agent runs on the server's default model until you pick one`);
1500
1570
  // Every session found: those imported now, those held before, and those whose file an earlier import read whole.
1501
1571
  const held = await importedIn(store);
1502
1572
  const runs = [...plan.projects.flatMap((p) => p.sessions.flatMap((s) => held.get(`${s.source}:${s.id}`) ?? [])), ...plan.held];
1503
- for (const line of summaryLines([...(await foundAll(store, runs)), ...(await untiedFound(plan))], open))
1573
+ const imported = { sessions: taken, agents: report.agents.filter((a) => a.runs > 0).length, stopped: report.stopped };
1574
+ for (const line of summaryLines([...(await foundAll(store, runs)), ...(await untiedFound(plan))], open, imported))
1504
1575
  out(line);
1505
1576
  return 0;
1506
1577
  }
@@ -1526,13 +1597,44 @@ async function foundAll(store, runIds) {
1526
1597
  /** The address the summary's Open line names on this machine: the one a local server listens on by default. */
1527
1598
  const LOCAL = "127.0.0.1"; // key-gate: loopback-rule the default address a server on this machine listens on; a hint printed, the line dials nothing
1528
1599
  /** Where a person opens the console: the server's public address when one is set (as the server takes it), else this
1529
- * machine's at `port`. A hint after an import, not a server setting. */
1600
+ * machine's at `port` (`--port`), else at the default port, said as a guess: a server started with no port takes the
1601
+ * first free one from it, and the import, which runs with the server stopped, cannot know which. A hint after an
1602
+ * import, not a server setting. */
1530
1603
  function openAt(env, port) {
1531
1604
  const given = env.AGENTRUN_PUBLIC_URL || env.RENDER_EXTERNAL_URL;
1532
1605
  const parsed = given && URL.canParse(given) ? new URL(given) : undefined;
1533
1606
  if (parsed && /^https?:$/.test(parsed.protocol))
1534
- return parsed.href.replace(/\/+$/, "");
1535
- return `http://${LOCAL}:${port === 0 ? "<the port the server picks>" : port}`;
1607
+ return { url: parsed.href.replace(/\/+$/, ""), known: true };
1608
+ // Port 0: any free port, which only the server's start knows.
1609
+ if (port === 0)
1610
+ return { known: false };
1611
+ return { url: `http://${LOCAL}:${port ?? DEFAULT_PORT}`, known: port !== undefined };
1612
+ }
1613
+ /** What a refused import says when the server holds the store: it runs with the server stopped. */
1614
+ const STOP_SERVER_FIRST = "Stop the server first (Ctrl+C where it runs, or `npx @parcha/agentrun service stop` when it runs as a service), run the import, then start the server again.";
1615
+ /** Progress on stderr when it is a terminal: one line rewritten in place, at most every 100 ms, cleared at the end; off a
1616
+ * terminal (a log, a pipe), nothing. It holds counts alone, never a name or a path, so nothing in it is a secret. */
1617
+ function terminalProgress() {
1618
+ const stream = process.stderr;
1619
+ if (!stream.isTTY)
1620
+ return { show: () => undefined, done: () => undefined };
1621
+ let shownAt = 0;
1622
+ let shown = false;
1623
+ return {
1624
+ show: (text) => {
1625
+ const now = Date.now();
1626
+ if (shown && now - shownAt < 100)
1627
+ return;
1628
+ shownAt = now;
1629
+ shown = true;
1630
+ stream.write(`\r\x1b[2K${text}`);
1631
+ },
1632
+ done: () => {
1633
+ if (shown)
1634
+ stream.write("\r\x1b[2K");
1635
+ shown = false;
1636
+ },
1637
+ };
1536
1638
  }
1537
1639
  /** The "/"-segments of `path` a key touches (by their index): each whose blanking takes a key out of the path. Blanked
1538
1640
  * with spaces, which end every shape and are in no environment's key; the blanked paths are never kept, so they go
@@ -4,6 +4,7 @@ export type RunKey = {
4
4
  who: string;
5
5
  field: string;
6
6
  saved: boolean;
7
+ where?: string;
7
8
  };
8
9
  /** The key `harness`'s run of model `ref` (the revision's; none, this host's default for the harness) sends, by the route
9
10
  * its wire takes (provider.ts; pi's, model.ts); undefined where it is not a model key this server names. */
@@ -6,7 +6,8 @@ import { DEFAULT_HARNESS } from "./harness.js";
6
6
  import { harnessOf } from "./harness-table.js";
7
7
  import { redactSecrets, valueMatcher } from "./learn/secrets.js";
8
8
  import { hostModel, MODEL_KEYS } from "./model.js";
9
- import { openRouterOnly, WIRES } from "./provider.js";
9
+ import { modelWire, openRouterOnly, WIRES } from "./provider.js";
10
+ import { savedGatewayIn } from "./model-gateway.js";
10
11
  const row = (id) => {
11
12
  const found = MODEL_KEYS.find((r) => r.id === id);
12
13
  return found && { who: found.label, field: found.field, saved: true };
@@ -16,8 +17,12 @@ const row = (id) => {
16
17
  export function runKeyOf(env, harness = DEFAULT_HARNESS, ref) {
17
18
  const named = ref ?? hostModel(env, "default", harness);
18
19
  const provider = named?.includes("/") ? named.slice(0, named.indexOf("/")) : undefined;
19
- const gateway = { who: "The gateway at AGENT_MODEL_BASE_URL", field: "AGENT_MODEL_API_KEY", saved: false };
20
+ // A gateway saved in the console (model-gateway.ts) is fixed there, never where AgentRun starts.
21
+ const gateway = savedGatewayIn(env) ? { who: "The model gateway saved in Settings → Model keys", field: "its key", saved: true, where: "enter its key again in Settings → Model keys → Use a model gateway, and test it there." } : { who: "The gateway at AGENT_MODEL_BASE_URL", field: "AGENT_MODEL_API_KEY", saved: false };
20
22
  const wire = harnessOf(env, harness)?.facts?.wire;
23
+ // A harness billed to its own plan (Cursor's) runs on no model key of this server's.
24
+ if (wire && !modelWire(wire))
25
+ return undefined;
21
26
  // Serve's gateway takes every request of the wire it serves, pi's too; a wire it does not serve never goes there.
22
27
  if (env.AGENT_MODEL_BASE_URL && (!wire || WIRES[wire].gateway))
23
28
  return gateway;
@@ -169,7 +174,7 @@ export function keyRefusal(text, key, secrets = []) {
169
174
  if (!at)
170
175
  return undefined;
171
176
  const detail = detailOf(said.slice(at[0].length));
172
- const where = key.saved ? "set it where AgentRun starts, or save it in Settings → Model keys." : "set it where AgentRun starts.";
177
+ const where = key.where ?? (key.saved ? "set it where AgentRun starts, or save it in Settings → Model keys." : "set it where AgentRun starts.");
173
178
  return `${key.who} refused ${key.field} (401${detail ? `: ${detail}` : ""}): ${where}`;
174
179
  }
175
180
  /** Codex's errors end on the address it sent the request to (", url: " and then serve's own loopback model proxy, with
@@ -33,6 +33,6 @@ export declare const TOOL_KEY_ROWS: readonly [{
33
33
  readonly unlocks: readonly ["decisions.jev"];
34
34
  }];
35
35
  /** What `vars` (the variables a tool needs that this server does not hold) are, as a person fixes them: each savable
36
- * key's "a <Label> key: save one in Settings → Tool keys (or set <VARS> where the server starts)", then any variable no
36
+ * key's "a <Label> key: save one in Settings → API Keys (or set <VARS> where the server starts)", then any variable no
37
37
  * key saves, to set where the server starts. */
38
38
  export declare function keyNeeded(vars: readonly string[]): string;
package/dist/key-words.js CHANGED
@@ -1,4 +1,4 @@
1
- // The keys a person may save on Settings → Tool keys (tool-keys.ts' TOOL_KEYS reads the tool rows from here), and the
1
+ // The keys a person may save on Settings → API Keys (tool-keys.ts' TOOL_KEYS reads the tool rows from here), and the
2
2
  // words for one a tool needs that this server does not hold: where the person saves it is named first, then the
3
3
  // variable to set where the server starts, since a key saved and then removed in Settings was never in the environment.
4
4
  import { MODEL_KEYS } from "./model.js";
@@ -15,7 +15,7 @@ export const TOOL_KEY_ROWS = [
15
15
  // Jev's decision provider (decisions.ts' `jev`), on TypeSafe's key: a workflow's judges, as Parallel's key unlocks its.
16
16
  { id: "typesafe", kind: "tool", label: "TypeSafe (Jev)", fields: ["TYPESAFE_API_KEY"], unlocks: ["decisions.jev"] },
17
17
  ];
18
- /** Every key Settings → Tool keys saves, tool keys and model keys alike (a saved model key reaches every run): its label
18
+ /** Every key Settings → API Keys saves, tool keys and model keys alike (a saved model key reaches every run): its label
19
19
  * and fields. */
20
20
  const SAVABLE = [
21
21
  ...TOOL_KEY_ROWS.map((row) => ({ label: row.label, fields: row.fields })),
@@ -23,7 +23,7 @@ const SAVABLE = [
23
23
  ];
24
24
  const article = (label) => (/^[AEIOU]/i.test(label) ? "an" : "a");
25
25
  /** What `vars` (the variables a tool needs that this server does not hold) are, as a person fixes them: each savable
26
- * key's "a <Label> key: save one in Settings → Tool keys (or set <VARS> where the server starts)", then any variable no
26
+ * key's "a <Label> key: save one in Settings → API Keys (or set <VARS> where the server starts)", then any variable no
27
27
  * key saves, to set where the server starts. */
28
28
  export function keyNeeded(vars) {
29
29
  const left = [...vars];
@@ -34,7 +34,7 @@ export function keyNeeded(vars) {
34
34
  continue;
35
35
  for (const field of hit)
36
36
  left.splice(left.indexOf(field), 1);
37
- parts.push(`${article(row.label)} ${row.label} key: save one in Settings → Tool keys (or set ${hit.join(" and ")} where the server starts)`);
37
+ parts.push(`${article(row.label)} ${row.label} key: save one in Settings → API Keys (or set ${hit.join(" and ")} where the server starts)`);
38
38
  }
39
39
  for (const name of left)
40
40
  parts.push(`${name}, set where the server starts`);
@@ -86,6 +86,9 @@ export declare function compactStateProblems(doc: unknown): string[];
86
86
  * H5's judge flagged 149 of 170 answers while 416 of 429 quotes were in the pages, and could not tell the 8 answers
87
87
  * quoting text no page held from the rest; code can. One line each, in words the compile retry acts on. */
88
88
  export declare function quoteCheckProblems(doc: unknown): string[];
89
+ /** The labels a run's loop events give `workflow`'s quote re-pick (quoteRule `repicks`): what marks a loop's exit a
90
+ * re-pick (learned-nodes.ts LoopRow `repick`). Any other loop that ran twice is an ordinary loop. */
91
+ export declare function repickLabels(workflow: unknown): Set<string>;
89
92
  /** What must never be stored, in every change's name and text, whatever the checks would refuse it for first: the
90
93
  * name and text scans (nameScanned, textOf) of each change, its text read whole (a file over its cap, one not a regular
91
94
  * file included), printable as checkDraft's are. A text that is not UTF-8 is `encoding`: unread, so never trusted.
@@ -496,14 +496,19 @@ const siteKey = (site) => site.keys.join("\u0000");
496
496
  /** The passes of a checked answer's re-pick loop: the draft, then one re-pick. */
497
497
  const REPICK_PASSES = 2;
498
498
  const quoteMissingText = ({ path, field, pages }) => `{"predicate": "quote_missing", "path": ${JSON.stringify(path)}${field ? `, "field": ${JSON.stringify(field)}` : ""}, "pages": ${JSON.stringify(pages)}}`;
499
+ /** The quote_missing a re-pick loop waits on: `step`'s, when it is a loop of REPICK_PASSES until `not` of a quote_missing. */
500
+ const repickCheckOf = (step) => isNode(step) && step.node === "loop" && step.maxIters === REPICK_PASSES && isObject(step.until) && step.until.predicate === "not" && isObject(step.until.of) && step.until.of.predicate === "quote_missing" ? step.until.of : undefined;
499
501
  /** Whether `step` is the re-pick of an answer `check` reads: a loop of REPICK_PASSES until that check's quote_missing (its
500
502
  * path, field and pages) no longer holds. */
501
- const repicks = (step, check) => {
502
- if (!isNode(step) || step.node !== "loop" || step.maxIters !== REPICK_PASSES || !isObject(step.until) || step.until.predicate !== "not" || !isObject(step.until.of))
503
- return false;
504
- const of = step.until.of;
505
- return of.predicate === "quote_missing" && of.path === check.path && (of.field ?? "") === check.field && JSON.stringify(of.pages) === JSON.stringify(check.pages);
503
+ const repickOn = (step, check) => {
504
+ const of = repickCheckOf(step);
505
+ return !!of && of.path === check.path && (of.field ?? "") === check.field && JSON.stringify(of.pages) === JSON.stringify(check.pages);
506
506
  };
507
+ /** The labels a run's loop events give `workflow`'s quote re-pick (quoteRule `repicks`): what marks a loop's exit a
508
+ * re-pick (learned-nodes.ts LoopRow `repick`). Any other loop that ran twice is an ordinary loop. */
509
+ export function repickLabels(workflow) {
510
+ return new Set(isObject(workflow) ? quoteRule(workflow, {}).repicks : []);
511
+ }
507
512
  /** Whether a step's `state` map names state key `key` as the whole marked placeholder `"{answer?}"` (a whole string):
508
513
  * null on a re-pick loop's first pass, before any draft exists, and the failed draft on its second. No path below the
509
514
  * key counts (`"{answer.x?}"`, `"{state.answer?}"`, unmarked `"{answer}"`): paths are not validated, so only the key
@@ -550,14 +555,24 @@ const quoteEscalatesIn = (node, depth = 0) => {
550
555
  * (its path and field; a place no one pair reads is refused, as quote_missing reads none of it). Its pages are state keys holding a page as
551
556
  * fetched (holdsPage). A composed workflow node writing the whole answer (its `as` the answer's path) whose child
552
557
  * passes this rule in its own state has checked the places in the answer its child's schema declares too; the parent
553
- * still checks any other place its own schema declares. `checked`: the places a passing workflow checked. */
558
+ * still checks any other place its own schema declares. `checked`: the places a passing workflow checked. `repicks`:
559
+ * the answer's re-pick as a run's loop events label it, whether the rule applies or not: the step writing the answer
560
+ * when it is a loop of REPICK_PASSES until `not` of a quote_missing, else that step's composed child's, which the DSL
561
+ * labels `<step>/<its label>` (scopeDepsToChild). */
554
562
  function quoteRule(workflow, schemasAround, depth = 0) {
555
- const none = { applies: false, problems: [], checked: [] };
556
563
  const output = isObject(workflow.output) ? workflow.output : {};
557
564
  const answerPath = typeof output.path === "string" ? output.path : "";
558
565
  const schemas = isObject(workflow.schemas) ? workflow.schemas : schemasAround;
559
566
  const schemaId = typeof output.schemaId === "string" ? output.schemaId : "";
560
- if (!answerPath || !Object.hasOwn(schemas, schemaId) || depth > 8)
567
+ if (!answerPath || depth > 8)
568
+ return { applies: false, problems: [], checked: [], repicks: [] };
569
+ const steps = isNode(workflow.root) && workflow.root.node === "chain" && Array.isArray(workflow.root.steps) ? workflow.root.steps : [workflow.root];
570
+ const answered = steps.findLastIndex((step) => writesKey(step, answerPath.split(".")[0]));
571
+ const writer = steps[answered];
572
+ const child = isNode(writer) && writer.node === "workflow" && isObject(writer.workflow) ? quoteRule(writer.workflow, schemas, depth + 1) : undefined;
573
+ const repicks = !isNode(writer) ? [] : repickCheckOf(writer) ? [String(writer.label)] : (child?.repicks ?? []).map((label) => `${String(writer.label)}/${label}`);
574
+ const none = { applies: false, problems: [], checked: [], repicks };
575
+ if (!Object.hasOwn(schemas, schemaId))
561
576
  return none;
562
577
  // Its refs read as the DSL reads them (resolveSchemaForWorkflow): the schema's own inline definitions first, then the catalog.
563
578
  const answerSchema = schemas[schemaId];
@@ -566,16 +581,12 @@ function quoteRule(workflow, schemasAround, depth = 0) {
566
581
  if ((!declared.length && !over) || !fetches(workflow.root))
567
582
  return none;
568
583
  if (over)
569
- return { applies: true, checked: [], problems: [`the answer's schema (${schemaId.slice(0, 64)}) holds quotes in more than ${QUOTE_SITES_MAX} places or nests past ${QUOTE_SITE_DEPTH} keys, past what the quote check reads, and the workflow fetches pages: give the answer fewer places holding quotes, each a quote, a list of quotes or a list of records holding one`] };
584
+ return { applies: true, checked: [], repicks, problems: [`the answer's schema (${schemaId.slice(0, 64)}) holds quotes in more than ${QUOTE_SITES_MAX} places or nests past ${QUOTE_SITE_DEPTH} keys, past what the quote check reads, and the workflow fetches pages: give the answer fewer places holding quotes, each a quote, a list of quotes or a list of records holding one`] };
570
585
  const where = (site) => `${schemaId}.${site.keys.join(".").replace(/\.(\[\]|\*)/g, "$1")}`.slice(0, 120);
571
586
  const pages = pageKeysOf(workflow.root);
572
- const steps = isNode(workflow.root) && workflow.root.node === "chain" && Array.isArray(workflow.root.steps) ? workflow.root.steps : [workflow.root];
573
- const answered = steps.findLastIndex((step) => writesKey(step, answerPath.split(".")[0]));
574
- const writer = steps[answered];
575
- const child = isNode(writer) && writer.node === "workflow" && isObject(writer.workflow) ? quoteRule(writer.workflow, schemas, depth + 1) : none;
576
- const covered = child.applies && !child.problems.length && isNode(writer) && writer.as === answerPath ? child.checked : [];
587
+ const covered = child?.applies && !child.problems.length && isNode(writer) && writer.as === answerPath ? child.checked : [];
577
588
  const sites = declared.filter((site) => !covered.includes(siteKey(site)));
578
- const passed = { applies: true, problems: [], checked: declared.map(siteKey) };
589
+ const passed = { applies: true, problems: [], checked: declared.map(siteKey), repicks };
579
590
  if (!sites.length)
580
591
  return passed;
581
592
  // A place no one path and field reads (quotes under two lists, in a map, in records with no quote key): quote_missing
@@ -620,18 +631,18 @@ function quoteRule(workflow, schemasAround, depth = 0) {
620
631
  // A check inside the loop's body hands back on the first draft's miss: the loop never re-picks.
621
632
  problems.push(`the re-pick loop ${JSON.stringify(String(writer.label ?? "(no label)").slice(0, 64))} holds the quote_missing escalate ${JSON.stringify(quoteEscalatesIn(writer.body)[0])} in its body, which hands back on the first draft's miss, so the loop never re-picks: the check after the loop, never inside it, as a step of the top-level chain`);
622
633
  }
623
- else if (!problems.length && first && isNode(writer) && writer.node === "loop" && repicks(writer, first) && blindRepicks(writer.body, answerPath.split(".")[0]).length) {
634
+ else if (!problems.length && first && isNode(writer) && writer.node === "loop" && repickOn(writer, first) && blindRepicks(writer.body, answerPath.split(".")[0]).length) {
624
635
  // The re-pick must see the failed draft, and only through a state map that names it optionally (never the pages).
625
636
  problems.push(`the step ${JSON.stringify(blindRepicks(writer.body, answerPath.split(".")[0])[0])} in the re-pick loop ${JSON.stringify(String(writer.label ?? "(no label)").slice(0, 64))} writes the answer without reading its failed draft, so its second pass writes the same miss again: give it ${draftWords(answerPath.split(".")[0])}. Naming it unmarked ("{${answerPath.split(".")[0]}}") fails the first pass, and no "state" map reads the whole state, the pages included`);
626
637
  }
627
- else if (!problems.length && first && !checks.every((check) => repicks(writer, check))) {
638
+ else if (!problems.length && first && !checks.every((check) => repickOn(writer, check))) {
628
639
  problems.push(`the step ${JSON.stringify(String(isNode(writer) ? writer.label ?? writer.node : "(no label)").slice(0, 64))} writes the answer and the escalate ${JSON.stringify(first.label)} hands it back on its first quote miss: give it one re-pick first, the step in a loop {"node": "loop", "label": "repick", "maxIters": ${REPICK_PASSES}, "until": {"predicate": "not", "of": ${quoteMissingText(first)}}, "body": <the step>} in its place, the step with ${draftWords(answerPath.split(".")[0])} and its instructions saying that a draft there failed the quote check, so a draft quoting text no page holds is written once more and only a second miss hands back: the check after the loop, never inside it`);
629
640
  }
630
641
  }
631
642
  // A composed workflow writing the answer that applies the rule and fails it: its own check is the one to fix.
632
- if (problems.length && child.problems.length)
633
- return { applies: true, checked: [], problems: child.problems.map((problem) => `the composed workflow step ${JSON.stringify(String(writer.label ?? "(no label)").slice(0, 64))} writes the answer: ${problem}`) };
634
- return problems.length ? { applies: true, problems, checked: [] } : passed;
643
+ if (problems.length && child?.problems.length)
644
+ return { applies: true, checked: [], repicks, problems: child.problems.map((problem) => `the composed workflow step ${JSON.stringify(String(writer.label ?? "(no label)").slice(0, 64))} writes the answer: ${problem}`) };
645
+ return problems.length ? { applies: true, problems, checked: [], repicks } : passed;
635
646
  }
636
647
  /** What a draft may write of a workflow (`place`), by itself: a good folder name, never a deletion, a regular file
637
648
  * within CAPS.file (a README within CAPS.readme), its text as textOf takes it, and in shape: a draft the DSL validates
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { LEARNED_MAX_TURNS, WORKFLOW_NAME } from "./workflow-draft.js";
3
3
  import { championOf, checkShares, promotionOf } from "./promote.js";
4
+ import { listed } from "../learning-words.js";
4
5
  import { excerptShown, redactSecrets } from "./secrets.js";
5
6
  import { isShadowRun } from "./audit.js";
6
7
  /** The info word that opens a workflow draft's block in a compile answer: ````workflow <name>, fenced with four backticks
@@ -143,6 +144,11 @@ const JUDGING_KINDS = ["judge", "pick", "sift", "route"];
143
144
  const QUOTE_CHECK_RULE = "An answer that quotes pages a call step fetched is checked in code: an escalate on `{\"predicate\": \"quote_missing\", \"path\": \"<the answer's quotes, e.g. answer.evidence>\", \"field\": \"quote\", \"pages\": [<the keys the call steps write>]}`, a step of the top-level chain after the step that writes the answer, hands back an answer quoting text no fetched page holds. Its pages are what the calls fetched, never a model's summary of them. Never ask a judge or an `ask` whether quotes are verbatim. Give the answer one re-pick before it hands back: make the step that writes the answer the body of a `loop` with `\"maxIters\": 2` and `\"until\": {\"predicate\": \"not\", \"of\": <that same quote_missing>}`; the step in the loop reads the compact facts and its own failed draft through its `state` map, e.g. `{\"facts\": \"{facts}\", \"draft\": \"{answer?}\"}`: the `?` makes the placeholder null on the first pass, before any draft exists, and the failed draft on the second (unmarked, `\"{answer}\"` fails the first pass; with no `state` map the step reads the whole state, pages included), and its instructions say that a draft there failed the quote check (recopy each quote exactly from the facts, or quote another line); keep the escalate a step of the top-level chain: the check after the loop, never inside it (a check in its body hands back on the first miss, so the loop never re-picks); only a second miss hands back. The loop's `until` reads one check: keep the answer's quotes in one place one `quote_missing` reads (a quote, a list of quotes or a list of records each holding its quote at one field), never a quote that may be a string or records, nor quotes in two places.";
144
145
  /** The compact-state rule (check.ts compactStateProblems): a model step off the fast tier never reads a page. */
145
146
  const COMPACT_STATE_RULE = "A model step off the fast tier (no `\"tier\": \"fast\"`: the answering step among them) never reads a page a call step fetched. Give it a `state` map naming only compact keys: the facts a fast-tier extract step wrote from the pages (the verbatim lines the answer will quote among them), the run's own small input fields, and, in a re-pick loop, its own draft as `\"{answer?}\"`. With no `state` map a step reads the whole state, every page in it. Pages reach the agent's model only through a fast-tier step's output.";
147
+ /** SDK execution is caller-owned, and nothing promotes an SDK agent's workflow (runner/harness-loops.ts skips the
148
+ * promotion gate; no shadow check runs where its tools run). So the words call it compiled and unchecked, and leave the
149
+ * choice to the agent: never an instruction to prefer it. */
150
+ const SDK_WORKFLOW_SELECTION = "What you write is a compiled workflow: no check has compared it with the agent's own answers, and nothing promotes it. The agent decides whether one fits a task under its original instructions and permissions; backend code can also choose it. Execution still requires an explicit MCP tool call through the registered bridge. Saving alone executes nothing; the server does not pre-run it before the native agent. The caller may derive argument values from the current request and observed tool data, but must not invent missing values.";
151
+ const SDK_WORKFLOW_APPLICABILITY = "Its description says what task it solves and exactly when it matches, not how the bridge is invoked; it never tells the agent to use it in place of the agent's own tool calls or on every task it could apply to. Input descriptions explain the data each field takes. Do not add an explicit-user-request or backend-only precondition unless the original job actually requires one; a required callback still runs through the registered bridge under the original policy.";
146
152
  /** This host's addendum to the DSL's author contract: the node kinds it runs, and its rules, each one the checks hold a
147
153
  * draft to (learn/workflow-draft.ts draftProblems; check.ts). */
148
154
  export function learnedHost(options) {
@@ -153,7 +159,7 @@ export function learnedHost(options) {
153
159
  name: "AgentRun backend SDK workflow bridge",
154
160
  nodeKinds: ["chain", "call", "escalate", "map", "parallel", "loop", "route", ...(model ? ["extract", "decide", "agent"] : []), ...(judge ? ["judge", "pick", "sift"] : [])],
155
161
  rules: [
156
- "The backend explicitly invokes a saved workflow through its registered MCP bridge. Saving it never automatically runs it on later tasks.",
162
+ SDK_WORKFLOW_SELECTION,
157
163
  tools.length ? `A call node runs via tool alone and names only this allowed callback catalog: ${tools.join(", ")}. Its arguments and output schema must match that callback. Never shell or executor.` : "There is no allowed tool callback: author no call node.",
158
164
  model ? "runNode is explicitly registered for tool-free model nodes. It owns model selection; name no model or tier and grant its model nodes no tools." : "This backend provides NO runNode: author no extract, decide or agent node. Never invent a model adapter.",
159
165
  judge ? "runJudge is explicitly registered for decision nodes; the backend owns its implementation." : "This backend provides NO runJudge: author no judge, pick, sift, verification or model-based predicate.",
@@ -313,7 +319,7 @@ export function compilePrompt(ask) {
313
319
  ? [
314
320
  COMPILE_OPENS.new,
315
321
  "This agent has done this job enough times to write it down. Compile the whole job, from the run's input to its answer, into one workflow:",
316
- sdk ? "The backend explicitly invokes it through its registered MCP bridge when appropriate. It is never automatically run before later tasks." : "on later runs it runs first, before you, and answers alone, or ends on an escalate node and hands the case back to you with what it found.",
322
+ sdk ? "Write a reusable job the caller can choose for a matching later task." : "on later runs it runs first, before you, and answers alone, or ends on an escalate node and hands the case back to you with what it found.",
317
323
  "Do the steps the runs below took, the way they took them, keeping every correction your owner gave. Name it for the job.",
318
324
  OUTPUT_FORMAT,
319
325
  ]
@@ -339,6 +345,7 @@ export function compilePrompt(ask) {
339
345
  ];
340
346
  return [
341
347
  ...why,
348
+ ...(sdk ? [SDK_WORKFLOW_SELECTION, SDK_WORKFLOW_APPLICABILITY] : []),
342
349
  "Use no tool in this turn.",
343
350
  "",
344
351
  "## The workflow language",
@@ -354,7 +361,7 @@ export function compilePrompt(ask) {
354
361
  "",
355
362
  "## This job",
356
363
  "",
357
- fields ? (sdk ? `This task was given these fields: ${fields}. Declare the input the backend must explicitly supply to the bridge; it is never automatically mapped from later tasks.` : `This run's input has these fields: ${fields}. The workflow's input schema requires them, by these names.`) : "This run's input is the message it was given.",
364
+ fields ? (sdk ? `This task was given these fields: ${fields}. Declare the data the caller supplies to the bridge, using field names and descriptions that explain that data. The server does not populate these arguments itself.` : `This run's input has these fields: ${fields}. The workflow's input schema requires them, by these names.`) : "This run's input is the message it was given.",
358
365
  ask.tools.length ? `A call node may run only these tools: ${ask.tools.join(", ")}.` : "There is no tool for a call node to run.",
359
366
  ...describedLines(ask.described ?? [], ask.tools),
360
367
  ...(ask.mode === "revise" && ask.current ? ["", `\`${ask.workflow}\` as it is now:`, ...fenced("its workflow.json", clean(ask.current, 32_000))] : []),
@@ -380,7 +387,7 @@ function heldLine(workflow, held) {
380
387
  }
381
388
  if (check && check.n !== undefined) {
382
389
  const shares = checkShares({ n: check.n, agreed: check.agreed ?? 0, alone: check.alone ?? 0 });
383
- return `Your learned workflow \`${workflow}\` does not run first: checked on ${check.n} ${check.n === 1 ? "input" : "inputs"} of your last ${check.compile_after} completed runs, it answered ${check.alone ?? 0} alone (${pct(shares.alone)}, at least ${pct(check.alone_min)} needed), and ${check.agreed ?? 0} of those said what you said (${pct(shares.agreement)}, at least ${pct(check.agree_min)} needed).`;
390
+ return `Your learned workflow \`${workflow}\` does not run first: checked on ${check.n} ${check.n === 1 ? "input" : "inputs"} of your last ${check.compile_after} completed runs, it answered ${check.alone ?? 0} alone (${pct(shares.alone)}, at least ${pct(check.alone_min)} needed), and ${check.agreed ?? 0} of those said what you said${check.agree_on?.length ? ` on ${listed(check.agree_on)}` : ""} (${pct(shares.agreement)}, at least ${pct(check.agree_min)} needed).`;
384
391
  }
385
392
  const why = `it was held (${clean(held.reason, 400).replace(/\n/g, " ").replace(/\.$/, "")}).`;
386
393
  return `Your learned workflow \`${workflow}\` does not run first: ${why} It stays held until a new revision of it.`;