@parcha/agentrun-serve 0.1.0-beta.56 → 0.1.0-beta.57

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 (275) hide show
  1. package/CHANGELOG.md +229 -0
  2. package/README.md +201 -52
  3. package/dist/acp-package.d.ts +2 -0
  4. package/dist/adapters.d.ts +15 -3
  5. package/dist/adapters.js +17 -6
  6. package/dist/agent-package.d.ts +3 -3
  7. package/dist/agent-package.js +17 -8
  8. package/dist/api-keys.d.ts +76 -0
  9. package/dist/api-keys.js +217 -0
  10. package/dist/api-only.d.ts +17 -5
  11. package/dist/api-only.js +34 -8
  12. package/dist/browser-hold.d.ts +23 -0
  13. package/dist/browser-hold.js +48 -0
  14. package/dist/browser-person.d.ts +3 -0
  15. package/dist/browser-person.js +4 -1
  16. package/dist/chatgpt-plan.d.ts +18 -8
  17. package/dist/chatgpt-plan.js +91 -34
  18. package/dist/claude-login.d.ts +74 -16
  19. package/dist/claude-login.js +215 -56
  20. package/dist/claude-sign-in.d.ts +17 -6
  21. package/dist/claude-sign-in.js +42 -39
  22. package/dist/cli.js +63 -6
  23. package/dist/composio-made.d.ts +4 -0
  24. package/dist/composio-made.js +4 -0
  25. package/dist/composio-preset.d.ts +43 -2
  26. package/dist/composio-preset.js +92 -4
  27. package/dist/computer-held-routes.d.ts +5 -4
  28. package/dist/computer-held-routes.js +29 -8
  29. package/dist/computer-held.d.ts +6 -1
  30. package/dist/computer-held.js +14 -0
  31. package/dist/computer-record.js +4 -2
  32. package/dist/computer-viewer.js +4 -1
  33. package/dist/console/assets/{backend-Boh7tC4i.js → backend-DVhHzJX2.js} +19 -19
  34. package/dist/console/assets/index-Bwn1oTem.css +1 -0
  35. package/dist/console/assets/index-okP-y8PK.js +747 -0
  36. package/dist/console/index.html +2 -2
  37. package/dist/decisions.d.ts +1 -1
  38. package/dist/decisions.js +1 -1
  39. package/dist/docker-host-addresses.d.ts +22 -11
  40. package/dist/docker-host-addresses.js +38 -26
  41. package/dist/env-switch.d.ts +10 -0
  42. package/dist/env-switch.js +33 -2
  43. package/dist/errors.d.ts +1 -0
  44. package/dist/errors.js +2 -0
  45. package/dist/fal-price.d.ts +58 -20
  46. package/dist/fal-price.js +341 -82
  47. package/dist/handed-values.d.ts +43 -1
  48. package/dist/handed-values.js +119 -2
  49. package/dist/harness-archive.d.ts +13 -10
  50. package/dist/harness-archive.js +60 -34
  51. package/dist/harness-check.d.ts +3 -1
  52. package/dist/harness-check.js +25 -46
  53. package/dist/harness-keys.d.ts +73 -27
  54. package/dist/harness-keys.js +194 -61
  55. package/dist/harness-recipe-entry.d.ts +8 -7
  56. package/dist/harness-recipe-entry.js +21 -32
  57. package/dist/harness-recipe.d.ts +38 -25
  58. package/dist/harness-recipe.js +49 -36
  59. package/dist/harness-sign-in.js +12 -23
  60. package/dist/harness-table.d.ts +10 -3
  61. package/dist/harness-table.js +26 -21
  62. package/dist/harness.d.ts +1 -0
  63. package/dist/harness.js +17 -5
  64. package/dist/hosted-search.d.ts +1 -1
  65. package/dist/hosted-search.js +1 -2
  66. package/dist/import-worker.d.ts +4 -2
  67. package/dist/import-worker.js +9 -2
  68. package/dist/in-flight.d.ts +26 -0
  69. package/dist/in-flight.js +52 -0
  70. package/dist/key-refusal.d.ts +9 -4
  71. package/dist/key-refusal.js +107 -25
  72. package/dist/learn/secrets.d.ts +13 -3
  73. package/dist/learn/secrets.js +118 -17
  74. package/dist/learning-cost.d.ts +6 -3
  75. package/dist/learning-cost.js +4 -2
  76. package/dist/link-check.js +1 -1
  77. package/dist/llms.txt +1 -1
  78. package/dist/marketplace.d.ts +77 -0
  79. package/dist/marketplace.js +224 -0
  80. package/dist/mcp-api-only-origins.d.ts +30 -0
  81. package/dist/mcp-api-only-origins.js +57 -0
  82. package/dist/mcp-gateway.d.ts +7 -5
  83. package/dist/mcp-gateway.js +9 -12
  84. package/dist/mcp-secret-writes.js +5 -3
  85. package/dist/mcp-servers-store.d.ts +28 -6
  86. package/dist/mcp-servers-store.js +53 -4
  87. package/dist/media-duration.d.ts +3 -0
  88. package/dist/media-duration.js +90 -9
  89. package/dist/model-form.d.ts +5 -4
  90. package/dist/model-form.js +11 -7
  91. package/dist/model.d.ts +5 -2
  92. package/dist/model.js +9 -5
  93. package/dist/ollama-provider.d.ts +7 -1
  94. package/dist/ollama-provider.js +14 -2
  95. package/dist/openapi.js +178 -27
  96. package/dist/otel/genai.d.ts +65 -0
  97. package/dist/otel/genai.js +116 -0
  98. package/dist/otel/tracer.d.ts +55 -0
  99. package/dist/otel/tracer.js +308 -0
  100. package/dist/page.d.ts +2 -0
  101. package/dist/page.js +3 -1
  102. package/dist/paid-calls.d.ts +1 -32
  103. package/dist/paid-calls.js +4 -39
  104. package/dist/provider.d.ts +9 -0
  105. package/dist/provider.js +50 -3
  106. package/dist/redact/match.d.ts +30 -3
  107. package/dist/redact/match.js +422 -41
  108. package/dist/refusal-words.d.ts +11 -0
  109. package/dist/refusal-words.js +11 -0
  110. package/dist/run-census.d.ts +67 -0
  111. package/dist/run-census.js +240 -0
  112. package/dist/run-computer.d.ts +6 -3
  113. package/dist/run-computer.js +4 -1
  114. package/dist/run-cut.d.ts +15 -6
  115. package/dist/run-cut.js +30 -9
  116. package/dist/run-files.d.ts +3 -0
  117. package/dist/run-files.js +3 -0
  118. package/dist/run-launch.d.ts +12 -1
  119. package/dist/run-launch.js +9 -10
  120. package/dist/run-learning-served.d.ts +2 -0
  121. package/dist/run-model-key.d.ts +8 -0
  122. package/dist/run-model-key.js +31 -1
  123. package/dist/run-reads-over-store.d.ts +24 -6
  124. package/dist/run-reads-over-store.js +67 -23
  125. package/dist/run-recordings.d.ts +5 -1
  126. package/dist/run-recordings.js +39 -14
  127. package/dist/run-timeline-served.d.ts +2 -0
  128. package/dist/run-timeline-served.js +2 -2
  129. package/dist/run-usage.d.ts +1 -0
  130. package/dist/runnable.d.ts +10 -1
  131. package/dist/runnable.js +20 -8
  132. package/dist/runner/adapter-loop.d.ts +11 -0
  133. package/dist/runner/adapter-loop.js +55 -10
  134. package/dist/runner/adapter-run-spec.d.ts +45 -8
  135. package/dist/runner/adapter-run-spec.js +150 -28
  136. package/dist/runner/adapters/pi.js +25 -3
  137. package/dist/runner/beside.js +4 -3
  138. package/dist/runner/big-writes.js +1 -10
  139. package/dist/runner/claim-secrets.d.ts +18 -3
  140. package/dist/runner/claim-secrets.js +35 -6
  141. package/dist/runner/cli-run-spec.d.ts +6 -0
  142. package/dist/runner/cli-run-spec.js +82 -35
  143. package/dist/runner/computer-journal.d.ts +9 -1
  144. package/dist/runner/computer-journal.js +26 -0
  145. package/dist/runner/conformance/harness.js +1 -1
  146. package/dist/runner/feedback-round.js +3 -0
  147. package/dist/runner/harness-loops.d.ts +6 -5
  148. package/dist/runner/harness-loops.js +7 -7
  149. package/dist/runner/held.d.ts +11 -5
  150. package/dist/runner/journal-kinds.d.ts +5 -0
  151. package/dist/runner/journal-kinds.js +5 -0
  152. package/dist/runner/main.js +7 -2
  153. package/dist/runner/mcp-claim.js +30 -3
  154. package/dist/runner/mcp-run.d.ts +12 -0
  155. package/dist/runner/mcp-run.js +12 -5
  156. package/dist/runner/model-route.d.ts +17 -0
  157. package/dist/runner/model-route.js +120 -2
  158. package/dist/runner/run-child-host.d.ts +3 -0
  159. package/dist/runner/run-child-host.js +69 -28
  160. package/dist/runner/run-child.js +5 -2
  161. package/dist/runner/runner.d.ts +14 -3
  162. package/dist/runner/runner.js +129 -33
  163. package/dist/runner/store-port.d.ts +1 -1
  164. package/dist/runner/store-secrets.d.ts +6 -0
  165. package/dist/runner/store-secrets.js +49 -7
  166. package/dist/runner/subagent.js +4 -40
  167. package/dist/runner/workflow-first.d.ts +11 -4
  168. package/dist/runner/workflow-first.js +14 -8
  169. package/dist/runner/workflow-spec.js +3 -2
  170. package/dist/runs-over-store.d.ts +15 -6
  171. package/dist/runs-over-store.js +33 -21
  172. package/dist/scrub-command.d.ts +73 -0
  173. package/dist/scrub-command.js +307 -0
  174. package/dist/secret-cut.d.ts +73 -0
  175. package/dist/secret-cut.js +291 -4
  176. package/dist/secret-rules.d.ts +143 -0
  177. package/dist/secret-rules.js +2564 -0
  178. package/dist/secrets.d.ts +7 -0
  179. package/dist/secrets.js +20 -0
  180. package/dist/server-keys.d.ts +20 -0
  181. package/dist/server-keys.js +25 -6
  182. package/dist/server.d.ts +52 -11
  183. package/dist/server.js +345 -118
  184. package/dist/skills/agentrun-serve/SKILL.md +4 -0
  185. package/dist/store/index.d.ts +1 -1
  186. package/dist/store/index.js +1 -1
  187. package/dist/store/journal/storage.js +1 -1
  188. package/dist/store/postgres/migrations/0027_run_launch_census.sql +31 -0
  189. package/dist/store/schema.d.ts +6 -0
  190. package/dist/store/schema.js +11 -1
  191. package/dist/store/seal.d.ts +6 -1
  192. package/dist/store/seal.js +5 -3
  193. package/dist/store/sqlite/run-launch.d.ts +9 -1
  194. package/dist/store/sqlite/run-launch.js +24 -13
  195. package/dist/store/sqlite/run-patch.d.ts +1 -1
  196. package/dist/store/sqlite/run-patch.js +13 -4
  197. package/dist/store/sqlite/store.js +34 -4
  198. package/dist/store/store.d.ts +43 -2
  199. package/dist/store/store.js +20 -0
  200. package/dist/store-reads/learning.d.ts +6 -3
  201. package/dist/store-reads/learning.js +22 -7
  202. package/dist/store-view.d.ts +3 -0
  203. package/dist/store-view.js +3 -3
  204. package/dist/suggestions.js +3 -2
  205. package/dist/template-eval.d.ts +20 -9
  206. package/dist/template-eval.js +115 -33
  207. package/dist/template-import.d.ts +10 -0
  208. package/dist/template-import.js +16 -7
  209. package/dist/templates.d.ts +10 -2
  210. package/dist/templates.js +28 -8
  211. package/dist/timeline/labels.d.ts +6 -4
  212. package/dist/timeline/labels.js +18 -6
  213. package/dist/timeline/timeline.d.ts +5 -0
  214. package/dist/timeline/timeline.js +14 -8
  215. package/dist/timeline/util.js +1 -1
  216. package/dist/timeline/web-calls.d.ts +26 -9
  217. package/dist/timeline/web-calls.js +124 -37
  218. package/dist/tool-gate.d.ts +42 -3
  219. package/dist/tool-gate.js +66 -5
  220. package/dist/tool-keys-store.d.ts +2 -4
  221. package/dist/tool-keys-store.js +5 -21
  222. package/dist/tool-keys.d.ts +2 -2
  223. package/dist/tool-keys.js +2 -2
  224. package/dist/tool-list.js +1 -1
  225. package/dist/tool-plane.d.ts +2 -2
  226. package/dist/tool-plane.js +35 -33
  227. package/dist/tools.js +13 -7
  228. package/dist/trigger-targets.d.ts +4 -0
  229. package/dist/trigger-targets.js +9 -2
  230. package/dist/triggers.d.ts +67 -4
  231. package/dist/triggers.js +171 -22
  232. package/dist/until.d.ts +3 -0
  233. package/dist/until.js +11 -0
  234. package/dist/web-fake.d.ts +1 -3
  235. package/dist/web-fake.js +7 -18
  236. package/dist/web-fetch.d.ts +6 -72
  237. package/dist/web-fetch.js +11 -265
  238. package/dist/web-run.d.ts +31 -0
  239. package/dist/web-run.js +90 -0
  240. package/dist/web-save.d.ts +6 -4
  241. package/dist/web-save.js +9 -12
  242. package/dist/web-search.d.ts +9 -127
  243. package/dist/web-search.js +23 -259
  244. package/dist/wires.d.ts +13 -0
  245. package/dist/wires.js +11 -0
  246. package/dist/workflow-run.d.ts +5 -4
  247. package/dist/workflow-run.js +5 -4
  248. package/dist/workspace/computer-deps.d.ts +2 -1
  249. package/dist/workspace/computer-deps.js +9 -2
  250. package/dist/workspace/computer-for-claim.d.ts +12 -1
  251. package/dist/workspace/computer-for-claim.js +77 -8
  252. package/dist/workspace/computer-kept.d.ts +3 -0
  253. package/dist/workspace/computer-kept.js +11 -2
  254. package/dist/workspace/index.d.ts +1 -1
  255. package/dist/workspace/index.js +1 -1
  256. package/dist/workspace/kind-skills.d.ts +4 -0
  257. package/dist/workspace/kind-skills.js +9 -0
  258. package/dist/workspace/synced-folder.js +3 -4
  259. package/dist/wrapped.d.ts +13 -5
  260. package/dist/wrapped.js +52 -26
  261. package/package.json +17 -11
  262. package/skills/agentrun-serve/SKILL.md +4 -0
  263. package/templates/README.md +30 -8
  264. package/dist/console/assets/index-CQ3cJRzI.js +0 -746
  265. package/dist/console/assets/index-DKkaS3a0.css +0 -1
  266. package/dist/exa-keyless.d.ts +0 -34
  267. package/dist/exa-keyless.js +0 -118
  268. package/dist/firecrawl-keyless.d.ts +0 -41
  269. package/dist/firecrawl-keyless.js +0 -152
  270. package/dist/keyless-mcp.d.ts +0 -36
  271. package/dist/keyless-mcp.js +0 -127
  272. package/dist/text-urls.d.ts +0 -38
  273. package/dist/text-urls.js +0 -170
  274. package/dist/web-fetch-direct.d.ts +0 -119
  275. package/dist/web-fetch-direct.js +0 -190
@@ -1,5 +1,5 @@
1
1
  import { posix } from "node:path";
2
- import { cutSpans, holds, MONEY_SHAPES, planCut, SECRET_SHAPES, shapeKinds } from "../redact/match.js";
2
+ import { CREDENTIAL_NAMES, cutSpans, holds, MONEY_SHAPES, planCut, SECRET_SHAPES, shapeKinds, squeeze } from "../redact/match.js";
3
3
  /** Whether `text` ends in a `Bearer` scheme and the blanks after it: the one place a shape is read across whitespace
4
4
  * (the scheme, then its token), so a reader that cuts a text at whitespace must not cut there (key-refusal.ts
5
5
  * redactedAnswer). */
@@ -25,9 +25,19 @@ export const PRINT_MAX = 4096;
25
25
  * form not found as it stands (percent encoded, split by whitespace, an NFKC variant), read in `text` as given, is
26
26
  * redacted whole, never in part, unless every character of it is inside what the finds cut: a cut can hide part of a
27
27
  * value, so the rest is looked for before the cut (redact/match.ts planCut). So is a text over `max` bytes (PRINT_MAX
28
- * unless the caller names more), and one whose cut leaves a value or a shape. */
29
- export function redactSecrets(text, values, max = PRINT_MAX) {
30
- return redactWith(text, values, max, SECRET_SHAPES);
28
+ * unless the caller names more), and one whose cut leaves a value or a shape. `held`: spans of `text` cut in place
29
+ * beside the finds (heldSpans, of values no longer at hand). */
30
+ export function redactSecrets(text, values, max = PRINT_MAX, held = []) {
31
+ return redactWith(text, values, max, SECRET_SHAPES, held);
32
+ }
33
+ /** Where redactSecrets cuts `values` in `text`, shapes left out: each span it cuts in place (UTF-16 offsets, overlapping
34
+ * ones merged, in order), or "whole" when its checks over them cut the text whole (a value split by a line break,
35
+ * percent encoded, an NFKC variant, read in the text as it came: redact/match.ts planCut). What a run's census keeps of
36
+ * a file, never the values (run-census.ts): redactSecrets given these spans as `held` cuts the text as it would have
37
+ * with the values among its own. */
38
+ export function heldSpans(text, values) {
39
+ const cut = planCut(text, derivedOf(values), []);
40
+ return cut === "whole" ? "whole" : cut.spans;
31
41
  }
32
42
  /** `text` as redactSecrets cuts it, and of a bank's numbers beside their words too (MONEY_SHAPES): what learning prints
33
43
  * and serves of what it learned or refused (a problem's path and detail, a note read), never a run's own view, which
@@ -51,11 +61,11 @@ export function valueLeft(text, values, cuts) {
51
61
  const needles = derivedOf(values);
52
62
  return holds(text, needles, { cuts: cuts ?? cutSpans(text, needles, SECRET_SHAPES) });
53
63
  }
54
- /** redactSecrets over `shapes`, each found in place (redact/match.ts planCut). */
55
- function redactWith(text, values, max, shapes) {
64
+ /** redactSecrets over `shapes`, each found in place, and `held` spans cut beside them (redact/match.ts planCut). */
65
+ function redactWith(text, values, max, shapes, held = []) {
56
66
  if (Buffer.byteLength(text) > max)
57
67
  return "[redacted]";
58
- const cut = planCut(text, derivedOf(values), shapes);
68
+ const cut = planCut(text, derivedOf(values), shapes, held);
59
69
  return cut === "whole" ? "[redacted]" : cut.out;
60
70
  }
61
71
  /** Each value set's Needles, by the array a caller passes, with a copy of the values it was derived of. A run's view
@@ -63,27 +73,39 @@ function redactWith(text, values, max, shapes) {
63
73
  * alignments, percent forms, folded needles, for every value, a private key's PEM among them) took seconds per view.
64
74
  * An array whose values changed since is derived again, never served a stale set: what a caller adds is always cut. */
65
75
  const DERIVED = new WeakMap();
66
- /** What the matcher looks for of a set of values, whatever the text: each value and its path spellings, its forms found
67
- * as they stand (as written, as JSON writes it, its plain needles and percent forms), its hex and folded needles, and
68
- * the needles the whole-text check reads (redact/match.ts Needles). */
76
+ /** What the matcher looks for of a set of values, whatever the text: each value, each string of a held JSON value
77
+ * that may be printed alone (heldFields) and their path spellings, their forms found as they stand (as written, as
78
+ * JSON writes it, their plain needles and percent forms), their hex and folded needles, the needles the whole-text
79
+ * check reads (redact/match.ts Needles), and the parts of each of many lines (partsOf), as written and squeezed: of
80
+ * each value but a JSON object or array, and of each string heldFields holds. */
69
81
  function derivedOf(values) {
70
82
  const kept = DERIVED.get(values);
71
83
  if (kept && kept.values.length === values.length && kept.values.every((value, at) => value === values[at]))
72
84
  return kept.derived;
73
- const given = withPathSpellings(values.filter((v) => v.length > 0));
85
+ const held = values.filter((v) => v.length > 0);
86
+ const fields = held.map(heldFields);
87
+ const strings = fields.flatMap((of) => of ?? []);
88
+ const whole = [...held, ...strings];
89
+ const given = withPathSpellings(whole);
74
90
  const needles = new Map(given.filter(longEnough).map((v) => [v, needlesOf(v)]));
91
+ // A held JSON value's own lines are no parts of it (a pretty-printed one has its public strings on lines of their
92
+ // own); the strings heldFields holds of it have theirs.
93
+ const parts = [...new Set([...held.filter((_, at) => fields[at] === undefined), ...strings].flatMap(partsOf))];
75
94
  const derived = {
76
- forms: [...new Set(given.flatMap((v) => {
77
- const of = needles.get(v);
78
- return [v, asJson(v), ...(of ? [...of.plain, ...percentForms(v)] : [])];
79
- }).filter((form) => form.length > 0))],
95
+ forms: [...new Set([...given.flatMap((v) => {
96
+ const of = needles.get(v);
97
+ return [v, asJson(v), ...(of ? [...of.plain, ...percentForms(v)] : [])];
98
+ }), ...parts].filter((form) => form.length > 0))],
80
99
  hexes: [...needles.values()].map((of) => of.hex),
81
100
  folds: [...needles.values()].flatMap((of) => of.folded),
82
- plain: [...new Set([...needles.values()].flatMap((of) => of.plain))],
101
+ plain: [...new Set([...[...needles.values()].flatMap((of) => of.plain), ...parts.map(squeeze)])],
83
102
  };
84
103
  DERIVED.set(values, { values: [...values], derived });
85
104
  return derived;
86
105
  }
106
+ /** What the matcher looks for of `values` (derivedOf, cached by array): the scrubber's held rule (secret-rules.ts) cuts
107
+ * each form, hex and folded identifier in place with redact/match.ts cutSpans. */
108
+ export const heldNeedles = (values) => derivedOf(values);
87
109
  /** A value shorter than this matches too much text by chance to be refused. */
88
110
  export const MIN_SECRET = 8;
89
111
  /** An excerpt of a run's input or answer as learning keeps it: `text` cut of the secrets `shown` knows, whole, then
@@ -98,7 +120,6 @@ export function excerptShown(text, shown, max) {
98
120
  const end = /[\uD800-\uDBFF]/.test(clean.charAt(max - 1)) ? max - 1 : max;
99
121
  return `${clean.slice(0, end)}…`;
100
122
  }
101
- const squeeze = (text) => text.normalize("NFKC").replace(/\s+/gu, "");
102
123
  /** The base64 of `secret` as it can sit inside a longer blob: the characters that depend on the secret's bytes alone,
103
124
  * at each of the three alignments, in both alphabets. */
104
125
  function base64Needles(secret) {
@@ -189,6 +210,86 @@ function needlesOf(value) {
189
210
  return { plain: [...new Set([squeeze(value), squeeze(asJson(value)), ...base64Needles(raw)])], hex: raw.toString("hex"), folded: foldedOf(value) };
190
211
  }
191
212
  const longEnough = (value) => [...value].length >= MIN_SECRET;
213
+ /** The fewest characters a line of a held value must have to be held as a part of it: a key's base64 line (64) is, a
214
+ * short line any text may hold ("-----END …-----", "}", a JSON field's name and a word) is not. */
215
+ const LINE_MIN = 40;
216
+ const ARMOR_BEGIN = /^-----BEGIN [^-]*-----$/;
217
+ const ARMOR_END = /^-----END [^-]*-----$/;
218
+ /** The parts of a held value of many lines that a reader may print without the rest (`head -n 11 key.pem`, a body
219
+ * with its armor stripped), each held as itself, found as it stands and cut in place, and found in each view: each
220
+ * line of its body of LINE_MIN characters or more, and its body with its line breaks gone. Its body is its lines but
221
+ * a first "-----BEGIN …-----" and a last "-----END …-----", its armor. A key's last body line is mostly shorter than
222
+ * LINE_MIN: one of MIN_SECRET characters or more is held with the END line after it, as written (`tail -n 2 key.pem`).
223
+ * A value of one line has none: it is matched whole. */
224
+ function partsOf(value) {
225
+ const lines = value.split(/\r\n|\r|\n/).map((line) => line.trim()).filter((line) => line.length > 0);
226
+ if (lines.length < 2)
227
+ return [];
228
+ const armored = ARMOR_END.test(lines.at(-1));
229
+ const body = lines.slice(ARMOR_BEGIN.test(lines[0]) ? 1 : 0, armored ? -1 : lines.length);
230
+ const parts = [...body.filter((line) => line.length >= LINE_MIN), body.join("")];
231
+ const last = body.at(-1);
232
+ if (armored && last !== undefined && last.length >= MIN_SECRET && last.length < LINE_MIN) {
233
+ const end = lines.at(-1);
234
+ const endAt = value.lastIndexOf(end);
235
+ parts.push(value.slice(value.lastIndexOf(last, endAt), endAt + end.length));
236
+ }
237
+ return parts.filter(longEnough);
238
+ }
239
+ /** Whether a held JSON value's string under the key `name` is a secret by its name (heldFields): its name with its
240
+ * separators dropped and lowered names a secret, a password, a token, a private value, a credential or an API key, or
241
+ * ends in "key" ("aws_secret_access_key", "SessionToken", "signing_secret", "private_key", "secret_key"); or, lowered,
242
+ * it is a credential parameter's whole name (redact/match.ts CREDENTIAL_NAMES: "signature"). Never one that names a
243
+ * public thing by its end (an id, a URI or URL, a type, an email, an endpoint, an expiry: "client_id", "token_uri",
244
+ * "access_key_id", "token_type"), a public key, or a token that is none (a page's, the next page's). */
245
+ function secretName(name) {
246
+ const flat = name.toLowerCase().replace(/[-_.\s]/g, "");
247
+ if (/(?:uri|url|id|type|email|endpoint|expiry|expires|pagetoken|nexttoken)$/.test(flat) || flat.includes("public"))
248
+ return false;
249
+ return /secret|password|passwd|token|private|credential|apikey/.test(flat) || flat.endsWith("key") || CREDENTIAL_NAMES.has(name.toLowerCase());
250
+ }
251
+ /** A JWK's private members (RFC 7518: an EC or OKP key's "d", an RSA key's "d", "p", "q", "dp", "dq" and "qi", a
252
+ * symmetric key's "k"), held in an object with a "kty" only: elsewhere a one-letter name says nothing. */
253
+ const JWK_PRIVATE = new Set(["d", "p", "q", "dp", "dq", "qi", "k"]);
254
+ /** The strings of a held JSON value (an object or an array, as it parses, at any depth) that may be printed alone, each
255
+ * held as itself (trimmed), as any held value: one that holds a line break (a service account's private key, `jq -r
256
+ * .private_key`), one whose key names a secret (secretName: an OAuth client's "client_secret", an AWS secret access
257
+ * key; never "page_token"), and a JWK's private member beside its "kty" (JWK_PRIVATE). An array's items have no key,
258
+ * so only the line-break rule holds them. Its other strings are not held: an id, a project, an email and public URLs
259
+ * ("client_id", "token_uri") are no secret, and would be cut wherever a text names them. Undefined where `value` is no
260
+ * JSON object or array. */
261
+ function heldFields(value) {
262
+ const head = value.trimStart()[0];
263
+ if (head !== "{" && head !== "[")
264
+ return undefined;
265
+ let parsed;
266
+ try {
267
+ parsed = JSON.parse(value);
268
+ }
269
+ catch {
270
+ return undefined;
271
+ }
272
+ const out = [];
273
+ // Walked with a stack of its own, not a call per level: a value nested thousands deep is read as any other.
274
+ // Each node with its key and whether its object is a JWK (holds a "kty").
275
+ const stack = [[parsed, undefined, false]];
276
+ for (let next = stack.pop(); next !== undefined; next = stack.pop()) {
277
+ const [node, key, jwk] = next;
278
+ if (typeof node === "string") {
279
+ if (/[\r\n]/.test(node) || (key !== undefined && (secretName(key) || (jwk && JWK_PRIVATE.has(key)))))
280
+ out.push(node.trim());
281
+ }
282
+ else if (Array.isArray(node))
283
+ for (const item of node)
284
+ stack.push([item, undefined, false]);
285
+ else if (node !== null && typeof node === "object") {
286
+ const kty = typeof node.kty === "string";
287
+ for (const [name, item] of Object.entries(node))
288
+ stack.push([item, name, kty]);
289
+ }
290
+ }
291
+ return out.filter(longEnough);
292
+ }
192
293
  /** A matcher for `values` in a text: plain, split by whitespace, as JSON writes it, percent or form encoded, base64 or
193
294
  * hex, and each hex identifier in a value folded: in any case, its separators dropped or moved (foldedOf). Values
194
295
  * shorter than MIN_SECRET are left out. `fold: false`, the matcher without the folded needles. */
@@ -100,8 +100,10 @@ export type AfterState = (typeof AFTER_STATES)[number];
100
100
  * leaves learning out and the after side keeps it in, so the figure never flatters learning. `withheld`: after a
101
101
  * takeover, how many runs either side reads have an unknown cost and how many one known only as at most
102
102
  * (`cost_upper_bound`); while any does there is no ratio, null when none does. `hand_backs`: of the served runs from
103
- * the takeover on, how many handed back; null before a takeover. `replay`: the serving promotion's, as given. Every one
104
- * is over every run, never only the latest a read lists. */
103
+ * the takeover on (`ran`), how many the workflow handed back itself (`back`: an escalate, a failed step, an answer cut
104
+ * by size or schema) and how many a restart cut (`cut`: the run ids `cut` names, its call ended `interrupted`,
105
+ * metrics.workflow_cut); null before a takeover. A cut run stays `handed_back` at agent cost: only the count moves.
106
+ * `replay`: the serving promotion's, as given. Every one is over every run, never only the latest a read lists. */
105
107
  export type CostSummary = {
106
108
  takeover: {
107
109
  n: number;
@@ -120,6 +122,7 @@ export type CostSummary = {
120
122
  hand_backs: {
121
123
  ran: number;
122
124
  back: number;
125
+ cut: number;
123
126
  } | null;
124
127
  withheld: {
125
128
  unknown: number;
@@ -127,7 +130,7 @@ export type CostSummary = {
127
130
  } | null;
128
131
  replay: CostReplay | null;
129
132
  };
130
- export declare function costSummary(runs: readonly CostRun[], replay?: CostReplay | null): CostSummary;
133
+ export declare function costSummary(runs: readonly CostRun[], replay?: CostReplay | null, cut?: ReadonlySet<string>): CostSummary;
131
134
  /** The paths of the runs that do a job: the bill's run index counts these. A replay checks a revision and an audit's
132
135
  * shadow audits a run: their spend is learning, booked where it falls (billOf) and carried by the runs they serve. */
133
136
  export declare const JOB_PATHS: readonly RunPath[];
@@ -67,7 +67,7 @@ export function tookOverOf(runs) {
67
67
  /** Why the after side has a figure or not: `priced`, it has; `no_served_runs`, no learned workflow has taken over (a
68
68
  * replay is no served run); `cost_unknown`, runs were served but none's all-in cost is known exactly. */
69
69
  export const AFTER_STATES = ["priced", "no_served_runs", "cost_unknown"];
70
- export function costSummary(runs, replay = null) {
70
+ export function costSummary(runs, replay = null, cut = new Set()) {
71
71
  const first = runs.findIndex((run) => SERVED_PATHS.includes(run.path));
72
72
  const beforeSide = (first < 0 ? runs : runs.slice(0, first)).filter((run) => run.path === "agent").map((run) => ({ value: run.cost_usd, bound: run.cost_upper_bound }));
73
73
  // Served runs alone: a replay (a check of a new revision, at workflow cost) and a run by hand are never the after side.
@@ -85,7 +85,9 @@ export function costSummary(runs, replay = null) {
85
85
  const atMost = read.filter(({ bound }) => bound).length;
86
86
  const withheld = first >= 0 && unknown + atMost > 0 ? { unknown, at_most: atMost } : null;
87
87
  const times = !withheld && before && after && after.runs >= CHEAPER_AFTER_RUNS && after.mean_usd > 0 ? Math.round((before.mean_usd / after.mean_usd) * 10) / 10 : null;
88
- const handBacks = first < 0 ? null : { ran: served.length, back: served.filter((run) => run.path === "handed_back").length };
88
+ const handedBack = served.filter((run) => run.path === "handed_back");
89
+ const cutBack = handedBack.filter((run) => cut.has(run.run_id)).length;
90
+ const handBacks = first < 0 ? null : { ran: served.length, back: handedBack.length - cutBack, cut: cutBack };
89
91
  const afterState = after ? "priced" : first < 0 ? "no_served_runs" : "cost_unknown";
90
92
  return { takeover: first < 0 ? null : { n: runs[first].n, run_id: runs[first].run_id }, before, after, after_state: afterState, times_cheaper: times, hand_backs: handBacks, withheld, replay };
91
93
  }
@@ -6,7 +6,7 @@
6
6
  // sets equal, and each value equal, except that a call's value read as "…" (a timeline read elides query values,
7
7
  // scrubUrls) matches any value for its key. Structural only: whether a cited item is in scope stays the rubric's call.
8
8
  import { lastJsonBlock } from "./answer-json.js";
9
- import { linksOf, linksWritten, TRAILING, trimmed, wholeUrl } from "./text-urls.js";
9
+ import { linksOf, linksWritten, TRAILING, trimmed, wholeUrl } from "@parcha/agentrun-web";
10
10
  import { scrubUrl } from "./timeline/index.js";
11
11
  import { WEB_FETCH_TOOL } from "./web-fetch.js";
12
12
  import { WEB_SEARCH_TOOL } from "./web-search.js";
package/dist/llms.txt CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  > The open platform's server for agents: make an agent (a prompt with tools, or a typed workflow), run it, and read what it did, over one HTTP API at `/v2`, an MCP endpoint at `/v2/mcp`, and a CLI. Every run is kept, with its timeline, its files and its cost.
4
4
 
5
- Auth: the API's routes take `Authorization: Bearer <token>`, all but `GET /v2/health`, `GET /v2/capabilities` and `GET /v2/openapi.json`; this file needs none. The MCP endpoint takes the Bearer token only. The token is the server's data directory's `.token` (`--data DIR`; without it, `$XDG_DATA_HOME/agentrun/agents`, else `~/.local/share/agentrun/agents`), or `AGENTRUN_TOKEN` when the server was started with it. Never print it. Links below are relative to this server.
5
+ Auth: the API's routes take `Authorization: Bearer <token>`, all but `GET /v2/health`, `GET /v2/capabilities` and `GET /v2/openapi.json`; this file needs none. The MCP endpoint takes the Bearer token only. The token is the server's data directory's `.token` (`--data DIR`; without it, `$XDG_DATA_HOME/agentrun/agents`, else `~/.local/share/agentrun/agents`), or `AGENTRUN_TOKEN` when the server was started with it. An API key the owner made in the console (Settings, AgentRun API keys; it starts `ar_key_`) is taken wherever the token is, except as the setup code; only the owner's signed-in session makes or revokes one. Never print it. Links below are relative to this server.
6
6
 
7
7
  ## Start
8
8
 
@@ -0,0 +1,77 @@
1
+ export declare const MARKETPLACE_URL = "https://marketplace.agentrun.ai";
2
+ export declare const MARKETPLACE_ENV = "AGENTRUN_MARKETPLACE";
3
+ /** How long a list read is answered before it is read again: the site's own cache-control (max-age=300). */
4
+ export declare const MARKETPLACE_TTL_MS: number;
5
+ /** How long a failed read is answered before the next try, so a console open on an offline server asks the network
6
+ * once a minute, not on every page. */
7
+ export declare const MARKETPLACE_RETRY_MS = 60000;
8
+ /** What one read may take: the list's bytes (today's is 68 KB), its entries, and the time the read may last. */
9
+ export declare const MARKETPLACE_LIMITS: {
10
+ readonly bytes: number;
11
+ readonly entries: 1000;
12
+ readonly ms: 10000;
13
+ };
14
+ /** One template on the marketplace. `title`, its display name; `summary`, its card's one line; `description`, the rest;
15
+ * `needs`, what it requires, in the marketplace's words; `harness`, its package's harness preference list (empty: any
16
+ * harness; left out when the list does not say), display only; `page_url`, its page there; `source`, the package an install
17
+ * reads (`github:<owner>/<repo>[/<path>]@<sha>`), when the list names one; `here`, the id of this server's package that
18
+ * is this one, when there is one (a bundled package by its name, or one imported from its source). */
19
+ export type MarketplaceTemplate = {
20
+ name: string;
21
+ title: string;
22
+ summary?: string;
23
+ description?: string;
24
+ category?: string;
25
+ tags: string[];
26
+ needs: string[];
27
+ harness?: string[];
28
+ page_url: string;
29
+ source?: string;
30
+ };
31
+ export type MarketplaceAnswer = {
32
+ /** The site read, or null when the marketplace is off here. */
33
+ url: string | null;
34
+ /** `read`: the list as read within the last 5 minutes; `stale`: the last read failed, and this is the list as read at
35
+ * `read_at`; `unreachable`: no read has worked yet, so the list is empty; `off`: this server reads no marketplace. */
36
+ state: "read" | "stale" | "unreachable" | "off";
37
+ read_at: string | null;
38
+ /** Why the last read failed (`stale`, `unreachable`), or why the marketplace is off. */
39
+ problem?: string;
40
+ templates: (MarketplaceTemplate & {
41
+ here?: string;
42
+ })[];
43
+ };
44
+ /** The marketplace this server reads, from the environment: its address, or null for off. Unset, the public one, except
45
+ * under --faux (a test's or a demo's server, which reaches no network unasked). `off` (or 0, false) turns it off. An
46
+ * address is an https origin (with a path, when the site is served under one); http is taken for a loopback host
47
+ * alone, a local copy of the site. Anything else stops the start: the owner set it, and a typo should not read as off. */
48
+ export declare function marketplaceUrlOf(env: NodeJS.ProcessEnv, faux: boolean): string | null;
49
+ /** One entry of the list read as a template, or undefined for one that is not (no name of a package's shape): an entry's
50
+ * other fields are kept where they are of their shape and dropped where not, so one odd field never hides a template. */
51
+ export declare function entryOf(raw: unknown, site: string): MarketplaceTemplate | undefined;
52
+ /** The list's JSON read as templates, in its order, each name once (its first entry), at most MARKETPLACE_LIMITS.entries.
53
+ * Anything but a list is the read's failure. */
54
+ export declare function listOf(json: unknown, site: string): MarketplaceTemplate[];
55
+ /** The package here that a marketplace entry is, by id: with a source, the package imported from it, else the bundled
56
+ * package of its name when the source is where this server's own packages live; with none (a list that names no
57
+ * sources), the package of its name, a bundled one first. */
58
+ export declare function hereOf(entry: Pick<MarketplaceTemplate, "name" | "source">, packages: readonly {
59
+ id: string;
60
+ name: string;
61
+ origin: unknown;
62
+ }[]): string | undefined;
63
+ /** The marketplace's list as this server reads it: on demand, kept MARKETPLACE_TTL_MS, one read at a time however many
64
+ * ask, and the last good list kept through a failed read. `fetchImpl`, `now` and `deadlineMs` (the read's time limit,
65
+ * MARKETPLACE_LIMITS.ms unless said) are a test's seams. */
66
+ export declare class Marketplace {
67
+ #private;
68
+ readonly url: string | null;
69
+ constructor(url: string | null, options?: {
70
+ fetchImpl?: typeof fetch;
71
+ now?: () => number;
72
+ deadlineMs?: number;
73
+ });
74
+ list(): Promise<Omit<MarketplaceAnswer, "templates"> & {
75
+ templates: MarketplaceTemplate[];
76
+ }>;
77
+ }
@@ -0,0 +1,224 @@
1
+ // The marketplace's templates (GET /v2/marketplace/templates): marketplace.agentrun.ai lists every template package,
2
+ // Parcha's and the community's, and publishes that list as /search.json, the one its own pages are built beside. The
3
+ // console lists the packages this server ships and those imported here, then the marketplace's others, so the two show
4
+ // the same templates. This server reads the list only when asked (no read at its start, none in the background), keeps
5
+ // it 5 minutes (the site's own cache-control), and keeps the last good one when a read fails. Nothing on the list is
6
+ // imported or run: an entry is display data and, when it names one, the package source an install reads (POST
7
+ // /v2/templates/import, with its publisher trusted once). Off with AGENTRUN_MARKETPLACE=off, and under --faux unless
8
+ // AGENTRUN_MARKETPLACE names an address; an address there reads that site's list in place of marketplace.agentrun.ai's.
9
+ import { HARNESS_ID_PATTERN } from "./harness.js";
10
+ import { parseSource } from "./template-source.js";
11
+ import { CATEGORIES } from "./templates.js";
12
+ export const MARKETPLACE_URL = "https://marketplace.agentrun.ai";
13
+ export const MARKETPLACE_ENV = "AGENTRUN_MARKETPLACE";
14
+ /** How long a list read is answered before it is read again: the site's own cache-control (max-age=300). */
15
+ export const MARKETPLACE_TTL_MS = 5 * 60_000;
16
+ /** How long a failed read is answered before the next try, so a console open on an offline server asks the network
17
+ * once a minute, not on every page. */
18
+ export const MARKETPLACE_RETRY_MS = 60_000;
19
+ /** What one read may take: the list's bytes (today's is 68 KB), its entries, and the time the read may last. */
20
+ export const MARKETPLACE_LIMITS = { bytes: 4 << 20, entries: 1000, ms: 10_000 };
21
+ /** Where the packages this server ships live on GitHub, so a marketplace entry that names one is the bundled package. */
22
+ const BUNDLED_REPO = "parcha-ai/agentrun";
23
+ const BUNDLED_PATH = "packages/serve/templates/";
24
+ const NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
25
+ const TAG = /^[a-z0-9-]{1,32}$/;
26
+ const HARNESS = new RegExp(HARNESS_ID_PATTERN);
27
+ const MAX = { name: 64, title: 120, summary: 300, description: 2000, tags: 8, needs: 16, need: 200, harness: 8 };
28
+ const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
29
+ /** The marketplace this server reads, from the environment: its address, or null for off. Unset, the public one, except
30
+ * under --faux (a test's or a demo's server, which reaches no network unasked). `off` (or 0, false) turns it off. An
31
+ * address is an https origin (with a path, when the site is served under one); http is taken for a loopback host
32
+ * alone, a local copy of the site. Anything else stops the start: the owner set it, and a typo should not read as off. */
33
+ export function marketplaceUrlOf(env, faux) {
34
+ const given = env[MARKETPLACE_ENV]?.trim();
35
+ if (!given)
36
+ return faux ? null : MARKETPLACE_URL;
37
+ if (/^(off|0|false|no)$/i.test(given))
38
+ return null;
39
+ let url;
40
+ try {
41
+ url = new URL(given);
42
+ }
43
+ catch {
44
+ throw new Error(`${MARKETPLACE_ENV}=${given} is not an address: set it to the marketplace's https address (default ${MARKETPLACE_URL}), or to off.`);
45
+ }
46
+ const local = url.protocol === "http:" && LOOPBACK.has(url.hostname);
47
+ if ((url.protocol !== "https:" && !local) || url.username || url.password || url.search || url.hash) {
48
+ throw new Error(`${MARKETPLACE_ENV}=${given} is not one: the marketplace is read over https (http on a loopback host alone), with no user, query or fragment. Default ${MARKETPLACE_URL}; off turns it off.`);
49
+ }
50
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
51
+ }
52
+ /** One line of text from the list: control characters made spaces, trimmed, and cut at `max`. Undefined for anything but
53
+ * a string with text in it. */
54
+ function line(value, max) {
55
+ if (typeof value !== "string")
56
+ return undefined;
57
+ const text = value.replace(/[\0-\x1f\x7f]+/g, " ").trim();
58
+ if (!text)
59
+ return undefined;
60
+ return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
61
+ }
62
+ /** One entry of the list read as a template, or undefined for one that is not (no name of a package's shape): an entry's
63
+ * other fields are kept where they are of their shape and dropped where not, so one odd field never hides a template. */
64
+ export function entryOf(raw, site) {
65
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
66
+ return undefined;
67
+ const e = raw;
68
+ if (typeof e.name !== "string" || e.name.length > MAX.name || !NAME.test(e.name))
69
+ return undefined;
70
+ const name = e.name;
71
+ const summary = line(e.summary, MAX.summary);
72
+ const description = line(e.description, MAX.description);
73
+ const category = typeof e.category === "string" && CATEGORIES.includes(e.category) ? e.category : undefined;
74
+ const tags = Array.isArray(e.tags) ? [...new Set(e.tags.filter((t) => typeof t === "string" && TAG.test(t)))].slice(0, MAX.tags) : [];
75
+ const needs = Array.isArray(e.needs) ? e.needs.map((n) => line(n, MAX.need)).filter((n) => !!n).slice(0, MAX.needs) : [];
76
+ // Its harnesses, in preference order: the ids of a harness's shape, each once. A list that says none leaves it out.
77
+ const harness = Array.isArray(e.harness) ? [...new Set(e.harness.filter((h) => typeof h === "string" && HARNESS.test(h)))].slice(0, MAX.harness) : undefined;
78
+ // Its page: the path the list gives, on the site itself; any other place, its page's usual one.
79
+ const usual = `${site}/templates/${name}/`;
80
+ let page_url = usual;
81
+ if (typeof e.url === "string" && e.url.startsWith("/") && !e.url.startsWith("//")) {
82
+ try {
83
+ const at = new URL(`${site}${e.url}`);
84
+ if (at.origin === new URL(site).origin)
85
+ page_url = at.href;
86
+ }
87
+ catch {
88
+ page_url = usual;
89
+ }
90
+ }
91
+ // Its source, kept as the list writes it (the commit it pins with it) when it reads as one: an install reads that.
92
+ let source;
93
+ if (typeof e.source === "string") {
94
+ try {
95
+ parseSource(e.source);
96
+ source = e.source.trim();
97
+ }
98
+ catch {
99
+ source = undefined;
100
+ }
101
+ }
102
+ return {
103
+ name, title: line(e.title, MAX.title) ?? name,
104
+ ...(summary ? { summary } : {}), ...(description ? { description } : {}), ...(category ? { category } : {}),
105
+ tags, needs, ...(harness ? { harness } : {}), page_url, ...(source ? { source } : {}),
106
+ };
107
+ }
108
+ /** The list's JSON read as templates, in its order, each name once (its first entry), at most MARKETPLACE_LIMITS.entries.
109
+ * Anything but a list is the read's failure. */
110
+ export function listOf(json, site) {
111
+ if (!Array.isArray(json))
112
+ throw new Error("The marketplace's list is not a list of templates.");
113
+ const seen = new Set();
114
+ const out = [];
115
+ for (const raw of json) {
116
+ const entry = entryOf(raw, site);
117
+ if (!entry || seen.has(entry.name))
118
+ continue;
119
+ seen.add(entry.name);
120
+ out.push(entry);
121
+ if (out.length >= MARKETPLACE_LIMITS.entries)
122
+ break;
123
+ }
124
+ return out;
125
+ }
126
+ /** The package here that a marketplace entry is, by id: with a source, the package imported from it, else the bundled
127
+ * package of its name when the source is where this server's own packages live; with none (a list that names no
128
+ * sources), the package of its name, a bundled one first. */
129
+ export function hereOf(entry, packages) {
130
+ const bundled = packages.find((p) => p.origin === null && p.name === entry.name);
131
+ if (!entry.source)
132
+ return (bundled ?? packages.find((p) => p.name === entry.name))?.id;
133
+ const source = parseSource(entry.source);
134
+ const imported = packages.find((p) => p.origin !== null && p.id === source.id);
135
+ if (imported)
136
+ return imported.id;
137
+ return `${source.owner}/${source.repo}`.toLowerCase() === BUNDLED_REPO && source.path === `${BUNDLED_PATH}${entry.name}` ? bundled?.id : undefined;
138
+ }
139
+ /** The marketplace's list as this server reads it: on demand, kept MARKETPLACE_TTL_MS, one read at a time however many
140
+ * ask, and the last good list kept through a failed read. `fetchImpl`, `now` and `deadlineMs` (the read's time limit,
141
+ * MARKETPLACE_LIMITS.ms unless said) are a test's seams. */
142
+ export class Marketplace {
143
+ url;
144
+ #fetch;
145
+ #now;
146
+ #held;
147
+ #failed;
148
+ #reading;
149
+ #deadlineMs;
150
+ constructor(url, options = {}) {
151
+ this.url = url;
152
+ this.#fetch = options.fetchImpl ?? fetch;
153
+ this.#now = options.now ?? Date.now;
154
+ this.#deadlineMs = options.deadlineMs ?? MARKETPLACE_LIMITS.ms;
155
+ }
156
+ async list() {
157
+ if (!this.url)
158
+ return { url: null, state: "off", read_at: null, problem: `This server reads no marketplace (${MARKETPLACE_ENV}=off, or --faux with it unset).`, templates: [] };
159
+ const now = this.#now();
160
+ const held = this.#held;
161
+ const fresh = held && now - held.at < MARKETPLACE_TTL_MS;
162
+ const waiting = this.#failed && now - this.#failed.at < MARKETPLACE_RETRY_MS;
163
+ if (!fresh && !waiting) {
164
+ try {
165
+ this.#held = await (this.#reading ??= this.#read().finally(() => { this.#reading = undefined; }));
166
+ this.#failed = undefined;
167
+ }
168
+ catch (error) {
169
+ this.#failed = { at: this.#now(), problem: error.message };
170
+ }
171
+ }
172
+ const kept = this.#held;
173
+ const read_at = kept ? new Date(kept.at).toISOString() : null;
174
+ if (this.#failed)
175
+ return kept ? { url: this.url, state: "stale", read_at, problem: this.#failed.problem, templates: kept.templates } : { url: this.url, state: "unreachable", read_at: null, problem: this.#failed.problem, templates: [] };
176
+ return { url: this.url, state: "read", read_at, templates: kept?.templates ?? [] };
177
+ }
178
+ async #read() {
179
+ const at = `${this.url}/search.json`;
180
+ // One deadline for the whole read: the answer's headers and every byte of its body.
181
+ const signal = AbortSignal.timeout(this.#deadlineMs);
182
+ let res;
183
+ try {
184
+ res = await this.#fetch(at, { redirect: "manual", signal, headers: { accept: "application/json", "user-agent": "agentrun-serve" } });
185
+ }
186
+ catch (error) {
187
+ throw new Error(signal.aborted ? `The marketplace (${this.url}) did not answer in ${this.#deadlineMs / 1000} s.` : `The marketplace (${this.url}) could not be reached: ${error.message}.`);
188
+ }
189
+ if (res.status >= 300 && res.status < 400) {
190
+ await res.body?.cancel();
191
+ throw new Error(`The marketplace (${this.url}) sent its list elsewhere (${res.status} to ${res.headers.get("location") ?? "nowhere"}): set ${MARKETPLACE_ENV} to the address it names.`);
192
+ }
193
+ if (res.status !== 200 || !res.body) {
194
+ await res.body?.cancel();
195
+ throw new Error(`The marketplace (${this.url}) answered ${res.status} for its list.`);
196
+ }
197
+ const declared = Number(res.headers.get("content-length"));
198
+ if (Number.isFinite(declared) && declared > MARKETPLACE_LIMITS.bytes) {
199
+ await res.body.cancel();
200
+ throw new Error(`The marketplace's list is ${declared} bytes, over the ${MARKETPLACE_LIMITS.bytes} this server reads.`);
201
+ }
202
+ const chunks = [];
203
+ let bytes = 0;
204
+ try {
205
+ for await (const chunk of res.body) {
206
+ bytes += chunk.byteLength;
207
+ if (bytes > MARKETPLACE_LIMITS.bytes)
208
+ throw new Error(`The marketplace's list is over the ${MARKETPLACE_LIMITS.bytes} bytes this server reads.`);
209
+ chunks.push(chunk);
210
+ }
211
+ }
212
+ catch (error) {
213
+ throw signal.aborted ? new Error(`The marketplace (${this.url}) did not finish its list in ${this.#deadlineMs / 1000} s.`) : error;
214
+ }
215
+ let json;
216
+ try {
217
+ json = JSON.parse(Buffer.concat(chunks).toString("utf8"));
218
+ }
219
+ catch {
220
+ throw new Error("The marketplace's list is not JSON.");
221
+ }
222
+ return { templates: listOf(json, this.url), at: this.#now() };
223
+ }
224
+ }
@@ -0,0 +1,30 @@
1
+ import { listMcpServers } from "./mcp-store.js";
2
+ /** The settings key the list is held under, as `{ origins: string[] }`. */
3
+ export declare const API_ONLY_MCP_ORIGINS_KEY = "mcp.api_only_origins";
4
+ type SettingsReader = {
5
+ settings: {
6
+ get(key: string): Promise<unknown>;
7
+ };
8
+ };
9
+ type SettingsWriter = {
10
+ settings: {
11
+ put(key: string, value: unknown): Promise<void>;
12
+ remove(key: string): Promise<void>;
13
+ };
14
+ };
15
+ /** Writes the list a server started with (`origins`, normalized) when it serves the API-only profile; removes it
16
+ * otherwise. */
17
+ export declare function holdApiOnlyMcpOrigins(store: SettingsWriter, apiOnly: boolean, origins: readonly string[]): Promise<void>;
18
+ /** The list the store holds, or undefined when it holds none (a full server's store). */
19
+ export declare function heldApiOnlyMcpOrigins(store: SettingsReader): Promise<readonly unknown[] | undefined>;
20
+ /** Why the saved server `name` (`row`) can't be used, or undefined when it can. It can't be used when it is a per_run
21
+ * server the API token saved, the store holds an API-only list, and its address's origin is not on that list. */
22
+ export declare function offApiOnlyMcpOrigins(store: SettingsReader, name: string, row: {
23
+ auth: string;
24
+ url: string;
25
+ createdAt?: number;
26
+ }): Promise<string | undefined>;
27
+ /** The names of the saved servers offApiOnlyMcpOrigins refuses now, sorted: none when the store holds no list. What an
28
+ * API-only start says once in its log (server.ts), by name alone, never an address. */
29
+ export declare function offApiOnlyMcpServers(store: SettingsReader & Parameters<typeof listMcpServers>[0]): Promise<string[]>;
30
+ export {};