@parcha/agentrun-serve 0.1.0-beta.61 → 0.1.0-beta.63

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 (228) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/README.md +128 -20
  3. package/dist/adapters.js +4 -2
  4. package/dist/agent-delete.d.ts +3 -3
  5. package/dist/agent-delete.js +50 -4
  6. package/dist/api-only.d.ts +4 -0
  7. package/dist/api-only.js +5 -1
  8. package/dist/archil-settings.d.ts +9 -0
  9. package/dist/archil-settings.js +8 -1
  10. package/dist/bash-read-only.d.ts +3 -0
  11. package/dist/bash-read-only.js +6 -3
  12. package/dist/chatgpt-plan.d.ts +33 -8
  13. package/dist/chatgpt-plan.js +141 -24
  14. package/dist/claude-login.d.ts +12 -5
  15. package/dist/claude-login.js +28 -3
  16. package/dist/cli.js +19 -8
  17. package/dist/composio-triggers.d.ts +9 -3
  18. package/dist/computers.d.ts +3 -0
  19. package/dist/computers.js +2 -1
  20. package/dist/console/assets/{backend-C9ffXUR5.js → backend-BxQ2G1M0.js} +2 -2
  21. package/dist/console/assets/index-C8Y5Zl8x.js +639 -0
  22. package/dist/console/assets/share-CjBJ_rxP.js +6 -0
  23. package/dist/console/assets/{styles-fjQBFfMv.css → styles-D0SufbzK.css} +1 -1
  24. package/dist/console/index.html +3 -3
  25. package/dist/console/share.html +3 -3
  26. package/dist/cut-pool.d.ts +14 -0
  27. package/dist/cut-pool.js +98 -0
  28. package/dist/cut-worker.d.ts +14 -0
  29. package/dist/cut-worker.js +16 -0
  30. package/dist/decisions.d.ts +4 -0
  31. package/dist/decisions.js +9 -1
  32. package/dist/env-switch.d.ts +3 -0
  33. package/dist/env-switch.js +3 -0
  34. package/dist/harness-opencode/adapter.d.ts +3 -1
  35. package/dist/harness-opencode/adapter.js +6 -2
  36. package/dist/harness-opencode/harness.d.ts +4 -0
  37. package/dist/harness-opencode/harness.js +6 -1
  38. package/dist/harness-table.d.ts +7 -0
  39. package/dist/harness-table.js +6 -3
  40. package/dist/host-tools.d.ts +18 -3
  41. package/dist/host-tools.js +27 -4
  42. package/dist/import.d.ts +8 -1
  43. package/dist/import.js +36 -5
  44. package/dist/key-check.js +22 -8
  45. package/dist/learn/ledger.d.ts +37 -16
  46. package/dist/learn/ledger.js +56 -24
  47. package/dist/learn/promote.d.ts +4 -1
  48. package/dist/learned-nodes.d.ts +2 -1
  49. package/dist/learned-nodes.js +2 -1
  50. package/dist/learning-cost.d.ts +5 -3
  51. package/dist/learning-model.js +7 -5
  52. package/dist/learning-work.d.ts +69 -0
  53. package/dist/learning-work.js +148 -0
  54. package/dist/mcp-gateway.d.ts +24 -0
  55. package/dist/mcp-gateway.js +97 -8
  56. package/dist/mcp-servers-store.d.ts +7 -10
  57. package/dist/mcp-servers-store.js +15 -9
  58. package/dist/native/cli.js +5 -1
  59. package/dist/ollama-provider.d.ts +10 -3
  60. package/dist/ollama-provider.js +17 -7
  61. package/dist/openapi.js +51 -20
  62. package/dist/otel/tracer.d.ts +6 -3
  63. package/dist/otel/tracer.js +24 -6
  64. package/dist/page.d.ts +7 -0
  65. package/dist/page.js +17 -4
  66. package/dist/place.d.ts +25 -9
  67. package/dist/place.js +37 -11
  68. package/dist/print.d.ts +3 -2
  69. package/dist/print.js +8 -6
  70. package/dist/run-export.js +7 -4
  71. package/dist/run-launch.d.ts +6 -1
  72. package/dist/run-launch.js +26 -6
  73. package/dist/run-model-key.d.ts +2 -1
  74. package/dist/run-model-key.js +2 -1
  75. package/dist/run-reads-over-store.d.ts +7 -0
  76. package/dist/run-reads-over-store.js +32 -4
  77. package/dist/run-view.js +9 -3
  78. package/dist/runnable.d.ts +6 -3
  79. package/dist/runnable.js +21 -11
  80. package/dist/runner/adapter-loop.js +95 -28
  81. package/dist/runner/adapter-run-spec.d.ts +20 -4
  82. package/dist/runner/adapter-run-spec.js +64 -30
  83. package/dist/runner/adapters/index.d.ts +6 -0
  84. package/dist/runner/adapters/index.js +5 -1
  85. package/dist/runner/adapters/pi.d.ts +42 -3
  86. package/dist/runner/adapters/pi.js +114 -13
  87. package/dist/runner/audit.d.ts +8 -2
  88. package/dist/runner/audit.js +34 -18
  89. package/dist/runner/book-cut.d.ts +6 -0
  90. package/dist/runner/book-cut.js +38 -0
  91. package/dist/runner/claim-secrets.d.ts +12 -5
  92. package/dist/runner/claim-secrets.js +28 -12
  93. package/dist/runner/cli-run-spec.d.ts +0 -2
  94. package/dist/runner/cli-run-spec.js +54 -25
  95. package/dist/runner/dispatch.js +2 -0
  96. package/dist/runner/harness-loops.d.ts +5 -0
  97. package/dist/runner/harness-loops.js +4 -1
  98. package/dist/runner/held.d.ts +6 -3
  99. package/dist/runner/learned-first.d.ts +5 -0
  100. package/dist/runner/learned-first.js +1 -1
  101. package/dist/runner/learning-end.d.ts +15 -8
  102. package/dist/runner/learning-end.js +23 -7
  103. package/dist/runner/live-ticker.js +3 -1
  104. package/dist/runner/loop-contract.d.ts +8 -1
  105. package/dist/runner/main.js +2 -0
  106. package/dist/runner/mcp-run.d.ts +5 -0
  107. package/dist/runner/mcp-run.js +18 -0
  108. package/dist/runner/meta-tools.js +4 -4
  109. package/dist/runner/metrics.d.ts +4 -2
  110. package/dist/runner/metrics.js +5 -3
  111. package/dist/runner/model-route.d.ts +4 -0
  112. package/dist/runner/model-route.js +1 -1
  113. package/dist/runner/native-loop.js +2 -2
  114. package/dist/runner/pr-checkout.d.ts +12 -0
  115. package/dist/runner/pr-checkout.js +21 -2
  116. package/dist/runner/promotion.d.ts +9 -2
  117. package/dist/runner/promotion.js +79 -28
  118. package/dist/runner/reflect-hook.d.ts +7 -0
  119. package/dist/runner/reflect-hook.js +2 -1
  120. package/dist/runner/run-child-host.d.ts +10 -6
  121. package/dist/runner/run-child-host.js +65 -41
  122. package/dist/runner/run-child.js +2 -0
  123. package/dist/runner/runner.d.ts +9 -0
  124. package/dist/runner/runner.js +158 -25
  125. package/dist/runner/store-port.d.ts +4 -1
  126. package/dist/runner/workflow-calls.d.ts +4 -3
  127. package/dist/runner/workflow-calls.js +41 -12
  128. package/dist/runner/workflow-first.js +4 -3
  129. package/dist/runner/workflow-loop.js +13 -1
  130. package/dist/runner/workflow-spec.js +1 -1
  131. package/dist/secret-cut.d.ts +4 -0
  132. package/dist/secret-cut.js +1 -1
  133. package/dist/secret-rules.d.ts +2 -1
  134. package/dist/secret-rules.js +88 -24
  135. package/dist/server.d.ts +10 -1
  136. package/dist/server.js +131 -44
  137. package/dist/share-host.d.ts +111 -0
  138. package/dist/share-host.js +669 -0
  139. package/dist/store/schema.d.ts +4 -3
  140. package/dist/store/schema.js +4 -3
  141. package/dist/store/seal.d.ts +8 -2
  142. package/dist/store/seal.js +13 -2
  143. package/dist/store/sqlite/learning-rows.js +2 -1
  144. package/dist/store/sqlite/run-patch.js +4 -4
  145. package/dist/store/sqlite/store.js +28 -4
  146. package/dist/store/store.d.ts +5 -0
  147. package/dist/store-reads/analytics.d.ts +15 -0
  148. package/dist/store-reads/analytics.js +17 -0
  149. package/dist/store-reads/journal.d.ts +2 -0
  150. package/dist/store-reads/journal.js +1 -1
  151. package/dist/store-reads/learning.d.ts +4 -3
  152. package/dist/store-reads/learning.js +62 -18
  153. package/dist/store-view.d.ts +3 -0
  154. package/dist/store-view.js +18 -1
  155. package/dist/suggestions.js +32 -3
  156. package/dist/templates.d.ts +3 -1
  157. package/dist/templates.js +7 -3
  158. package/dist/tool-gate.d.ts +25 -9
  159. package/dist/tool-gate.js +58 -19
  160. package/dist/tool-list.d.ts +4 -0
  161. package/dist/tool-list.js +4 -0
  162. package/dist/tool-plane.d.ts +1 -0
  163. package/dist/tool-plane.js +6 -2
  164. package/dist/tools.js +2 -2
  165. package/dist/trigger-composio.js +1 -1
  166. package/dist/webhooks.d.ts +3 -0
  167. package/dist/webhooks.js +5 -0
  168. package/dist/workspace/archil-claim.d.ts +7 -3
  169. package/dist/workspace/archil-claim.js +13 -5
  170. package/dist/workspace/archil-mount-credential.d.ts +6 -0
  171. package/dist/workspace/archil-mount-credential.js +11 -0
  172. package/dist/workspace/attach.js +22 -5
  173. package/dist/workspace/computer-deps.d.ts +5 -3
  174. package/dist/workspace/computer-deps.js +11 -9
  175. package/dist/workspace/computer-for-claim.d.ts +6 -2
  176. package/dist/workspace/computer-for-claim.js +43 -12
  177. package/dist/workspace/computer-janitor.d.ts +7 -4
  178. package/dist/workspace/computer-janitor.js +7 -4
  179. package/dist/workspace/computer-kept.d.ts +7 -1
  180. package/dist/workspace/computer-kept.js +7 -1
  181. package/dist/workspace/kind-skills/desktop/SKILL.md +17 -4
  182. package/dist/workspace/mount-revoke-left.d.ts +16 -4
  183. package/dist/workspace/mount-revoke-left.js +42 -22
  184. package/dist/workspace/resolve-computer.d.ts +11 -5
  185. package/dist/workspace/resolve-computer.js +22 -13
  186. package/dist/workspace/run-end-computers.js +1 -1
  187. package/dist/workspace/run-tools.d.ts +10 -3
  188. package/dist/workspace/run-tools.js +5 -4
  189. package/dist/wrapped.d.ts +29 -2
  190. package/dist/wrapped.js +20 -3
  191. package/launcher/agentrun-serve +1 -1
  192. package/package.json +12 -12
  193. package/templates/kyb/agent.md +7 -1
  194. package/templates/kyb/evals/list-file-fuzzy-alias/case.yaml +10 -0
  195. package/templates/kyb/evals/list-file-fuzzy-alias/fixtures/web.json +58 -0
  196. package/templates/kyb/evals/list-file-fuzzy-alias/graders/finds-the-transliteration.md +17 -0
  197. package/templates/kyb/evals/list-file-fuzzy-alias/graders/greps-the-files.md +11 -0
  198. package/templates/kyb/evals/list-file-fuzzy-alias/graders/saves-the-uk-file.md +8 -0
  199. package/templates/kyb/evals/list-file-fuzzy-alias/prompt.md +7 -0
  200. package/templates/kyb/evals/list-file-hit/case.yaml +10 -0
  201. package/templates/kyb/evals/list-file-hit/fixtures/web.json +58 -0
  202. package/templates/kyb/evals/list-file-hit/graders/greps-the-files.md +11 -0
  203. package/templates/kyb/evals/list-file-hit/graders/hits-by-company-number.md +18 -0
  204. package/templates/kyb/evals/list-file-hit/graders/saves-the-uk-file.md +8 -0
  205. package/templates/kyb/evals/list-file-hit/prompt.md +7 -0
  206. package/templates/kyb/evals/list-file-no-hit/case.yaml +10 -0
  207. package/templates/kyb/evals/list-file-no-hit/fixtures/web.json +58 -0
  208. package/templates/kyb/evals/list-file-no-hit/graders/greps-the-files.md +11 -0
  209. package/templates/kyb/evals/list-file-no-hit/graders/no-hit-by-whole-file.md +12 -0
  210. package/templates/kyb/evals/list-file-no-hit/graders/saves-the-uk-file.md +8 -0
  211. package/templates/kyb/evals/list-file-no-hit/prompt.md +7 -0
  212. package/templates/kyb/evals/list-file-short-name/case.yaml +9 -0
  213. package/templates/kyb/evals/list-file-short-name/fixtures/web.json +58 -0
  214. package/templates/kyb/evals/list-file-short-name/graders/finds-the-short-name.md +19 -0
  215. package/templates/kyb/evals/list-file-short-name/graders/greps-the-files.md +11 -0
  216. package/templates/kyb/evals/list-file-short-name/graders/saves-the-uk-file.md +8 -0
  217. package/templates/kyb/evals/list-file-short-name/prompt.md +7 -0
  218. package/templates/kyb/evals/list-file-split-name/case.yaml +11 -0
  219. package/templates/kyb/evals/list-file-split-name/fixtures/web.json +58 -0
  220. package/templates/kyb/evals/list-file-split-name/graders/finds-the-director.md +18 -0
  221. package/templates/kyb/evals/list-file-split-name/graders/greps-the-files.md +11 -0
  222. package/templates/kyb/evals/list-file-split-name/graders/saves-the-uk-file.md +8 -0
  223. package/templates/kyb/evals/list-file-split-name/prompt.md +7 -0
  224. package/templates/kyb/kyb.schema.json +2 -2
  225. package/templates/kyb/rules/SANCTIONS.md +82 -13
  226. package/dist/console/assets/index-BnZV3lvW.js +0 -639
  227. package/dist/console/assets/share-B1o5mJ56.js +0 -6
  228. /package/dist/console/assets/{styles-D_znYrHR.js → styles-BGZxYkky.js} +0 -0
@@ -0,0 +1,669 @@
1
+ // The share host (`agentrun-serve --share-host`, AGENTRUN_SHARE_HOST=1): the serve install behind agentrun.ai/r/<id>,
2
+ // with a store of its own. It answers under /r/ alone, so the site it sits behind routes one path to it:
3
+ // /r/<id> a share's page (the console's share.html, its asset URLs moved under /r/_assets/)
4
+ // /r/<id>/bundle.json the stored bytes, exactly as they were posted and scanned
5
+ // /r/_assets/* the page's assets (the console's build)
6
+ // /r/v2/shares POST stores a bundle, GET lists the caller's own; DELETE /r/v2/shares/<id> deletes one
7
+ // /r/v2/health public
8
+ // Every other address is a 404, answered before anything else reads the request (server.ts): the console, /v2 and with
9
+ // it every run, agent, key, computer, sign-in, MCP and trigger route. The host runs no runner and holds no model key.
10
+ //
11
+ // An upload, in order: the token (api-token.ts; its id owns the share), the token's quota, the body within its cap, a
12
+ // canonical `agentrun.share/1` document of the export's closed shape and caps whose sha256 and file digests hold
13
+ // (checkShareBundle), then the scrubber in cut mode with this host's held values over the whole body and every string
14
+ // (screenShare). A value it finds refuses it unless the bundle declares it restored, exactly where the host's own scrub
15
+ // finds it and of a kind that restores (label, personal, jev; never a key format, a held value or a dump); a restored
16
+ // record that names no such value refuses it too, and so does a scrub that fails: 422 with counts by rule, never a
17
+ // value, nothing stored. The host never repairs a bundle: what
18
+ // it stores, and later serves, is the posted bytes it scanned. A share's URL is on AGENTRUN_PUBLIC_URL (else, on loopback,
19
+ // the server's own address), never a Host header.
20
+ import { createHash, randomBytes } from "node:crypto";
21
+ import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
22
+ import { join } from "node:path";
23
+ import { packageSha256 } from "./agent-package.js";
24
+ import { ApiError } from "./errors.js";
25
+ import { sendHostedAsset, sendHostedSharePage } from "./page.js";
26
+ import { readCapped } from "./push-handler.js";
27
+ import { EXPORT_CAPS, SHARE_FORMAT, SHARE_RUN_FIELDS } from "./run-export.js";
28
+ import { RESTORABLE, SCRUB_RULES, scrub } from "./secret-cut.js";
29
+ import { effectContext } from "./share-context.js";
30
+ import { isObject, stable } from "./validate.js";
31
+ export { SHARE_HOST_CSP } from "./page.js";
32
+ /** Where everything a share host serves lives. */
33
+ export const SHARE_ROOT = "/r/";
34
+ /** The share host's API. */
35
+ export const SHARE_API = "/r/v2/";
36
+ /** The most shares one token keeps: a delete makes room. No share expires. */
37
+ export const SHARE_QUOTA = 100;
38
+ /** The most reads one upload's per-string scrub makes, a distinct string once per context it stands under (a file's
39
+ * path, a call's command): each is a scrub of its own (about 0.1 ms), so past it the upload is 413 before any is read.
40
+ * With the body's cap it bounds what one upload asks of the scrubber: the whole body once, and at most this many reads,
41
+ * each of a string with a place of its own in the body, so together no more than the body; each context's command is
42
+ * read once (screenShare). */
43
+ export const SHARE_STRINGS = 50_000;
44
+ /** The rule ids of Jev's cuts (Scrubber beta 3; "jev" until its id is fixed). A share host never runs Jev (it holds no
45
+ * model key), so a restored record of one names a value the host can't find: it is not checked, and counted in the
46
+ * answer, never refused. The value itself is scrubbed as every other, and a hit there needs its own record. */
47
+ export const SHARE_JEV_RULES = new Set(["jev", ...SCRUB_RULES.filter((rule) => rule.kind === "jev").map((rule) => rule.id)]);
48
+ /** The most bytes an upload's body may hold: the export's document cap, and room for nothing else. */
49
+ export const SHARE_BODY_BYTES = EXPORT_CAPS.documentBytes;
50
+ /** A share's id: 128 bits of randomness in base32 (lowercase, no padding). The URL is the capability. */
51
+ export const SHARE_ID = /^[a-z2-7]{26}$/;
52
+ /** The share host's API, by method, path and name. Nothing else under /r/v2/ is served. */
53
+ export const SHARE_HOST_ROUTES = [
54
+ { method: "GET", path: "/r/v2/health", pattern: /^\/r\/v2\/health$/, name: "getShareHealth" },
55
+ { method: "POST", path: "/r/v2/shares", pattern: /^\/r\/v2\/shares$/, name: "createShare" },
56
+ { method: "GET", path: "/r/v2/shares", pattern: /^\/r\/v2\/shares$/, name: "listShares" },
57
+ { method: "DELETE", path: "/r/v2/shares/{id}", pattern: /^\/r\/v2\/shares\/([^/]+)$/, name: "deleteShare" },
58
+ ];
59
+ const BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
60
+ /** A new share id: 16 random bytes as 26 base32 letters. */
61
+ export function newShareId() {
62
+ const bytes = randomBytes(16);
63
+ let bits = 0;
64
+ let value = 0;
65
+ let out = "";
66
+ for (const byte of bytes) {
67
+ value = (value << 8) | byte;
68
+ bits += 8;
69
+ while (bits >= 5) {
70
+ out += BASE32[(value >>> (bits - 5)) & 31];
71
+ bits -= 5;
72
+ }
73
+ }
74
+ if (bits > 0)
75
+ out += BASE32[(value << (5 - bits)) & 31];
76
+ return out;
77
+ }
78
+ // ---------- the bundle's shape
79
+ /** The bundle's keys, each one there (run-export.ts exportBundle writes every one). */
80
+ const TOP = ["agent", "cuts", "files", "format", "graph", "omitted", "restored", "rows", "run", "sha256", "source"];
81
+ const RUN_FIELDS = new Set([...SHARE_RUN_FIELDS, "imported_from"]);
82
+ const CUT_KINDS = new Set(["format", "held", "dump", "label", "personal", "jev"]);
83
+ const HEX64 = /^[0-9a-f]{64}$/;
84
+ const refuse = (why) => {
85
+ throw new ApiError("bad_request", `This is not a share bundle the host takes: ${why}.`);
86
+ };
87
+ /** A body's bytes as text, or a 400: bytes that are not UTF-8 are refused, never replaced, and a byte-order mark is kept
88
+ * (so the JSON read refuses it), so the text checked, scrubbed and stored is the bytes sent. */
89
+ const STRICT_UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
90
+ function bodyText(bytes) {
91
+ try {
92
+ return STRICT_UTF8.decode(bytes);
93
+ }
94
+ catch {
95
+ return refuse("the body is not UTF-8");
96
+ }
97
+ }
98
+ /** `value` is an object whose keys are `required` and those of `optional`, no other. */
99
+ function closed(value, at, required, optional = []) {
100
+ if (!isObject(value))
101
+ return refuse(`${at} is not an object`);
102
+ const allowed = new Set([...required, ...optional]);
103
+ for (const key of Object.keys(value))
104
+ if (!allowed.has(key))
105
+ refuse(`${at} has a field ${JSON.stringify(key.slice(0, 64))} the format does not name`);
106
+ for (const key of required)
107
+ if (!Object.hasOwn(value, key))
108
+ refuse(`${at} has no ${key}`);
109
+ return value;
110
+ }
111
+ const string = (value, at) => (typeof value === "string" ? value : refuse(`${at} is not a string`));
112
+ const count = (value, at) => (Number.isSafeInteger(value) && value >= 0 ? value : refuse(`${at} is not a whole number`));
113
+ const array = (value, at) => (Array.isArray(value) ? value : refuse(`${at} is not an array`));
114
+ /** The sha256 a bundle names: over the canonical JSON of the document without its sha256 (run-export.ts). */
115
+ const digestOf = (doc) => {
116
+ const { sha256: _named, ...rest } = doc;
117
+ return createHash("sha256").update(stable(rest)).digest("hex");
118
+ };
119
+ /** Each run field's type as the run's view serves it (the openapi Run, and the view's own fields): a string, a number
120
+ * or an object, any of them null too. The page reads them as such (a title's text, a cost's figures), so a stored
121
+ * share never breaks its own page. */
122
+ const RUN_FIELD_TYPES = {
123
+ kind: "string", status: "string", state: "string", title: "string", created_at: "string", ended_at: "string", stopped_for: "string", effort: "string",
124
+ approvals: "string", budget_refused_calls: "number", result: "object", error: "object", review: "object", cost: "object",
125
+ };
126
+ function runShape(run) {
127
+ for (const [field, type] of Object.entries(RUN_FIELD_TYPES)) {
128
+ const value = run[field];
129
+ if (value === undefined || value === null)
130
+ continue;
131
+ const ok = type === "object" ? isObject(value) : type === "number" ? Number.isFinite(value) : typeof value === "string";
132
+ if (!ok)
133
+ refuse(`run.${field} is not ${type === "object" ? "an object" : `a ${type}`} or null`);
134
+ }
135
+ }
136
+ /** A workflow run's graph as the page draws it (RunGraphView): the fields of the route's graph it reads, each of its
137
+ * type, so a stored share never breaks its own page. Other keys may stay: the scrubber reads the graph whole. */
138
+ function graphShape(value) {
139
+ if (!isObject(value))
140
+ return refuse("graph is neither null nor an object");
141
+ const objects = (items, at) => items.forEach((item, index) => isObject(item) || refuse(`${at}/${index} is not an object`));
142
+ const run = isObject(value.run) ? value.run : refuse("graph.run is not an object");
143
+ string(run.status, "graph.run.status");
144
+ if (typeof run.paused !== "boolean")
145
+ refuse("graph.run.paused is not true or false");
146
+ const flow = isObject(value.graph) ? value.graph : refuse("graph.graph is not an object");
147
+ for (const item of array(flow.nodes, "graph.graph.nodes")) {
148
+ const node = isObject(item) ? item : refuse("graph.graph.nodes holds a node that is not an object");
149
+ string(node.path, "graph.graph.nodes[].path");
150
+ string(node.kind, "graph.graph.nodes[].kind");
151
+ }
152
+ objects(array(flow.edges, "graph.graph.edges"), "graph.graph.edges");
153
+ const runs = isObject(value.nodes) ? value.nodes : refuse("graph.nodes is not an object");
154
+ for (const node of Object.values(runs))
155
+ if (!isObject(node))
156
+ refuse("graph.nodes holds a run of a node that is not an object");
157
+ objects(array(value.decisions, "graph.decisions"), "graph.decisions");
158
+ objects(array(value.effects, "graph.effects"), "graph.effects");
159
+ const totals = isObject(value.totals) ? value.totals : refuse("graph.totals is not an object");
160
+ count(totals.decisions, "graph.totals.decisions");
161
+ count(totals.effects, "graph.totals.effects");
162
+ }
163
+ /** `text` read as a share bundle the host takes, or a 400 that says why (never quoting a value of it): canonical JSON (the
164
+ * bytes the export writes: what is hashed, scanned and stored is one text), `agentrun.share/1`, the export's closed keys
165
+ * at every level it fixes (the run's allowlist, agent, source, files, omitted, cuts, restored; rows and the graph are
166
+ * the served shapes, read by the scrubber whole), its caps on files, each file's size and digest, and the document's
167
+ * sha256. */
168
+ export function checkShareBundle(text) {
169
+ let doc;
170
+ try {
171
+ doc = JSON.parse(text);
172
+ }
173
+ catch {
174
+ return refuse("the body is not JSON");
175
+ }
176
+ const top = closed(doc, "the bundle", TOP);
177
+ if (top.format !== SHARE_FORMAT)
178
+ refuse(`its format is not ${SHARE_FORMAT}`);
179
+ if (stable(doc) !== text)
180
+ refuse("the body is not canonical JSON (keys sorted, no whitespace), as the export writes it");
181
+ const source = closed(top.source, "source", ["agentrun", "scrubber"]);
182
+ string(source.agentrun, "source.agentrun");
183
+ const scrubber = closed(source.scrubber, "source.scrubber", ["version", "rules"]);
184
+ count(scrubber.version, "source.scrubber.version");
185
+ string(scrubber.rules, "source.scrubber.rules");
186
+ const agent = closed(top.agent, "agent", ["name", "kind"]);
187
+ string(agent.name, "agent.name");
188
+ string(agent.kind, "agent.kind");
189
+ const run = closed(top.run, "run", [], [...RUN_FIELDS]);
190
+ runShape(run);
191
+ if (run.imported_from !== undefined && run.imported_from !== null)
192
+ string(closed(run.imported_from, "run.imported_from", ["source"]).source, "run.imported_from.source");
193
+ array(top.rows, "rows");
194
+ if (top.graph !== null)
195
+ graphShape(top.graph);
196
+ const files = array(top.files, "files");
197
+ if (files.length > EXPORT_CAPS.files)
198
+ refuse(`it carries more than ${EXPORT_CAPS.files} files`);
199
+ let total = 0;
200
+ for (const [index, entry] of files.entries()) {
201
+ const at = `files/${index}`;
202
+ const file = closed(entry, at, ["path", "bytes", "sha256", "encoding", "content"]);
203
+ const path = string(file.path, `${at}.path`);
204
+ const content = string(file.content, `${at}.content`);
205
+ if (file.encoding !== "utf8")
206
+ refuse(`${at} is not utf8 text`);
207
+ const bytes = Buffer.byteLength(content);
208
+ if (bytes > EXPORT_CAPS.fileBytes)
209
+ refuse(`${at} is over ${EXPORT_CAPS.fileBytes} bytes`);
210
+ total += bytes;
211
+ if (count(file.bytes, `${at}.bytes`) !== bytes)
212
+ refuse(`${at}.bytes is not its content's size`);
213
+ if (file.sha256 !== packageSha256([{ path, encoding: "utf8", content }]))
214
+ refuse(`${at}.sha256 is not its digest`);
215
+ }
216
+ if (total > EXPORT_CAPS.filesBytes)
217
+ refuse(`its files are over ${EXPORT_CAPS.filesBytes} bytes in all`);
218
+ for (const [index, entry] of array(top.omitted, "omitted").entries()) {
219
+ const item = closed(entry, `omitted/${index}`, ["what", "why"], ["path"]);
220
+ string(item.what, `omitted/${index}.what`);
221
+ string(item.why, `omitted/${index}.why`);
222
+ if (item.path !== undefined)
223
+ string(item.path, `omitted/${index}.path`);
224
+ }
225
+ const record = (entry, at, extra) => {
226
+ const cut = closed(entry, at, ["id", "at", "start", "end", "rule", "kind", ...extra]);
227
+ for (const field of ["id", "at", "rule"])
228
+ string(cut[field], `${at}.${field}`);
229
+ count(cut.start, `${at}.start`);
230
+ count(cut.end, `${at}.end`);
231
+ if (!CUT_KINDS.has(String(cut.kind)))
232
+ refuse(`${at}.kind is not a cut's kind`);
233
+ return cut;
234
+ };
235
+ for (const [index, entry] of array(top.cuts, "cuts").entries()) {
236
+ const cut = record(entry, `cuts/${index}`, ["restorable", "shape"]);
237
+ if (typeof cut.restorable !== "boolean")
238
+ refuse(`cuts/${index}.restorable is not a boolean`);
239
+ string(cut.shape, `cuts/${index}.shape`);
240
+ }
241
+ for (const [index, entry] of array(top.restored, "restored").entries())
242
+ record(entry, `restored/${index}`, []);
243
+ const named = string(top.sha256, "sha256");
244
+ if (!HEX64.test(named) || named !== digestOf(top))
245
+ refuse("its sha256 is not the digest of its content");
246
+ return { sha256: named };
247
+ }
248
+ /** Where a restored value may stand: a string of the run the export cut (run-export.ts), never the bundle's own words
249
+ * (its format, source, cuts, restored or sha256). */
250
+ const RESTORED_AT = /^\/(?:agent|run|rows|graph|omitted)\/|^\/files\/\d+\/(?:path|content)$/;
251
+ /** A rule id a refusal may name: the scrubber's own; anything else a record says is "unknown". */
252
+ const RULE_IDS = new Set([...SCRUB_RULES.map((rule) => rule.id), ...SHARE_JEV_RULES]);
253
+ /** Whether a cut of `kind` may be restored: the scrubber's table for the kind alone, never a record's or a cut's word. */
254
+ const restorable = (kind) => typeof kind === "string" && Object.hasOwn(RESTORABLE, kind) && RESTORABLE[kind];
255
+ const pointer = (key) => key.replaceAll("~", "~0").replaceAll("/", "~1");
256
+ const bump = (counts, rule) => void (counts[rule] = (counts[rule] ?? 0) + 1);
257
+ /** `doc` written as stable() writes it, and every string value's place in that text, in the order of the text. */
258
+ function placesOf(doc) {
259
+ const parts = [];
260
+ const places = [];
261
+ let length = 0;
262
+ const put = (text) => void (parts.push(text), (length += text.length));
263
+ const walk = (value, at) => {
264
+ if (typeof value === "string") {
265
+ const encoded = JSON.stringify(value);
266
+ places.push({ at, value, from: length + 1, to: length + encoded.length - 1 });
267
+ put(encoded);
268
+ }
269
+ else if (Array.isArray(value)) {
270
+ put("[");
271
+ value.forEach((item, index) => (index && put(","), walk(item, `${at}/${index}`)));
272
+ put("]");
273
+ }
274
+ else if (isObject(value)) {
275
+ put("{");
276
+ Object.keys(value).sort().forEach((key, index) => (index && put(","), put(`${JSON.stringify(key)}:`), walk(value[key], `${at}/${pointer(key)}`)));
277
+ put("}");
278
+ }
279
+ else
280
+ put(JSON.stringify(value));
281
+ };
282
+ walk(doc, "");
283
+ return { text: parts.join(""), places };
284
+ }
285
+ /** A file's content's pointer in a bundle: its index is group 1. */
286
+ const FILE_CONTENT_AT = /^\/files\/(\d{1,6})\/content$/;
287
+ /** A workflow call's output in a bundle (graph.effects[i].output), or a string inside it: the effect's index is group 1. */
288
+ const EFFECT_OUTPUT_AT = /^\/graph\/effects\/(\d{1,6})\/output(?:\/|$)/;
289
+ /** For each index 0..value.length of `value`, its offset in JSON.stringify(value) less the opening quote. */
290
+ function encodedOffsets(value) {
291
+ const offsets = [0];
292
+ let at = 0;
293
+ for (let index = 0; index < value.length;) {
294
+ const code = value.charCodeAt(index);
295
+ const pair = code >= 0xd800 && code <= 0xdbff && (value.charCodeAt(index + 1) & 0xfc00) === 0xdc00;
296
+ if (pair)
297
+ offsets.push(at + 1); // a valid pair is written as itself, two units
298
+ at += JSON.stringify(value.slice(index, index + (pair ? 2 : 1))).length - 2;
299
+ offsets.push(at);
300
+ index += pair ? 2 : 1;
301
+ }
302
+ return offsets;
303
+ }
304
+ /** The scrubber over a bundle as a host reads it, refusing (422, counts by rule id, never a value or where) unless every
305
+ * value it finds is a declared restore.
306
+ *
307
+ * Strict at its core: the scrubber in cut mode with `held` over the whole body, and again over every string value alone
308
+ * (as the export cut them: each at its pointer, so a value a string's own context gives away is found though its JSON
309
+ * escaping hides it from the whole-body read). A scrub that fails or throws is `scrub_failed`. The one exception is a
310
+ * filter over those hits: a hit of one string is excused when the scrubber's table says its kind restores (label,
311
+ * personal, jev; never format, held or dump) AND one `restored` record names it exactly (at, rule, start, end); a hit of
312
+ * the whole body is excused when it lies in one string and overlaps an excused hit there of its rule. Any hit left is
313
+ * `scrub_found`; a `restored` record that excuses no hit (a stale or edited bundle) is `restored_unmatched`, unless its
314
+ * rule is Jev's (SHARE_JEV_RULES), which the host never runs: that one is counted in `unchecked`, by rule, and taken.
315
+ * The kind a record says is never read. More than `strings` reads (each distinct string once per context it stands
316
+ * under) is 413 before any scrub. The cut text is
317
+ * never used: the host stores what was sent or nothing. */
318
+ export async function screenShare(text, held, cutPass = (body, opts) => scrub(body, opts), strings = SHARE_STRINGS) {
319
+ const failed = () => new ApiError("input_invalid", "The share host's scrub of this bundle failed, so it is refused (the scrub fails closed). Nothing was stored.", { details: { reason: "scrub_failed" } });
320
+ const pass = async (body, context) => {
321
+ let result;
322
+ try {
323
+ result = await cutPass(body, { mode: "cut", held, ...(context?.path !== undefined ? { path: context.path } : {}), ...(context?.command !== undefined ? { command: context.command } : {}), ...(context?.flattened ? { flattened: true } : {}) });
324
+ }
325
+ catch {
326
+ throw failed();
327
+ }
328
+ if (!result.ok)
329
+ throw failed();
330
+ return result.cuts;
331
+ };
332
+ const doc = JSON.parse(text);
333
+ const { text: rebuilt, places } = placesOf(doc);
334
+ // Every string value alone, read with the context the export cut it with (run-export.ts): a file's content knowing its
335
+ // path, and every string in a workflow call's output knowing that call's tool and input (share-context.ts
336
+ // effectContext), so a .pgpass's or a .env's plain contents are a dump. A Timeline row's output is read with none: its
337
+ // call's context comes from the run's calls, which no bundle carries. Each context is made once, for its file or call,
338
+ // and named by a small id: a read is keyed by that id and its text, never by the context's own text (a call's command
339
+ // can be megabytes, and its output thousands of strings). A text is read once per context it stands under, and those
340
+ // reads are what the cap counts: more than `strings` is 413 before any scrub. The run's title is read as the export cut
341
+ // it (run-export.ts): lines flattened onto one, so a transcript's env command and its output there is a dump.
342
+ const files = Array.isArray(doc.files) ? doc.files : [];
343
+ const effects = isObject(doc.graph) && Array.isArray(doc.graph.effects) ? doc.graph.effects : [];
344
+ const contexts = [undefined, { flattened: true }]; // id 0: no context; id 1: the run's title
345
+ const ids = new Map(); // a context's id by its path and command, interned once per file or call
346
+ const idOfPlace = new Map(); // "f<index>" or "e<index>": its context's id
347
+ const intern = (context) => {
348
+ if (context?.path === undefined && context?.command === undefined)
349
+ return 0;
350
+ const name = JSON.stringify([context.path ?? null, context.command ?? null]);
351
+ let id = ids.get(name);
352
+ if (id === undefined)
353
+ ids.set(name, (id = contexts.push(context) - 1));
354
+ return id;
355
+ };
356
+ const contextIdOf = (at) => {
357
+ if (at === "/run/title")
358
+ return 1;
359
+ const fileIndex = FILE_CONTENT_AT.exec(at)?.[1];
360
+ const effectIndex = fileIndex === undefined ? EFFECT_OUTPUT_AT.exec(at)?.[1] : undefined;
361
+ if (fileIndex === undefined && effectIndex === undefined)
362
+ return 0;
363
+ const owner = fileIndex !== undefined ? `f${fileIndex}` : `e${effectIndex}`;
364
+ let id = idOfPlace.get(owner);
365
+ if (id === undefined) {
366
+ const file = fileIndex !== undefined ? files[Number(fileIndex)] : undefined;
367
+ const context = fileIndex !== undefined ? (isObject(file) && typeof file.path === "string" ? { path: file.path } : undefined) : effectContext(effects[Number(effectIndex)]);
368
+ idOfPlace.set(owner, (id = intern(context)));
369
+ }
370
+ return id;
371
+ };
372
+ // Each context's texts (every one of them read once), in the order first seen.
373
+ const reads = new Map();
374
+ const placeIds = [];
375
+ let distinct = 0;
376
+ for (const place of places) {
377
+ const id = place.value ? contextIdOf(place.at) : 0;
378
+ placeIds.push(id);
379
+ if (!place.value)
380
+ continue;
381
+ let texts = reads.get(id);
382
+ if (!texts)
383
+ reads.set(id, (texts = new Map()));
384
+ if (!texts.has(place.value)) {
385
+ texts.set(place.value, undefined);
386
+ distinct++;
387
+ }
388
+ }
389
+ if (distinct > strings)
390
+ throw new ApiError("payload_too_large", `This bundle holds ${distinct} distinct strings (a text under two calls' contexts counted twice), over the ${strings} a share host scrubs one by one, so it is refused before any is read. Nothing was stored.`, { details: { reason: "share_strings", limit: strings, strings: distinct } });
391
+ const whole = await pass(text);
392
+ // A context's texts read together, so the scrubber reads that context's command once for them all (secret-rules.ts
393
+ // factsOf).
394
+ for (const [id, texts] of reads)
395
+ for (const value of texts.keys())
396
+ texts.set(value, await pass(value, contexts[id]));
397
+ const hits = new Map();
398
+ const hitsAt = new Map();
399
+ const key = (at, rule, start, end) => JSON.stringify([at, rule, start, end]);
400
+ for (const [index, place] of places.entries()) {
401
+ if (!place.value)
402
+ continue;
403
+ for (const cut of reads.get(placeIds[index]).get(place.value)) {
404
+ const hit = { at: place.at, rule: cut.rule, restorable: restorable(cut.kind), start: cut.start, end: cut.end };
405
+ hits.set(key(hit.at, hit.rule, hit.start, hit.end), hit);
406
+ const at = hitsAt.get(place.at);
407
+ if (at)
408
+ at.push(hit);
409
+ else
410
+ hitsAt.set(place.at, [hit]);
411
+ }
412
+ }
413
+ // The exception: each restored record excuses the one restorable hit it names exactly, once.
414
+ const excused = new Set();
415
+ const unmatched = {};
416
+ const unchecked = {};
417
+ for (const entry of Array.isArray(doc.restored) ? doc.restored : []) {
418
+ const record = isObject(entry) ? entry : {};
419
+ const hit = typeof record.at === "string" && RESTORED_AT.test(record.at) ? hits.get(key(record.at, record.rule, record.start, record.end)) : undefined;
420
+ if (hit && hit.restorable && !excused.has(hit))
421
+ excused.add(hit);
422
+ else if (typeof record.rule === "string" && SHARE_JEV_RULES.has(record.rule))
423
+ bump(unchecked, record.rule);
424
+ else
425
+ bump(unmatched, typeof record.rule === "string" && RULE_IDS.has(record.rule) ? record.rule : "unknown");
426
+ }
427
+ const found = {};
428
+ for (const hit of hits.values())
429
+ if (!excused.has(hit))
430
+ bump(found, hit.rule);
431
+ const wholeFound = {};
432
+ const starts = places.map((place) => place.from);
433
+ // Each string's offsets once, however many of the whole body's finds fall in it.
434
+ const offsetsOf = new Map();
435
+ const offsetsIn = (place) => {
436
+ let offsets = offsetsOf.get(place);
437
+ if (!offsets)
438
+ offsetsOf.set(place, (offsets = encodedOffsets(place.value)));
439
+ return offsets;
440
+ };
441
+ for (const cut of whole) {
442
+ const place = rebuilt === text ? places[upperBound(starts, cut.start) - 1] : undefined;
443
+ const inside = place !== undefined && cut.start >= place.from && cut.end <= place.to;
444
+ const offsets = inside && restorable(cut.kind) ? offsetsIn(place) : undefined;
445
+ const covered = offsets !== undefined && (hitsAt.get(place.at) ?? []).some((hit) => excused.has(hit) && hit.rule === cut.rule && place.from + offsets[hit.start] < cut.end && cut.start < place.from + offsets[hit.end]);
446
+ if (!covered)
447
+ bump(wholeFound, cut.rule);
448
+ }
449
+ // A value both reads find is one value: each rule's count is the larger read's.
450
+ for (const [rule, n] of Object.entries(wholeFound))
451
+ found[rule] = Math.max(found[rule] ?? 0, n);
452
+ const words = (counts) => Object.entries(counts).map(([rule, n]) => `${rule} ${n}`).join(", ");
453
+ const total = (counts) => Object.values(counts).reduce((sum, n) => sum + n, 0);
454
+ if (total(found) > 0) {
455
+ const n = total(found);
456
+ throw new ApiError("input_invalid", `The share host's scrub found ${n} value${n === 1 ? "" : "s"} in this bundle that no restore declares (by rule: ${words(found)}), so it is refused. A restore keeps a label, personal or jev cut, never a known key format, a held value or a dump. Nothing was stored; export the run again with the cuts in place.`, { details: { reason: "scrub_found", counts: found, ...(total(unmatched) ? { unmatched } : {}), ...(total(unchecked) ? { unchecked } : {}) } });
457
+ }
458
+ if (total(unmatched) > 0) {
459
+ const n = total(unmatched);
460
+ throw new ApiError("input_invalid", `${n} restored record${n === 1 ? "" : "s"} of this bundle name${n === 1 ? "s" : ""} no value the share host's scrub finds there (by rule: ${words(unmatched)}): a stale or edited bundle, so it is refused. Nothing was stored; export the run again.`, { details: { reason: "restored_unmatched", counts: unmatched, ...(total(unchecked) ? { unchecked } : {}) } });
461
+ }
462
+ return { unchecked };
463
+ }
464
+ /** The number of sorted `values` at or below `at`. */
465
+ function upperBound(values, at) {
466
+ let low = 0;
467
+ let high = values.length;
468
+ while (low < high) {
469
+ const mid = (low + high) >>> 1;
470
+ if (values[mid] <= at)
471
+ low = mid + 1;
472
+ else
473
+ high = mid;
474
+ }
475
+ return low;
476
+ }
477
+ /** The shares of one host, in files under `dir`, written to a temp file and renamed, 0600 in 0700 folders. Kept in
478
+ * memory once read: this process is the folder's one writer. */
479
+ export class ShareStore {
480
+ dir;
481
+ index;
482
+ queue = Promise.resolve();
483
+ constructor(dir) {
484
+ this.dir = dir;
485
+ }
486
+ all() {
487
+ return (this.index ??= (async () => {
488
+ const found = new Map();
489
+ const names = await readdir(this.dir).catch((error) => (error.code === "ENOENT" ? [] : Promise.reject(error)));
490
+ for (const name of names) {
491
+ if (!SHARE_ID.test(name))
492
+ continue;
493
+ const folder = join(this.dir, name);
494
+ const meta = await readFile(join(folder, "meta.json"), "utf8").then((text) => JSON.parse(text), (error) => (error.code === "ENOENT" ? null : undefined));
495
+ // No meta: a create that stopped between the bytes and the meta (both are renamed in whole), bytes nothing names.
496
+ if (meta === null)
497
+ await rm(folder, { recursive: true, force: true });
498
+ if (!meta || meta.id !== name)
499
+ continue;
500
+ found.set(name, meta);
501
+ // A delete that stopped after its tombstone: its bytes go now.
502
+ if (meta.deleted_at)
503
+ await rm(join(folder, "bundle.json"), { force: true });
504
+ }
505
+ return found;
506
+ })().catch((error) => {
507
+ this.index = undefined;
508
+ throw error;
509
+ }));
510
+ }
511
+ /** One write at a time: a quota is read and a share made in one step. */
512
+ serial(work) {
513
+ const next = this.queue.then(work, work);
514
+ this.queue = next.catch(() => undefined);
515
+ return next;
516
+ }
517
+ async get(id) {
518
+ return SHARE_ID.test(id) ? (await this.all()).get(id) : undefined;
519
+ }
520
+ /** The live shares `tokenId` made, oldest first. */
521
+ async list(tokenId) {
522
+ return [...(await this.all()).values()].filter((meta) => meta.token_id === tokenId && !meta.deleted_at).sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id));
523
+ }
524
+ /** A 403 when `tokenId` keeps its quota of shares already. */
525
+ async roomFor(tokenId, quota) {
526
+ const used = (await this.list(tokenId)).length;
527
+ if (used >= quota)
528
+ throw new ApiError("forbidden", `This token keeps ${used} shares, its most (${quota}). Delete one (DELETE /r/v2/shares/<id>) to make room.`, { details: { reason: "share_quota", limit: quota, used } });
529
+ }
530
+ /** Stores `body` as a new share of `tokenId`, the quota checked again inside the write. */
531
+ create(tokenId, body, sha256, quota) {
532
+ return this.serial(async () => {
533
+ await this.roomFor(tokenId, quota);
534
+ const index = await this.all();
535
+ let id = newShareId();
536
+ while (index.has(id))
537
+ id = newShareId();
538
+ const folder = join(this.dir, id);
539
+ await mkdir(this.dir, { recursive: true, mode: 0o700 });
540
+ await mkdir(folder, { mode: 0o700 });
541
+ const meta = { id, sha256, token_id: tokenId, created_at: new Date().toISOString(), bytes: Buffer.byteLength(body) };
542
+ try {
543
+ await writeAtomic(join(folder, "bundle.json"), body);
544
+ await writeAtomic(join(folder, "meta.json"), `${JSON.stringify(meta)}\n`);
545
+ }
546
+ catch (error) {
547
+ await rm(folder, { recursive: true, force: true }).catch(() => undefined);
548
+ throw error;
549
+ }
550
+ index.set(id, meta);
551
+ return meta;
552
+ });
553
+ }
554
+ /** The stored bytes of live share `id`. */
555
+ bytes(id) {
556
+ return readFile(join(this.dir, id, "bundle.json"));
557
+ }
558
+ /** Deletes share `id` of `tokenId`: its bytes go, its meta stays as the tombstone its page's 410 reads. */
559
+ delete(id, tokenId) {
560
+ return this.serial(async () => {
561
+ const meta = await this.get(id);
562
+ if (!meta)
563
+ throw new ApiError("not_found", `There is no share ${id} on this host.`);
564
+ if (meta.token_id !== tokenId)
565
+ throw new ApiError("forbidden", `The share ${id} was made with another token; only that token deletes it.`);
566
+ if (!meta.deleted_at) {
567
+ const gone = { ...meta, deleted_at: new Date().toISOString() };
568
+ await writeAtomic(join(this.dir, id, "meta.json"), `${JSON.stringify(gone)}\n`);
569
+ (await this.all()).set(id, gone);
570
+ }
571
+ // Again on a deleted share: a removal an earlier delete never finished (it failed, or the process stopped).
572
+ await rm(join(this.dir, id, "bundle.json"), { force: true });
573
+ });
574
+ }
575
+ }
576
+ async function writeAtomic(file, text) {
577
+ const temp = `${file}.${randomBytes(6).toString("hex")}.tmp`;
578
+ await writeFile(temp, text, { mode: 0o600, flag: "wx" });
579
+ await rename(temp, file);
580
+ }
581
+ const json = (res, status, body) => {
582
+ const bytes = Buffer.from(JSON.stringify(body));
583
+ res.writeHead(status, { "content-type": "application/json", "content-length": bytes.length, "cache-control": "no-store", "x-content-type-options": "nosniff" });
584
+ res.end(res.req?.method === "HEAD" ? undefined : bytes);
585
+ };
586
+ const notFound = (raw) => new ApiError("not_found", `${raw} is not served here: a share host serves /r/<id>, /r/<id>/bundle.json, /r/_assets/ and /r/v2/ alone.`);
587
+ const allow = (methods) => new ApiError("method_not_allowed", `this address answers ${methods}`, {}, { allow: methods });
588
+ /** The share host's answer to every request, under /r/ or not: `fail` renders a refusal (server.ts's envelope). */
589
+ export function shareHost(deps) {
590
+ const store = new ShareStore(join(deps.data, "shares"));
591
+ const quota = deps.quota ?? SHARE_QUOTA;
592
+ const urlOf = (id) => `${deps.origin().replace(/\/+$/, "")}${SHARE_ROOT}${id}`;
593
+ const view = (meta) => ({ id: meta.id, url: urlOf(meta.id), sha256: meta.sha256, created_at: meta.created_at, bytes: meta.bytes });
594
+ const tokenOf = (req, route) => {
595
+ const id = deps.who(req);
596
+ if (id !== undefined)
597
+ return id;
598
+ deps.authFailed?.(route, req.headers.authorization === undefined ? "no_token" : "wrong_token");
599
+ throw new ApiError("unauthenticated", "the share host's API takes one of its tokens as a Bearer header");
600
+ };
601
+ /** A share for its page or bytes: live, else 410 for a deleted one, 404 for none. */
602
+ const live = async (id, raw) => {
603
+ const meta = await store.get(id);
604
+ if (!meta)
605
+ throw notFound(raw);
606
+ if (meta.deleted_at)
607
+ throw new ApiError("purged", `The share ${id} was deleted by its owner.`, { details: { deleted_at: meta.deleted_at } });
608
+ return meta;
609
+ };
610
+ return async (req, res, raw) => {
611
+ if (!raw.startsWith(SHARE_ROOT))
612
+ throw notFound(raw);
613
+ const method = req.method === "HEAD" ? "GET" : req.method;
614
+ if (raw.startsWith(SHARE_API)) {
615
+ const route = SHARE_HOST_ROUTES.filter((entry) => entry.pattern.test(raw));
616
+ if (route.length === 0)
617
+ throw notFound(raw);
618
+ const found = route.find((entry) => entry.method === method);
619
+ if (!found)
620
+ throw allow(route.map((entry) => entry.method).join(", "));
621
+ if (found.name === "getShareHealth")
622
+ return json(res, 200, { status: "ok", share_host: true, version: deps.version });
623
+ const tokenId = tokenOf(req, raw);
624
+ if (found.name === "listShares") {
625
+ const mine = await store.list(tokenId);
626
+ return json(res, 200, { shares: mine.map(view), quota: { limit: quota, used: mine.length } });
627
+ }
628
+ if (found.name === "deleteShare") {
629
+ const id = found.pattern.exec(raw)[1];
630
+ if (!SHARE_ID.test(id))
631
+ throw new ApiError("not_found", "There is no such share on this host.");
632
+ await store.delete(id, tokenId);
633
+ res.writeHead(204, { "cache-control": "no-store" });
634
+ return void res.end();
635
+ }
636
+ // createShare: the quota before the body is read, and again as the share is made.
637
+ await store.roomFor(tokenId, quota);
638
+ if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json"))
639
+ throw new ApiError("unsupported_media_type", "a share's body is its bundle, application/json");
640
+ const text = bodyText(await readCapped(req, SHARE_BODY_BYTES));
641
+ const { sha256 } = checkShareBundle(text);
642
+ const { unchecked } = await screenShare(text, deps.held(), deps.scrub, deps.strings);
643
+ const meta = await store.create(tokenId, text, sha256, quota);
644
+ // Restores of Jev's cuts the host took unchecked (it never runs Jev), by rule, when there are any.
645
+ return json(res, 201, { id: meta.id, url: urlOf(meta.id), sha256: meta.sha256, ...(Object.keys(unchecked).length ? { restored_unchecked: unchecked } : {}) });
646
+ }
647
+ const rest = raw.slice(SHARE_ROOT.length);
648
+ if (method !== "GET")
649
+ throw allow("GET, HEAD");
650
+ if (rest.startsWith("_assets/"))
651
+ return sendHostedAsset(req, res, raw, deps.console, rest.slice("_assets/".length));
652
+ const page = /^([^/]+)\/?$/.exec(rest);
653
+ const bytes = /^([^/]+)\/bundle\.json$/.exec(rest);
654
+ const id = (page ?? bytes)?.[1];
655
+ if (id === undefined || !SHARE_ID.test(id))
656
+ throw notFound(raw);
657
+ await live(id, raw);
658
+ if (page)
659
+ return sendHostedSharePage(req, res, deps.console);
660
+ const body = await store.bytes(id).catch(() => undefined);
661
+ if (body === undefined)
662
+ throw notFound(raw);
663
+ res.writeHead(200, {
664
+ "content-type": "application/json; charset=utf-8", "content-length": body.length, "x-content-type-options": "nosniff", "x-robots-tag": "noindex",
665
+ "content-security-policy": "default-src 'none'; frame-ancestors 'none'; sandbox", "referrer-policy": "no-referrer", "cache-control": "no-store",
666
+ });
667
+ res.end(req.method === "HEAD" ? undefined : body);
668
+ };
669
+ }