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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (273) hide show
  1. package/CHANGELOG.md +748 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +2190 -2
  5. package/dist/adapters.d.ts +234 -0
  6. package/dist/adapters.js +585 -0
  7. package/dist/agents.d.ts +130 -0
  8. package/dist/agents.js +308 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +384 -0
  11. package/dist/background.d.ts +28 -0
  12. package/dist/background.js +376 -0
  13. package/dist/bound-files.d.ts +4 -0
  14. package/dist/bound-files.js +164 -0
  15. package/dist/box/record.d.ts +6 -0
  16. package/dist/box/record.js +41 -0
  17. package/dist/box/sweep.d.ts +53 -0
  18. package/dist/box/sweep.js +193 -0
  19. package/dist/box-egress.d.ts +98 -0
  20. package/dist/box-egress.js +259 -0
  21. package/dist/box-image.d.ts +98 -0
  22. package/dist/box-image.js +285 -0
  23. package/dist/box-relay-vm.d.ts +80 -0
  24. package/dist/box-relay-vm.js +389 -0
  25. package/dist/box-relay.d.ts +45 -0
  26. package/dist/box-relay.js +227 -0
  27. package/dist/boxes.d.ts +72 -0
  28. package/dist/boxes.js +189 -0
  29. package/dist/browser-cost.d.ts +41 -0
  30. package/dist/browser-cost.js +158 -0
  31. package/dist/cap.d.ts +332 -0
  32. package/dist/cap.js +992 -0
  33. package/dist/catalog.d.ts +20 -0
  34. package/dist/catalog.js +53 -0
  35. package/dist/cli.d.ts +2 -0
  36. package/dist/cli.js +167 -0
  37. package/dist/coding-tools.d.ts +35 -0
  38. package/dist/coding-tools.js +87 -0
  39. package/dist/console/THIRD-PARTY-NOTICES.txt +1721 -0
  40. package/dist/console/assets/index-34jfpIbQ.js +481 -0
  41. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  42. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  53. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  54. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  57. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  58. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  59. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  60. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  61. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  62. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  63. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  64. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  65. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  66. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  67. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  68. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  69. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  70. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  71. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  72. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  73. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  74. package/dist/console/index.html +15 -0
  75. package/dist/content-filter.d.ts +7 -0
  76. package/dist/content-filter.js +23 -0
  77. package/dist/daytona-api.d.ts +21 -0
  78. package/dist/daytona-api.js +101 -0
  79. package/dist/decision-rows.d.ts +19 -0
  80. package/dist/decision-rows.js +123 -0
  81. package/dist/decisions.d.ts +94 -0
  82. package/dist/decisions.js +184 -0
  83. package/dist/effort-guidance.d.ts +5 -0
  84. package/dist/effort-guidance.js +14 -0
  85. package/dist/environment.d.ts +5 -0
  86. package/dist/environment.js +11 -0
  87. package/dist/errors.d.ts +74 -0
  88. package/dist/errors.js +69 -0
  89. package/dist/exa-keyless.d.ts +35 -0
  90. package/dist/exa-keyless.js +202 -0
  91. package/dist/fetch-page.d.ts +114 -0
  92. package/dist/fetch-page.js +182 -0
  93. package/dist/files.d.ts +65 -0
  94. package/dist/files.js +158 -0
  95. package/dist/grade.d.ts +93 -0
  96. package/dist/grade.js +328 -0
  97. package/dist/graph-served.d.ts +23 -0
  98. package/dist/graph-served.js +75 -0
  99. package/dist/graph-view.d.ts +102 -0
  100. package/dist/graph-view.js +219 -0
  101. package/dist/harness-app.d.ts +40 -0
  102. package/dist/harness-app.js +708 -0
  103. package/dist/harness-opencode/adapter.d.ts +45 -0
  104. package/dist/harness-opencode/adapter.js +272 -0
  105. package/dist/harness-opencode/binary.d.ts +18 -0
  106. package/dist/harness-opencode/binary.js +87 -0
  107. package/dist/harness-opencode/config.d.ts +24 -0
  108. package/dist/harness-opencode/config.js +61 -0
  109. package/dist/harness-opencode/harness.d.ts +77 -0
  110. package/dist/harness-opencode/harness.js +620 -0
  111. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  112. package/dist/harness-opencode/host/mcp.js +208 -0
  113. package/dist/harness-opencode/host/policy.d.ts +71 -0
  114. package/dist/harness-opencode/host/policy.js +419 -0
  115. package/dist/harness-opencode/host/server.d.ts +55 -0
  116. package/dist/harness-opencode/host/server.js +165 -0
  117. package/dist/harness-opencode/index.d.ts +9 -0
  118. package/dist/harness-opencode/index.js +6 -0
  119. package/dist/harness-opencode/verify.d.ts +32 -0
  120. package/dist/harness-opencode/verify.js +75 -0
  121. package/dist/harness-opencode/versions.d.ts +33 -0
  122. package/dist/harness-opencode/versions.js +64 -0
  123. package/dist/harness.d.ts +56 -0
  124. package/dist/harness.js +77 -0
  125. package/dist/home-path.d.ts +27 -0
  126. package/dist/home-path.js +78 -0
  127. package/dist/host-tools.d.ts +30 -0
  128. package/dist/host-tools.js +154 -0
  129. package/dist/host.d.ts +39 -0
  130. package/dist/host.js +85 -0
  131. package/dist/hosted-search.d.ts +27 -0
  132. package/dist/hosted-search.js +133 -0
  133. package/dist/import-sources.d.ts +104 -0
  134. package/dist/import-sources.js +629 -0
  135. package/dist/import-summary.d.ts +25 -0
  136. package/dist/import-summary.js +75 -0
  137. package/dist/import-worker.d.ts +26 -0
  138. package/dist/import-worker.js +41 -0
  139. package/dist/import.d.ts +145 -0
  140. package/dist/import.js +1222 -0
  141. package/dist/index.d.ts +7 -0
  142. package/dist/index.js +6 -0
  143. package/dist/key-check.d.ts +37 -0
  144. package/dist/key-check.js +112 -0
  145. package/dist/key-refusal.d.ts +51 -0
  146. package/dist/key-refusal.js +191 -0
  147. package/dist/learn/check.d.ts +108 -0
  148. package/dist/learn/check.js +277 -0
  149. package/dist/learn/grade.d.ts +80 -0
  150. package/dist/learn/grade.js +445 -0
  151. package/dist/learn/index.d.ts +7 -0
  152. package/dist/learn/index.js +11 -0
  153. package/dist/learn/invisible.d.ts +5 -0
  154. package/dist/learn/invisible.js +42 -0
  155. package/dist/learn/notes.d.ts +59 -0
  156. package/dist/learn/notes.js +147 -0
  157. package/dist/learn/reflect.d.ts +49 -0
  158. package/dist/learn/reflect.js +213 -0
  159. package/dist/learn/secrets.d.ts +18 -0
  160. package/dist/learn/secrets.js +131 -0
  161. package/dist/learn/skills.d.ts +97 -0
  162. package/dist/learn/skills.js +271 -0
  163. package/dist/learned-workflow.d.ts +59 -0
  164. package/dist/learned-workflow.js +191 -0
  165. package/dist/learning-routes.d.ts +196 -0
  166. package/dist/learning-routes.js +609 -0
  167. package/dist/learning-run.d.ts +306 -0
  168. package/dist/learning-run.js +819 -0
  169. package/dist/learning-words.d.ts +76 -0
  170. package/dist/learning-words.js +174 -0
  171. package/dist/learning.d.ts +418 -0
  172. package/dist/learning.js +946 -0
  173. package/dist/llm.d.ts +40 -0
  174. package/dist/llm.js +37 -0
  175. package/dist/llms.txt +37 -0
  176. package/dist/mcp-servers.d.ts +118 -0
  177. package/dist/mcp-servers.js +450 -0
  178. package/dist/mcp.d.ts +51 -0
  179. package/dist/mcp.js +392 -0
  180. package/dist/model.d.ts +186 -0
  181. package/dist/model.js +485 -0
  182. package/dist/monid.d.ts +74 -0
  183. package/dist/monid.js +277 -0
  184. package/dist/openapi/agentrun-v2.openapi.json +4806 -0
  185. package/dist/openapi.d.ts +10 -0
  186. package/dist/openapi.js +1727 -0
  187. package/dist/owner.d.ts +55 -0
  188. package/dist/owner.js +222 -0
  189. package/dist/packs.d.ts +71 -0
  190. package/dist/packs.js +180 -0
  191. package/dist/page.d.ts +32 -0
  192. package/dist/page.js +133 -0
  193. package/dist/paid-calls.d.ts +50 -0
  194. package/dist/paid-calls.js +110 -0
  195. package/dist/pause.d.ts +70 -0
  196. package/dist/pause.js +97 -0
  197. package/dist/pdf-pages.d.ts +44 -0
  198. package/dist/pdf-pages.js +147 -0
  199. package/dist/place.d.ts +69 -0
  200. package/dist/place.js +137 -0
  201. package/dist/print.d.ts +20 -0
  202. package/dist/print.js +29 -0
  203. package/dist/propose.d.ts +40 -0
  204. package/dist/propose.js +112 -0
  205. package/dist/quiet-sqlite-warning.d.ts +1 -0
  206. package/dist/quiet-sqlite-warning.js +14 -0
  207. package/dist/request-start.d.ts +22 -0
  208. package/dist/request-start.js +350 -0
  209. package/dist/result.d.ts +3 -0
  210. package/dist/result.js +5 -0
  211. package/dist/rows.d.ts +46 -0
  212. package/dist/rows.js +121 -0
  213. package/dist/run-box.d.ts +186 -0
  214. package/dist/run-box.js +590 -0
  215. package/dist/run-manifest.d.ts +27 -0
  216. package/dist/run-manifest.js +60 -0
  217. package/dist/runnable.d.ts +83 -0
  218. package/dist/runnable.js +170 -0
  219. package/dist/runs.d.ts +1062 -0
  220. package/dist/runs.js +3020 -0
  221. package/dist/secret-cut.d.ts +27 -0
  222. package/dist/secret-cut.js +109 -0
  223. package/dist/secrets.d.ts +62 -0
  224. package/dist/secrets.js +158 -0
  225. package/dist/server-lock.d.ts +44 -0
  226. package/dist/server-lock.js +140 -0
  227. package/dist/server.d.ts +722 -0
  228. package/dist/server.js +2118 -0
  229. package/dist/sessions.d.ts +4 -0
  230. package/dist/sessions.js +105 -0
  231. package/dist/sign-ins.d.ts +99 -0
  232. package/dist/sign-ins.js +288 -0
  233. package/dist/skills.d.ts +43 -0
  234. package/dist/skills.js +96 -0
  235. package/dist/stats.d.ts +106 -0
  236. package/dist/stats.js +103 -0
  237. package/dist/tool-gate.d.ts +266 -0
  238. package/dist/tool-gate.js +554 -0
  239. package/dist/tool-keys.d.ts +187 -0
  240. package/dist/tool-keys.js +315 -0
  241. package/dist/tool-plane.d.ts +228 -0
  242. package/dist/tool-plane.js +400 -0
  243. package/dist/tools.d.ts +202 -0
  244. package/dist/tools.js +372 -0
  245. package/dist/trigger-secrets.d.ts +32 -0
  246. package/dist/trigger-secrets.js +143 -0
  247. package/dist/triggers.d.ts +439 -0
  248. package/dist/triggers.js +863 -0
  249. package/dist/turn-end.d.ts +24 -0
  250. package/dist/turn-end.js +15 -0
  251. package/dist/turns.d.ts +34 -0
  252. package/dist/turns.js +202 -0
  253. package/dist/uploads.d.ts +104 -0
  254. package/dist/uploads.js +474 -0
  255. package/dist/usage-lines.d.ts +26 -0
  256. package/dist/usage-lines.js +28 -0
  257. package/dist/usage.d.ts +29 -0
  258. package/dist/usage.js +58 -0
  259. package/dist/validate.d.ts +57 -0
  260. package/dist/validate.js +184 -0
  261. package/dist/web-fetch.d.ts +64 -0
  262. package/dist/web-fetch.js +262 -0
  263. package/dist/web-search.d.ts +54 -0
  264. package/dist/web-search.js +136 -0
  265. package/dist/webhooks.d.ts +189 -0
  266. package/dist/webhooks.js +503 -0
  267. package/dist/workspace-paths.d.ts +33 -0
  268. package/dist/workspace-paths.js +104 -0
  269. package/dist/workspace.d.ts +88 -0
  270. package/dist/workspace.js +369 -0
  271. package/launcher/agentrun-serve +109 -0
  272. package/package.json +100 -4
  273. package/skills/agentrun-serve/SKILL.md +128 -0
@@ -0,0 +1,88 @@
1
+ import { type Stats } from "node:fs";
2
+ import { type FileHandle } from "node:fs/promises";
3
+ /** The types a file is served as in the page (every known type but PDF); any other is a download. */
4
+ export declare const INLINE_TYPES: ReadonlySet<string>;
5
+ /** The type of a file at `path`, by its extension; undefined for one the table does not know. */
6
+ export declare const typeOf: (path: string) => string | undefined;
7
+ /** Why a path under work/ is not read: it is missing, a link is on the way (or is the entry), it is not a regular file,
8
+ * it has another hard link, it is larger than the reader takes, or it is unreadable to this server (a tool in the box
9
+ * created it owner-only, so its access mask gives this server nothing). */
10
+ export type RefusedReason = "missing" | "link" | "not_regular" | "hard_link" | "over_cap" | "unreadable" | "unheld";
11
+ /** A path under work/ this server does not read, and why. */
12
+ export declare class WorkRefused extends Error {
13
+ readonly path: string;
14
+ readonly reason: RefusedReason;
15
+ constructor(path: string, reason: RefusedReason);
16
+ }
17
+ /** Test seams, tests only: before the walk enters a directory it listed (after its lstat, before its pin); after a
18
+ * directory is pinned and before it is read; after a directory is listed and before its entries are looked at; after a
19
+ * file is opened and checked, before the caller reads it; after a capped read's size check, before the bytes are read.
20
+ * `byPath` walks as the confinement does where there is no /proc/self/fd (macOS), on any platform. */
21
+ export declare const workspaceTestHooks: {
22
+ byPath?: boolean;
23
+ beforeEnter?: (path: string) => Promise<void> | void;
24
+ afterPin?: (path: string) => Promise<void> | void;
25
+ afterList?: (path: string) => Promise<void> | void;
26
+ afterOpen?: (path: string) => Promise<void> | void;
27
+ afterSizeCheck?: (path: string) => Promise<void> | void;
28
+ };
29
+ /** How many directories deep `walkWork` goes by default. */
30
+ export declare const WALK_DEPTH = 16;
31
+ /** Whether this process reaches a held directory handle by path through /proc/self/fd, probed once. The confinement
32
+ * walks on such handles when it does and by path when not (macOS); by path, a directory swapped for a link after the
33
+ * walk could take a write's temporary file and rename, or a removal, outside the root, and Node has no openat, so a
34
+ * write or a removal is made only where this holds. */
35
+ export declare function writesHeld(): boolean;
36
+ /** Opens `rel` under `work` for reading, held: a regular file with one link, reached through no link. Close the handle. */
37
+ export declare function openWorkFile(work: string, rel: string): Promise<{
38
+ handle: FileHandle;
39
+ stats: Stats;
40
+ }>;
41
+ /** `rel` under `work` as text, read as `openWorkFile` reads it. */
42
+ export declare function readWorkText(work: string, rel: string): Promise<string>;
43
+ /** `rel` under `work`, its bytes, read as `openWorkFile` reads it; refused ("over_cap") when larger than `maxBytes`. */
44
+ export declare function readWorkBytes(work: string, rel: string, { maxBytes }: {
45
+ maxBytes: number;
46
+ }): Promise<Buffer>;
47
+ /**
48
+ * Each regular file (with one link) and directory under `work`, by its path below it, with its own stats and whether
49
+ * this server may read it: a link is skipped and never followed, so no target's size or time is read. Each entry left out
50
+ * for what it is goes to `refused` with its reason (a link, not a regular file, another hard link), and so does a
51
+ * directory that cannot be read: its contents are unknown, never empty. work/ itself unread throws `WorkRefused` (no
52
+ * working copy). `skip` (given the name and its path below `work`) leaves it, and what is below it, out unreported;
53
+ * `visit` returning false stops the walk.
54
+ * Directories are entered down to `depth` levels.
55
+ */
56
+ export declare function walkWork(work: string, visit: (path: string, stats: Stats, readable: boolean) => boolean | void, { skip, depth, refused }?: {
57
+ skip?: (name: string, path: string) => boolean;
58
+ depth?: number;
59
+ refused?: (path: string, reason: RefusedReason) => void;
60
+ }): Promise<void>;
61
+ /**
62
+ * Writes `bytes` to `rel` under `work` whole and durably (files.ts writeDurable), as a file of `mode`: through a temporary
63
+ * file in the same directory, a dot-name of the server's own, renamed over the file. The directories on the way are made
64
+ * when missing, and each is synced into its parent before this resolves. A link on the way or at the file, or a directory
65
+ * there, is refused: never followed and never replaced. Answers the stats of the file this call wrote. `asTool`, a run's
66
+ * file tool writing a bound box's work/ (bound-files.ts): a file with another hard link is refused, a file already there
67
+ * keeps its mode, and a new one gets `mode` as given, whatever this process's umask.
68
+ */
69
+ export declare function writeWorkFile(work: string, rel: string, bytes: Uint8Array, mode?: number, asTool?: boolean): Promise<Stats>;
70
+ /** Removes the regular file `rel` under `work`, reached through no link: refused when it is missing, a link, or not a
71
+ * regular file. A directory it leaves empty stays. */
72
+ export declare function removeWorkFile(work: string, rel: string): Promise<void>;
73
+ /** Throws unless the kernel refuses a hard link to a file the linker cannot write (fs.protected_hardlinks = 1): with a
74
+ * run's commands under a uid of their own, it keeps them from linking this server's files into their workspace. */
75
+ export declare function assertHardlinkProtection(read?: () => string): void;
76
+ type Mirror = (path: string, data: string | Uint8Array) => Promise<void>;
77
+ /** In a run's process whose box is remote: each file writeInWork files below `work` is copied into the box as well, at the
78
+ * same path below its work/ (run-box.ts), so the run's tools there read what its host tools filed. */
79
+ export declare function mirrorWrites(work: string, mirror: Mirror): void;
80
+ /** Writes `data` as a new file `name` in `dirs` below a run's `work`, never through a link: a box's command can plant one
81
+ * there, and this process writes with the server's rights. Each directory is made when missing and opened without
82
+ * following a link, the next reached through the one held before it (/proc/self/fd), and the file is created, never
83
+ * replaced: a link in the way refuses the write (ELOOP, ENOTDIR or EEXIST). Where no handle is held (writesHeld: macOS
84
+ * and any host without /proc/self/fd) each step is reached by its path, which a link swapped in between two steps could
85
+ * turn: there a run whose place is a box gets no write (ENOTSUP), and a runner run, whose tools make no link, still
86
+ * writes by path. */
87
+ export declare function writeInWork(work: string, dirs: readonly string[], name: string, data: string | Uint8Array): Promise<void>;
88
+ export {};
@@ -0,0 +1,369 @@
1
+ // A run's work/ as this server reads it (the console's file view and listing, a skill's SKILL.md), and an agent's home as
2
+ // it reads and writes it: never through a link. Each read and write goes through pi-durable-disk's confinement, which
3
+ // walks down from the root on held directory handles without following, so a component swapped for a link between a
4
+ // check and the open is refused, not followed. On top of it: the path must be the root joined with its own names (a link
5
+ // anywhere on the way, even one pointing inside the root, is refused), only regular files and directories are read, and a
6
+ // file with a second hard link is refused, since it could be one of this server's own files linked in.
7
+ import { randomBytes } from "node:crypto";
8
+ import { closeSync, constants, openSync, readFileSync, realpathSync, statSync } from "node:fs";
9
+ import { access, lstat, mkdir, open, readdir, unlink } from "node:fs/promises";
10
+ import { dirname, extname, join, resolve } from "node:path";
11
+ import { Confinement } from "@parcha/pi-durable-disk/internals";
12
+ import { RUN_META, syncDir, writeDurable } from "./files.js";
13
+ import { remotePlace, storedPlace } from "./place.js";
14
+ /** The type a file is served as, by its extension: a run's files, a home's, and an upload whose reservation names none.
15
+ * A Map, so only its own extensions resolve: an object's would also give its prototype's (`.constructor`, `.__proto__`). */
16
+ const TYPES = new Map(Object.entries({
17
+ txt: "text/plain; charset=utf-8", md: "text/markdown; charset=utf-8", csv: "text/csv; charset=utf-8", json: "application/json", jsonl: "application/x-ndjson",
18
+ html: "text/html; charset=utf-8", htm: "text/html; charset=utf-8", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", pdf: "application/pdf",
19
+ }));
20
+ /** The types a file is served as in the page (every known type but PDF); any other is a download. */
21
+ export const INLINE_TYPES = new Set([...TYPES.values()].filter((type) => type !== "application/pdf"));
22
+ /** The type of a file at `path`, by its extension; undefined for one the table does not know. */
23
+ export const typeOf = (path) => TYPES.get(extname(path).slice(1).toLowerCase());
24
+ /** A path under work/ this server does not read, and why. */
25
+ export class WorkRefused extends Error {
26
+ path;
27
+ reason;
28
+ constructor(path, reason) {
29
+ super(`${path}: not read (${reason.replace("_", " ")})`);
30
+ this.path = path;
31
+ this.reason = reason;
32
+ }
33
+ }
34
+ const reasonOf = (error) => {
35
+ const code = error?.code;
36
+ return code === "ENOENT" ? "missing" : code === "EACCES" ? "unreadable" : "link";
37
+ };
38
+ /** Test seams, tests only: before the walk enters a directory it listed (after its lstat, before its pin); after a
39
+ * directory is pinned and before it is read; after a directory is listed and before its entries are looked at; after a
40
+ * file is opened and checked, before the caller reads it; after a capped read's size check, before the bytes are read.
41
+ * `byPath` walks as the confinement does where there is no /proc/self/fd (macOS), on any platform. */
42
+ export const workspaceTestHooks = {};
43
+ /** How many directories deep `walkWork` goes by default. */
44
+ export const WALK_DEPTH = 16;
45
+ let held;
46
+ /** Whether this process reaches a held directory handle by path through /proc/self/fd, probed once. The confinement
47
+ * walks on such handles when it does and by path when not (macOS); by path, a directory swapped for a link after the
48
+ * walk could take a write's temporary file and rename, or a removal, outside the root, and Node has no openat, so a
49
+ * write or a removal is made only where this holds. */
50
+ export function writesHeld() {
51
+ if (workspaceTestHooks.byPath !== undefined)
52
+ return !workspaceTestHooks.byPath;
53
+ if (held === undefined) {
54
+ let dir;
55
+ try {
56
+ dir = openSync("/", constants.O_RDONLY | constants.O_DIRECTORY);
57
+ held = statSync(`/proc/self/fd/${dir}/.`).isDirectory();
58
+ }
59
+ catch {
60
+ held = false;
61
+ }
62
+ finally {
63
+ if (dir !== undefined)
64
+ closeSync(dir);
65
+ }
66
+ }
67
+ return held;
68
+ }
69
+ const confinementOf = (work) => {
70
+ const real = realpathSync(work);
71
+ return { real, confinement: new Confinement(real, [], { byPath: !writesHeld() }) };
72
+ };
73
+ /** Opens `rel` under `work` for reading, held: a regular file with one link, reached through no link. Close the handle. */
74
+ export async function openWorkFile(work, rel) {
75
+ const { real, confinement } = confinementOf(work);
76
+ const abs = join(real, rel);
77
+ const pin = await confinement.pinEntry(abs, rel, { access: "read", follow: false }).catch((error) => {
78
+ throw new WorkRefused(rel, reasonOf(error));
79
+ });
80
+ try {
81
+ if (pin.canonical !== abs)
82
+ throw new WorkRefused(rel, "link");
83
+ const handle = await pin.openFile(constants.O_RDONLY).catch((error) => {
84
+ throw new WorkRefused(rel, reasonOf(error));
85
+ });
86
+ // The handle is the caller's only once every check passed; on any failure before that it is closed here.
87
+ try {
88
+ const stats = await handle.stat();
89
+ const refused = !stats.isFile() ? "not_regular" : stats.nlink !== 1 ? "hard_link" : undefined;
90
+ if (refused)
91
+ throw new WorkRefused(rel, refused);
92
+ await workspaceTestHooks.afterOpen?.(rel);
93
+ return { handle, stats };
94
+ }
95
+ catch (error) {
96
+ await handle.close().catch(() => undefined);
97
+ throw error;
98
+ }
99
+ }
100
+ finally {
101
+ await pin.close();
102
+ }
103
+ }
104
+ /** `rel` under `work` as text, read as `openWorkFile` reads it. */
105
+ export async function readWorkText(work, rel) {
106
+ const { handle } = await openWorkFile(work, rel);
107
+ try {
108
+ return await handle.readFile("utf8");
109
+ }
110
+ finally {
111
+ await handle.close();
112
+ }
113
+ }
114
+ /** `rel` under `work`, its bytes, read as `openWorkFile` reads it; refused ("over_cap") when larger than `maxBytes`. */
115
+ export async function readWorkBytes(work, rel, { maxBytes }) {
116
+ const { handle, stats } = await openWorkFile(work, rel);
117
+ try {
118
+ if (stats.size > maxBytes)
119
+ throw new WorkRefused(rel, "over_cap");
120
+ await workspaceTestHooks.afterSizeCheck?.(rel);
121
+ // At most one byte past the cap: a file that grew after its stat is refused without being read whole.
122
+ const buffer = Buffer.alloc(maxBytes + 1);
123
+ let read = 0;
124
+ for (let got; read < buffer.length && (got = (await handle.read(buffer, read, buffer.length - read, read)).bytesRead) > 0;)
125
+ read += got;
126
+ if (read > maxBytes)
127
+ throw new WorkRefused(rel, "over_cap");
128
+ return buffer.subarray(0, read);
129
+ }
130
+ finally {
131
+ await handle.close();
132
+ }
133
+ }
134
+ /**
135
+ * Each regular file (with one link) and directory under `work`, by its path below it, with its own stats and whether
136
+ * this server may read it: a link is skipped and never followed, so no target's size or time is read. Each entry left out
137
+ * for what it is goes to `refused` with its reason (a link, not a regular file, another hard link), and so does a
138
+ * directory that cannot be read: its contents are unknown, never empty. work/ itself unread throws `WorkRefused` (no
139
+ * working copy). `skip` (given the name and its path below `work`) leaves it, and what is below it, out unreported;
140
+ * `visit` returning false stops the walk.
141
+ * Directories are entered down to `depth` levels.
142
+ */
143
+ export async function walkWork(work, visit, { skip = () => false, depth = WALK_DEPTH, refused = () => { } } = {}) {
144
+ const { real, confinement } = confinementOf(work);
145
+ const into = async (rel, level) => {
146
+ const abs = rel ? join(real, rel) : real;
147
+ // A directory not read is reported, never taken as empty: a caller must not infer that what it held is gone.
148
+ let failed;
149
+ const pin = await confinement.pinDir(abs, rel || ".", { access: "read" }).catch((error) => void (failed = reasonOf(error)));
150
+ if (!pin) {
151
+ // work/ itself unread is no working copy, never an empty one.
152
+ if (!rel)
153
+ throw new WorkRefused(".", failed ?? "missing");
154
+ refused(rel, failed ?? "missing");
155
+ return true;
156
+ }
157
+ try {
158
+ if (pin.canonical !== abs) {
159
+ if (!rel)
160
+ throw new WorkRefused(".", "link");
161
+ refused(rel, "link");
162
+ return true;
163
+ }
164
+ await workspaceTestHooks.afterPin?.(rel || ".");
165
+ const names = await readdir(pin.dir).catch((error) => void (failed = reasonOf(error)));
166
+ if (!names) {
167
+ if (!rel)
168
+ throw new WorkRefused(".", failed ?? "unreadable");
169
+ refused(rel, failed ?? "unreadable");
170
+ return true;
171
+ }
172
+ await workspaceTestHooks.afterList?.(rel || ".");
173
+ for (const name of names) {
174
+ if (skip(name, rel ? `${rel}/${name}` : name))
175
+ continue;
176
+ // By the held directory: a name swapped for a link reads as the link, which is skipped.
177
+ let gone = false;
178
+ const stats = await lstat(`${pin.dir}/${name}`).catch((error) => void (gone = error?.code === "ENOENT"));
179
+ const path = rel ? `${rel}/${name}` : name;
180
+ if (!stats) {
181
+ // Gone since the listing: nothing to say. Any other failure (a directory that lists but cannot be searched)
182
+ // is an entry never read, so it is reported, never left out as if it were not there.
183
+ if (!gone)
184
+ refused(path, "unreadable");
185
+ continue;
186
+ }
187
+ if (stats.isSymbolicLink()) {
188
+ refused(path, "link");
189
+ continue;
190
+ }
191
+ if (stats.isDirectory()) {
192
+ if (visit(path, stats, true) === false)
193
+ return false;
194
+ await workspaceTestHooks.beforeEnter?.(path);
195
+ if (level < depth && !(await into(path, level + 1)))
196
+ return false;
197
+ }
198
+ else if (!stats.isFile())
199
+ refused(path, "not_regular");
200
+ else if (stats.nlink !== 1)
201
+ refused(path, "hard_link");
202
+ else {
203
+ const readable = await access(`${pin.dir}/${name}`, constants.R_OK).then(() => true, () => false);
204
+ if (visit(path, stats, readable) === false)
205
+ return false;
206
+ }
207
+ }
208
+ return true;
209
+ }
210
+ finally {
211
+ await pin.close();
212
+ }
213
+ };
214
+ await into("", 0);
215
+ }
216
+ /** A write's or a removal's failure that is a refusal: a link on the way (the confinement's refusal), a directory that
217
+ * is missing or this server may not enter, or a file where a directory is on the way (a directory where the file is).
218
+ * Any other failure, a full disk say, is thrown as it is. */
219
+ const REFUSALS = { permission_denied: "link", ELOOP: "link", ENOENT: "missing", EACCES: "unreadable", ENOTDIR: "not_regular", EISDIR: "not_regular" };
220
+ const refusing = (rel) => (error) => {
221
+ const reason = error instanceof WorkRefused ? error.reason : REFUSALS[error?.code ?? ""];
222
+ throw reason ? new WorkRefused(rel, reason) : error;
223
+ };
224
+ /** Pins the directory holding `rel` under `work` for writing, every directory on the way reached through no link (and,
225
+ * with `parents`, made when missing). Close the pin. */
226
+ async function pinForWrite(work, rel, parents) {
227
+ if (!writesHeld())
228
+ throw new WorkRefused(rel, "unheld");
229
+ const { real, confinement } = confinementOf(work);
230
+ const abs = join(real, rel);
231
+ const refuse = refusing(rel);
232
+ // Checked before the walk makes any directory, so none is made through a link.
233
+ const { canonical } = await confinement.locate(abs, rel, "write", false).catch(refuse);
234
+ if (canonical !== abs)
235
+ throw new WorkRefused(rel, "link");
236
+ // Whether the walk is to make a directory (the file's own is missing).
237
+ const making = parents && !(await lstat(dirname(abs)).catch(() => null));
238
+ const pin = await confinement.pinEntry(abs, rel, { access: "write", follow: false, parents }).catch(refuse);
239
+ if (pin.canonical !== abs) {
240
+ await pin.close();
241
+ throw new WorkRefused(rel, "link");
242
+ }
243
+ return { pin, refuse, real, making };
244
+ }
245
+ /** What is at the pinned entry, by lstat: nothing (undefined), else a regular file, or refused. */
246
+ async function entryOf(pin, refuse, rel) {
247
+ const stats = await lstat(pin.entry).catch((error) => (error?.code === "ENOENT" ? undefined : refuse(error)));
248
+ if (stats && !stats.isFile())
249
+ throw new WorkRefused(rel, stats.isSymbolicLink() ? "link" : "not_regular");
250
+ return stats;
251
+ }
252
+ /**
253
+ * Writes `bytes` to `rel` under `work` whole and durably (files.ts writeDurable), as a file of `mode`: through a temporary
254
+ * file in the same directory, a dot-name of the server's own, renamed over the file. The directories on the way are made
255
+ * when missing, and each is synced into its parent before this resolves. A link on the way or at the file, or a directory
256
+ * there, is refused: never followed and never replaced. Answers the stats of the file this call wrote. `asTool`, a run's
257
+ * file tool writing a bound box's work/ (bound-files.ts): a file with another hard link is refused, a file already there
258
+ * keeps its mode, and a new one gets `mode` as given, whatever this process's umask.
259
+ */
260
+ export async function writeWorkFile(work, rel, bytes, mode = 0o600, asTool = false) {
261
+ const { pin, refuse, real, making } = await pinForWrite(work, rel, true);
262
+ try {
263
+ const before = await entryOf(pin, refuse, rel);
264
+ if (asTool && before && before.nlink !== 1)
265
+ throw new WorkRefused(rel, "hard_link");
266
+ const kept = asTool && before ? before.mode & 0o777 : mode;
267
+ // A link swapped in after that check is replaced by the rename, never written through.
268
+ const stats = await writeDurable(pin.entry, bytes, kept, `${pin.dir}/.agentrun-${process.pid}-${randomBytes(6).toString("hex")}.tmp`, asTool).catch(refuse);
269
+ // writeDurable synced the file's own directory; a directory made above it survives a crash once its parent is synced.
270
+ if (making) {
271
+ let at = real;
272
+ for (const name of dirname(rel).split("/")) {
273
+ await syncDir(at);
274
+ at = join(at, name);
275
+ }
276
+ }
277
+ return stats;
278
+ }
279
+ finally {
280
+ await pin.close();
281
+ }
282
+ }
283
+ /** Removes the regular file `rel` under `work`, reached through no link: refused when it is missing, a link, or not a
284
+ * regular file. A directory it leaves empty stays. */
285
+ export async function removeWorkFile(work, rel) {
286
+ const { pin, refuse } = await pinForWrite(work, rel, false);
287
+ try {
288
+ if (!(await entryOf(pin, refuse, rel)))
289
+ throw new WorkRefused(rel, "missing");
290
+ // unlink never follows the name it removes: a link swapped in after the check is removed, not its target.
291
+ await unlink(pin.entry).catch(refuse);
292
+ }
293
+ finally {
294
+ await pin.close();
295
+ }
296
+ }
297
+ /** Throws unless the kernel refuses a hard link to a file the linker cannot write (fs.protected_hardlinks = 1): with a
298
+ * run's commands under a uid of their own, it keeps them from linking this server's files into their workspace. */
299
+ export function assertHardlinkProtection(read = () => readFileSync("/proc/sys/fs/protected_hardlinks", "utf8")) {
300
+ let value;
301
+ try {
302
+ value = read().trim();
303
+ }
304
+ catch (error) {
305
+ throw new Error(`agentrun-serve: fs.protected_hardlinks cannot be read (${error.message}); a run's workspace could hold a link to this server's files`);
306
+ }
307
+ if (value !== "1")
308
+ throw new Error(`agentrun-serve: fs.protected_hardlinks is ${value}, not 1; a run's workspace could hold a link to this server's files`);
309
+ }
310
+ const NO_LINK_DIR = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;
311
+ const NEW_FILE = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW;
312
+ /** Whether the run whose work/ is `work` runs in a box that binds it, by the place its start kept (serve.json beside
313
+ * work/). A remote box's commands never reach this machine's work/: what comes back from it is pulled, and a pull writes
314
+ * no link. */
315
+ function boxedRun(work) {
316
+ try {
317
+ const place = storedPlace(JSON.parse(readFileSync(join(dirname(work), RUN_META), "utf8")).place);
318
+ return place.mode === "sandbox" && !remotePlace(place);
319
+ }
320
+ catch {
321
+ return false;
322
+ }
323
+ }
324
+ const mirrors = new Map();
325
+ /** In a run's process whose box is remote: each file writeInWork files below `work` is copied into the box as well, at the
326
+ * same path below its work/ (run-box.ts), so the run's tools there read what its host tools filed. */
327
+ export function mirrorWrites(work, mirror) {
328
+ mirrors.set(resolve(work), mirror);
329
+ }
330
+ /** Writes `data` as a new file `name` in `dirs` below a run's `work`, never through a link: a box's command can plant one
331
+ * there, and this process writes with the server's rights. Each directory is made when missing and opened without
332
+ * following a link, the next reached through the one held before it (/proc/self/fd), and the file is created, never
333
+ * replaced: a link in the way refuses the write (ELOOP, ENOTDIR or EEXIST). Where no handle is held (writesHeld: macOS
334
+ * and any host without /proc/self/fd) each step is reached by its path, which a link swapped in between two steps could
335
+ * turn: there a run whose place is a box gets no write (ENOTSUP), and a runner run, whose tools make no link, still
336
+ * writes by path. */
337
+ export async function writeInWork(work, dirs, name, data) {
338
+ const byHandle = writesHeld();
339
+ if (!byHandle && boxedRun(work))
340
+ throw Object.assign(new Error("this host reaches a run's directories by path, which a box's command could turn through a link"), { code: "ENOTSUP" });
341
+ let dir = await open(work, NO_LINK_DIR);
342
+ let path = work;
343
+ const below = (part) => (byHandle ? `/proc/self/fd/${dir.fd}/${part}` : join(path, part));
344
+ try {
345
+ for (const part of dirs) {
346
+ await mkdir(below(part)).catch((error) => {
347
+ if (error.code !== "EEXIST")
348
+ throw error;
349
+ });
350
+ const next = await open(below(part), NO_LINK_DIR);
351
+ await dir.close();
352
+ [dir, path] = [next, join(path, part)];
353
+ }
354
+ const file = await open(below(name), NEW_FILE, 0o644);
355
+ try {
356
+ await file.writeFile(data);
357
+ }
358
+ finally {
359
+ await file.close();
360
+ }
361
+ }
362
+ finally {
363
+ await dir.close();
364
+ }
365
+ // The box's copy is a convenience to its tools; the file filed here is the record, and stands whatever the copy does.
366
+ await mirrors.get(resolve(work))?.([...dirs, name].join("/"), data).catch((error) => {
367
+ process.stderr.write(`${JSON.stringify({ at: new Date().toISOString(), event: "box_mirror_failed", message: `${[...dirs, name].join("/")} was filed in work/ but not copied into the run's box: ${error?.message ?? String(error)}` })}\n`);
368
+ });
369
+ }
@@ -0,0 +1,109 @@
1
+ #!/bin/sh
2
+ # agentrun-serve's launcher: it hands the server its secrets over a pipe and starts it with none of them in its
3
+ # environment, so no process of the server's user can read them from /proc/<pid>/environ or cmdline.
4
+ #
5
+ # agentrun-serve [ARG...] the server (../dist/cli.js beside this launcher) with ARGs
6
+ # agentrun-serve -- COMMAND [ARG...] COMMAND, which starts the server (the image's: tini -- node .../cli.js)
7
+ #
8
+ # Each secret named below that is set goes into one pipe as NAME=VALUE and a NUL, AGENTRUN_SECRETS_LEN bytes in all,
9
+ # on fd AGENTRUN_SECRETS_FD; the server reads exactly that many bytes first thing and closes the pipe. First, each
10
+ # secret moves out of the environment into this shell's own memory, so no process it starts (the seal key's, mktemp,
11
+ # mkfifo, rm, env) inherits one; only this launcher's own initial environment, gone at the exec, ever held them. The
12
+ # pipe is a FIFO whose name is gone before any secret is written, and only this shell writes it, with its builtin
13
+ # printf; `env -u` drops every name from what COMMAND inherits too. The condition: this runs before any run's process
14
+ # exists. A process of the same user started earlier could open the FIFO while it is named.
15
+ #
16
+ # AGENTRUN_SEAL_KEY, the key the server keeps tool keys under (src/tool-keys.ts), is one of them. Not set, it is the
17
+ # one in agentrun/seal.key under XDG_CONFIG_HOME (or ~/.config), made here the first time: 32 random bytes in base64,
18
+ # 0600 in a 0700 directory, written by this shell's printf, never on a command line. It is outside the data directory
19
+ # on purpose: a copy of that holds the tool keys as ciphertext alone.
20
+ #
21
+ # BROWSERBASE_PROJECT_ID is no secret, but a tool key's field: every field a person may save is on this list, so a
22
+ # saved one is read by the same name and reaches a run's process over its pipe, as the launcher's does.
23
+ #
24
+ # After MODAL_TOKEN_SECRET, the keys of pi-ai's other providers, which a pi run's model may need (GEMINI_API_KEY,
25
+ # DEEPSEEK_API_KEY, Bedrock's AWS keys, ...): the server holds each, and a run's process gets one over its pipe only when
26
+ # its model is that provider's (../src/model.ts' PROVIDER_KEYS). The custody test checks every key pi-ai's table names is
27
+ # here. Any other variable named like a key (a KEY, TOKEN, SECRET, PASSWORD, PASSWD, PASS, PAT, CREDENTIAL, CREDENTIALS or
28
+ # DSN segment, or a last PWD after another) stays in the server's environment, as this list does not take it, and in no
29
+ # run's: name it here to keep it from the server's too.
30
+ SECRETS='AGENTRUN_TOKEN AGENTRUN_API_KEY AGENT_MODEL_API_KEY OPENAI_API_KEY ANTHROPIC_API_KEY BROWSERBASE_API_KEY BROWSERBASE_PROJECT_ID KERNEL_API_KEY OPENROUTER_API_KEY TYPESAFE_API_KEY PARALLEL_API_KEY MONID_API_KEY AGENTRUN_SEAL_KEY DAYTONA_API_KEY MODAL_TOKEN_ID MODAL_TOKEN_SECRET ANTHROPIC_AUTH_TOKEN ANTHROPIC_OAUTH_TOKEN AI_GATEWAY_API_KEY ANT_LING_API_KEY AWS_ACCESS_KEY_ID AWS_BEARER_TOKEN_BEDROCK AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AZURE_OPENAI_API_KEY BASETEN_API_KEY CEREBRAS_API_KEY CLOUDFLARE_API_KEY COPILOT_GITHUB_TOKEN DEEPSEEK_API_KEY FIREWORKS_API_KEY GEMINI_API_KEY GOOGLE_CLOUD_API_KEY GROQ_API_KEY HF_TOKEN KIMI_API_KEY META_API_KEY MINIMAX_API_KEY MINIMAX_CN_API_KEY MISTRAL_API_KEY MOONSHOT_API_KEY NVIDIA_API_KEY OPENCODE_API_KEY QWEN_TOKEN_PLAN_API_KEY QWEN_TOKEN_PLAN_CN_API_KEY RADIUS_API_KEY TOGETHER_API_KEY XAI_API_KEY XIAOMI_API_KEY XIAOMI_TOKEN_PLAN_AMS_API_KEY XIAOMI_TOKEN_PLAN_CN_API_KEY XIAOMI_TOKEN_PLAN_SGP_API_KEY ZAI_API_KEY ZAI_CODING_CN_API_KEY'
31
+ set -eu
32
+ # Each secret out of the environment and into an unexported variable of this shell (agentrun_secret_<NAME>).
33
+ for name in $SECRETS; do
34
+ eval "given=\${$name+x}"
35
+ [ -n "$given" ] || continue
36
+ eval "agentrun_secret_$name=\${$name}"
37
+ unset "$name"
38
+ done
39
+ # Written only by this shell's own printf, never a program that would take a secret on its command line.
40
+ case $(command -V printf 2>/dev/null) in
41
+ *builtin*) ;;
42
+ *) echo "agentrun-serve: this sh has no builtin printf, so it cannot hand the secrets over without a command line holding them" >&2; exit 1 ;;
43
+ esac
44
+ # Lengths in bytes: the C locale, for this shell only; the caller's own goes back before the exec.
45
+ locale=${LC_ALL-}
46
+ locale_set=${LC_ALL+x}
47
+ LC_ALL=C
48
+
49
+ # Every other process this launcher starts, it starts here, before it writes a secret. First the seal key's, when it is
50
+ # not given.
51
+ config=${XDG_CONFIG_HOME:-${HOME:+$HOME/.config}}
52
+ if [ -z "${agentrun_secret_AGENTRUN_SEAL_KEY+x}" ] && [ -n "$config" ]; then
53
+ keys=$config/agentrun
54
+ # Made whole beside its name, then linked to it, which fails if another start made it first: each start reads one.
55
+ if [ ! -e "$keys/seal.key" ] && (umask 077 && mkdir -p "$keys") && made=$(head -c 32 /dev/urandom | base64) && [ ${#made} -eq 44 ]; then
56
+ (umask 077 && printf '%s\n' "$made" >"$keys/seal.key.$$" && { ln "$keys/seal.key.$$" "$keys/seal.key" 2>/dev/null || :; }) || :
57
+ rm -f "$keys/seal.key.$$"
58
+ fi
59
+ made=
60
+ # Only a key no other user can read, in a directory no other user can: one they can is refused, never changed.
61
+ case $(ls -ld "$keys" 2>/dev/null):$(ls -l "$keys/seal.key" 2>/dev/null) in
62
+ d???------*:-??-------*) IFS= read -r agentrun_secret_AGENTRUN_SEAL_KEY <"$keys/seal.key" || : ;;
63
+ esac
64
+ if [ -z "${agentrun_secret_AGENTRUN_SEAL_KEY:-}" ]; then
65
+ unset agentrun_secret_AGENTRUN_SEAL_KEY
66
+ echo "agentrun-serve: no seal key in $keys/seal.key (none, or another user can read it or its directory), so the server keeps no tool key" >&2
67
+ fi
68
+ fi
69
+ dir=$(mktemp -d "${TMPDIR:-/tmp}/agentrun-serve.XXXXXX")
70
+ mkfifo -m 600 "$dir/secrets"
71
+ exec 3<>"$dir/secrets"
72
+ rm -f "$dir/secrets"
73
+ rmdir "$dir"
74
+
75
+ # From here to the exec: this shell's builtins only.
76
+ total=0
77
+ for name in $SECRETS; do
78
+ eval "given=\${agentrun_secret_$name+x}"
79
+ [ -n "$given" ] || continue
80
+ eval "value=\${agentrun_secret_$name}"
81
+ total=$((total + ${#name} + ${#value} + 2))
82
+ done
83
+ # A pipe is sure to hold one page unread (a FIFO may get no more: Linux gives a new pipe two pages once its user is over
84
+ # fs.pipe-user-pages-soft): more could block this shell before the server is there to read it.
85
+ if [ "$total" -gt 4096 ]; then
86
+ echo "agentrun-serve: the secrets come to $total bytes, more than the 4096 a pipe is sure to hold" >&2
87
+ exit 1
88
+ fi
89
+ for name in $SECRETS; do
90
+ eval "given=\${agentrun_secret_$name+x}"
91
+ [ -n "$given" ] || continue
92
+ eval "value=\${agentrun_secret_$name}"
93
+ printf '%s=%s\000' "$name" "$value" >&3
94
+ unset "agentrun_secret_$name"
95
+ done
96
+ value=
97
+ if [ -n "$locale_set" ]; then LC_ALL=$locale; else unset LC_ALL; fi
98
+
99
+ if [ "${1-}" = "--" ]; then
100
+ shift
101
+ else
102
+ # The server beside this launcher, found by node from this file's real path: a package manager's bin is a link.
103
+ set -- node --input-type=module -e 'import { realpathSync } from "node:fs"; import { pathToFileURL } from "node:url"; const cli = new URL("../dist/cli.js", pathToFileURL(realpathSync(process.argv[1]))); process.argv[1] = cli.pathname; await import(cli.href);' "$0" "$@"
104
+ fi
105
+ set -- AGENTRUN_SECRETS_FD=3 "AGENTRUN_SECRETS_LEN=$total" "$@"
106
+ for name in $SECRETS; do
107
+ set -- -u "$name" "$@"
108
+ done
109
+ exec env "$@"