@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.30

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 (273) hide show
  1. package/CHANGELOG.md +748 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +2190 -2
  5. package/dist/adapters.d.ts +234 -0
  6. package/dist/adapters.js +585 -0
  7. package/dist/agents.d.ts +130 -0
  8. package/dist/agents.js +308 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +384 -0
  11. package/dist/background.d.ts +28 -0
  12. package/dist/background.js +376 -0
  13. package/dist/bound-files.d.ts +4 -0
  14. package/dist/bound-files.js +164 -0
  15. package/dist/box/record.d.ts +6 -0
  16. package/dist/box/record.js +41 -0
  17. package/dist/box/sweep.d.ts +53 -0
  18. package/dist/box/sweep.js +193 -0
  19. package/dist/box-egress.d.ts +98 -0
  20. package/dist/box-egress.js +259 -0
  21. package/dist/box-image.d.ts +98 -0
  22. package/dist/box-image.js +285 -0
  23. package/dist/box-relay-vm.d.ts +80 -0
  24. package/dist/box-relay-vm.js +389 -0
  25. package/dist/box-relay.d.ts +45 -0
  26. package/dist/box-relay.js +227 -0
  27. package/dist/boxes.d.ts +72 -0
  28. package/dist/boxes.js +189 -0
  29. package/dist/browser-cost.d.ts +41 -0
  30. package/dist/browser-cost.js +158 -0
  31. package/dist/cap.d.ts +332 -0
  32. package/dist/cap.js +992 -0
  33. package/dist/catalog.d.ts +20 -0
  34. package/dist/catalog.js +53 -0
  35. package/dist/cli.d.ts +2 -0
  36. package/dist/cli.js +167 -0
  37. package/dist/coding-tools.d.ts +35 -0
  38. package/dist/coding-tools.js +87 -0
  39. package/dist/console/THIRD-PARTY-NOTICES.txt +1721 -0
  40. package/dist/console/assets/index-34jfpIbQ.js +481 -0
  41. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  42. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  53. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  54. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  57. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  58. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  59. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  60. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  61. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  62. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  63. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  64. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  65. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  66. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  67. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  68. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  69. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  70. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  71. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  72. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  73. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  74. package/dist/console/index.html +15 -0
  75. package/dist/content-filter.d.ts +7 -0
  76. package/dist/content-filter.js +23 -0
  77. package/dist/daytona-api.d.ts +21 -0
  78. package/dist/daytona-api.js +101 -0
  79. package/dist/decision-rows.d.ts +19 -0
  80. package/dist/decision-rows.js +123 -0
  81. package/dist/decisions.d.ts +94 -0
  82. package/dist/decisions.js +184 -0
  83. package/dist/effort-guidance.d.ts +5 -0
  84. package/dist/effort-guidance.js +14 -0
  85. package/dist/environment.d.ts +5 -0
  86. package/dist/environment.js +11 -0
  87. package/dist/errors.d.ts +74 -0
  88. package/dist/errors.js +69 -0
  89. package/dist/exa-keyless.d.ts +35 -0
  90. package/dist/exa-keyless.js +202 -0
  91. package/dist/fetch-page.d.ts +114 -0
  92. package/dist/fetch-page.js +182 -0
  93. package/dist/files.d.ts +65 -0
  94. package/dist/files.js +158 -0
  95. package/dist/grade.d.ts +93 -0
  96. package/dist/grade.js +328 -0
  97. package/dist/graph-served.d.ts +23 -0
  98. package/dist/graph-served.js +75 -0
  99. package/dist/graph-view.d.ts +102 -0
  100. package/dist/graph-view.js +219 -0
  101. package/dist/harness-app.d.ts +40 -0
  102. package/dist/harness-app.js +708 -0
  103. package/dist/harness-opencode/adapter.d.ts +45 -0
  104. package/dist/harness-opencode/adapter.js +272 -0
  105. package/dist/harness-opencode/binary.d.ts +18 -0
  106. package/dist/harness-opencode/binary.js +87 -0
  107. package/dist/harness-opencode/config.d.ts +24 -0
  108. package/dist/harness-opencode/config.js +61 -0
  109. package/dist/harness-opencode/harness.d.ts +77 -0
  110. package/dist/harness-opencode/harness.js +620 -0
  111. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  112. package/dist/harness-opencode/host/mcp.js +208 -0
  113. package/dist/harness-opencode/host/policy.d.ts +71 -0
  114. package/dist/harness-opencode/host/policy.js +419 -0
  115. package/dist/harness-opencode/host/server.d.ts +55 -0
  116. package/dist/harness-opencode/host/server.js +165 -0
  117. package/dist/harness-opencode/index.d.ts +9 -0
  118. package/dist/harness-opencode/index.js +6 -0
  119. package/dist/harness-opencode/verify.d.ts +32 -0
  120. package/dist/harness-opencode/verify.js +75 -0
  121. package/dist/harness-opencode/versions.d.ts +33 -0
  122. package/dist/harness-opencode/versions.js +64 -0
  123. package/dist/harness.d.ts +56 -0
  124. package/dist/harness.js +77 -0
  125. package/dist/home-path.d.ts +27 -0
  126. package/dist/home-path.js +78 -0
  127. package/dist/host-tools.d.ts +30 -0
  128. package/dist/host-tools.js +154 -0
  129. package/dist/host.d.ts +39 -0
  130. package/dist/host.js +85 -0
  131. package/dist/hosted-search.d.ts +27 -0
  132. package/dist/hosted-search.js +133 -0
  133. package/dist/import-sources.d.ts +104 -0
  134. package/dist/import-sources.js +629 -0
  135. package/dist/import-summary.d.ts +25 -0
  136. package/dist/import-summary.js +75 -0
  137. package/dist/import-worker.d.ts +26 -0
  138. package/dist/import-worker.js +41 -0
  139. package/dist/import.d.ts +145 -0
  140. package/dist/import.js +1222 -0
  141. package/dist/index.d.ts +7 -0
  142. package/dist/index.js +6 -0
  143. package/dist/key-check.d.ts +37 -0
  144. package/dist/key-check.js +112 -0
  145. package/dist/key-refusal.d.ts +51 -0
  146. package/dist/key-refusal.js +191 -0
  147. package/dist/learn/check.d.ts +108 -0
  148. package/dist/learn/check.js +277 -0
  149. package/dist/learn/grade.d.ts +80 -0
  150. package/dist/learn/grade.js +445 -0
  151. package/dist/learn/index.d.ts +7 -0
  152. package/dist/learn/index.js +11 -0
  153. package/dist/learn/invisible.d.ts +5 -0
  154. package/dist/learn/invisible.js +42 -0
  155. package/dist/learn/notes.d.ts +59 -0
  156. package/dist/learn/notes.js +147 -0
  157. package/dist/learn/reflect.d.ts +49 -0
  158. package/dist/learn/reflect.js +213 -0
  159. package/dist/learn/secrets.d.ts +18 -0
  160. package/dist/learn/secrets.js +131 -0
  161. package/dist/learn/skills.d.ts +97 -0
  162. package/dist/learn/skills.js +271 -0
  163. package/dist/learned-workflow.d.ts +59 -0
  164. package/dist/learned-workflow.js +191 -0
  165. package/dist/learning-routes.d.ts +196 -0
  166. package/dist/learning-routes.js +609 -0
  167. package/dist/learning-run.d.ts +306 -0
  168. package/dist/learning-run.js +819 -0
  169. package/dist/learning-words.d.ts +76 -0
  170. package/dist/learning-words.js +174 -0
  171. package/dist/learning.d.ts +418 -0
  172. package/dist/learning.js +946 -0
  173. package/dist/llm.d.ts +40 -0
  174. package/dist/llm.js +37 -0
  175. package/dist/llms.txt +37 -0
  176. package/dist/mcp-servers.d.ts +118 -0
  177. package/dist/mcp-servers.js +450 -0
  178. package/dist/mcp.d.ts +51 -0
  179. package/dist/mcp.js +392 -0
  180. package/dist/model.d.ts +186 -0
  181. package/dist/model.js +485 -0
  182. package/dist/monid.d.ts +74 -0
  183. package/dist/monid.js +277 -0
  184. package/dist/openapi/agentrun-v2.openapi.json +4806 -0
  185. package/dist/openapi.d.ts +10 -0
  186. package/dist/openapi.js +1727 -0
  187. package/dist/owner.d.ts +55 -0
  188. package/dist/owner.js +222 -0
  189. package/dist/packs.d.ts +71 -0
  190. package/dist/packs.js +180 -0
  191. package/dist/page.d.ts +32 -0
  192. package/dist/page.js +133 -0
  193. package/dist/paid-calls.d.ts +50 -0
  194. package/dist/paid-calls.js +110 -0
  195. package/dist/pause.d.ts +70 -0
  196. package/dist/pause.js +97 -0
  197. package/dist/pdf-pages.d.ts +44 -0
  198. package/dist/pdf-pages.js +147 -0
  199. package/dist/place.d.ts +69 -0
  200. package/dist/place.js +137 -0
  201. package/dist/print.d.ts +20 -0
  202. package/dist/print.js +29 -0
  203. package/dist/propose.d.ts +40 -0
  204. package/dist/propose.js +112 -0
  205. package/dist/quiet-sqlite-warning.d.ts +1 -0
  206. package/dist/quiet-sqlite-warning.js +14 -0
  207. package/dist/request-start.d.ts +22 -0
  208. package/dist/request-start.js +350 -0
  209. package/dist/result.d.ts +3 -0
  210. package/dist/result.js +5 -0
  211. package/dist/rows.d.ts +46 -0
  212. package/dist/rows.js +121 -0
  213. package/dist/run-box.d.ts +186 -0
  214. package/dist/run-box.js +590 -0
  215. package/dist/run-manifest.d.ts +27 -0
  216. package/dist/run-manifest.js +60 -0
  217. package/dist/runnable.d.ts +83 -0
  218. package/dist/runnable.js +170 -0
  219. package/dist/runs.d.ts +1062 -0
  220. package/dist/runs.js +3020 -0
  221. package/dist/secret-cut.d.ts +27 -0
  222. package/dist/secret-cut.js +109 -0
  223. package/dist/secrets.d.ts +62 -0
  224. package/dist/secrets.js +158 -0
  225. package/dist/server-lock.d.ts +44 -0
  226. package/dist/server-lock.js +140 -0
  227. package/dist/server.d.ts +722 -0
  228. package/dist/server.js +2118 -0
  229. package/dist/sessions.d.ts +4 -0
  230. package/dist/sessions.js +105 -0
  231. package/dist/sign-ins.d.ts +99 -0
  232. package/dist/sign-ins.js +288 -0
  233. package/dist/skills.d.ts +43 -0
  234. package/dist/skills.js +96 -0
  235. package/dist/stats.d.ts +106 -0
  236. package/dist/stats.js +103 -0
  237. package/dist/tool-gate.d.ts +266 -0
  238. package/dist/tool-gate.js +554 -0
  239. package/dist/tool-keys.d.ts +187 -0
  240. package/dist/tool-keys.js +315 -0
  241. package/dist/tool-plane.d.ts +228 -0
  242. package/dist/tool-plane.js +400 -0
  243. package/dist/tools.d.ts +202 -0
  244. package/dist/tools.js +372 -0
  245. package/dist/trigger-secrets.d.ts +32 -0
  246. package/dist/trigger-secrets.js +143 -0
  247. package/dist/triggers.d.ts +439 -0
  248. package/dist/triggers.js +863 -0
  249. package/dist/turn-end.d.ts +24 -0
  250. package/dist/turn-end.js +15 -0
  251. package/dist/turns.d.ts +34 -0
  252. package/dist/turns.js +202 -0
  253. package/dist/uploads.d.ts +104 -0
  254. package/dist/uploads.js +474 -0
  255. package/dist/usage-lines.d.ts +26 -0
  256. package/dist/usage-lines.js +28 -0
  257. package/dist/usage.d.ts +29 -0
  258. package/dist/usage.js +58 -0
  259. package/dist/validate.d.ts +57 -0
  260. package/dist/validate.js +184 -0
  261. package/dist/web-fetch.d.ts +64 -0
  262. package/dist/web-fetch.js +262 -0
  263. package/dist/web-search.d.ts +54 -0
  264. package/dist/web-search.js +136 -0
  265. package/dist/webhooks.d.ts +189 -0
  266. package/dist/webhooks.js +503 -0
  267. package/dist/workspace-paths.d.ts +33 -0
  268. package/dist/workspace-paths.js +104 -0
  269. package/dist/workspace.d.ts +88 -0
  270. package/dist/workspace.js +369 -0
  271. package/launcher/agentrun-serve +109 -0
  272. package/package.json +100 -4
  273. package/skills/agentrun-serve/SKILL.md +128 -0
@@ -0,0 +1,202 @@
1
+ // web_search's keyless fallback: Exa's public MCP endpoint (https://mcp.exa.ai/mcp, docs.exa.ai/reference/exa-mcp),
2
+ // which answers its `web_search_exa` tool with no key at a free rate limit. One search is one MCP exchange over its
3
+ // streamable HTTP transport: `initialize` (its session id, when it names one), `notifications/initialized`, then
4
+ // `tools/call` of web_search_exa with `{query, numResults}`, at most 8. Exa answers one text block, a result per section split by
5
+ // `---` lines, each `Title:`, `URL:`, `Published:`, `Author:`, then `Highlights:` (or `Text:`) and its lines; a `Note:`
6
+ // line may lead it. That text is read into the same Search every web_search answers, and no more than 1 MiB of an
7
+ // answer is read. Past its free limit Exa answers a 429 with Retry-After, or (when its search API refuses the keyless
8
+ // call) a 200 whose tool result is marked isError and `ai.exa/rateLimited`, its text telling the user to put an API key
9
+ // in their MCP URL. Either is tried once more, a new exchange after a jittered 1 to 3 s or the Retry-After Exa names when
10
+ // it is 5 s or less (past that, as with its daily limit, the limit does not lift within a search, and it is not tried
11
+ // again); still limited, the search answers RATE_LIMITED, in our words, never Exa's. Any other failure Exa answers is
12
+ // ours too, quoting only the first sentence of Exa's (exaSaid). A 403 is a connection keyless use
13
+ // refuses (Exa takes it over IPv4, straight to the endpoint), never tried again. Both say which limit they met
14
+ // (ExaLimited), for the caller's fallback. A search ends at 60 s, its retry and wait included. No key is sent, ever.
15
+ // Exa is dialled over IPv4 alone (ipv4Fetch): its name looked up for family 4 and the connection made to that address,
16
+ // so a host whose default route is IPv6 reaches it the one way keyless use is taken.
17
+ import { lookup as dnsLookup } from "node:dns";
18
+ import { clip, TITLE_CAP } from "./fetch-page.js";
19
+ import { snippetOf } from "./web-search.js";
20
+ export const EXA_MCP_URL = "https://mcp.exa.ai/mcp";
21
+ export const EXA_SEARCH_TOOL = "web_search_exa";
22
+ /** Under `--faux` only: a module whose default export is the fetch Exa's MCP exchange goes through (the tests' fake
23
+ * MCP server), in place of Exa's endpoint. */
24
+ export const FAUX_EXA_ENV = "AGENTRUN_SERVE_FAUX_EXA";
25
+ /** The MCP revision this client speaks; the server answers the one it takes. */
26
+ const PROTOCOL = "2025-06-18";
27
+ const TIMEOUT_MS = 60_000;
28
+ /** The most results Exa's free endpoint is asked for (its default is 10). Its own cap on purpose, not web search's
29
+ * RESULTS_MAX: the hosted providers take more, and Exa's keyless limit is per request. */
30
+ const RESULTS_MAX = 8;
31
+ const ACCEPT = "application/json, text/event-stream";
32
+ /** The most of an answer read: a search's text is a few kilobytes; past this the rest is never read. */
33
+ const MAX_BYTES = 1 << 20;
34
+ /** What a search answers when Exa's free limit holds after the one retry. Exa's own words name a fix (an API key in
35
+ * its MCP URL) that means nothing to a person here, so they are never passed on. */
36
+ export const RATE_LIMITED = "Free web search is rate-limited right now. Try again in a minute, or add a Parallel key in Settings → Tool keys to search with a key.";
37
+ /** The most of Exa's own words a failure quotes: the first sentence of its first line, cut on a word. */
38
+ const SAID_MAX = 120;
39
+ /** A failure Exa answered, in our words: the first sentence of its text, short and quoted. Its later lines (a fix for its
40
+ * MCP URL, a timestamp) are never passed on, so a deployment that does not mark its free limit says no setup text. */
41
+ function exaSaid(text) {
42
+ const line = text.split("\n").map((part) => part.trim()).find(Boolean) ?? "";
43
+ const sentence = /^.*?[.!?](?=\s|$)/.exec(line)?.[0] ?? line;
44
+ const short = sentence.length <= SAID_MAX ? sentence : `${sentence.slice(0, SAID_MAX - 1).replace(/\s+\S*$/, "")}…`;
45
+ return short ? `Free web search failed. Exa said: "${short}"` : "Free web search failed: Exa gave no answer";
46
+ }
47
+ /** The `_meta` key Exa's MCP server marks a tool result reporting its free limit with (isError as well). */
48
+ const RATE_LIMITED_META = "ai.exa/rateLimited";
49
+ /** The longest Retry-After waited out before the one retry. */
50
+ const RETRY_AFTER_MAX_S = 5;
51
+ /** The seconds a Retry-After names, as seconds or a date; undefined when it names none. */
52
+ function retryAfterOf(response) {
53
+ const said = response.headers.get("retry-after")?.trim();
54
+ if (!said)
55
+ return undefined;
56
+ if (/^\d+$/.test(said))
57
+ return Number(said);
58
+ const at = Date.parse(said);
59
+ return Number.isNaN(at) ? undefined : Math.max(0, Math.ceil((at - Date.now()) / 1000));
60
+ }
61
+ /** The wait before the one retry: the Retry-After Exa named, else 1 to 3 s, each with jitter so runs limited together
62
+ * do not all ask again at once. */
63
+ const waitOf = (retryAfterS) => (retryAfterS === undefined ? 1_000 + Math.random() * 2_000 : retryAfterS * 1_000 + Math.random() * 500);
64
+ /** `ms` of waiting that `signal` ends, rejecting with its reason. */
65
+ const sleep = (ms, signal) => new Promise((resolve, reject) => {
66
+ if (signal.aborted)
67
+ return reject(signal.reason);
68
+ const stop = () => {
69
+ clearTimeout(timer);
70
+ reject(signal.reason);
71
+ };
72
+ const timer = setTimeout(() => {
73
+ signal.removeEventListener("abort", stop);
74
+ resolve();
75
+ }, ms);
76
+ signal.addEventListener("abort", stop, { once: true });
77
+ });
78
+ /** A fetch that reaches hosts over IPv4 alone: each name looked up for family 4 (through `lookup`, default the system
79
+ * resolver) and the connection dialled at the address found, never an IPv6 one. undici loads at the first request, so
80
+ * a run that never searches never loads it; `close` ends the connections. */
81
+ export function ipv4Fetch(lookup = dnsLookup) {
82
+ const ipv4 = (host, options, callback) => lookup(host, { ...options, family: 4 }, callback);
83
+ let opened;
84
+ const open = () => (opened ??= import("undici").then(({ Agent, fetch }) => ({ dispatcher: new Agent({ connect: { family: 4, lookup: ipv4 } }), dial: fetch })));
85
+ const send = async (url, init) => {
86
+ const { dispatcher, dial } = await open();
87
+ return dial(url, { ...init, dispatcher });
88
+ };
89
+ return { send: send, close: async () => void (opened && (await (await opened).dispatcher.close())) };
90
+ }
91
+ /** At most MAX_BYTES of a body, as text; the rest is not read. */
92
+ async function boundedText(response) {
93
+ const reader = response.body?.getReader();
94
+ const chunks = [];
95
+ for (let size = 0; reader && size < MAX_BYTES;) {
96
+ const { done, value } = await reader.read();
97
+ if (done)
98
+ break;
99
+ chunks.push(value);
100
+ size += value.byteLength;
101
+ }
102
+ await reader?.cancel().catch(() => undefined);
103
+ return Buffer.concat(chunks).subarray(0, MAX_BYTES).toString("utf8");
104
+ }
105
+ /** A JSON-RPC answer's body: JSON, or the `data:` lines of an event stream, the one answering `id`. */
106
+ async function answerOf(response, id) {
107
+ const text = await boundedText(response);
108
+ const messages = /event-stream/i.test(response.headers.get("content-type") ?? "")
109
+ ? text.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim())
110
+ : [text];
111
+ for (const message of messages) {
112
+ try {
113
+ const parsed = JSON.parse(message);
114
+ if (parsed.id === id)
115
+ return parsed;
116
+ }
117
+ catch { }
118
+ }
119
+ return undefined;
120
+ }
121
+ /** Exa's text for one result as a Hit, or undefined when it names no URL. */
122
+ function hitOf(section) {
123
+ const lines = section.split("\n");
124
+ const field = (name) => lines.find((line) => line.startsWith(`${name}:`))?.slice(name.length + 1).trim();
125
+ const url = field("URL");
126
+ if (!url || !URL.canParse(url))
127
+ return undefined;
128
+ const known = (value) => (value && value !== "N/A" ? value : undefined);
129
+ const body = lines.findIndex((line) => /^(Highlights|Text):/.test(line));
130
+ const snippet = body < 0 ? "" : [lines[body].replace(/^(Highlights|Text):\s*/, ""), ...lines.slice(body + 1)].join(" ").trim();
131
+ const published = known(field("Published"));
132
+ return { url, title: clip(known(field("Title")) ?? "", TITLE_CAP), snippet: snippetOf(snippet), ...(published ? { published } : {}) };
133
+ }
134
+ /** `query` searched on Exa's keyless MCP endpoint through `send` (a test's fake; default a fetch over IPv4 alone,
135
+ * ipv4Fetch, closed when the search ends), at most `n` results: once, and once more past Exa's free limit after
136
+ * `pause` (default a wait the search's signal ends; a test's records it). */
137
+ export async function exaSearch(query, n, { send, signal, pause = sleep } = {}) {
138
+ const deadline = AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), ...(signal ? [signal] : [])]);
139
+ const own = send ? undefined : ipv4Fetch();
140
+ const dial = send ?? own.send;
141
+ try {
142
+ const first = await exchange(query, n, dial, deadline);
143
+ if (!("limit" in first) || first.limit !== "rate_limited" || (first.retryAfterS ?? 0) > RETRY_AFTER_MAX_S)
144
+ return first;
145
+ await pause(waitOf(first.retryAfterS), deadline);
146
+ return await exchange(query, n, dial, deadline);
147
+ }
148
+ catch (error) {
149
+ const name = error?.name;
150
+ return { error: name === "TimeoutError" ? "Exa's search did not answer within 60 s" : name === "AbortError" ? "the search was stopped" : `Exa's search failed: ${String(error?.message ?? error).slice(0, 300)}` };
151
+ }
152
+ finally {
153
+ await own?.close().catch(() => undefined);
154
+ }
155
+ }
156
+ /** One MCP exchange searching `query` through `dial`, each request ended by `deadline`; a failure to reach Exa throws. */
157
+ async function exchange(query, n, dial, deadline) {
158
+ let session;
159
+ const post = (body) => dial(EXA_MCP_URL, {
160
+ method: "POST",
161
+ headers: { "content-type": "application/json", accept: ACCEPT, "mcp-protocol-version": PROTOCOL, ...(session ? { "mcp-session-id": session } : {}) },
162
+ body: JSON.stringify({ jsonrpc: "2.0", ...body }),
163
+ signal: deadline,
164
+ });
165
+ const refused = async (response, step) => {
166
+ if (response.ok)
167
+ return undefined;
168
+ await response.body?.cancel().catch(() => undefined);
169
+ if (response.status === 429) {
170
+ const retryAfterS = retryAfterOf(response);
171
+ return { error: RATE_LIMITED, limit: "rate_limited", ...(retryAfterS === undefined ? {} : { retryAfterS }) };
172
+ }
173
+ if (response.status === 403)
174
+ return { error: "Exa refused keyless use from this connection (403): it takes keyless searches only over IPv4, straight to its endpoint, not over IPv6 or through a proxy", limit: "connection_refused" };
175
+ return { error: `Exa's MCP endpoint answered ${response.status} to ${step}` };
176
+ };
177
+ const opened = await post({ id: 1, method: "initialize", params: { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "agentrun-serve", version: "1" } } });
178
+ const failed = await refused(opened, "initialize");
179
+ if (failed)
180
+ return failed;
181
+ session = opened.headers.get("mcp-session-id") ?? undefined;
182
+ if (!(await answerOf(opened, 1))?.result)
183
+ return { error: "Exa's MCP endpoint did not answer initialize" };
184
+ const ready = await post({ method: "notifications/initialized" });
185
+ await ready.body?.cancel().catch(() => undefined);
186
+ const called = await post({ id: 2, method: "tools/call", params: { name: EXA_SEARCH_TOOL, arguments: { query, numResults: Math.min(n, RESULTS_MAX) } } });
187
+ const late = await refused(called, "the search");
188
+ if (late)
189
+ return late;
190
+ const answer = await answerOf(called, 2);
191
+ if (answer?.error)
192
+ return { error: exaSaid(typeof answer.error.message === "string" ? answer.error.message : "") };
193
+ const meta = answer?.result?._meta;
194
+ if (answer?.result?.isError === true && typeof meta === "object" && meta !== null && meta[RATE_LIMITED_META] === true)
195
+ return { error: RATE_LIMITED, limit: "rate_limited" };
196
+ const content = Array.isArray(answer?.result?.content) ? answer.result.content : undefined;
197
+ const said = content?.flatMap((part) => (part.type === "text" && typeof part.text === "string" ? [part.text] : [])).join("\n") ?? "";
198
+ if (!content || answer?.result?.isError === true)
199
+ return { error: exaSaid(said) };
200
+ const hits = said.split(/\n-{3,}\n/).flatMap((section) => hitOf(section) ?? []);
201
+ return { provider: "exa-keyless", query, results: hits.slice(0, n) };
202
+ }
@@ -0,0 +1,114 @@
1
+ import type { TSchema } from "@earendil-works/pi-ai";
2
+ import type { PublicFetchOptions } from "@parcha/pi-browser";
3
+ /** On a page that was read, `chars`: the length of `text`, the part of the page's text this answer holds. `truncated`
4
+ * while more of it follows this part, and `next_offset` where that begins; `offset` where this part begins, when not 0;
5
+ * `original_chars` the whole text's length in characters, when it is known and this part is not all of it;
6
+ * `beyond_read` on the last part a read reaches of a page that goes on past PAGE_READ_MAX_CHARS; `links_omitted`, with the
7
+ * first part, how many of the page's links its caps left out. `html_chars`, on every part of a page whose HTML readPage
8
+ * cut before it was read: the page's whole length in characters. Its text, all its parts together, is then the start of
9
+ * the page's, so no part gives original_chars, and the last part (no truncated: no part follows) still says the page was
10
+ * cut. `converted: "text"` when the text is the page's plain text, its conversion to markdown having run out of time. */
11
+ export type Page = {
12
+ ok: boolean;
13
+ url: string;
14
+ status: number;
15
+ title: string;
16
+ text: string;
17
+ chars?: number;
18
+ truncated?: true;
19
+ original_chars?: number;
20
+ beyond_read?: true;
21
+ offset?: number;
22
+ next_offset?: number;
23
+ html_chars?: number;
24
+ converted?: "text";
25
+ links: string[];
26
+ links_omitted?: number;
27
+ refused?: string;
28
+ error?: string;
29
+ };
30
+ /** web_fetch's legacy name: a revision or a call node naming it runs web_fetch under it (tools.ts). */
31
+ export declare const FETCH_PAGE_TOOL = "fetch_page";
32
+ /** Under `--faux` only: a module whose default export gives `{ lookup, fetchImpl }` for the fetch (the tests' fake
33
+ * network), in place of the system's resolver and undici. */
34
+ export declare const FAUX_WEB_ENV = "AGENTRUN_SERVE_FAUX_WEB";
35
+ /** The most of a page's text one answer holds (max_chars at most), what it holds when max_chars is not given, and the
36
+ * least max_chars a tool's call may ask for (a smaller one is refused, saying so). */
37
+ export declare const TEXT_CAP = 50000;
38
+ export declare const PAGE_CHARS = 20000;
39
+ export declare const MAX_CHARS_MIN = 200;
40
+ /** The most of a page's TEXT web_fetch reads, from either provider: its first million characters (not HTML_READ_CHARS,
41
+ * readPage's cut of the HTML before any text is read). A part reads within it, Parallel is never asked for more of a
42
+ * page than that and one character (web-fetch.ts), and an offset at or past it is refused. */
43
+ export declare const PAGE_READ_MAX_CHARS = 1000000;
44
+ /** A page's links, with its first part only: at most LINKS_CAP of them, in at most LINKS_CHARS characters of the answer. */
45
+ export declare const LINKS_CAP = 200;
46
+ export declare const LINKS_CHARS = 20000;
47
+ export declare const TITLE_CAP = 500;
48
+ /** The longest URL fetched: a longer one is refused before anything is sent. */
49
+ export declare const URL_MAX = 4096;
50
+ export declare const TIMEOUT_MS = 30000;
51
+ /** Where readPage cuts a page's HTML before it reads it, scripts and styles aside (not PAGE_READ_MAX_CHARS, the most of
52
+ * the text read): pi-browser's READ_MAX_CHARS, held here so the tool's words name it without loading pi-browser where
53
+ * nothing is fetched (fetch-page-cut.test holds the two equal). */
54
+ export declare const HTML_READ_CHARS = 1000000;
55
+ export declare const clip: (text: string, max: number) => string;
56
+ /** Which part of a page's text an answer holds: from `offset` (0 by default), about `maxChars` characters (PAGE_CHARS by
57
+ * default, at most TEXT_CAP). */
58
+ export type Part = {
59
+ offset?: number;
60
+ maxChars?: number;
61
+ };
62
+ /** Why a tool's call may not read `part`, or undefined: an offset that is not a whole number of 0 or more, a maxChars that
63
+ * is not a number of MAX_CHARS_MIN or more (one past TEXT_CAP reads TEXT_CAP). */
64
+ export declare function partProblem({ offset, maxChars }: Part): string | undefined;
65
+ /** `part` in range: a whole offset of 0 or more, a whole maxChars of 1 to TEXT_CAP. */
66
+ export declare const partOf: (part?: Part) => Required<Part>;
67
+ /** Where the longest run of `text` from `start` ends whose JSON string takes at most `budget` characters (less its
68
+ * quotes): a character takes one, a quote, a backslash or a control character JSON writes short (\n, \t) two, any other
69
+ * control character or a lone surrogate six. A surrogate pair is never split. While a character is left the run holds
70
+ * one at least, whatever it takes, so a part always advances (only a budget under six can be passed, by that one). */
71
+ export declare function partEnd(text: string, start: number, budget: number): number;
72
+ /** A page's text as it is read once: its first PAGE_READ_MAX_CHARS characters (`text`), whether the page's text goes on
73
+ * past them (`beyond`), and its whole length where it is known (`length`). */
74
+ export type Text = {
75
+ text: string;
76
+ beyond: boolean;
77
+ length?: number;
78
+ };
79
+ /** `text` as read: `whole` says whether it is all of the page's text, so its length is the page's (a provider that cut
80
+ * it, or readPage's cut of its HTML, gives none). The cut at PAGE_READ_MAX_CHARS never splits a surrogate pair: where
81
+ * it would, it is one unit short. */
82
+ export declare function textOf(text: string, whole: boolean): Text;
83
+ /** The part of a page's text an answer holds, and what it says of the rest. */
84
+ export declare function pageText({ text, beyond, length }: Text, part?: Part): Pick<Page, "text" | "chars" | "truncated" | "original_chars" | "beyond_read" | "offset" | "next_offset">;
85
+ /** A page's links as its first part holds them: in page order, at most LINKS_CAP of them, each one that fits in what is
86
+ * left of LINKS_CHARS (as JSON, with its comma); and how many of them that left out, when any. */
87
+ export declare function linksWithin(links: Iterable<string>): Pick<Page, "links" | "links_omitted">;
88
+ /** A page read once, before any part of it is taken: its final url, status and title, its Text, the links its first part
89
+ * holds (linksWithin), and readPage's `html_chars` and `converted` where it gave them. */
90
+ export type Read = {
91
+ ok: true;
92
+ url: string;
93
+ status: number;
94
+ title: string;
95
+ links: string[];
96
+ links_omitted?: number;
97
+ html_chars?: number;
98
+ converted?: "text";
99
+ } & Text;
100
+ /** A Page that was not read, saying why. */
101
+ export type Unread = Page & {
102
+ ok: false;
103
+ };
104
+ /** The part `part` names of a page read once, as a Page: the links with its first part only. */
105
+ export declare function partOfRead({ text, beyond, length, links, links_omitted, html_chars, converted, ...page }: Read, part?: Part): Page;
106
+ /** The page at `url`, read once through the guarded direct fetch, or why it was not. The rest of `options` are the
107
+ * guard's resolver and fetch, for a test; a signal ends it early. */
108
+ export declare function readDirect(url: unknown, options?: Omit<PublicFetchOptions, "maxBytes">): Promise<Read | Unread>;
109
+ /** The part `options` names of the page at `url`, as a Page, read through the guarded direct fetch. */
110
+ export declare function fetchPage(url: unknown, { offset, maxChars, ...options }?: Omit<PublicFetchOptions, "maxBytes"> & Part): Promise<Page>;
111
+ /** The fetch's resolver and fetch in the run's process: the faux module's under `--faux` with one named, else none. */
112
+ export declare function fetchOptions(env: NodeJS.ProcessEnv, fauxEnv: string): Promise<Omit<PublicFetchOptions, "maxBytes" | "signal">>;
113
+ /** A page tool's arguments: `url`, and the part of its text to read (`offset`, `max_chars`). */
114
+ export declare const URL_PARAMETERS: TSchema;
@@ -0,0 +1,182 @@
1
+ // The guarded direct fetch: one web page from a public host, as a Page: { ok, url, status, title, text, chars, links,
2
+ // refused?, error? }. web_fetch reads a page through it (web-fetch.ts); fetch_page, its legacy name, runs web_fetch. The
3
+ // fetch is pi-browser's public-host guard (publicFetch): every redirect hop resolved, checked and dialled at the address
4
+ // checked, http(s) only, a byte cap and a timeout. Before it, a URL on a port other than 80 or 443, or longer than
5
+ // URL_MAX, is refused here as well. A refusal or a failure is a Page with ok false, never a throw, so an agent reads why
6
+ // and a workflow can branch on it.
7
+ //
8
+ // A page is read once (a Read: its first PAGE_READ_MAX_CHARS characters of text, and what is known of the rest), and its
9
+ // text comes in parts of that: about max_chars characters from offset (a Part), counted as the answer holds them, so a
10
+ // part is within its bound whatever the page holds (web_fetch keeps a run's reads, web-fetch.ts). A part that is not the whole page says so: truncated while more
11
+ // follows, with the offset that reads on (next_offset), and the page's whole length (original_chars) where it is known.
12
+ // Every field of a Page is held to a cap (its text, its title, its URL, its links), so one answer is too: serve's
13
+ // host-bounds test holds it to the host's result bound.
14
+ import { pathToFileURL } from "node:url";
15
+ /** web_fetch's legacy name: a revision or a call node naming it runs web_fetch under it (tools.ts). */
16
+ export const FETCH_PAGE_TOOL = "fetch_page";
17
+ /** Under `--faux` only: a module whose default export gives `{ lookup, fetchImpl }` for the fetch (the tests' fake
18
+ * network), in place of the system's resolver and undici. */
19
+ export const FAUX_WEB_ENV = "AGENTRUN_SERVE_FAUX_WEB";
20
+ /** The most of a page's text one answer holds (max_chars at most), what it holds when max_chars is not given, and the
21
+ * least max_chars a tool's call may ask for (a smaller one is refused, saying so). */
22
+ export const TEXT_CAP = 50_000;
23
+ export const PAGE_CHARS = 20_000;
24
+ export const MAX_CHARS_MIN = 200;
25
+ /** The most of a page's TEXT web_fetch reads, from either provider: its first million characters (not HTML_READ_CHARS,
26
+ * readPage's cut of the HTML before any text is read). A part reads within it, Parallel is never asked for more of a
27
+ * page than that and one character (web-fetch.ts), and an offset at or past it is refused. */
28
+ export const PAGE_READ_MAX_CHARS = 1_000_000;
29
+ /** A page's links, with its first part only: at most LINKS_CAP of them, in at most LINKS_CHARS characters of the answer. */
30
+ export const LINKS_CAP = 200;
31
+ export const LINKS_CHARS = 20_000;
32
+ export const TITLE_CAP = 500;
33
+ /** The longest URL fetched: a longer one is refused before anything is sent. */
34
+ export const URL_MAX = 4_096;
35
+ export const TIMEOUT_MS = 30_000;
36
+ /** Where readPage cuts a page's HTML before it reads it, scripts and styles aside (not PAGE_READ_MAX_CHARS, the most of
37
+ * the text read): pi-browser's READ_MAX_CHARS, held here so the tool's words name it without loading pi-browser where
38
+ * nothing is fetched (fetch-page-cut.test holds the two equal). */
39
+ export const HTML_READ_CHARS = 1_000_000;
40
+ export const clip = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
41
+ /** Why a tool's call may not read `part`, or undefined: an offset that is not a whole number of 0 or more, a maxChars that
42
+ * is not a number of MAX_CHARS_MIN or more (one past TEXT_CAP reads TEXT_CAP). */
43
+ export function partProblem({ offset, maxChars }) {
44
+ const shown = (value) => (typeof value === "number" ? String(value) : String(JSON.stringify(value)).slice(0, 40));
45
+ if (offset !== undefined && !(Number.isInteger(offset) && offset >= 0))
46
+ return `offset must be a whole number, 0 or more (it was ${shown(offset)})`;
47
+ if (offset !== undefined && offset >= PAGE_READ_MAX_CHARS)
48
+ return `offset must be under ${PAGE_READ_MAX_CHARS.toLocaleString("en-US")}: web_fetch reads a page's first ${PAGE_READ_MAX_CHARS.toLocaleString("en-US")} characters (it was ${shown(offset)})`;
49
+ if (maxChars !== undefined && !(typeof maxChars === "number" && maxChars >= MAX_CHARS_MIN))
50
+ return `max_chars must be ${typeof maxChars === "number" ? "" : "a number, "}at least ${MAX_CHARS_MIN} (it was ${shown(maxChars)})`;
51
+ return undefined;
52
+ }
53
+ /** `part` in range: a whole offset of 0 or more, a whole maxChars of 1 to TEXT_CAP. */
54
+ export const partOf = (part = {}) => ({
55
+ offset: Math.max(0, Math.floor(Number(part.offset) || 0)),
56
+ maxChars: Math.max(1, Math.min(TEXT_CAP, Math.floor(Number(part.maxChars) || PAGE_CHARS))),
57
+ });
58
+ /** Where the longest run of `text` from `start` ends whose JSON string takes at most `budget` characters (less its
59
+ * quotes): a character takes one, a quote, a backslash or a control character JSON writes short (\n, \t) two, any other
60
+ * control character or a lone surrogate six. A surrogate pair is never split. While a character is left the run holds
61
+ * one at least, whatever it takes, so a part always advances (only a budget under six can be passed, by that one). */
62
+ export function partEnd(text, start, budget) {
63
+ let at = start;
64
+ for (let used = 0; at < text.length;) {
65
+ const unit = text.charCodeAt(at);
66
+ let width = 1;
67
+ let cost = 1;
68
+ if (unit >= 0xd800 && unit <= 0xdbff && at + 1 < text.length && (text.charCodeAt(at + 1) & 0xfc00) === 0xdc00)
69
+ [width, cost] = [2, 2];
70
+ else if ((unit & 0xf800) === 0xd800)
71
+ cost = 6;
72
+ else if (unit === 0x22 || unit === 0x5c || unit === 0x08 || unit === 0x09 || unit === 0x0a || unit === 0x0c || unit === 0x0d)
73
+ cost = 2;
74
+ else if (unit < 0x20)
75
+ cost = 6;
76
+ if (used + cost > budget && at > start)
77
+ break;
78
+ used += cost;
79
+ at += width;
80
+ }
81
+ return at;
82
+ }
83
+ /** `text` as read: `whole` says whether it is all of the page's text, so its length is the page's (a provider that cut
84
+ * it, or readPage's cut of its HTML, gives none). The cut at PAGE_READ_MAX_CHARS never splits a surrogate pair: where
85
+ * it would, it is one unit short. */
86
+ export function textOf(text, whole) {
87
+ const beyond = text.length > PAGE_READ_MAX_CHARS;
88
+ const split = (text.charCodeAt(PAGE_READ_MAX_CHARS - 1) & 0xfc00) === 0xd800 && (text.charCodeAt(PAGE_READ_MAX_CHARS) & 0xfc00) === 0xdc00;
89
+ return { text: beyond ? text.slice(0, PAGE_READ_MAX_CHARS - (split ? 1 : 0)) : text, beyond, ...(whole ? { length: text.length } : {}) };
90
+ }
91
+ /** The part of a page's text an answer holds, and what it says of the rest. */
92
+ export function pageText({ text, beyond, length }, part = {}) {
93
+ const { offset, maxChars } = partOf(part);
94
+ const start = Math.min(offset, text.length);
95
+ const end = partEnd(text, start, maxChars);
96
+ const held = text.slice(start, end);
97
+ const more = end < text.length;
98
+ // The last part a read reaches of a page that goes on past it.
99
+ const last = !more && beyond;
100
+ return {
101
+ text: held,
102
+ chars: held.length,
103
+ ...(more ? { truncated: true } : {}),
104
+ ...(length !== undefined && (offset > 0 || more || last) ? { original_chars: length } : {}),
105
+ ...(last ? { beyond_read: true } : {}),
106
+ ...(offset > 0 ? { offset } : {}),
107
+ ...(more ? { next_offset: end } : {}),
108
+ };
109
+ }
110
+ /** A page's links as its first part holds them: in page order, at most LINKS_CAP of them, each one that fits in what is
111
+ * left of LINKS_CHARS (as JSON, with its comma); and how many of them that left out, when any. */
112
+ export function linksWithin(links) {
113
+ const kept = [];
114
+ let used = 0;
115
+ let omitted = 0;
116
+ for (const link of links) {
117
+ const cost = JSON.stringify(link).length + 1;
118
+ if (kept.length === LINKS_CAP || used + cost > LINKS_CHARS) {
119
+ omitted += 1;
120
+ continue;
121
+ }
122
+ kept.push(link);
123
+ used += cost;
124
+ }
125
+ return { links: kept, ...(omitted ? { links_omitted: omitted } : {}) };
126
+ }
127
+ /** The part `part` names of a page read once, as a Page: the links with its first part only. */
128
+ export function partOfRead({ text, beyond, length, links, links_omitted, html_chars, converted, ...page }, part = {}) {
129
+ const first = partOf(part).offset === 0;
130
+ return { ...page, ...pageText({ text, beyond, length }, part), ...(html_chars === undefined ? {} : { html_chars }), ...(converted ? { converted } : {}), links: first ? links : [], ...(first && links_omitted ? { links_omitted } : {}) };
131
+ }
132
+ /** The page at `url`, read once through the guarded direct fetch, or why it was not. The rest of `options` are the
133
+ * guard's resolver and fetch, for a test; a signal ends it early. */
134
+ export async function readDirect(url, options = {}) {
135
+ const failed = (fields) => ({ ok: false, url: typeof url === "string" ? clip(url, URL_MAX) : "", status: 0, title: "", text: "", links: [], ...fields });
136
+ if (typeof url !== "string" || !URL.canParse(url))
137
+ return failed({ error: "url is not an absolute URL" });
138
+ if (url.length > URL_MAX)
139
+ return failed({ error: `url is longer than ${URL_MAX.toLocaleString("en-US")} characters` });
140
+ const { port } = new URL(url);
141
+ if (port && port !== "80" && port !== "443")
142
+ return failed({ refused: `refused: port ${port} is not 80 or 443` });
143
+ const { BrowserFailureError, publicFetch, readPage } = await import("@parcha/pi-browser");
144
+ try {
145
+ const signal = AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), ...(options.signal ? [options.signal] : [])]);
146
+ const answer = await publicFetch(url, { ...options, signal });
147
+ if (answer.body === null)
148
+ return failed({ url: clip(answer.url, URL_MAX), status: answer.status, error: `the page answered ${answer.status}` });
149
+ // The caller's stop reaches the read too; the timeout is the network's, and readPage keeps its own deadline.
150
+ const read = /html/i.test(answer.contentType) ? await readPage(answer.body, answer.url, options.signal ? { signal: options.signal } : {}) : null;
151
+ const page = read ?? { title: "", text: answer.body, links: [] };
152
+ return { ok: true, url: clip(answer.url, URL_MAX), status: answer.status, title: clip(page.title, TITLE_CAP), ...textOf(page.text, !read?.truncated), ...(read?.truncated ? { html_chars: read.html_chars } : {}), ...(read?.converted === "text" ? { converted: "text" } : {}), ...linksWithin(page.links) };
153
+ }
154
+ catch (error) {
155
+ if (error instanceof BrowserFailureError && error.failure.code === "refused")
156
+ return failed({ refused: error.message });
157
+ return failed({ error: error?.message ?? String(error) });
158
+ }
159
+ }
160
+ /** The part `options` names of the page at `url`, as a Page, read through the guarded direct fetch. */
161
+ export async function fetchPage(url, { offset, maxChars, ...options } = {}) {
162
+ const read = await readDirect(url, options);
163
+ return read.ok ? partOfRead(read, { offset, maxChars }) : read;
164
+ }
165
+ /** The fetch's resolver and fetch in the run's process: the faux module's under `--faux` with one named, else none. */
166
+ export async function fetchOptions(env, fauxEnv) {
167
+ const faux = env[fauxEnv] ? env[FAUX_WEB_ENV] : undefined;
168
+ if (!faux)
169
+ return {};
170
+ return (await import(pathToFileURL(faux).href)).default();
171
+ }
172
+ /** A page tool's arguments: `url`, and the part of its text to read (`offset`, `max_chars`). */
173
+ export const URL_PARAMETERS = {
174
+ type: "object",
175
+ additionalProperties: false,
176
+ properties: {
177
+ url: { type: "string", minLength: 1, description: "An absolute http(s) URL." },
178
+ offset: { type: "integer", minimum: 0, description: "Where in the page's text to start, in characters (default 0). An answer that stops short of the page's end gives the offset that reads on." },
179
+ max_chars: { type: "integer", minimum: MAX_CHARS_MIN, maximum: TEXT_CAP, description: `About how many characters of the page's text to read (default ${PAGE_CHARS.toLocaleString("en-US")}, at least ${MAX_CHARS_MIN}, at most ${TEXT_CAP.toLocaleString("en-US")}).` },
180
+ },
181
+ required: ["url"],
182
+ };
@@ -0,0 +1,65 @@
1
+ import { type Stats } from "node:fs";
2
+ import type { Json } from "./validate.js";
3
+ /** The server's own file in each run's directory: the run's title, input and how it was asked to run. */
4
+ export declare const RUN_META = "serve.json";
5
+ /** A cancelled run's mark in its directory, written before its process is told: the run's process sends no model
6
+ * request once it is there, however the cancel and the process's start interleave. */
7
+ export declare const RUN_CANCELLED = "cancelled";
8
+ /** A run's launch mark in its directory, written before its process is spawned and removed once that process serves
9
+ * or exits: found at a start, the server went down while it launched the run. */
10
+ export declare const RUN_LAUNCHING = "launching";
11
+ /** Set in a run's process environment when the server opens the run for a person's follow-up to a run whose turn had
12
+ * ended (it answered, or the person stopped it): that open resumes no cut work, so it writes no "resumed" row (app.ts). */
13
+ export declare const FOLLOW_UP_OPEN_ENV = "AGENTRUN_FOLLOW_UP_OPEN";
14
+ /** The server's API token (`ar_local_...`), in the data directory, made at its first start when it is given none. */
15
+ export declare const TOKEN_FILE = ".token";
16
+ /** The server-wide door token, in the data directory: the door of a run an older server started takes it. */
17
+ export declare const DOOR_TOKEN_FILE = ".door-token";
18
+ /** A run's own door token, in its directory, made at its first launch and handed to its process alone (its
19
+ * `--serve-token-file`): the server's calls to that run's door carry it, and so do that run's calls to the box relay
20
+ * (box-relay.ts), which takes a call for a run only with that run's token. */
21
+ export declare const RUN_DOOR_TOKEN = "door-token";
22
+ /** Run directory `dir`'s own door token (RUN_DOOR_TOKEN), when it has one. */
23
+ export declare function runDoorToken(dir: string): string | undefined;
24
+ /** Why a run fails whose launch mark a start finds (`error.details.reason`, openapi.ts). */
25
+ export declare const LAUNCH_LOST = "server_lost_at_launch";
26
+ /** Why a run fails that the store has running with no serve.json: its server went down before it set the run up. */
27
+ export declare const SETUP_LOST = "server_lost_at_setup";
28
+ /** The server's data directory when none is given (`--data`): `agentrun/agents` under XDG_DATA_HOME, or ~/.local/share.
29
+ * The server, its import and reset-password default to it. `npx @parcha/agentrun` keeps its own, ~/.agentrun, and
30
+ * passes it as --data. */
31
+ export declare const defaultData: (env?: NodeJS.ProcessEnv) => string;
32
+ /** The server's own data directory, on its reading of the environment (startServe): an npx hint names it (adapters.ts
33
+ * npxLine). */
34
+ export declare const DATA_ENV = "AGENTRUN_SERVE_DATA";
35
+ export declare const HOMES_DIR = "homes";
36
+ /** Paths in an agent's home that only the host reads and writes (another component owns them): the home API reads and
37
+ * writes neither, and lists each by its name alone. `learning` (learning.ts, read through its own API) and `sign-ins`
38
+ * (sign-ins.ts: the agent's saved sign-ins, sealed pointers to its browser vendor's objects, shown without them on
39
+ * GET /agents/{id}). */
40
+ export declare const HOME_HOST_OWNED: string[];
41
+ /** An agent's home directory's name: its id in lower case, then 16 hex digits of the id's SHA-256. Ids that differ only
42
+ * in case get names that differ in any case, so on a disk that folds case (macOS's, by default) they never share one. */
43
+ export declare const homeKey: (agentId: string) => string;
44
+ export declare const homeOf: (data: string, agentId: string) => string;
45
+ /** The file parsed as JSON, or null when it is missing, unreadable, or not whole JSON (a half-written file). */
46
+ export declare const readJson: (path: string) => Promise<Json | null>;
47
+ /** A temporary file beside `path`, this write's own: two writes of one file at once never share one, so neither renames
48
+ * the other's away nor writes into the file the other renamed. */
49
+ export declare const tempOf: (path: string) => string;
50
+ /** Writes `text` to `path` whole: through a temporary file and a rename, so a reader never sees half of it. */
51
+ export declare function writeWhole(path: string, text: string, mode?: number): Promise<void>;
52
+ /** Syncs the directory `path`, so the entries made in it survive a crash of the machine. */
53
+ export declare function syncDir(path: string): Promise<void>;
54
+ /** Writes `text` (or bytes) to `path` whole and durably: the temporary file is synced before the rename, and the
55
+ * directory after it, so once this resolves a crash, even of the machine, leaves the new text in place, never the old or
56
+ * none. `temp` is the temporary file, created only if nothing is there yet: a link planted at it is never written through.
57
+ * Answers the stats of the file it wrote, read before the rename: a write of `path` that lands after it is not them.
58
+ * `exact`: the file gets `mode` itself, whatever this process's umask takes away (set on its handle, never by path). */
59
+ export declare function writeDurable(path: string, text: string | Uint8Array, mode?: number, temp?: string, exact?: boolean): Promise<Stats>;
60
+ /** writeDurable, synchronously: on disk, the file and then its directory synced, when it returns. For a record that
61
+ * must be durable before the next line runs, with nothing between them that could let anything else happen first. */
62
+ export declare function writeDurableSync(path: string, text: string, mode?: number): void;
63
+ /** Runs `work` once every call queued before it under `key` in `queues` has settled: one at a time per key. The queue
64
+ * holds only settled turns, so one that failed never fails the next, and a key is dropped once its last turn settles. */
65
+ export declare function serialBy<T>(queues: Map<string, Promise<unknown>>, key: string, work: () => Promise<T>): Promise<T>;