@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
@@ -0,0 +1,487 @@
1
+ // The webhook a person sets through /v2/settings/webhook: one URL this server POSTs to when a run comes to need its
2
+ // person (`run.needs_input`, its status input_required) and when it ends (`run.ended`: completed, failed or cancelled,
3
+ // once carried back). Each message is signed by the Standard Webhooks spec (standardwebhooks.com), so a receiver checks
4
+ // it with any of that spec's libraries: `webhook-id` (the same on every try: the receiver's idempotency key),
5
+ // `webhook-timestamp` (Unix seconds) and `webhook-signature: v1,<base64 HMAC-SHA256 of "{id}.{timestamp}.{body}">`
6
+ // under the secret `whsec_<base64 of 32 bytes>`, which this server makes at the first PUT, shows once, and keeps in
7
+ // DIR/webhook.json only sealed under the tool keys' seal key (tool-keys.ts). A message not answered 2xx is tried again
8
+ // on the spec's schedule, cut at about a day; a 410 turns the webhook off. Messages and the last attempts live in
9
+ // DIR/webhook-outbox.json, so a restart goes on with those pending. Never in store.sqlite, which runs open.
10
+ // With them, in the same write, the ledger: the end and the wait each run's notices were queued for. A run's moment is
11
+ // queued once, by whichever server sees it, and a start queues each end the agent store holds that the ledger does not
12
+ // (catchUp): a kill between the store's end and the outbox write loses no run.ended, and sends none twice.
13
+ import { createHash, createHmac, randomBytes } from "node:crypto";
14
+ import { readFileSync, rmSync } from "node:fs";
15
+ import { join } from "node:path";
16
+ import { seal, unseal } from "@parcha/pi-durable-agent";
17
+ import { ApiError, invalid } from "./errors.js";
18
+ import { writeDurableSync } from "./files.js";
19
+ import { SEAL_KEY_ENV, sealKeyOf } from "./tool-keys.js";
20
+ import { isObject, unknownFields } from "./validate.js";
21
+ export const WEBHOOK_EVENTS = ["run.needs_input", "run.ended"];
22
+ /** The message types: a run's two notices, and the test send's. */
23
+ export const MESSAGE_TYPES = [...WEBHOOK_EVENTS, "webhook.test"];
24
+ export const WEBHOOK_FILE = "webhook.json";
25
+ export const OUTBOX_FILE = "webhook-outbox.json";
26
+ /** The waits before each try again, after the first at once: the Standard Webhooks schedule, cut at about a day. */
27
+ export const RETRY_MS = [5_000, 300_000, 1_800_000, 7_200_000, 18_000_000, 36_000_000];
28
+ const TIMEOUT_MS = 15_000;
29
+ /** How soon an outbox write that failed is tried again. */
30
+ const OUTBOX_RETRY_MS = 5_000;
31
+ /** How far back an end's run.ended is still queued: past the outbox's own retries (RETRY_MS, about a day), a notice
32
+ * would not be sent any more. */
33
+ const END_NOTICE_WINDOW_MS = 24 * 3_600_000;
34
+ /** In the data directory: when a server that keeps the ledger first started. An end before it was an older server's,
35
+ * which kept no ledger, so it is never queued again. */
36
+ export const END_NOTICES_SINCE = "end-notices-since";
37
+ /** How many attempts the log keeps, and with them the messages they tried, for a redelivery. */
38
+ export const ATTEMPTS_KEPT = 50;
39
+ const FORMAT = "webhook/1";
40
+ const MAX_URL = 2048;
41
+ const aad = `${FORMAT}|secret`;
42
+ const iso = (ms) => new Date(ms).toISOString();
43
+ /** The signature header of `body`, sent as message `id` at `timestamp` (Unix seconds), under `secret` (`whsec_...`). */
44
+ export const signatureOf = (secret, id, timestamp, body) => `v1,${createHmac("sha256", Buffer.from(secret.slice("whsec_".length), "base64")).update(`${id}.${timestamp}.${body}`).digest("base64")}`;
45
+ /** The webhook as `file` keeps it, if it holds one. */
46
+ function configIn(file) {
47
+ try {
48
+ const doc = JSON.parse(readFileSync(file, "utf8"));
49
+ return isObject(doc) && doc.v === 1 && typeof doc.url === "string" && typeof doc.secret === "string" ? doc : undefined;
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ }
55
+ /** Its secret, opened under `key`, or why it is not. */
56
+ function opened(key, config) {
57
+ if (!key)
58
+ return { signing: "seal_key_missing" };
59
+ try {
60
+ return { secret: unseal(key, Buffer.from(config.secret, "base64"), aad).toString("utf8") };
61
+ }
62
+ catch {
63
+ return { signing: "unreadable" };
64
+ }
65
+ }
66
+ /** The signing secret of the webhook data directory `data` keeps, opened with the seal key of `env`, or why it does not
67
+ * open (no seal key, or one it was not sealed under); undefined when it keeps none. Read for an import, which cuts it
68
+ * out of what it keeps. */
69
+ export function webhookSecretIn(data, env) {
70
+ const config = configIn(join(data, WEBHOOK_FILE));
71
+ return config && opened(sealKeyOf(env[SEAL_KEY_ENV]), config);
72
+ }
73
+ export class Webhooks {
74
+ say;
75
+ retryMs;
76
+ file;
77
+ outbox;
78
+ key;
79
+ messages;
80
+ attempts;
81
+ /** The ledger, by run: written with the messages, in the same write. */
82
+ notices;
83
+ /** When this data directory's ledger began (END_NOTICES_SINCE). */
84
+ since;
85
+ /** The runs told of since this server started: their ledger entries are this server's news, which a start's catch-up
86
+ * never drops. */
87
+ told = new Set();
88
+ base = "";
89
+ timers = new Set();
90
+ /** The tries in flight, which close() stops and waits for: nothing is written once it is closed. */
91
+ trying = new Set();
92
+ stop = new AbortController();
93
+ closed = false;
94
+ /** The outbox as held here is not on disk: its last write failed. Written again soon, and at the close. */
95
+ unsaved = false;
96
+ saving;
97
+ /** The webhook as held here when its write failed (a 410 that turned it off, on a full disk): read in place of the
98
+ * file until a write lands, as the next PUT's does. */
99
+ held;
100
+ /** The messages with a try in flight, by id, and how many: kept in the outbox until each lands, so one whose earlier
101
+ * attempts left the log meanwhile can still be redelivered. */
102
+ sending = new Map();
103
+ /** `env` is the server's own (withSecrets); `say` takes a log line's fields; `retryMs` the waits between tries. */
104
+ constructor(data, env, say, retryMs = RETRY_MS) {
105
+ this.say = say;
106
+ this.retryMs = retryMs;
107
+ this.file = join(data, WEBHOOK_FILE);
108
+ this.outbox = join(data, OUTBOX_FILE);
109
+ this.key = sealKeyOf(env[SEAL_KEY_ENV]);
110
+ // Read, or written at this first start, before anything ends here: a run that ends later is after it.
111
+ this.since = this.noticesSince(join(data, END_NOTICES_SINCE));
112
+ ({ messages: this.messages, attempts: this.attempts, notices: this.notices } = this.readOutbox());
113
+ // A restart goes on with the messages an earlier server left pending, each at its next try's time; a test send is
114
+ // tried once, so one left in flight failed.
115
+ const tests = this.messages.filter((m) => m.status === "pending" && m.type === "webhook.test");
116
+ for (const test of tests)
117
+ Object.assign(test, { status: "failed", next_at: null });
118
+ if (tests.length)
119
+ this.writeOutbox();
120
+ for (const message of this.messages)
121
+ if (message.status === "pending")
122
+ this.schedule(message, Math.max(0, (message.next_at ?? 0) - Date.now()));
123
+ }
124
+ /** Where the page is, for each notice's link to its run. */
125
+ attach(base) {
126
+ this.base = base.replace(/\/+$/, "");
127
+ }
128
+ /** GET: the URL, whether the secret signs here, and why the webhook is off, if it is; never the secret. */
129
+ view() {
130
+ const config = this.config();
131
+ if (!config)
132
+ return { configured: false };
133
+ const opened = this.secret(config);
134
+ return { configured: true, url: config.url, signing: ("secret" in opened ? "sealed" : opened.signing), disabled: config.disabled ?? null, updated_at: config.updated_at };
135
+ }
136
+ /** PUT: the URL, and the webhook on again. The first makes the secret and answers it, once; a later one keeps it. */
137
+ save(body) {
138
+ const issues = unknownFields(body, ["url"]);
139
+ const url = typeof body.url === "string" && body.url.length <= MAX_URL ? URL.parse(body.url) : null;
140
+ if (body.url === undefined)
141
+ issues.push({ field: "url", reason: "missing", message: "url is the http or https address to POST each message to" });
142
+ else if (!url || !["http:", "https:"].includes(url.protocol))
143
+ issues.push({ field: "url", reason: "invalid", message: `url is an http or https address of at most ${MAX_URL} characters` });
144
+ else if (url.username || url.password)
145
+ issues.push({ field: "url", reason: "invalid", message: "url holds no user or password: the receiver checks the signature" });
146
+ if (issues.length)
147
+ throw invalid(issues);
148
+ const was = this.config();
149
+ if (!was && !this.key)
150
+ throw new ApiError("no_sealing_key", `This server was handed no seal key (${SEAL_KEY_ENV}), so it keeps no webhook secret: it never keeps one in the clear.`);
151
+ const secret = was ? undefined : `whsec_${randomBytes(32).toString("base64")}`;
152
+ this.write({ url: url.href, secret: was?.secret ?? seal(this.key, Buffer.from(secret, "utf8"), aad).toString("base64"), updated_at: new Date().toISOString() });
153
+ return { created: !was, view: this.view(), ...(secret ? { secret } : {}) };
154
+ }
155
+ /** DELETE: the webhook gone, and its pending messages with it; the log of attempts stays. */
156
+ remove() {
157
+ if (!this.config())
158
+ return;
159
+ rmSync(this.file, { force: true });
160
+ this.held = undefined;
161
+ this.drop("the webhook was removed");
162
+ }
163
+ /** GET .../deliveries: the last attempts, newest first. */
164
+ attemptsView() {
165
+ return { attempts: [...this.attempts].reverse() };
166
+ }
167
+ /** A run's moment, told by runs.ts each time it sees it (a wait reached, an end the agent store has): queued once, when
168
+ * a webhook is set and on, and kept in the ledger in the same write. `marker` makes its webhook-id: the same moment,
169
+ * seen again after a restart, has the same id, which is a receiver's idempotency key. An end before the ledger began,
170
+ * before the webhook was set, or past the outbox's day counts as sent. */
171
+ emit(type, run, marker) {
172
+ if (this.closed)
173
+ return "closed";
174
+ this.told.add(run.run_id);
175
+ const ends = type === "run.ended";
176
+ const seen = this.notices[run.run_id];
177
+ if ((ends ? seen?.ended : seen?.wait) === marker)
178
+ return this.unsaved ? "unsaved" : "queued";
179
+ const config = this.config();
180
+ if (!config || config.disabled) {
181
+ // A wait seen while nothing is to be sent is noted here, never written for it: told again, it reads no file.
182
+ if (!ends)
183
+ this.notices[run.run_id] = { wait: marker };
184
+ return "off";
185
+ }
186
+ if (ends && !this.due(marker, config))
187
+ return "queued";
188
+ const id = `msg_${createHash("sha256").update(`${run.run_id}\n${type}\n${marker}`).digest("hex").slice(0, 32)}`;
189
+ // A new wait replaces the last; one after an end is a continued run's, past that end, which the store no longer holds.
190
+ this.notices[run.run_id] = ends ? { ...seen, ended: marker } : { wait: marker };
191
+ this.prune(config);
192
+ // One an earlier server queued before it kept a ledger: recorded now, and still sent once.
193
+ if (this.messages.some((m) => m.id === id))
194
+ this.writeOutbox();
195
+ else {
196
+ const data = { run_id: run.run_id, agent_id: run.agent_id, status: run.status, title: run.title, url: `${this.base}/#/runs/${encodeURIComponent(run.run_id)}`, ...(run.pending ? { pending: run.pending } : {}) };
197
+ this.schedule(this.enqueue(id, type, data), 0);
198
+ }
199
+ return this.unsaved ? "unsaved" : "queued";
200
+ }
201
+ /** A start's catch-up, once its runs are read (`rows`, the agent store's: a row with no state is an ended one). First,
202
+ * before anything is awaited, the ledger as the store now stands: a run the store no longer has goes, and a wait of a
203
+ * run it holds as ended goes (an end the webhook was off for never moved it past). Then each end the store holds that
204
+ * the ledger does not, and that is still due, is queued under the store's end time, so under the same webhook-id: its
205
+ * server was killed between the store's end and the outbox write, or that write never reached the disk. `describe`
206
+ * gives its notice. */
207
+ async catchUp(rows, describe) {
208
+ const config = this.config();
209
+ if (this.closed || !config || config.disabled)
210
+ return;
211
+ const store = new Map([...rows].map((row) => [row.id, row]));
212
+ let dropped = false;
213
+ for (const [id, noticed] of Object.entries(this.notices)) {
214
+ const row = store.get(id);
215
+ if (this.told.has(id) || (row && (row.state === "running" || noticed.wait === undefined)))
216
+ continue;
217
+ if (row && noticed.ended)
218
+ this.notices[id] = { ended: noticed.ended };
219
+ else
220
+ delete this.notices[id];
221
+ dropped = true;
222
+ }
223
+ if (dropped)
224
+ this.writeOutbox();
225
+ for (const { id, state, endedAt } of store.values()) {
226
+ if (state === "running" || !endedAt || this.notices[id]?.ended === endedAt || !this.due(endedAt, config))
227
+ continue;
228
+ const run = await describe(id).catch((error) => (this.say({ condition: "notice_unread", run: id, error: error.message }), null));
229
+ if (run)
230
+ this.emit("run.ended", run, endedAt);
231
+ }
232
+ }
233
+ /** POST .../test: a `webhook.test` message tried once now, never again; its attempt. */
234
+ test() {
235
+ this.need();
236
+ return this.attempt(this.enqueue(`msg_${randomBytes(16).toString("hex")}`, "webhook.test", {}), { retry: false, redelivery: false });
237
+ }
238
+ /** POST .../deliveries/{webhook_id}/redeliver: the message sent again once now, under its own webhook-id and body. */
239
+ redeliver(id) {
240
+ this.need();
241
+ const message = this.messages.find((m) => m.id === id);
242
+ if (!message)
243
+ throw new ApiError("not_found", `no message ${id} among the last ${ATTEMPTS_KEPT} attempts`);
244
+ return this.attempt(message, { retry: false, redelivery: true });
245
+ }
246
+ /** Stops: no try starts, those in flight are cut and waited for, and nothing more is written. A message cut here is
247
+ * still pending on disk, for the next server (its receiver may get it twice, under the same webhook-id). */
248
+ async close() {
249
+ this.closed = true;
250
+ for (const timer of this.timers)
251
+ clearTimeout(timer);
252
+ this.timers.clear();
253
+ clearTimeout(this.saving);
254
+ this.stop.abort();
255
+ await Promise.allSettled([...this.trying]);
256
+ // A notice a failed write left only here is written now, while the data directory is still this server's.
257
+ if (this.unsaved)
258
+ this.store();
259
+ }
260
+ config() {
261
+ return this.held ?? configIn(this.file);
262
+ }
263
+ /** Throws when the write fails: what was held stays held. */
264
+ write(config) {
265
+ writeDurableSync(this.file, `${JSON.stringify({ v: 1, ...config }, null, 2)}\n`);
266
+ this.held = undefined;
267
+ }
268
+ /** The outbox as the last server left it; an older server's (v2) has no ledger. */
269
+ readOutbox() {
270
+ try {
271
+ const doc = JSON.parse(readFileSync(this.outbox, "utf8"));
272
+ if (!isObject(doc) || (doc.v !== 2 && doc.v !== 3) || !Array.isArray(doc.messages) || !Array.isArray(doc.attempts))
273
+ return { messages: [], attempts: [], notices: {} };
274
+ const notices = isObject(doc.notices) ? Object.fromEntries(Object.entries(doc.notices).filter(([, n]) => isObject(n))) : {};
275
+ return { messages: doc.messages.filter((m) => isObject(m) && typeof m.id === "string" && typeof m.body === "string"), attempts: doc.attempts.filter(isObject), notices };
276
+ }
277
+ catch {
278
+ return { messages: [], attempts: [], notices: {} };
279
+ }
280
+ }
281
+ /** Whether an end's run.ended is still to be queued: at or after the ledger began, the webhook was set, and the
282
+ * outbox's day began (a marker that names no time is not judged by one). The catch-up and the ledger's pruning read the
283
+ * same line, so the ledger never forgets an end a start would look for. */
284
+ due(endedAt, config) {
285
+ const at = Date.parse(endedAt);
286
+ return !Number.isFinite(at) || at >= Math.max(this.since, Date.parse(config.updated_at), Date.now() - END_NOTICE_WINDOW_MS);
287
+ }
288
+ /** The ledger without what no start looks for: a run whose end is no longer due goes, with the wait it ended past. A
289
+ * wait with no end after it stays while the run stands at it, however long: never pruned by age, so the same question
290
+ * is never asked again. */
291
+ prune(config) {
292
+ for (const [id, noticed] of Object.entries(this.notices))
293
+ if (noticed.ended && !this.due(noticed.ended, config))
294
+ delete this.notices[id];
295
+ }
296
+ /** When this data directory's ledger began: read, or written now, once and durably, at the first start of a server
297
+ * that keeps one. One that cannot be written is taken as now, and said, so a start never sends an older server's ends
298
+ * again. */
299
+ noticesSince(file) {
300
+ try {
301
+ const at = Date.parse(readFileSync(file, "utf8").trim());
302
+ if (Number.isFinite(at))
303
+ return at;
304
+ }
305
+ catch { }
306
+ const now = Date.now();
307
+ try {
308
+ writeDurableSync(file, `${new Date(now).toISOString()}\n`);
309
+ }
310
+ catch (error) {
311
+ this.say({ condition: "notices_since_unwritable", file, error: error.code ?? "unknown" });
312
+ }
313
+ return now;
314
+ }
315
+ writeOutbox() {
316
+ // Closed, the data directory may be another server's already.
317
+ if (this.closed)
318
+ return;
319
+ if (this.store() || this.saving)
320
+ return;
321
+ // Not saved: kept, and written again until a write lands (or the close writes it).
322
+ const timer = setTimeout(() => { this.saving = undefined; this.writeOutbox(); }, OUTBOX_RETRY_MS);
323
+ timer.unref();
324
+ this.saving = timer;
325
+ }
326
+ /** The outbox written whole: the last attempts, and the messages pending or tried by one of those (a redelivery sends
327
+ * one again). False when the write failed, which the log says once until one lands. */
328
+ store() {
329
+ this.attempts = this.attempts.slice(-ATTEMPTS_KEPT);
330
+ const tried = new Set(this.attempts.map((a) => a.webhook_id));
331
+ this.messages = this.messages.filter((m) => m.status === "pending" || tried.has(m.id) || this.sending.has(m.id));
332
+ try {
333
+ writeDurableSync(this.outbox, `${JSON.stringify({ v: 3, messages: this.messages, attempts: this.attempts, notices: this.notices })}\n`);
334
+ this.unsaved = false;
335
+ return true;
336
+ }
337
+ catch (error) {
338
+ if (!this.unsaved)
339
+ this.say({ condition: "outbox_unwritable", file: this.outbox, error: error.code ?? "unknown" });
340
+ this.unsaved = true;
341
+ return false;
342
+ }
343
+ }
344
+ /** The secret, opened, or why it is not. */
345
+ secret(config) {
346
+ return opened(this.key, config);
347
+ }
348
+ enqueue(id, type, data) {
349
+ const created = new Date().toISOString();
350
+ const message = { id, type, body: JSON.stringify({ type, timestamp: created, data }), created_at: created, status: "pending", attempts: 0, next_at: Date.now() };
351
+ this.messages.push(message);
352
+ this.writeOutbox();
353
+ return message;
354
+ }
355
+ schedule(message, delayMs) {
356
+ if (this.closed)
357
+ return;
358
+ const timer = setTimeout(() => {
359
+ this.timers.delete(timer);
360
+ // No try rejects unhandled, which would stop the server: one that throws is said, and its message stays as it was.
361
+ this.attempt(message, { retry: true, redelivery: false }).catch((error) => {
362
+ try {
363
+ this.say({ condition: "attempt_failed", webhook_id: message.id, error: error instanceof Error ? error.message : String(error) });
364
+ }
365
+ catch { }
366
+ });
367
+ }, delayMs);
368
+ timer.unref();
369
+ this.timers.add(timer);
370
+ }
371
+ attempt(message, how) {
372
+ this.sending.set(message.id, (this.sending.get(message.id) ?? 0) + 1);
373
+ const trying = this.tryOnce(message, how).finally(() => {
374
+ this.trying.delete(trying);
375
+ const left = this.sending.get(message.id) - 1;
376
+ if (left)
377
+ this.sending.set(message.id, left);
378
+ else
379
+ this.sending.delete(message.id);
380
+ });
381
+ this.trying.add(trying);
382
+ return trying;
383
+ }
384
+ /** One try: POSTed, signed, to the URL set now; no redirect followed, at most 15 s. Not 2xx: tried again after the
385
+ * next wait (`retry`), else failed, and the log says so. A 410 turns the webhook off. A redelivery is a try of its
386
+ * own: it settles a message still pending when it lands, and never fails one. */
387
+ async tryOnce(message, how) {
388
+ const now = Date.now();
389
+ const attempt = { webhook_id: message.id, type: message.type, at: iso(now), status_code: null, latency_ms: 0, error: null, retry_at: null, redelivery: how.redelivery };
390
+ if (this.closed || (message.status !== "pending" && !how.redelivery))
391
+ return attempt;
392
+ const config = this.config();
393
+ let failure;
394
+ if (!config)
395
+ failure = "the webhook was removed";
396
+ else if (config.disabled)
397
+ failure = "the webhook is off";
398
+ else {
399
+ const opened = this.secret(config);
400
+ if (!("secret" in opened))
401
+ failure = `the secret does not open here (${opened.signing}): set the webhook again`;
402
+ else {
403
+ const timestamp = String(Math.floor(now / 1000));
404
+ const started = performance.now();
405
+ try {
406
+ const res = await fetch(config.url, {
407
+ method: "POST", redirect: "manual", signal: AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), this.stop.signal]),
408
+ headers: { "content-type": "application/json", "user-agent": "agentrun-serve-webhook/1", "webhook-id": message.id, "webhook-timestamp": timestamp, "webhook-signature": signatureOf(opened.secret, message.id, timestamp, message.body) },
409
+ body: message.body,
410
+ });
411
+ await res.body?.cancel().catch(() => undefined);
412
+ attempt.status_code = res.status;
413
+ if (res.status < 200 || res.status > 299)
414
+ failure = res.status >= 300 && res.status < 400 ? `answered ${res.status}: a redirect is not followed` : `answered ${res.status}`;
415
+ }
416
+ catch (error) {
417
+ failure = error.name === "TimeoutError" ? `no answer in ${TIMEOUT_MS / 1000} s` : `not reached: ${error.cause?.code ?? error.message}`;
418
+ }
419
+ attempt.latency_ms = Math.round(performance.now() - started);
420
+ }
421
+ }
422
+ if (this.closed)
423
+ return attempt;
424
+ attempt.error = failure ?? null;
425
+ this.attempts.push(attempt);
426
+ // The schedule counts the message's own tries: a redelivery is a try of its own, and leaves it as it was.
427
+ if (!how.redelivery)
428
+ message.attempts += 1;
429
+ // A 410 turns off the webhook as this try found it: one set again or removed while the try waited is not its to turn
430
+ // off, and the 410 is then a failure like any other.
431
+ const standing = this.config();
432
+ const gone = attempt.status_code === 410 && config !== undefined && standing !== undefined && standing.url === config.url && standing.updated_at === config.updated_at && !standing.disabled;
433
+ const wait = how.retry && failure && config && !gone ? this.retryMs[message.attempts - 1] : undefined;
434
+ if (!failure)
435
+ Object.assign(message, { status: "delivered", next_at: null });
436
+ // A redelivery that failed leaves the message as it is, and so does a try that ends after one delivered it.
437
+ else if (!how.redelivery && message.status === "pending") {
438
+ if (wait !== undefined) {
439
+ // Jitter, so messages that failed together do not all come back together.
440
+ const delay = Math.round(wait * (0.8 + 0.4 * Math.random()));
441
+ message.next_at = Date.now() + delay;
442
+ attempt.retry_at = iso(message.next_at);
443
+ this.schedule(message, delay);
444
+ }
445
+ else {
446
+ Object.assign(message, { status: "failed", next_at: null });
447
+ this.say({ condition: "delivery_failed", type: message.type, webhook_id: message.id, attempts: message.attempts, ...(attempt.status_code !== null ? { status_code: attempt.status_code } : {}), error: failure });
448
+ }
449
+ }
450
+ if (gone) {
451
+ // Gone: the receiver says this endpoint is no more. Off, its pending messages dropped, until a PUT sets it again.
452
+ const disabled = { at: attempt.at, reason: "the receiver answered 410 Gone" };
453
+ const off = { ...standing, disabled };
454
+ try {
455
+ this.write(off);
456
+ }
457
+ catch (error) {
458
+ // Off here all the same: held, and the next PUT writes the webhook whole.
459
+ this.held = off;
460
+ this.say({ condition: "webhook_unwritable", file: this.file, error: error.code ?? "unknown" });
461
+ }
462
+ this.say({ condition: "webhook_disabled", url: standing.url, reason: disabled.reason });
463
+ this.drop("the webhook is off: its receiver answered 410");
464
+ return attempt;
465
+ }
466
+ this.writeOutbox();
467
+ return attempt;
468
+ }
469
+ /** Every pending message failed, with `why` in the log. */
470
+ drop(why) {
471
+ const pending = this.messages.filter((m) => m.status === "pending");
472
+ for (const message of pending)
473
+ Object.assign(message, { status: "failed", next_at: null });
474
+ if (pending.length)
475
+ this.say({ condition: "messages_dropped", count: pending.length, reason: why });
476
+ this.writeOutbox();
477
+ }
478
+ /** The webhook, set and on: a test or a redelivery sends nothing to one a 410 turned off, as no try does. */
479
+ need() {
480
+ const config = this.config();
481
+ if (!config)
482
+ throw new ApiError("not_found", "no webhook is set: PUT /v2/settings/webhook sets one");
483
+ if (config.disabled)
484
+ throw new ApiError("webhook_off", `the webhook is off (${config.disabled.reason}): set it again with PUT /v2/settings/webhook`);
485
+ return config;
486
+ }
487
+ }
@@ -0,0 +1,33 @@
1
+ import type { ToolRegistration } from "@earendil-works/pi-durable";
2
+ /**
3
+ * `text` with the workspace's absolute path taken out: `<work>/notes/a.md` reads `notes/a.md`, the workspace itself `.`,
4
+ * a path beside it `../x` (pi's tools resolve a relative path before they refuse it), and pi's refusal ("<path>: outside
5
+ * the workspace <work>") names no directory. `works` is the workspace as the environment names it and as the kernel
6
+ * resolves it (they differ under a symlinked directory). For a refusal, an error, and a write's or edit's result; a
7
+ * read's result is the file's own text and is never changed.
8
+ */
9
+ export declare function workspaceRelative(text: string, works: readonly string[]): string;
10
+ /**
11
+ * Refuses `given`, a path a call gave that leaves the workspace, in the one words every refusal uses:
12
+ * `<given>: outside the workspace`, and no other path (not the workspace, a box's work dir, or where it resolves). It is
13
+ * the confinement's typed refusal (`PathOutsideWorkError`, `outside_work`), so its type tells it from any other error.
14
+ * For a tool that checks a path itself (a box's file tools); pi's own tools refuse through the confinement, named by
15
+ * `asGivenRefusals`.
16
+ */
17
+ export declare function refuseOutsideWorkspace(given: string): never;
18
+ /**
19
+ * pi's file `tools`, each with its confinement's refusal named by the path the call gave, as it gave it:
20
+ * `../../.token: outside the workspace`. The confinement names no path itself: pi's tools resolve a path against the
21
+ * workspace before they ask for it, so every path it sees is the host's own (`<data>/runs/.token`), and the call's
22
+ * `path` is the only one the model gave. A refusal is told by its type (`PathOutsideWorkError`), never by its text; one
23
+ * already named (`refuseOutsideWorkspace`), every other error, and every result are the tool's own.
24
+ */
25
+ export declare function asGivenRefusals(tools: readonly ToolRegistration[]): ToolRegistration[];
26
+ /** `path` as the kernel resolves it, or itself when it cannot be resolved. */
27
+ export declare const realOf: (path: string) => string;
28
+ /** How a run's rows name a file path, a whole path (never a text): one in the run's directory relative to its workspace
29
+ * (`<run>/work`: `hello.md`, `.`, `../work 2024/a.md`, `..`), and any other path, or one that is not absolute, exactly
30
+ * as given. Checked against the workspace as serve names it and as the kernel resolves it (a harness's CLI sends the
31
+ * resolved one: its working directory is `work/`). By `path.relative`, segment by segment, so a sibling whose name
32
+ * starts with `work` is never taken for it. Text, such as a tool's error, goes through `workspaceRelative`. */
33
+ export declare function rowPaths(runDir: string): (path: string) => string;
@@ -0,0 +1,104 @@
1
+ // How serve names a path in the run's workspace to a person or a model: relative to the workspace, never by the server's
2
+ // data directory. The rule is one for every place that shows a path: a host tool's error or write result
3
+ // (host-tools.ts), and a timeline row's file (runs.ts, through the projector's `path` option). A refusal of a path
4
+ // outside the workspace names the path the call gave, as it gave it, and no other (`asGivenRefusals`), wherever the
5
+ // coding tools come from (coding-tools.ts: pi's own runs and the other harnesses' host tools, on the runner and in a box).
6
+ import { realpathSync } from "node:fs";
7
+ import { dirname, isAbsolute, join, relative, sep } from "node:path";
8
+ import { PathOutsideWorkError } from "@parcha/pi-durable-disk";
9
+ /**
10
+ * `text` with the workspace's absolute path taken out: `<work>/notes/a.md` reads `notes/a.md`, the workspace itself `.`,
11
+ * a path beside it `../x` (pi's tools resolve a relative path before they refuse it), and pi's refusal ("<path>: outside
12
+ * the workspace <work>") names no directory. `works` is the workspace as the environment names it and as the kernel
13
+ * resolves it (they differ under a symlinked directory). For a refusal, an error, and a write's or edit's result; a
14
+ * read's result is the file's own text and is never changed.
15
+ */
16
+ export function workspaceRelative(text, works) {
17
+ const escape = (path) => path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
18
+ // A name counts only where a path starts (not inside a longer one), and, unless a "/" follows, where it ends (a quote, a
19
+ // space, a separator or the text's end).
20
+ const start = "(?<![\\w./~-])";
21
+ const end = "(?![^'\"\\s,;:)\\]])";
22
+ let out = text;
23
+ // Longest first, so a name inside another is taken out before the outer one could take its prefix.
24
+ for (const work of [...new Set(works)].filter((w) => w.length > 1).sort((a, b) => b.length - a.length)) {
25
+ const name = `${start}${escape(work)}`;
26
+ out = out
27
+ .replace(new RegExp(`outside the workspace ${name}${end}`, "g"), "outside the workspace")
28
+ .replace(new RegExp(`${name}/`, "g"), "")
29
+ .replace(new RegExp(`${name}${end}`, "g"), ".");
30
+ const parent = dirname(work);
31
+ if (parent.length > 1)
32
+ out = out.replace(new RegExp(`${start}${escape(parent)}/`, "g"), "../").replace(new RegExp(`${start}${escape(parent)}${end}`, "g"), "..");
33
+ }
34
+ return out;
35
+ }
36
+ /** A refusal already named by the path the call gave: `asGivenRefusals` passes it on as it is. */
37
+ class GivenPathRefusal extends PathOutsideWorkError {
38
+ }
39
+ /**
40
+ * Refuses `given`, a path a call gave that leaves the workspace, in the one words every refusal uses:
41
+ * `<given>: outside the workspace`, and no other path (not the workspace, a box's work dir, or where it resolves). It is
42
+ * the confinement's typed refusal (`PathOutsideWorkError`, `outside_work`), so its type tells it from any other error.
43
+ * For a tool that checks a path itself (a box's file tools); pi's own tools refuse through the confinement, named by
44
+ * `asGivenRefusals`.
45
+ */
46
+ export function refuseOutsideWorkspace(given) {
47
+ throw new GivenPathRefusal(given, "outside_work", `${given}: outside the workspace`);
48
+ }
49
+ /**
50
+ * pi's file `tools`, each with its confinement's refusal named by the path the call gave, as it gave it:
51
+ * `../../.token: outside the workspace`. The confinement names no path itself: pi's tools resolve a path against the
52
+ * workspace before they ask for it, so every path it sees is the host's own (`<data>/runs/.token`), and the call's
53
+ * `path` is the only one the model gave. A refusal is told by its type (`PathOutsideWorkError`), never by its text; one
54
+ * already named (`refuseOutsideWorkspace`), every other error, and every result are the tool's own.
55
+ */
56
+ export function asGivenRefusals(tools) {
57
+ return tools.map((tool) => ({
58
+ ...tool,
59
+ async execute(args, api, context) {
60
+ try {
61
+ return await tool.execute(args, api, context);
62
+ }
63
+ catch (error) {
64
+ const reason = error instanceof PathOutsideWorkError ? error.reason : undefined;
65
+ const given = args?.path;
66
+ if (reason === undefined || error instanceof GivenPathRefusal || typeof given !== "string" || given === "")
67
+ throw error;
68
+ throw new GivenPathRefusal(given, reason, `${given}: ${error.message}`);
69
+ }
70
+ },
71
+ }));
72
+ }
73
+ /** `path` as the kernel resolves it, or itself when it cannot be resolved. */
74
+ export const realOf = (path) => {
75
+ try {
76
+ return realpathSync(path);
77
+ }
78
+ catch {
79
+ return path;
80
+ }
81
+ };
82
+ /** How a run's rows name a file path, a whole path (never a text): one in the run's directory relative to its workspace
83
+ * (`<run>/work`: `hello.md`, `.`, `../work 2024/a.md`, `..`), and any other path, or one that is not absolute, exactly
84
+ * as given. Checked against the workspace as serve names it and as the kernel resolves it (a harness's CLI sends the
85
+ * resolved one: its working directory is `work/`). By `path.relative`, segment by segment, so a sibling whose name
86
+ * starts with `work` is never taken for it. Text, such as a tool's error, goes through `workspaceRelative`. */
87
+ export function rowPaths(runDir) {
88
+ if (!isAbsolute(runDir))
89
+ return (path) => path;
90
+ const work = join(runDir, "work");
91
+ const works = [...new Set([work, realOf(work)])];
92
+ /** Whether `rel`, a `path.relative`, stays inside its base: not `..`, not under `..`, not absolute (another root). */
93
+ const within = (rel) => rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
94
+ return (path) => {
95
+ if (!isAbsolute(path))
96
+ return path;
97
+ for (const named of works) {
98
+ if (!within(relative(dirname(named), path)))
99
+ continue;
100
+ return relative(named, path) || ".";
101
+ }
102
+ return path;
103
+ };
104
+ }