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

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 (229) hide show
  1. package/CHANGELOG.md +560 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +1723 -2
  5. package/dist/adapters.d.ts +205 -0
  6. package/dist/adapters.js +459 -0
  7. package/dist/agents.d.ts +124 -0
  8. package/dist/agents.js +302 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +324 -0
  11. package/dist/bound-files.d.ts +4 -0
  12. package/dist/bound-files.js +164 -0
  13. package/dist/box/record.d.ts +6 -0
  14. package/dist/box/record.js +41 -0
  15. package/dist/box/sweep.d.ts +53 -0
  16. package/dist/box/sweep.js +193 -0
  17. package/dist/box-image.d.ts +98 -0
  18. package/dist/box-image.js +283 -0
  19. package/dist/box-relay.d.ts +42 -0
  20. package/dist/box-relay.js +222 -0
  21. package/dist/boxes.d.ts +54 -0
  22. package/dist/boxes.js +182 -0
  23. package/dist/cap.d.ts +224 -0
  24. package/dist/cap.js +721 -0
  25. package/dist/catalog.d.ts +20 -0
  26. package/dist/catalog.js +53 -0
  27. package/dist/cli.d.ts +2 -0
  28. package/dist/cli.js +167 -0
  29. package/dist/coding-tools.d.ts +31 -0
  30. package/dist/coding-tools.js +81 -0
  31. package/dist/console/THIRD-PARTY-NOTICES.txt +1141 -0
  32. package/dist/console/assets/index-BN7oVcO4.js +445 -0
  33. package/dist/console/assets/index-By-jkqki.css +1 -0
  34. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  35. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  36. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  37. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  38. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  39. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  40. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  41. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  42. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  53. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  54. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  57. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  58. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  59. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  60. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  61. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  62. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  63. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  64. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  65. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  66. package/dist/console/index.html +15 -0
  67. package/dist/daytona-api.d.ts +21 -0
  68. package/dist/daytona-api.js +101 -0
  69. package/dist/decision-rows.d.ts +11 -0
  70. package/dist/decision-rows.js +116 -0
  71. package/dist/decisions.d.ts +94 -0
  72. package/dist/decisions.js +184 -0
  73. package/dist/effort-guidance.d.ts +5 -0
  74. package/dist/effort-guidance.js +14 -0
  75. package/dist/environment.d.ts +5 -0
  76. package/dist/environment.js +11 -0
  77. package/dist/errors.d.ts +72 -0
  78. package/dist/errors.js +66 -0
  79. package/dist/exa-keyless.d.ts +35 -0
  80. package/dist/exa-keyless.js +202 -0
  81. package/dist/fetch-page.d.ts +114 -0
  82. package/dist/fetch-page.js +182 -0
  83. package/dist/files.d.ts +60 -0
  84. package/dist/files.js +153 -0
  85. package/dist/grade.d.ts +96 -0
  86. package/dist/grade.js +348 -0
  87. package/dist/graph-view.d.ts +100 -0
  88. package/dist/graph-view.js +212 -0
  89. package/dist/harness-app.d.ts +38 -0
  90. package/dist/harness-app.js +626 -0
  91. package/dist/harness.d.ts +53 -0
  92. package/dist/harness.js +74 -0
  93. package/dist/home-path.d.ts +27 -0
  94. package/dist/home-path.js +78 -0
  95. package/dist/host-tools.d.ts +20 -0
  96. package/dist/host-tools.js +140 -0
  97. package/dist/host.d.ts +39 -0
  98. package/dist/host.js +81 -0
  99. package/dist/hosted-search.d.ts +27 -0
  100. package/dist/hosted-search.js +129 -0
  101. package/dist/import-sources.d.ts +104 -0
  102. package/dist/import-sources.js +629 -0
  103. package/dist/import-summary.d.ts +25 -0
  104. package/dist/import-summary.js +75 -0
  105. package/dist/import-worker.d.ts +26 -0
  106. package/dist/import-worker.js +41 -0
  107. package/dist/import.d.ts +145 -0
  108. package/dist/import.js +1221 -0
  109. package/dist/index.d.ts +7 -0
  110. package/dist/index.js +6 -0
  111. package/dist/key-check.d.ts +36 -0
  112. package/dist/key-check.js +108 -0
  113. package/dist/key-refusal.d.ts +51 -0
  114. package/dist/key-refusal.js +187 -0
  115. package/dist/learn/check.d.ts +99 -0
  116. package/dist/learn/check.js +259 -0
  117. package/dist/learn/grade.d.ts +79 -0
  118. package/dist/learn/grade.js +433 -0
  119. package/dist/learn/index.d.ts +7 -0
  120. package/dist/learn/index.js +11 -0
  121. package/dist/learn/invisible.d.ts +5 -0
  122. package/dist/learn/invisible.js +42 -0
  123. package/dist/learn/notes.d.ts +59 -0
  124. package/dist/learn/notes.js +146 -0
  125. package/dist/learn/reflect.d.ts +49 -0
  126. package/dist/learn/reflect.js +167 -0
  127. package/dist/learn/secrets.d.ts +18 -0
  128. package/dist/learn/secrets.js +111 -0
  129. package/dist/learn/skills.d.ts +84 -0
  130. package/dist/learn/skills.js +198 -0
  131. package/dist/learning-routes.d.ts +196 -0
  132. package/dist/learning-routes.js +609 -0
  133. package/dist/learning-run.d.ts +304 -0
  134. package/dist/learning-run.js +797 -0
  135. package/dist/learning-words.d.ts +73 -0
  136. package/dist/learning-words.js +171 -0
  137. package/dist/learning.d.ts +377 -0
  138. package/dist/learning.js +801 -0
  139. package/dist/llm.d.ts +40 -0
  140. package/dist/llm.js +37 -0
  141. package/dist/llms.txt +37 -0
  142. package/dist/mcp-servers.d.ts +115 -0
  143. package/dist/mcp-servers.js +445 -0
  144. package/dist/mcp.d.ts +51 -0
  145. package/dist/mcp.js +392 -0
  146. package/dist/model.d.ts +184 -0
  147. package/dist/model.js +484 -0
  148. package/dist/monid.d.ts +74 -0
  149. package/dist/monid.js +277 -0
  150. package/dist/openapi/agentrun-v2.openapi.json +4805 -0
  151. package/dist/openapi.d.ts +10 -0
  152. package/dist/openapi.js +1417 -0
  153. package/dist/owner.d.ts +55 -0
  154. package/dist/owner.js +222 -0
  155. package/dist/packs.d.ts +71 -0
  156. package/dist/packs.js +180 -0
  157. package/dist/page.d.ts +32 -0
  158. package/dist/page.js +133 -0
  159. package/dist/paid-calls.d.ts +46 -0
  160. package/dist/paid-calls.js +110 -0
  161. package/dist/pause.d.ts +68 -0
  162. package/dist/pause.js +97 -0
  163. package/dist/pdf-pages.d.ts +44 -0
  164. package/dist/pdf-pages.js +147 -0
  165. package/dist/place.d.ts +46 -0
  166. package/dist/place.js +105 -0
  167. package/dist/print.d.ts +20 -0
  168. package/dist/print.js +29 -0
  169. package/dist/propose.d.ts +38 -0
  170. package/dist/propose.js +82 -0
  171. package/dist/quiet-sqlite-warning.d.ts +1 -0
  172. package/dist/quiet-sqlite-warning.js +14 -0
  173. package/dist/request-start.d.ts +14 -0
  174. package/dist/request-start.js +226 -0
  175. package/dist/result.d.ts +3 -0
  176. package/dist/result.js +5 -0
  177. package/dist/rows.d.ts +46 -0
  178. package/dist/rows.js +121 -0
  179. package/dist/run-box.d.ts +134 -0
  180. package/dist/run-box.js +440 -0
  181. package/dist/run-manifest.d.ts +27 -0
  182. package/dist/run-manifest.js +60 -0
  183. package/dist/runnable.d.ts +80 -0
  184. package/dist/runnable.js +162 -0
  185. package/dist/runs.d.ts +840 -0
  186. package/dist/runs.js +2279 -0
  187. package/dist/secret-cut.d.ts +27 -0
  188. package/dist/secret-cut.js +109 -0
  189. package/dist/secrets.d.ts +50 -0
  190. package/dist/secrets.js +140 -0
  191. package/dist/server-lock.d.ts +44 -0
  192. package/dist/server-lock.js +140 -0
  193. package/dist/server.d.ts +626 -0
  194. package/dist/server.js +1756 -0
  195. package/dist/sessions.d.ts +4 -0
  196. package/dist/sessions.js +105 -0
  197. package/dist/skills.d.ts +31 -0
  198. package/dist/skills.js +68 -0
  199. package/dist/stats.d.ts +101 -0
  200. package/dist/stats.js +82 -0
  201. package/dist/tool-keys.d.ts +151 -0
  202. package/dist/tool-keys.js +273 -0
  203. package/dist/tool-plane.d.ts +143 -0
  204. package/dist/tool-plane.js +242 -0
  205. package/dist/tools.d.ts +147 -0
  206. package/dist/tools.js +253 -0
  207. package/dist/turn-end.d.ts +23 -0
  208. package/dist/turn-end.js +14 -0
  209. package/dist/turns.d.ts +34 -0
  210. package/dist/turns.js +202 -0
  211. package/dist/uploads.d.ts +104 -0
  212. package/dist/uploads.js +474 -0
  213. package/dist/usage.d.ts +29 -0
  214. package/dist/usage.js +58 -0
  215. package/dist/validate.d.ts +55 -0
  216. package/dist/validate.js +175 -0
  217. package/dist/web-fetch.d.ts +64 -0
  218. package/dist/web-fetch.js +262 -0
  219. package/dist/web-search.d.ts +54 -0
  220. package/dist/web-search.js +136 -0
  221. package/dist/webhooks.d.ts +182 -0
  222. package/dist/webhooks.js +487 -0
  223. package/dist/workspace-paths.d.ts +33 -0
  224. package/dist/workspace-paths.js +104 -0
  225. package/dist/workspace.d.ts +88 -0
  226. package/dist/workspace.js +369 -0
  227. package/launcher/agentrun-serve +109 -0
  228. package/package.json +94 -4
  229. package/skills/agentrun-serve/SKILL.md +128 -0
package/dist/monid.js ADDED
@@ -0,0 +1,277 @@
1
+ // monid (monid.ai): one key, and a catalog of paid data endpoints from many providers behind three calls. An agent finds
2
+ // an endpoint in plain words (discover), reads its input schemas and price (inspect), and runs it (run), paid per call
3
+ // from the key's workspace wallet. Three table tools here (tools.ts), on every harness: pi binds each, another harness
4
+ // runs each as a host tool (host-tools.ts), both under its wire name (catalog.ts: `monid.run` is `monid_run`), as a
5
+ // model API takes no dot in a tool's name.
6
+ //
7
+ // A run is sent once and never again: it spends money, and a request that failed after it left may have run. An async
8
+ // provider answers 202 with a run id, read again every POLL_MS until it ends, for at most WAIT_MS in all; a run the
9
+ // caller stops, or one that outlasts the wait, is asked to stop. Every answer reaches the model as JSON, cut at CLIP
10
+ // characters, the whole of it then filed under the run's work/evidence/monid/.
11
+ //
12
+ // What a run charged is the run's spend (cap.ts): marked before it is sent at the price an inspect quoted (else an
13
+ // allowance), then booked once in the run's records as a TOOL_COST (`monid.run`, charged by monid), its cost if monid
14
+ // reports one, else unknown unless monid says it charged nothing, which the cap counts at what the run was held at; and
15
+ // under a cap a run is refused before it is sent unless the run's spend plus what it is held at fits. discover and
16
+ // inspect cost nothing, and are never refused.
17
+ import { randomUUID } from "node:crypto";
18
+ import { lstat } from "node:fs/promises";
19
+ import { join } from "node:path";
20
+ import { writeInWork } from "./workspace.js";
21
+ import { defineExtension, defineTool, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
22
+ import { registerLabel, TOOL_COST, TOOL_STARTED } from "@parcha/pi-durable-agent/timeline";
23
+ import { paidCall } from "./cap.js";
24
+ import { wireName } from "./catalog.js";
25
+ import { fauxFetch } from "./decisions.js";
26
+ import { settleOnRoot } from "./paid-calls.js";
27
+ import { forModel } from "./result.js";
28
+ import { isObject } from "./validate.js";
29
+ export const MONID_KEY_ENV = "MONID_API_KEY";
30
+ /** Under `faux` only (startServe's `fauxMonid`): a module whose default export is the fetch monid's calls go through, in
31
+ * place of monid's API (the tests' fake). */
32
+ export const FAUX_MONID_ENV = "AGENTRUN_SERVE_FAUX_MONID";
33
+ export const MONID_API = "https://api.monid.ai";
34
+ /** The most characters of one answer the model reads. */
35
+ export const CLIP = 60_000;
36
+ const TERMINAL = ["COMPLETED", "FAILED", "BLOCKED", "STOPPED", "TIMED_OUT"];
37
+ /** The shortest limit a read of a run gets near the deadline: it outlives the deadline by this much at most. */
38
+ const MIN_READ_MS = 100;
39
+ /** On an answer monid charged nothing for: the run never ran (refused as sent), was blocked or stopped, or the provider
40
+ * failed. A symbol, so the model never reads it. */
41
+ const UNCHARGED = Symbol("monid.uncharged");
42
+ const uncharged = (answer) => Object.assign(answer, { [UNCHARGED]: true });
43
+ const pause = (ms, signal) => new Promise((resolve) => {
44
+ const timer = setTimeout(resolve, ms);
45
+ signal?.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
46
+ });
47
+ /** An amount monid reports (`{value, currency, unit?}`), in its currency: a micro-dollar amount in dollars. */
48
+ const money = (amount) => (isObject(amount) && typeof amount.value === "number" ? { value: amount.unit === "MICRO_DOLLAR" ? amount.value / 1e6 : amount.value, currency: String(amount.currency ?? "USD") } : undefined);
49
+ /** What a run cost: `cost` on a run read back, else a sync answer's settled `billing.reportedCost`. */
50
+ export const costOf = (record) => money(record.cost) ?? money(isObject(record.billing) ? record.billing.reportedCost : undefined);
51
+ /** Why a request got no answer to pass on, in words. */
52
+ function failure(status, body) {
53
+ const said = typeof body.message === "string" ? body.message : JSON.stringify(body).slice(0, 500);
54
+ if (status === 402)
55
+ return { error: `the monid wallet's balance is too low for this call (402): ${said}`, status };
56
+ if (status === 401)
57
+ return { error: `monid refused the key (401): ${said}`, status };
58
+ return status ? { error: `monid answered ${status}: ${said}`, status } : { error: `monid could not be reached: ${said}` };
59
+ }
60
+ /** A run's record as the model reads it: its output, or why it has none, with its id and cost. */
61
+ function outcome(status, record) {
62
+ const cost = costOf(record);
63
+ const at = { ...(typeof record.runId === "string" ? { runId: record.runId } : {}), ...(cost ? { cost } : {}) };
64
+ const state = typeof record.status === "string" ? record.status : status === 408 ? "TIMED_OUT" : undefined;
65
+ const provider = isObject(record.providerResponse) ? record.providerResponse : {};
66
+ const code = Number(provider.httpStatus ?? 200);
67
+ if (state === "COMPLETED" && code >= 400) {
68
+ const said = isObject(provider.error) && typeof provider.error.message === "string" ? provider.error.message : "no message";
69
+ return uncharged({ error: `the provider answered ${code}: ${said} (monid charges nothing for a provider's error)`, status: code, ...at });
70
+ }
71
+ if (state === "COMPLETED")
72
+ return { ...record, ...at };
73
+ if (state === "BLOCKED")
74
+ return uncharged({ error: `a control gate of the monid workspace, such as its budget, refused the run (BLOCKED): ${typeof record.reason === "string" ? record.reason : "no reason given"}`, ...(record.controls !== undefined ? { controls: record.controls } : {}), ...at });
75
+ if (state === "FAILED")
76
+ return { error: "the run failed inside monid (FAILED); it is not sent again", ...at };
77
+ if (state === "TIMED_OUT")
78
+ return { error: "the run went past monid's time budget (TIMED_OUT)", status: 408, ...at };
79
+ if (state === "STOPPED")
80
+ return uncharged({ error: "the run was stopped before it completed (STOPPED); a stopped run is not billed", ...at });
81
+ // Refused as it was sent (a 4xx other than a timeout): it never ran. Any other answer with no state may have run.
82
+ const refused = { ...failure(status, record), ...at };
83
+ return status >= 400 && status < 500 && status !== 408 ? uncharged(refused) : refused;
84
+ }
85
+ /** What a run's answer says monid charged, in USD: its cost; else undefined when monid charged nothing (UNCHARGED), and
86
+ * null for every other answer, which may have been charged (one with no cost, FAILED, TIMED_OUT, a run stopped by its
87
+ * caller or the wait, a run whose sending failed): never $0 for a charge no one knows, and counted by the cap at what
88
+ * the run was held at (paidCall). A cost in another currency is unknown too. */
89
+ export function chargeOf(answer) {
90
+ const cost = money(answer.cost);
91
+ if (cost)
92
+ return cost.currency === "USD" ? cost.value : null;
93
+ return answer[UNCHARGED] ? undefined : null;
94
+ }
95
+ /** monid's three calls on `key`, each answering what the model reads, never throwing. */
96
+ export function monidClient(options) {
97
+ const { key, requestMs = 30_000, pollMs = 2_000, waitMs = 150_000, sleep = pause } = options;
98
+ const send = options.fetch ?? fetch;
99
+ const call = async (method, path, body, signal, ms = requestMs) => {
100
+ const limit = AbortSignal.timeout(ms);
101
+ try {
102
+ const res = await send(`${MONID_API}${path}`, { method, headers: { authorization: `Bearer ${key}`, ...(body ? { "content-type": "application/json" } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}), signal: signal ? AbortSignal.any([signal, limit]) : limit });
103
+ const text = await res.text();
104
+ const json = (() => { try {
105
+ return JSON.parse(text);
106
+ }
107
+ catch {
108
+ return undefined;
109
+ } })();
110
+ return { status: res.status, body: isObject(json) ? json : { message: text.slice(0, 500) } };
111
+ }
112
+ catch (error) {
113
+ return { status: 0, body: { message: signal?.aborted ? "stopped by the caller" : limit.aborted ? `no answer in ${ms / 1000} s` : String(error?.message ?? error) } };
114
+ }
115
+ };
116
+ const read = async (path, args, signal) => {
117
+ const res = await call("POST", path, args, signal);
118
+ return res.status >= 200 && res.status < 300 ? res.body : failure(res.status, res.body);
119
+ };
120
+ const stop = async (runId, why) => {
121
+ const res = await call("POST", `/v1/runs/${encodeURIComponent(runId)}/stop`, undefined, undefined, 10_000);
122
+ return { error: `the run ${why}; ${res.status === 202 ? "monid was asked to stop it" : `monid refused to stop it (${res.status || "no answer"})`}, and a metered endpoint bills what it used before the stop`, runId };
123
+ };
124
+ return {
125
+ discover: (args, signal) => read("/v1/discover", args, signal),
126
+ inspect: (args, signal) => read("/v1/inspect", args, signal),
127
+ async run(args, signal) {
128
+ const deadline = Date.now() + waitMs;
129
+ const first = await call("POST", "/v1/run", { provider: args.provider, endpoint: args.endpoint, input: args.input ?? {} }, signal, waitMs);
130
+ if (first.status === 0)
131
+ return { error: `${first.body.message}: the run may have gone ahead at monid, and is not sent again` };
132
+ if (first.status !== 202 || typeof first.body.runId !== "string")
133
+ return outcome(first.status, first.body);
134
+ const runId = first.body.runId;
135
+ for (let record = first.body;;) {
136
+ if (TERMINAL.includes(String(record.status)))
137
+ return outcome(200, record);
138
+ if (signal?.aborted)
139
+ return stop(runId, "was stopped by the caller");
140
+ if (Date.now() >= deadline)
141
+ return stop(runId, `did not end in ${waitMs / 1000} s`);
142
+ await sleep(Math.max(0, Math.min(pollMs, deadline - Date.now())), signal);
143
+ // Past the deadline, or stopped, the stop goes now: a read here would hold it while the paid run goes on.
144
+ if (signal?.aborted || Date.now() >= deadline)
145
+ continue;
146
+ const polled = await call("GET", `/v1/runs/${encodeURIComponent(runId)}`, undefined, signal, Math.min(requestMs, Math.max(MIN_READ_MS, deadline - Date.now())));
147
+ // A read is safe to repeat: no answer, a 429 or a 5xx is read again until the deadline; any other refusal ends it.
148
+ if (polled.status === 200)
149
+ record = polled.body;
150
+ else if (polled.status >= 400 && polled.status < 500 && polled.status !== 429)
151
+ return { ...failure(polled.status, polled.body), runId };
152
+ }
153
+ },
154
+ };
155
+ }
156
+ /** `answer` as the model reads it: JSON, cut at CLIP characters, the whole then filed under `work`'s evidence/monid/
157
+ * (by run id, else by `label` and the time) and the cut saying where. A copy that cannot be filed (a full disk) still
158
+ * answers, cut and saying so: the answer may have been paid for. */
159
+ export async function monidText(answer, work, label) {
160
+ const text = JSON.stringify(answer);
161
+ if (text.length <= CLIP)
162
+ return text;
163
+ const runId = typeof answer.runId === "string" && /^[A-Za-z0-9_-]{1,80}$/.test(answer.runId) ? answer.runId : undefined;
164
+ const name = `${runId ?? `${label}-${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID().slice(0, 8)}`}.json`;
165
+ const cut = `${text.slice(0, CLIP)}\n[cut at ${CLIP} of ${text.length} characters; `;
166
+ try {
167
+ // Never through a link a box's command planted in work/ (workspace.ts). An answer filed already keeps its file;
168
+ // anything else in its place (a planted link) is no filing, and the answer says it could not be saved.
169
+ await writeInWork(work, ["evidence", "monid"], name, text).catch(async (error) => {
170
+ if (error.code !== "EEXIST" || !(await lstat(join(work, "evidence", "monid", name)).then((held) => held.isFile(), () => false)))
171
+ throw error;
172
+ });
173
+ }
174
+ catch (error) {
175
+ // The error's code only (ENOSPC, ENOTDIR): its message names the server's paths.
176
+ return `${cut}the whole answer could not be saved (${error?.code ?? "write failed"})]`;
177
+ }
178
+ return `${cut}the whole answer is in the run's files at evidence/monid/${name}]`;
179
+ }
180
+ const KINDS = ["discover", "inspect", "run"];
181
+ const [DISCOVER, INSPECT, RUN] = KINDS.map((kind) => wireName(`monid.${kind}`));
182
+ // What a person reads for each call, in a run's timeline, and what each tool is called where calls are counted.
183
+ const endpointOf = (a) => (typeof a.provider === "string" && typeof a.endpoint === "string" ? ` ${a.provider} ${a.endpoint}` : "");
184
+ registerLabel(DISCOVER, (a) => (typeof a.query === "string" ? `Searched monid's catalog for "${a.query.slice(0, 60)}"` : "Searched monid's catalog"), undefined, { name: "Search monid's catalog" });
185
+ registerLabel(INSPECT, (a) => `Looked up the monid endpoint${endpointOf(a)}`, undefined, { name: "Look up a monid endpoint" });
186
+ registerLabel(RUN, (a) => `Ran the monid endpoint${endpointOf(a)}`, undefined, { name: "Run a monid endpoint" });
187
+ const named = { provider: { type: "string", minLength: 1, description: `The provider's slug, as ${DISCOVER} gave it.` }, endpoint: { type: "string", minLength: 1, description: `The endpoint's path, as ${DISCOVER} gave it.` } };
188
+ const SPECS = {
189
+ discover: {
190
+ summary: "Search monid's catalog of paid data endpoints in plain words: { results: [{ provider, endpoint, description, score, price }] }.",
191
+ description: `Search monid's catalog of paid data endpoints (people and company data, web and social media scrapers, search, and more, from many providers) with a plain-language query of what you need. Answers JSON: results, each a provider, an endpoint, what it does, a relevance score and its price. Next, ${INSPECT} the result that fits, then ${RUN} it.`,
192
+ properties: { query: { type: "string", minLength: 1, maxLength: 1000, description: "What you need, in a short plain sentence." }, limit: { type: "integer", minimum: 1, maximum: 40, description: "How many results (default 5)." }, minScore: { type: "number", minimum: 0, maximum: 1, description: "The lowest relevance to keep (default 0.2)." } },
193
+ required: ["query"], replay: "safe",
194
+ },
195
+ inspect: {
196
+ summary: "One monid endpoint before it runs: the JSON Schemas of its input (path, query, body), its price, notes and documentation.",
197
+ description: `Read one monid endpoint before you run it: the JSON Schemas of its input (pathParams, queryParams, body), its price, notes and documentation link. Then ${RUN} it with input that fits those schemas.`,
198
+ properties: named, required: ["provider", "endpoint"], replay: "safe",
199
+ },
200
+ run: {
201
+ summary: "Run one monid endpoint, paid per call from the monid wallet: its output, price and cost; a slow provider is waited for, about two minutes at most.",
202
+ description: `Run one monid endpoint with its input, once ${INSPECT} has shown what it takes and what it costs. Each call is paid from the monid wallet: call it once per answer you need, never to retry a failure, which says why. Answers JSON: the run's output, its price and cost. A slow provider is waited for, about two minutes at most.`,
203
+ properties: { ...named, input: { type: "object", description: `The endpoint's input as one object, shaped by the schemas ${INSPECT} gave; {} when it takes none.` } },
204
+ required: ["provider", "endpoint"], replay: "unsafe",
205
+ },
206
+ };
207
+ /** What a run is held at when no inspect in this run's process quoted its price: an allowance, not a price, set high on
208
+ * purpose. A crash between sending a run and recording its charge leaves the cap counting it, so a cap errs toward
209
+ * refusing sooner, never toward passing unseen. */
210
+ export const MONID_RUN_ALLOWANCE_USD = 1;
211
+ /** Each endpoint's per-call price in USD, as an inspect in this run's process quoted it. */
212
+ const quoted = new Map();
213
+ const quoteKey = (args) => JSON.stringify([args.provider, args.endpoint]);
214
+ /** A record on the run's root, where its spend is read on every harness (cap.ts, harness-app.ts). */
215
+ const record = (api, kind, data, context) => api.commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind, data })), context);
216
+ /** monid's tool `kind` for a run, under its wire name: the key and the faux hook read from `env` (the run's process's,
217
+ * with its secrets) at each call, an answer too long for the model filed under `work()`, read at the call. A run goes
218
+ * through the run's cap (paidCall), is marked before it is sent (TOOL_STARTED, held at its quoted price or the
219
+ * allowance) and settled by its charge (TOOL_COST): a crash between the two leaves the cap counting the held figure
220
+ * and the run's cost unknown, never $0. pi binds it (monidTool); another harness runs it as a host tool
221
+ * (host-tools.ts), whose `api` commits to the run's store as pi's does. */
222
+ export function monidRegistration(kind, env, work) {
223
+ const { description, properties, required, replay } = SPECS[kind];
224
+ return defineTool({
225
+ name: wireName(`monid.${kind}`), description, replay,
226
+ parameters: { type: "object", additionalProperties: false, properties, required },
227
+ execute: async (args, api, context) => {
228
+ const faux = await fauxFetch(env, FAUX_MONID_ENV);
229
+ const client = monidClient({ key: env[MONID_KEY_ENV] ?? "", ...(faux ? { fetch: faux } : {}) });
230
+ const call = () => client[kind](args, context?.abortSignal);
231
+ const label = { tool: "monid.run", charged_by: "monid", call: api.callId };
232
+ // What the run is held at, under the cap and on its mark: the price an inspect quoted, else the allowance.
233
+ const quote = quoted.get(quoteKey(args));
234
+ const held = quote ?? MONID_RUN_ALLOWANCE_USD;
235
+ const basis = quote !== undefined ? `the price ${INSPECT} quoted` : `no ${INSPECT} in this run quoted its price, so it is held at the $${MONID_RUN_ALLOWANCE_USD} allowance; ${INSPECT} gives its quote`;
236
+ const send = async () => {
237
+ try {
238
+ await record(api, TOOL_STARTED, { ...label, heldUsd: held }, context);
239
+ }
240
+ catch (error) {
241
+ return uncharged({ error: `${RUN} was not sent: its mark could not be written (${String(error?.message ?? error).slice(0, 200)})` });
242
+ }
243
+ const answer = await call();
244
+ // Settled at what it charged: $0 only when monid charged nothing, null (unknown) when it may have and did not say.
245
+ // Paid for, it answers even when this cannot be written, never a failure the model would retry.
246
+ const usd = chargeOf(answer);
247
+ // Written to the run's root when it is set (paid-calls.ts settleIn): a stopped turn's call can no longer commit.
248
+ const settle = { ...label, usd: usd === undefined ? 0 : usd };
249
+ await (settleOnRoot(TOOL_COST, settle) ?? record(api, TOOL_COST, settle, context)).catch(() => undefined);
250
+ return answer;
251
+ };
252
+ const paid = kind === "run" ? await paidCall(RUN, send, chargeOf, { usd: held, basis }) : { result: await call() };
253
+ if ("refused" in paid)
254
+ return forModel(JSON.stringify({ error: paid.refused }), { isError: true });
255
+ const answer = paid.result;
256
+ const price = kind === "inspect" && isObject(answer.price) && answer.price.type === "PER_CALL" ? money(answer.price.amount) : undefined;
257
+ if (price?.currency === "USD")
258
+ quoted.set(quoteKey(args), price.value);
259
+ const cost = money(answer.cost);
260
+ return forModel(await monidText(answer, work(), kind), { isError: answer.error !== undefined, ...(cost ? { details: { cost } } : {}) });
261
+ },
262
+ });
263
+ }
264
+ /** The three, as another harness's host tools. */
265
+ export const monidTools = (env, work) => KINDS.map((kind) => monidRegistration(kind, env, work));
266
+ /** The table's entry for `monid.<kind>`: it needs MONID_API_KEY, and no workflow node names it yet. */
267
+ export const monidTool = (kind) => ({
268
+ summary: SPECS[kind].summary,
269
+ needs: [MONID_KEY_ENV],
270
+ nodes: false,
271
+ bind: async (host) => {
272
+ const tool = monidRegistration(kind, host.env, () => host.where.work);
273
+ const extension = defineExtension({ name: `monid-${kind}`, tools: [tool] });
274
+ host.install(extension);
275
+ return { tools: [tool], extensions: [extension] };
276
+ },
277
+ });