@parcha/agentrun-serve 0.1.0-beta.46 → 0.1.0-beta.48

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 (292) hide show
  1. package/CHANGELOG.md +211 -1
  2. package/NOTICE +4 -0
  3. package/README.md +350 -53
  4. package/dist/acp-package.d.ts +53 -6
  5. package/dist/acp-package.js +3 -3
  6. package/dist/adapter-facts.d.ts +3 -4
  7. package/dist/adapter-facts.js +4 -4
  8. package/dist/adapters.d.ts +3 -5
  9. package/dist/adapters.js +1 -31
  10. package/dist/agents-store.d.ts +5 -3
  11. package/dist/agents-store.js +13 -8
  12. package/dist/answer-json.d.ts +10 -0
  13. package/dist/answer-json.js +24 -0
  14. package/dist/api-only.d.ts +11 -11
  15. package/dist/api-only.js +16 -11
  16. package/dist/archil-routes.js +2 -1
  17. package/dist/browser-live.d.ts +9 -4
  18. package/dist/browser-live.js +18 -5
  19. package/dist/cap.js +10 -2
  20. package/dist/chatgpt-plan.js +2 -1
  21. package/dist/cli.js +109 -41
  22. package/dist/composio-made.d.ts +19 -2
  23. package/dist/composio-made.js +17 -5
  24. package/dist/composio-preset.d.ts +42 -7
  25. package/dist/composio-preset.js +106 -70
  26. package/dist/composio-triggers.d.ts +9 -4
  27. package/dist/composio-triggers.js +20 -13
  28. package/dist/computer-attach.d.ts +11 -10
  29. package/dist/computer-attach.js +13 -14
  30. package/dist/computer-commands.d.ts +3 -0
  31. package/dist/computer-commands.js +3 -2
  32. package/dist/computer-lost.d.ts +4 -0
  33. package/dist/computer-lost.js +8 -3
  34. package/dist/computer-routes.d.ts +8 -5
  35. package/dist/computer-routes.js +7 -5
  36. package/dist/computer-setting.d.ts +2 -0
  37. package/dist/computer-setting.js +2 -0
  38. package/dist/computers.d.ts +14 -76
  39. package/dist/computers.js +24 -68
  40. package/dist/conformance.d.ts +4 -0
  41. package/dist/conformance.js +6 -0
  42. package/dist/console/assets/index-CTGegcKt.css +1 -0
  43. package/dist/console/assets/index-D1Se6mgG.js +715 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/cost-heal.d.ts +13 -0
  46. package/dist/cost-heal.js +27 -0
  47. package/dist/dial-relay.d.ts +6 -2
  48. package/dist/dial-relay.js +9 -12
  49. package/dist/email/routes.js +2 -1
  50. package/dist/errors.d.ts +2 -0
  51. package/dist/errors.js +5 -0
  52. package/dist/exa-keyless.d.ts +1 -1
  53. package/dist/exa-keyless.js +1 -1
  54. package/dist/faux-computers.d.ts +2 -3
  55. package/dist/faux-computers.js +9 -31
  56. package/dist/github-connection.js +2 -1
  57. package/dist/harness-archive.d.ts +19 -2
  58. package/dist/harness-archive.js +49 -15
  59. package/dist/harness-check.d.ts +75 -0
  60. package/dist/harness-check.js +518 -0
  61. package/dist/harness-cursor.d.ts +28 -0
  62. package/dist/harness-cursor.js +42 -0
  63. package/dist/harness-goose.d.ts +4 -29
  64. package/dist/harness-goose.js +6 -86
  65. package/dist/harness-module.d.ts +4 -0
  66. package/dist/harness-module.js +1 -0
  67. package/dist/harness-owned.d.ts +52 -0
  68. package/dist/harness-owned.js +92 -0
  69. package/dist/harness-recipe.d.ts +127 -0
  70. package/dist/harness-recipe.js +335 -0
  71. package/dist/harness-table.d.ts +120 -5
  72. package/dist/harness-table.js +280 -6
  73. package/dist/harness.d.ts +2 -0
  74. package/dist/harness.js +5 -4
  75. package/dist/host-check.d.ts +6 -0
  76. package/dist/host-check.js +14 -0
  77. package/dist/host.d.ts +10 -3
  78. package/dist/host.js +17 -3
  79. package/dist/import-sources.d.ts +2 -0
  80. package/dist/import-sources.js +2 -0
  81. package/dist/import-summary.d.ts +15 -5
  82. package/dist/import-summary.js +24 -8
  83. package/dist/import.d.ts +24 -4
  84. package/dist/import.js +108 -26
  85. package/dist/key-refusal.d.ts +3 -1
  86. package/dist/key-refusal.js +26 -5
  87. package/dist/key-words.d.ts +1 -1
  88. package/dist/key-words.js +4 -4
  89. package/dist/learn/check.d.ts +3 -0
  90. package/dist/learn/check.js +31 -20
  91. package/dist/learn/compile.js +12 -5
  92. package/dist/learn/promote.d.ts +80 -2
  93. package/dist/learn/promote.js +95 -3
  94. package/dist/learn/secrets.d.ts +4 -0
  95. package/dist/learn/secrets.js +23 -0
  96. package/dist/learned-nodes.d.ts +4 -3
  97. package/dist/learned-workflow.js +4 -1
  98. package/dist/learning-cost.d.ts +6 -16
  99. package/dist/learning-cost.js +6 -12
  100. package/dist/learning-model.d.ts +18 -0
  101. package/dist/learning-model.js +77 -0
  102. package/dist/learning-words.d.ts +2 -0
  103. package/dist/learning-words.js +1 -1
  104. package/dist/listen-first.d.ts +10 -0
  105. package/dist/listen-first.js +25 -1
  106. package/dist/llms.txt +2 -1
  107. package/dist/mcp-gateway.d.ts +2 -1
  108. package/dist/mcp-gateway.js +31 -15
  109. package/dist/mcp-probe.d.ts +18 -6
  110. package/dist/mcp-probe.js +41 -8
  111. package/dist/mcp-secret-writes.d.ts +8 -0
  112. package/dist/mcp-secret-writes.js +104 -4
  113. package/dist/mcp-servers-store.d.ts +11 -5
  114. package/dist/mcp-servers-store.js +46 -20
  115. package/dist/model-form.d.ts +2 -1
  116. package/dist/model-form.js +30 -16
  117. package/dist/model-gateway.d.ts +113 -0
  118. package/dist/model-gateway.js +433 -0
  119. package/dist/model.d.ts +5 -3
  120. package/dist/model.js +26 -18
  121. package/dist/monid.js +1 -1
  122. package/dist/native/binding.d.ts +4 -0
  123. package/dist/native/binding.js +9 -0
  124. package/dist/native/cli.d.ts +3 -2
  125. package/dist/native/cli.js +6 -5
  126. package/dist/openapi.d.ts +2 -0
  127. package/dist/openapi.js +356 -43
  128. package/dist/owner.d.ts +4 -2
  129. package/dist/owner.js +10 -4
  130. package/dist/page.d.ts +9 -0
  131. package/dist/page.js +10 -2
  132. package/dist/port-models.js +17 -10
  133. package/dist/provider.d.ts +3 -3
  134. package/dist/provider.js +12 -3
  135. package/dist/public-address.d.ts +28 -0
  136. package/dist/public-address.js +62 -0
  137. package/dist/run-launch.d.ts +1 -1
  138. package/dist/run-launch.js +1 -1
  139. package/dist/run-secrets.d.ts +3 -2
  140. package/dist/run-secrets.js +7 -4
  141. package/dist/run-trace.js +6 -3
  142. package/dist/runner/adapter-loop.d.ts +14 -8
  143. package/dist/runner/adapter-loop.js +58 -24
  144. package/dist/runner/adapter-run-spec.d.ts +15 -2
  145. package/dist/runner/adapter-run-spec.js +48 -10
  146. package/dist/runner/adapters/index.d.ts +4 -2
  147. package/dist/runner/adapters/index.js +6 -26
  148. package/dist/runner/adapters/pi.d.ts +5 -2
  149. package/dist/runner/adapters/pi.js +7 -4
  150. package/dist/runner/audit.d.ts +7 -0
  151. package/dist/runner/audit.js +15 -6
  152. package/dist/runner/claim-secrets.js +5 -1
  153. package/dist/runner/cli-run-spec.js +22 -10
  154. package/dist/runner/compare-end.d.ts +43 -0
  155. package/dist/runner/compare-end.js +95 -0
  156. package/dist/runner/computer-journal.d.ts +3 -0
  157. package/dist/runner/computer-journal.js +22 -2
  158. package/dist/runner/conformance/host-tools.d.ts +4 -0
  159. package/dist/runner/conformance/host-tools.js +14 -0
  160. package/dist/runner/harness-loops.d.ts +6 -1
  161. package/dist/runner/harness-loops.js +94 -54
  162. package/dist/runner/held.d.ts +5 -4
  163. package/dist/runner/journal-kinds.d.ts +4 -1
  164. package/dist/runner/journal-kinds.js +3 -0
  165. package/dist/runner/loop-contract.d.ts +10 -0
  166. package/dist/runner/main.d.ts +5 -5
  167. package/dist/runner/main.js +62 -11
  168. package/dist/runner/mcp-claim.js +40 -12
  169. package/dist/runner/meta-tools.js +4 -2
  170. package/dist/runner/metrics.d.ts +26 -0
  171. package/dist/runner/metrics.js +44 -1
  172. package/dist/runner/presence.d.ts +44 -0
  173. package/dist/runner/presence.js +96 -0
  174. package/dist/runner/promotion.d.ts +70 -7
  175. package/dist/runner/promotion.js +178 -28
  176. package/dist/runner/run-child-host.js +40 -10
  177. package/dist/runner/runner.d.ts +5 -0
  178. package/dist/runner/runner.js +8 -0
  179. package/dist/runner/sdk-loop.js +25 -1
  180. package/dist/runner/store-port.d.ts +3 -0
  181. package/dist/runner/store-secrets.js +19 -7
  182. package/dist/runner/workflow-first.d.ts +5 -2
  183. package/dist/runner/workflow-first.js +6 -3
  184. package/dist/runner/workflow-spec.js +3 -2
  185. package/dist/runs-over-store.d.ts +7 -2
  186. package/dist/runs-over-store.js +12 -4
  187. package/dist/sdk/check.d.ts +31 -0
  188. package/dist/sdk/check.js +58 -0
  189. package/dist/sdk/runs.d.ts +11 -3
  190. package/dist/sdk/runs.js +90 -15
  191. package/dist/sdk/schema.js +12 -4
  192. package/dist/secret-writes.d.ts +16 -3
  193. package/dist/secret-writes.js +28 -3
  194. package/dist/server-secrets-store.js +5 -0
  195. package/dist/server.d.ts +34 -2
  196. package/dist/server.js +437 -90
  197. package/dist/sign-ins-secrets.js +4 -1
  198. package/dist/skills/agentrun-serve/SKILL.md +11 -0
  199. package/dist/slack-url.d.ts +5 -0
  200. package/dist/slack-url.js +11 -0
  201. package/dist/slack.d.ts +107 -0
  202. package/dist/slack.js +292 -0
  203. package/dist/start-switches.d.ts +28 -0
  204. package/dist/start-switches.js +37 -0
  205. package/dist/stats.d.ts +1 -1
  206. package/dist/stats.js +2 -1
  207. package/dist/stop-signals.d.ts +11 -0
  208. package/dist/stop-signals.js +22 -0
  209. package/dist/store/agent-body.d.ts +1 -1
  210. package/dist/store/agent-body.js +2 -2
  211. package/dist/store/index.d.ts +3 -3
  212. package/dist/store/index.js +1 -1
  213. package/dist/store/postgres/migrations/0020_runners.sql +18 -0
  214. package/dist/store/postgres/store.d.ts +1 -1
  215. package/dist/store/postgres/store.js +4 -2
  216. package/dist/store/schema.d.ts +13 -5
  217. package/dist/store/schema.js +20 -11
  218. package/dist/store/seal.d.ts +16 -4
  219. package/dist/store/sqlite/store.d.ts +1 -1
  220. package/dist/store/sqlite/store.js +112 -28
  221. package/dist/store/store.d.ts +78 -24
  222. package/dist/store/store.js +11 -0
  223. package/dist/store-reads/analytics.js +3 -2
  224. package/dist/store-reads/cap.d.ts +7 -0
  225. package/dist/store-reads/cap.js +11 -1
  226. package/dist/store-reads/journal.js +27 -1
  227. package/dist/store-reads/learning.d.ts +23 -2
  228. package/dist/store-reads/learning.js +29 -8
  229. package/dist/store-reads/runs.d.ts +9 -0
  230. package/dist/store-reads/runs.js +19 -6
  231. package/dist/store-reads/stats.d.ts +4 -1
  232. package/dist/store-reads/stats.js +15 -6
  233. package/dist/store-view.d.ts +125 -14
  234. package/dist/store-view.js +156 -21
  235. package/dist/telemetry.d.ts +7 -7
  236. package/dist/telemetry.js +38 -15
  237. package/dist/template-eval.js +5 -2
  238. package/dist/template-github-permissions.d.ts +5 -1
  239. package/dist/template-github-permissions.js +7 -3
  240. package/dist/timeline/index.d.ts +1 -1
  241. package/dist/timeline/index.js +1 -1
  242. package/dist/timeline/timeline.d.ts +8 -0
  243. package/dist/timeline/timeline.js +30 -0
  244. package/dist/tool-gate.d.ts +8 -4
  245. package/dist/tool-gate.js +6 -7
  246. package/dist/tool-keys-store.js +2 -2
  247. package/dist/tool-keys.js +2 -1
  248. package/dist/tool-plane.d.ts +4 -0
  249. package/dist/tool-plane.js +12 -12
  250. package/dist/trigger-adapter.d.ts +3 -4
  251. package/dist/trigger-adapter.js +2 -2
  252. package/dist/trigger-composio.js +3 -3
  253. package/dist/trigger-email.js +0 -2
  254. package/dist/trigger-feed.js +0 -2
  255. package/dist/trigger-schedule.js +3 -0
  256. package/dist/trigger-secrets-shown.d.ts +6 -3
  257. package/dist/trigger-secrets-shown.js +22 -13
  258. package/dist/trigger-targets.d.ts +12 -3
  259. package/dist/trigger-targets.js +90 -10
  260. package/dist/triggers.d.ts +2 -2
  261. package/dist/validate.js +5 -1
  262. package/dist/viewer-credential.d.ts +25 -0
  263. package/dist/viewer-credential.js +51 -0
  264. package/dist/webhooks.d.ts +82 -8
  265. package/dist/webhooks.js +128 -45
  266. package/dist/wires.d.ts +6 -1
  267. package/dist/wires.js +5 -0
  268. package/dist/workspace/attach.d.ts +3 -2
  269. package/dist/workspace/attach.js +2 -1
  270. package/dist/workspace/attached-computers.d.ts +6 -8
  271. package/dist/workspace/attached-computers.js +27 -24
  272. package/dist/workspace/computer-deps.d.ts +2 -3
  273. package/dist/workspace/computer-deps.js +3 -6
  274. package/dist/workspace/computer-for-claim.js +72 -96
  275. package/dist/workspace/computer-kept.d.ts +0 -7
  276. package/dist/workspace/computer-kept.js +0 -17
  277. package/dist/workspace/resolve-computer.d.ts +23 -14
  278. package/dist/workspace/resolve-computer.js +66 -61
  279. package/dist/workspace/synced-folder.d.ts +20 -15
  280. package/dist/workspace/synced-folder.js +33 -43
  281. package/launcher/agentrun-serve +4 -1
  282. package/package.json +18 -10
  283. package/skills/agentrun-serve/SKILL.md +11 -0
  284. package/templates/README.md +1 -1
  285. package/templates/code-review/agent.md +2 -3
  286. package/templates/code-review/evals/mentions-defused/case.yaml +0 -1
  287. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -27
  288. package/templates/code-review/evals/other-repo/case.yaml +0 -1
  289. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +0 -18
  290. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +1 -1
  291. package/dist/console/assets/index-C2MYaUBa.css +0 -1
  292. package/dist/console/assets/index-CZZeCReB.js +0 -701
package/dist/import.d.ts CHANGED
@@ -72,6 +72,9 @@ export type ImportOptions = {
72
72
  signal?: AbortSignal;
73
73
  /** Each key secretlint finds, as it finds it: for what the CLI prints, cut with the keys the import cuts. */
74
74
  onKeys?: (keys: readonly string[]) => void;
75
+ /** How far the import is, for the CLI's progress line: `keys`, the sessions read for keys before anything is written
76
+ * (`done` of `total`); `write`, the sessions written or passed over. Counts alone, never a name or a path. */
77
+ onProgress?: (step: "keys" | "write", done: number, total: number) => void;
75
78
  /** Read each session file through secretlint for the cut (default). Setup's count sets it false: a count keeps no
76
79
  * transcript, so it reads none, and a server's start never scans a whole history to say how many sessions it has. */
77
80
  keys?: boolean;
@@ -111,7 +114,7 @@ export type ProjectPlan = {
111
114
  * again: theirs, and (when measuring) those of planned sessions the store holds already. `children`: the files of each
112
115
  * session's subagents, whose usage is its run's: Claude Code's by the session file beside them, Codex's by `source:thread`; `untied`, those of subagents whose file names
113
116
  * no parent, counted in a summary's totals alone. `found`: each other planned session measured,
114
- * when the plan was made to (`measure`). */
117
+ * when the plan was made to (`measure`). `stopped`: `signal` ended the listing with session files still unlisted. */
115
118
  export type Plan = {
116
119
  projects: ProjectPlan[];
117
120
  skipped: Skipped[];
@@ -124,6 +127,7 @@ export type Plan = {
124
127
  }[];
125
128
  found?: Found[];
126
129
  secretsFound?: number;
130
+ stopped?: true;
127
131
  };
128
132
  export type ImportReport = {
129
133
  agents: {
@@ -146,6 +150,9 @@ export type ImportReport = {
146
150
  /** Keys and tokens cut out of what it wrote (secret-cut.ts): the environment's values, the saved keys, and those of a
147
151
  * known format secretlint found. */
148
152
  secretsRemoved?: number;
153
+ /** `signal` ended it with sessions of the plan still to take, or the plan was itself stopped (`Plan.stopped`): the
154
+ * next import takes the rest. Absent when a stop came with nothing left to take: the import is whole. */
155
+ stopped?: true;
149
156
  };
150
157
  /** The projects of `plan` for the owner to choose from, the latest active first (then by folder), at most MAX_CANDIDATES.
151
158
  * With `env`, the values of its keys are cut from a name and a folder as the import cuts them. */
@@ -208,10 +215,23 @@ export declare function leftOutOf(skipped: readonly Pick<Skipped, "kind" | "what
208
215
  export declare function describePlan(plan: Plan, store?: ImportStore, { verbose }?: {
209
216
  verbose?: boolean;
210
217
  }): Promise<string[]>;
211
- /** `agentrun-serve import ARGS`: its exit code. */
212
- export declare function importCommand(args: string[], usage: string, { home, temp, env, out, }?: {
218
+ /** What `importCommand` takes besides its arguments. */
219
+ type ImportDeps = {
213
220
  home?: string;
214
221
  env?: NodeJS.ProcessEnv;
215
222
  out?: (line: string) => void;
216
223
  temp?: string;
217
- }): Promise<number>;
224
+ /** Where the import says how far it is while it works (default: one line on stderr, on a terminal only). */
225
+ progress?: Progress;
226
+ };
227
+ /** `agentrun-serve import ARGS`: its exit code. The first Ctrl+C (or SIGTERM) once it writes stops it between two
228
+ * sessions: each is written whole (importRun is atomic), what is written stays, and the next import picks up the rest.
229
+ * Its listeners stay until everything it says is printed, since its lines are held until the end; a Ctrl+C it took is
230
+ * in the code (130) whenever it came. */
231
+ export declare function importCommand(args: string[], usage: string, deps?: ImportDeps): Promise<number>;
232
+ /** Where the CLI says how far an import is: `show` a line in place of the last, `done` clears it. */
233
+ export type Progress = {
234
+ show: (text: string) => void;
235
+ done: () => void;
236
+ };
237
+ export {};
package/dist/import.js CHANGED
@@ -14,8 +14,9 @@ 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 { stopOnce } from "./stop-signals.js";
19
20
  import { catalogPrices, providerModels } from "./model.js";
20
21
  import { logLine } from "./print.js";
21
22
  import { launchBody } from "./run-launch.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);
@@ -1047,7 +1057,6 @@ async function estimateOf(entries, catalog) {
1047
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
1048
1058
  * revision with no instructions is refused every run (runnable.ts), so an import never writes one. */
1049
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.`;
1050
- const SOURCE_NAMES = { "claude-code": "Claude Code", codex: "Codex", pi: "pi" };
1051
1060
  /** The revision of `source`'s harness this agent keeps already (one per source, by its note), or a new one to write: its
1052
1061
  * id, and the `NewRevision` the caller stores (through agents.create for the agent's first, agents.addRevision for the
1053
1062
  * rest). The body is built and checked here (bodyOf), its instructions and skills cut. `model`: the harness's latest
@@ -1111,7 +1120,7 @@ export async function runImport(store, plan, options) {
1111
1120
  const add = (keys) => (cut.add(keys), options.onKeys?.(keys));
1112
1121
  // This server's own secrets, then every key the import finds.
1113
1122
  add(options.own ?? []);
1114
- const report = { agents: [], skipped: [...plan.skipped], already: plan.already };
1123
+ const report = { agents: [], skipped: [...plan.skipped], already: plan.already, ...(plan.stopped ? { stopped: true } : {}) };
1115
1124
  let prices;
1116
1125
  const catalog = () => (prices ??= catalogPrices());
1117
1126
  const held = await importedIn(store);
@@ -1122,12 +1131,18 @@ export async function runImport(store, plan, options) {
1122
1131
  return at > 0 && (await (models ??= providerModels(options.env))).getModel(ref.slice(0, at), ref.slice(at + 1)) !== undefined;
1123
1132
  };
1124
1133
  // Every key of the import is known before anything of it is written.
1125
- 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);
1126
1139
  const scannedAs = known.stamps;
1127
1140
  const epoch0 = new Date(0).toISOString();
1128
1141
  for (const project of plan.projects) {
1129
- if (options.signal?.aborted)
1142
+ if (options.signal?.aborted) {
1143
+ report.stopped = true;
1130
1144
  break;
1145
+ }
1131
1146
  const existing = await store.agents.get(project.agentId);
1132
1147
  const created = !existing;
1133
1148
  const files = await projectFiles(project.cwd, report.skipped);
@@ -1137,6 +1152,7 @@ export async function runImport(store, plan, options) {
1137
1152
  add(await secretsIn(textNow));
1138
1153
  const byStart = [...project.sessions].sort((a, b) => (a.startedAt ?? "").localeCompare(b.startedAt ?? ""));
1139
1154
  const latest = byStart.at(-1);
1155
+ const name = keptName(project, text);
1140
1156
  // The latest session's harness names the agent's current revision; its model, each harness's latest a catalog lists. The
1141
1157
  // latest source is last in the order, so it is the last revision written — created with the agent, or added current.
1142
1158
  const order = [...new Set(project.sessions.map((s) => s.source))].sort((a, b) => (a === latest.source ? 1 : 0) - (b === latest.source ? 1 : 0));
@@ -1145,7 +1161,7 @@ export async function runImport(store, plan, options) {
1145
1161
  for (const source of order) {
1146
1162
  const model = byStart.findLast((s) => s.source === source && s.model)?.model;
1147
1163
  const pinned = model && (await inCatalog(model)) ? model : undefined;
1148
- const resolved = await revisionFor(store, project.agentId, source, files, pinned, keptName(project, text), text);
1164
+ const resolved = await revisionFor(store, project.agentId, source, files, pinned, name, text);
1149
1165
  if (resolved.create && model && !pinned)
1150
1166
  (report.modelsLeftOut ??= []).push({ cwd: project.cwd, source, model });
1151
1167
  revisions.set(source, resolved.id);
@@ -1154,7 +1170,7 @@ export async function runImport(store, plan, options) {
1154
1170
  }
1155
1171
  if (created) {
1156
1172
  // The agent and its first revision in one commit, the rest added; the latest is last, so the current one.
1157
- 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]);
1158
1174
  for (const revision of toWrite.slice(1))
1159
1175
  await store.agents.addRevision({ agentId: project.agentId, ...revision });
1160
1176
  }
@@ -1170,8 +1186,11 @@ export async function runImport(store, plan, options) {
1170
1186
  // A record or response counted once across the import's files, those its runs here hold already included.
1171
1187
  const seen = await seenIn(store, project.agentId);
1172
1188
  for (const files of byRun(project.sessions)) {
1173
- if (options.signal?.aborted)
1189
+ options.onProgress?.("write", written++, toTake);
1190
+ if (options.signal?.aborted) {
1191
+ report.stopped = true;
1174
1192
  break;
1193
+ }
1175
1194
  const listed = files[0];
1176
1195
  // A run the store holds already is left as it is: importRun is atomic, so a held run is a whole run.
1177
1196
  if (held.get(`${listed.source}:${listed.id}`) !== undefined) {
@@ -1324,10 +1343,27 @@ export async function describePlan(plan, store, { verbose = false } = {}) {
1324
1343
  });
1325
1344
  return [...lines, ...(plan.already ? [`already imported, unchanged: ${plan.already} session files`] : []), ...(verbose ? plan.skipped.map((s) => `skipped ${s.what}: ${s.why}`) : [])];
1326
1345
  }
1327
- /** `agentrun-serve import ARGS`: its exit code. */
1328
- 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(),
1329
1365
  // The folder whose projects are left out as temporary (the OS's temp directory).
1330
- temp = tmpdir(), env, out = console.log, } = {}) {
1366
+ temp = tmpdir(), env, out = console.log, progress, }, stops) {
1331
1367
  // The server's own secrets, kept sealed in the store, open only under the server's seal key: it is
1332
1368
  // booted the one way the server and runner boot it (seal-key.ts bootSealKey) once the store is open (keyed below), and
1333
1369
  // checked against it. The key handed over wins (this process's, else a caller's own environment's: a test's), else the
@@ -1395,8 +1431,8 @@ temp = tmpdir(), env, out = console.log, } = {}) {
1395
1431
  console.error(`${error.message}\n\n${usage}`);
1396
1432
  return 2;
1397
1433
  }
1398
- const port = values.port === undefined ? DEFAULT_PORT : Number(values.port);
1399
- 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)) {
1400
1436
  console.error(`--port takes a port number\n\n${usage}`);
1401
1437
  return 2;
1402
1438
  }
@@ -1472,7 +1508,7 @@ temp = tmpdir(), env, out = console.log, } = {}) {
1472
1508
  out(`${plan.secretsFound} secret${plan.secretsFound === 1 ? "" : "s"} would be removed`);
1473
1509
  for (const line of leftOutLines(plan.skipped))
1474
1510
  out(line);
1475
- for (const line of summaryLines(found, open, { dryRun: true }))
1511
+ for (const line of summaryLines(found, open))
1476
1512
  out(line);
1477
1513
  return 0;
1478
1514
  }
@@ -1487,7 +1523,7 @@ temp = tmpdir(), env, out = console.log, } = {}) {
1487
1523
  }
1488
1524
  catch (error) {
1489
1525
  if (error instanceof StoreFromEarlierVersion || error instanceof StoreOwned) {
1490
- warnings.push(`agentrun-serve import: ${error.message}`);
1526
+ warnings.push(`agentrun-serve import: ${error.message}${error instanceof StoreOwned ? `\n${STOP_SERVER_FIRST}` : ""}`);
1491
1527
  return 1;
1492
1528
  }
1493
1529
  throw error;
@@ -1501,9 +1537,22 @@ temp = tmpdir(), env, out = console.log, } = {}) {
1501
1537
  return 1;
1502
1538
  throw error;
1503
1539
  }
1504
- const options = await optionsFrom(store);
1505
- const plan = await planImport(options, store);
1506
- 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
+ }
1507
1556
  for (const agent of report.agents)
1508
1557
  out(`${agent.cwd} ${agent.created ? "new agent" : "agent held"} ${agent.id} imported ${agent.runs}${agent.already ? `, already imported ${agent.already}` : ""}`);
1509
1558
  if (report.already)
@@ -1511,7 +1560,8 @@ temp = tmpdir(), env, out = console.log, } = {}) {
1511
1560
  if (values.verbose)
1512
1561
  for (const s of report.skipped)
1513
1562
  out(`skipped ${s.what}: ${s.why}`);
1514
- 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}`);
1515
1565
  out(`${report.secretsRemoved ?? 0} secret${report.secretsRemoved === 1 ? "" : "s"} removed`);
1516
1566
  for (const line of leftOutLines(report.skipped))
1517
1567
  out(line);
@@ -1520,7 +1570,8 @@ temp = tmpdir(), env, out = console.log, } = {}) {
1520
1570
  // Every session found: those imported now, those held before, and those whose file an earlier import read whole.
1521
1571
  const held = await importedIn(store);
1522
1572
  const runs = [...plan.projects.flatMap((p) => p.sessions.flatMap((s) => held.get(`${s.source}:${s.id}`) ?? [])), ...plan.held];
1523
- 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))
1524
1575
  out(line);
1525
1576
  return 0;
1526
1577
  }
@@ -1546,13 +1597,44 @@ async function foundAll(store, runIds) {
1546
1597
  /** The address the summary's Open line names on this machine: the one a local server listens on by default. */
1547
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
1548
1599
  /** Where a person opens the console: the server's public address when one is set (as the server takes it), else this
1549
- * 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. */
1550
1603
  function openAt(env, port) {
1551
1604
  const given = env.AGENTRUN_PUBLIC_URL || env.RENDER_EXTERNAL_URL;
1552
1605
  const parsed = given && URL.canParse(given) ? new URL(given) : undefined;
1553
1606
  if (parsed && /^https?:$/.test(parsed.protocol))
1554
- return parsed.href.replace(/\/+$/, "");
1555
- 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
+ };
1556
1638
  }
1557
1639
  /** The "/"-segments of `path` a key touches (by their index): each whose blanking takes a key out of the path. Blanked
1558
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. */
@@ -26,7 +27,8 @@ export declare const answerPasses: {
26
27
  /** `text`, a run's answer as serve serves it (its final answer, or a string in its workflow output), with no held secret
27
28
  * in it, and NEVER cut: an answer is shown whole. The same rule as redacted() (redactSecrets over `secrets`), over the
28
29
  * whole text, read in pieces of about ANSWER_PIECE characters cut at whitespace. No form of a held value redactSecrets
29
- * finds as it stands (as written, JSON-escaped, base64, hex) holds whitespace, so a cut there splits none. A run of more
30
+ * finds as it stands (as written, JSON-escaped, base64, hex) holds whitespace, so a cut there splits none; the one shape
31
+ * read across whitespace, a Bearer scheme and its token, is never cut between the two (endsInScheme). A run of more
30
32
  * than ANSWER_PIECE characters with no whitespace is no person's text and is shown as "[redacted]", unread. A value split
31
33
  * by whitespace across a cut, or a form only found across pieces, still shows to one valueMatcher pass over the joined
32
34
  * output, and then the whole answer is "[redacted]", as redactSecrets does with a text that still holds a value. */
@@ -4,9 +4,10 @@
4
4
  // count, a file name, a duration, another service's status) is no refused key, and the error is left as it is.
5
5
  import { DEFAULT_HARNESS } from "./harness.js";
6
6
  import { harnessOf } from "./harness-table.js";
7
- import { redactSecrets, valueMatcher } from "./learn/secrets.js";
7
+ import { endsInScheme, 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;
@@ -77,7 +82,8 @@ export const answerPasses = { count: 0 };
77
82
  /** `text`, a run's answer as serve serves it (its final answer, or a string in its workflow output), with no held secret
78
83
  * in it, and NEVER cut: an answer is shown whole. The same rule as redacted() (redactSecrets over `secrets`), over the
79
84
  * whole text, read in pieces of about ANSWER_PIECE characters cut at whitespace. No form of a held value redactSecrets
80
- * finds as it stands (as written, JSON-escaped, base64, hex) holds whitespace, so a cut there splits none. A run of more
85
+ * finds as it stands (as written, JSON-escaped, base64, hex) holds whitespace, so a cut there splits none; the one shape
86
+ * read across whitespace, a Bearer scheme and its token, is never cut between the two (endsInScheme). A run of more
81
87
  * than ANSWER_PIECE characters with no whitespace is no person's text and is shown as "[redacted]", unread. A value split
82
88
  * by whitespace across a cut, or a form only found across pieces, still shows to one valueMatcher pass over the joined
83
89
  * output, and then the whole answer is "[redacted]", as redactSecrets does with a text that still holds a value. */
@@ -99,6 +105,21 @@ export function redactedAnswer(text, secrets) {
99
105
  continue;
100
106
  }
101
107
  to = from + space + 1;
108
+ // A cut after a Bearer scheme would leave its token at the head of the next piece, where no shape reads it (the
109
+ // shape is the scheme, then the token). The cut moves back to the whitespace before the scheme; with none in this
110
+ // piece, the scheme and its token are read as one run, to the next whitespace, as a run with no whitespace is.
111
+ if (endsInScheme(text.slice(from, to))) {
112
+ const before = text.slice(from, to).trimEnd().search(/\s[^\s]*$/);
113
+ if (before > 0)
114
+ to = from + before + 1;
115
+ else {
116
+ const next = text.slice(to).search(/\s/);
117
+ to = next < 0 ? text.length : to + next;
118
+ parts.push(to - from > ANSWER_PIECE ? "[redacted]" : redactSecrets(text.slice(from, to), secrets, Buffer.byteLength(text.slice(from, to))));
119
+ from = to;
120
+ continue;
121
+ }
122
+ }
102
123
  }
103
124
  const piece = text.slice(from, to);
104
125
  parts.push(redactSecrets(piece, secrets, Buffer.byteLength(piece)));
@@ -169,7 +190,7 @@ export function keyRefusal(text, key, secrets = []) {
169
190
  if (!at)
170
191
  return undefined;
171
192
  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.";
193
+ const where = key.where ?? (key.saved ? "set it where AgentRun starts, or save it in Settings → Model keys." : "set it where AgentRun starts.");
173
194
  return `${key.who} refused ${key.field} (401${detail ? `: ${detail}` : ""}): ${where}`;
174
195
  }
175
196
  /** 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