@nexum-hub/agent 0.0.0-stage → 0.0.2

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 (343) hide show
  1. package/README.md +133 -2
  2. package/contracts/v2/common.schema.json +262 -0
  3. package/contracts/v2/fixtures/inputs.json +244 -0
  4. package/contracts/v2/fixtures/wire.json +6493 -0
  5. package/contracts/v2/model/agent.close.input.schema.json +14 -0
  6. package/contracts/v2/model/agent.close.output.schema.json +101 -0
  7. package/contracts/v2/model/agent.list.input.schema.json +57 -0
  8. package/contracts/v2/model/agent.list.output.schema.json +220 -0
  9. package/contracts/v2/model/agent.open.input.schema.json +35 -0
  10. package/contracts/v2/model/agent.open.output.schema.json +41 -0
  11. package/contracts/v2/model/agent.run.cancel.input.schema.json +18 -0
  12. package/contracts/v2/model/agent.run.cancel.output.schema.json +100 -0
  13. package/contracts/v2/model/agent.run.get.input.schema.json +41 -0
  14. package/contracts/v2/model/agent.run.get.output.schema.json +100 -0
  15. package/contracts/v2/model/agent.run.input.input.schema.json +30 -0
  16. package/contracts/v2/model/agent.run.input.output.schema.json +100 -0
  17. package/contracts/v2/model/agent.run.list.input.schema.json +47 -0
  18. package/contracts/v2/model/agent.run.list.output.schema.json +41 -0
  19. package/contracts/v2/model/agent.run.start.input.schema.json +73 -0
  20. package/contracts/v2/model/agent.run.start.output.schema.json +100 -0
  21. package/contracts/v2/wire/bodies.schema.json +383 -0
  22. package/contracts/v2/wire/envelope.schema.json +2280 -0
  23. package/contracts/v2/wire/events.schema.json +242 -0
  24. package/contracts/v2/wire/maintenance.schema.json +308 -0
  25. package/contracts/v2/wire/operations.schema.json +1791 -0
  26. package/contracts/v2/wire/stream.schema.json +74 -0
  27. package/contracts/v2/wire/types.schema.json +2616 -0
  28. package/dist/adapters/mcp-http.d.ts +22 -0
  29. package/dist/adapters/mcp-http.js +472 -0
  30. package/dist/adapters/mcp-http.js.map +1 -0
  31. package/dist/adapters/mcp-oauth.d.ts +29 -0
  32. package/dist/adapters/mcp-oauth.js +653 -0
  33. package/dist/adapters/mcp-oauth.js.map +1 -0
  34. package/dist/adapters/mcp-wire.d.ts +21 -0
  35. package/dist/adapters/mcp-wire.js +307 -0
  36. package/dist/adapters/mcp-wire.js.map +1 -0
  37. package/dist/adapters/mcp.d.ts +56 -0
  38. package/dist/adapters/mcp.js +1989 -0
  39. package/dist/adapters/mcp.js.map +1 -0
  40. package/dist/adapters/openapi-http.d.ts +29 -0
  41. package/dist/adapters/openapi-http.js +504 -0
  42. package/dist/adapters/openapi-http.js.map +1 -0
  43. package/dist/adapters/openapi-request.d.ts +26 -0
  44. package/dist/adapters/openapi-request.js +597 -0
  45. package/dist/adapters/openapi-request.js.map +1 -0
  46. package/dist/adapters/openapi-schema.d.ts +22 -0
  47. package/dist/adapters/openapi-schema.js +471 -0
  48. package/dist/adapters/openapi-schema.js.map +1 -0
  49. package/dist/adapters/openapi-typegen.d.ts +11 -0
  50. package/dist/adapters/openapi-typegen.js +185 -0
  51. package/dist/adapters/openapi-typegen.js.map +1 -0
  52. package/dist/adapters/openapi-types.d.ts +99 -0
  53. package/dist/adapters/openapi-types.js +2 -0
  54. package/dist/adapters/openapi-types.js.map +1 -0
  55. package/dist/adapters/openapi.d.ts +7 -0
  56. package/dist/adapters/openapi.js +768 -0
  57. package/dist/adapters/openapi.js.map +1 -0
  58. package/dist/application/activation.d.ts +28 -0
  59. package/dist/application/activation.js +289 -0
  60. package/dist/application/activation.js.map +1 -0
  61. package/dist/application/attachments.d.ts +24 -0
  62. package/dist/application/attachments.js +87 -0
  63. package/dist/application/attachments.js.map +1 -0
  64. package/dist/application/authority.d.ts +32 -0
  65. package/dist/application/authority.js +213 -0
  66. package/dist/application/authority.js.map +1 -0
  67. package/dist/application/catalog.d.ts +11 -0
  68. package/dist/application/catalog.js +177 -0
  69. package/dist/application/catalog.js.map +1 -0
  70. package/dist/application/config.d.ts +24 -0
  71. package/dist/application/config.js +140 -0
  72. package/dist/application/config.js.map +1 -0
  73. package/dist/application/connection.d.ts +35 -0
  74. package/dist/application/connection.js +465 -0
  75. package/dist/application/connection.js.map +1 -0
  76. package/dist/application/data-plane.d.ts +35 -0
  77. package/dist/application/data-plane.js +437 -0
  78. package/dist/application/data-plane.js.map +1 -0
  79. package/dist/application/diagnostics.d.ts +4 -0
  80. package/dist/application/diagnostics.js +65 -0
  81. package/dist/application/diagnostics.js.map +1 -0
  82. package/dist/application/dispatcher.d.ts +4 -0
  83. package/dist/application/dispatcher.js +16 -0
  84. package/dist/application/dispatcher.js.map +1 -0
  85. package/dist/application/main.d.ts +12 -0
  86. package/dist/application/main.js +167 -0
  87. package/dist/application/main.js.map +1 -0
  88. package/dist/application/maintenance.d.ts +27 -0
  89. package/dist/application/maintenance.js +244 -0
  90. package/dist/application/maintenance.js.map +1 -0
  91. package/dist/application/packages.d.ts +25 -0
  92. package/dist/application/packages.js +208 -0
  93. package/dist/application/packages.js.map +1 -0
  94. package/dist/application/processes.d.ts +49 -0
  95. package/dist/application/processes.js +180 -0
  96. package/dist/application/processes.js.map +1 -0
  97. package/dist/application/run-view.d.ts +17 -0
  98. package/dist/application/run-view.js +286 -0
  99. package/dist/application/run-view.js.map +1 -0
  100. package/dist/application/runtime.d.ts +78 -0
  101. package/dist/application/runtime.js +1747 -0
  102. package/dist/application/runtime.js.map +1 -0
  103. package/dist/application/tasks.d.ts +38 -0
  104. package/dist/application/tasks.js +23 -0
  105. package/dist/application/tasks.js.map +1 -0
  106. package/dist/application/user-state.d.ts +20 -0
  107. package/dist/application/user-state.js +52 -0
  108. package/dist/application/user-state.js.map +1 -0
  109. package/dist/application/work-git.d.ts +14 -0
  110. package/dist/application/work-git.js +67 -0
  111. package/dist/application/work-git.js.map +1 -0
  112. package/dist/cli.d.ts +2 -0
  113. package/dist/cli.js +40 -0
  114. package/dist/cli.js.map +1 -0
  115. package/dist/contracts/caller.d.ts +51 -0
  116. package/dist/contracts/caller.js +95 -0
  117. package/dist/contracts/caller.js.map +1 -0
  118. package/dist/contracts/error-data.d.ts +6 -0
  119. package/dist/contracts/error-data.js +51 -0
  120. package/dist/contracts/error-data.js.map +1 -0
  121. package/dist/contracts/errors.d.ts +10 -0
  122. package/dist/contracts/errors.js +28 -0
  123. package/dist/contracts/errors.js.map +1 -0
  124. package/dist/contracts/json.d.ts +9 -0
  125. package/dist/contracts/json.js +104 -0
  126. package/dist/contracts/json.js.map +1 -0
  127. package/dist/contracts/types.d.ts +122 -0
  128. package/dist/contracts/types.js +19 -0
  129. package/dist/contracts/types.js.map +1 -0
  130. package/dist/contracts/validation.d.ts +4 -0
  131. package/dist/contracts/validation.js +157 -0
  132. package/dist/contracts/validation.js.map +1 -0
  133. package/dist/contracts/wire-validation.d.ts +9 -0
  134. package/dist/contracts/wire-validation.js +399 -0
  135. package/dist/contracts/wire-validation.js.map +1 -0
  136. package/dist/contracts/wire.d.ts +1083 -0
  137. package/dist/contracts/wire.js +62 -0
  138. package/dist/contracts/wire.js.map +1 -0
  139. package/dist/extension-api.d.ts +12 -0
  140. package/dist/extension-api.js +2 -0
  141. package/dist/extension-api.js.map +1 -0
  142. package/dist/extensions/api.d.ts +72 -0
  143. package/dist/extensions/api.js +2 -0
  144. package/dist/extensions/api.js.map +1 -0
  145. package/dist/extensions/host-requests.d.ts +23 -0
  146. package/dist/extensions/host-requests.js +60 -0
  147. package/dist/extensions/host-requests.js.map +1 -0
  148. package/dist/extensions/materials.d.ts +37 -0
  149. package/dist/extensions/materials.js +691 -0
  150. package/dist/extensions/materials.js.map +1 -0
  151. package/dist/extensions/package-loader.d.ts +28 -0
  152. package/dist/extensions/package-loader.js +177 -0
  153. package/dist/extensions/package-loader.js.map +1 -0
  154. package/dist/extensions/packages.d.ts +73 -0
  155. package/dist/extensions/packages.js +441 -0
  156. package/dist/extensions/packages.js.map +1 -0
  157. package/dist/extensions/registry.d.ts +92 -0
  158. package/dist/extensions/registry.js +1540 -0
  159. package/dist/extensions/registry.js.map +1 -0
  160. package/dist/extensions/resources.d.ts +105 -0
  161. package/dist/extensions/resources.js +595 -0
  162. package/dist/extensions/resources.js.map +1 -0
  163. package/dist/extensions/state.d.ts +25 -0
  164. package/dist/extensions/state.js +10 -0
  165. package/dist/extensions/state.js.map +1 -0
  166. package/dist/extensions/transfer.d.ts +81 -0
  167. package/dist/extensions/transfer.js +16 -0
  168. package/dist/extensions/transfer.js.map +1 -0
  169. package/dist/index.d.ts +7 -0
  170. package/dist/index.js +25 -0
  171. package/dist/index.js.map +1 -0
  172. package/dist/maintenance/configuration.d.ts +79 -0
  173. package/dist/maintenance/configuration.js +1503 -0
  174. package/dist/maintenance/configuration.js.map +1 -0
  175. package/dist/maintenance/credentials.d.ts +23 -0
  176. package/dist/maintenance/credentials.js +177 -0
  177. package/dist/maintenance/credentials.js.map +1 -0
  178. package/dist/maintenance/files.d.ts +2 -0
  179. package/dist/maintenance/files.js +40 -0
  180. package/dist/maintenance/files.js.map +1 -0
  181. package/dist/maintenance/npm.d.ts +71 -0
  182. package/dist/maintenance/npm.js +1013 -0
  183. package/dist/maintenance/npm.js.map +1 -0
  184. package/dist/maintenance/oauth.d.ts +45 -0
  185. package/dist/maintenance/oauth.js +686 -0
  186. package/dist/maintenance/oauth.js.map +1 -0
  187. package/dist/maintenance/requests.d.ts +347 -0
  188. package/dist/maintenance/requests.js +959 -0
  189. package/dist/maintenance/requests.js.map +1 -0
  190. package/dist/maintenance/work-git.d.ts +29 -0
  191. package/dist/maintenance/work-git.js +776 -0
  192. package/dist/maintenance/work-git.js.map +1 -0
  193. package/dist/process/backend.d.ts +54 -0
  194. package/dist/process/backend.js +39 -0
  195. package/dist/process/backend.js.map +1 -0
  196. package/dist/process/environment-windows.d.ts +15 -0
  197. package/dist/process/environment-windows.js +151 -0
  198. package/dist/process/environment-windows.js.map +1 -0
  199. package/dist/process/environment.d.ts +28 -0
  200. package/dist/process/environment.js +410 -0
  201. package/dist/process/environment.js.map +1 -0
  202. package/dist/process/launch.d.ts +31 -0
  203. package/dist/process/launch.js +281 -0
  204. package/dist/process/launch.js.map +1 -0
  205. package/dist/process/managed.d.ts +36 -0
  206. package/dist/process/managed.js +459 -0
  207. package/dist/process/managed.js.map +1 -0
  208. package/dist/process/output-log.d.ts +50 -0
  209. package/dist/process/output-log.js +552 -0
  210. package/dist/process/output-log.js.map +1 -0
  211. package/dist/process/pipes.d.ts +16 -0
  212. package/dist/process/pipes.js +588 -0
  213. package/dist/process/pipes.js.map +1 -0
  214. package/dist/process/pty.d.ts +22 -0
  215. package/dist/process/pty.js +512 -0
  216. package/dist/process/pty.js.map +1 -0
  217. package/dist/process/windows-conout-worker.d.ts +1 -0
  218. package/dist/process/windows-conout-worker.js +90 -0
  219. package/dist/process/windows-conout-worker.js.map +1 -0
  220. package/dist/process/windows-conout.d.ts +46 -0
  221. package/dist/process/windows-conout.js +140 -0
  222. package/dist/process/windows-conout.js.map +1 -0
  223. package/dist/process/windows-helper.d.ts +43 -0
  224. package/dist/process/windows-helper.js +255 -0
  225. package/dist/process/windows-helper.js.map +1 -0
  226. package/dist/process/windows-job.d.ts +39 -0
  227. package/dist/process/windows-job.js +224 -0
  228. package/dist/process/windows-job.js.map +1 -0
  229. package/dist/process/windows-pipes.d.ts +16 -0
  230. package/dist/process/windows-pipes.js +475 -0
  231. package/dist/process/windows-pipes.js.map +1 -0
  232. package/dist/results/artifacts.d.ts +118 -0
  233. package/dist/results/artifacts.js +873 -0
  234. package/dist/results/artifacts.js.map +1 -0
  235. package/dist/results/encoder.d.ts +57 -0
  236. package/dist/results/encoder.js +1179 -0
  237. package/dist/results/encoder.js.map +1 -0
  238. package/dist/results/mcp.d.ts +95 -0
  239. package/dist/results/mcp.js +656 -0
  240. package/dist/results/mcp.js.map +1 -0
  241. package/dist/results/media.d.ts +19 -0
  242. package/dist/results/media.js +301 -0
  243. package/dist/results/media.js.map +1 -0
  244. package/dist/results/normalize.d.ts +29 -0
  245. package/dist/results/normalize.js +464 -0
  246. package/dist/results/normalize.js.map +1 -0
  247. package/dist/runtime/control-scripts.d.ts +23 -0
  248. package/dist/runtime/control-scripts.js +242 -0
  249. package/dist/runtime/control-scripts.js.map +1 -0
  250. package/dist/runtime/engine.d.ts +177 -0
  251. package/dist/runtime/engine.js +1159 -0
  252. package/dist/runtime/engine.js.map +1 -0
  253. package/dist/runtime/globals.d.ts +1 -0
  254. package/dist/runtime/globals.js +31 -0
  255. package/dist/runtime/globals.js.map +1 -0
  256. package/dist/runtime/material-retention.d.ts +34 -0
  257. package/dist/runtime/material-retention.js +671 -0
  258. package/dist/runtime/material-retention.js.map +1 -0
  259. package/dist/runtime/modules.d.ts +50 -0
  260. package/dist/runtime/modules.js +320 -0
  261. package/dist/runtime/modules.js.map +1 -0
  262. package/dist/runtime/names.d.ts +2 -0
  263. package/dist/runtime/names.js +22 -0
  264. package/dist/runtime/names.js.map +1 -0
  265. package/dist/runtime/operations.d.ts +20 -0
  266. package/dist/runtime/operations.js +137 -0
  267. package/dist/runtime/operations.js.map +1 -0
  268. package/dist/runtime/paths.d.ts +3 -0
  269. package/dist/runtime/paths.js +38 -0
  270. package/dist/runtime/paths.js.map +1 -0
  271. package/dist/runtime/promises.d.ts +9 -0
  272. package/dist/runtime/promises.js +78 -0
  273. package/dist/runtime/promises.js.map +1 -0
  274. package/dist/runtime/retention.d.ts +88 -0
  275. package/dist/runtime/retention.js +735 -0
  276. package/dist/runtime/retention.js.map +1 -0
  277. package/dist/runtime/run-log.d.ts +30 -0
  278. package/dist/runtime/run-log.js +207 -0
  279. package/dist/runtime/run-log.js.map +1 -0
  280. package/dist/runtime/scripts.d.ts +84 -0
  281. package/dist/runtime/scripts.js +387 -0
  282. package/dist/runtime/scripts.js.map +1 -0
  283. package/dist/runtime/tasks.d.ts +54 -0
  284. package/dist/runtime/tasks.js +290 -0
  285. package/dist/runtime/tasks.js.map +1 -0
  286. package/dist/sdk/maintenance.d.ts +3 -0
  287. package/dist/sdk/maintenance.js +80 -0
  288. package/dist/sdk/maintenance.js.map +1 -0
  289. package/dist/sdk/output-extension.d.ts +3 -0
  290. package/dist/sdk/output-extension.js +44 -0
  291. package/dist/sdk/output-extension.js.map +1 -0
  292. package/dist/sdk/output.d.ts +52 -0
  293. package/dist/sdk/output.js +350 -0
  294. package/dist/sdk/output.js.map +1 -0
  295. package/dist/sdk/runtime.d.ts +3 -0
  296. package/dist/sdk/runtime.js +26 -0
  297. package/dist/sdk/runtime.js.map +1 -0
  298. package/dist/sdk/sh.d.ts +3 -0
  299. package/dist/sdk/sh.js +384 -0
  300. package/dist/sdk/sh.js.map +1 -0
  301. package/dist/sdk/state.d.ts +2 -0
  302. package/dist/sdk/state.js +69 -0
  303. package/dist/sdk/state.js.map +1 -0
  304. package/dist/sdk/transfer.d.ts +3 -0
  305. package/dist/sdk/transfer.js +141 -0
  306. package/dist/sdk/transfer.js.map +1 -0
  307. package/dist/services/extensions.d.ts +19 -0
  308. package/dist/services/extensions.js +183 -0
  309. package/dist/services/extensions.js.map +1 -0
  310. package/dist/services/state.d.ts +37 -0
  311. package/dist/services/state.js +125 -0
  312. package/dist/services/state.js.map +1 -0
  313. package/dist/services/transfer.d.ts +86 -0
  314. package/dist/services/transfer.js +948 -0
  315. package/dist/services/transfer.js.map +1 -0
  316. package/dist/storage/schema.d.ts +8 -0
  317. package/dist/storage/schema.js +241 -0
  318. package/dist/storage/schema.js.map +1 -0
  319. package/dist/storage/sqlite.d.ts +241 -0
  320. package/dist/storage/sqlite.js +1855 -0
  321. package/dist/storage/sqlite.js.map +1 -0
  322. package/dist/storage/transfers.d.ts +90 -0
  323. package/dist/storage/transfers.js +2 -0
  324. package/dist/storage/transfers.js.map +1 -0
  325. package/dist/transfer/io.d.ts +74 -0
  326. package/dist/transfer/io.js +425 -0
  327. package/dist/transfer/io.js.map +1 -0
  328. package/dist/transfer/offers.d.ts +72 -0
  329. package/dist/transfer/offers.js +380 -0
  330. package/dist/transfer/offers.js.map +1 -0
  331. package/dist/transfer/stream-slots.d.ts +12 -0
  332. package/dist/transfer/stream-slots.js +28 -0
  333. package/dist/transfer/stream-slots.js.map +1 -0
  334. package/dist/work/catalog.d.ts +43 -0
  335. package/dist/work/catalog.js +198 -0
  336. package/dist/work/catalog.js.map +1 -0
  337. package/dist/work/discovery.d.ts +70 -0
  338. package/dist/work/discovery.js +465 -0
  339. package/dist/work/discovery.js.map +1 -0
  340. package/dist/work/service.d.ts +83 -0
  341. package/dist/work/service.js +703 -0
  342. package/dist/work/service.js.map +1 -0
  343. package/package.json +66 -4
@@ -0,0 +1,873 @@
1
+ import { createHash } from "node:crypto";
2
+ import { Blob, File } from "node:buffer";
3
+ import { constants, lstatSync, realpathSync } from "node:fs";
4
+ import { lstat, mkdir, mkdtemp, open, opendir, realpath, rename, rm, stat, } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { Readable } from "node:stream";
7
+ import { MIMEType, types } from "node:util";
8
+ import { AgentError, requireCondition } from "../contracts/errors.js";
9
+ import { authorizeCall } from "../contracts/caller.js";
10
+ import { canonicalJson, isPlainRecord, newId } from "../contracts/json.js";
11
+ import { contains, privateDirectory } from "../runtime/paths.js";
12
+ const resourceId = /^res_[0-9a-f]{32}$/;
13
+ const denied = new Set([
14
+ "forbidden",
15
+ "permission_denied",
16
+ "access_denied",
17
+ "resource_forbidden",
18
+ "path_not_allowed",
19
+ "unauthorized",
20
+ ]);
21
+ const metadataLimit = 16384;
22
+ const chunkSize = 65536;
23
+ const NativeBlob = Blob;
24
+ const nativeBlob = new NativeBlob([]);
25
+ const blobSymbols = Object.getOwnPropertySymbols(nativeBlob);
26
+ const blobHandleKey = blobSymbols.find((key) => key.description === "kHandle");
27
+ const blobLengthKey = blobSymbols.find((key) => key.description === "kLength");
28
+ const blobTypeKey = blobSymbols.find((key) => key.description === "kType");
29
+ const nativeHandle = Object.getOwnPropertyDescriptor(nativeBlob, blobHandleKey).value;
30
+ const nativeHandlePrototype = Object.getPrototypeOf(nativeHandle);
31
+ const nativeHandleSlice = Object.getOwnPropertyDescriptor(nativeHandlePrototype, "slice").value;
32
+ const nativeHandleReader = Object.getOwnPropertyDescriptor(nativeHandlePrototype, "getReader").value;
33
+ const nativeFile = new File([], "reference", { lastModified: 0 });
34
+ const fileStateKey = Object.getOwnPropertySymbols(nativeFile).find((key) => !blobSymbols.includes(key));
35
+ const nativeFileStatePrototype = Object.getPrototypeOf(Object.getOwnPropertyDescriptor(nativeFile, fileStateKey).value);
36
+ const arrayBufferSize = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
37
+ const sharedSize = Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, "byteLength").get;
38
+ const typedPrototype = Object.getPrototypeOf(Uint8Array.prototype);
39
+ const viewBuffer = Object.getOwnPropertyDescriptor(typedPrototype, "buffer").get;
40
+ const viewOffset = Object.getOwnPropertyDescriptor(typedPrototype, "byteOffset").get;
41
+ const viewSize = Object.getOwnPropertyDescriptor(typedPrototype, "byteLength").get;
42
+ const dataBuffer = Object.getOwnPropertyDescriptor(DataView.prototype, "buffer").get;
43
+ const dataOffset = Object.getOwnPropertyDescriptor(DataView.prototype, "byteOffset").get;
44
+ const dataSize = Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get;
45
+ function boundedInteger(value, maximum) {
46
+ return (Number.isSafeInteger(value) &&
47
+ value >= 0 &&
48
+ value <= maximum);
49
+ }
50
+ /**
51
+ * Node's public Blob getters inspect JS Symbol fields; they are not brand probes.
52
+ * This proves execution-safe native identity, not opaque queue byte length.
53
+ * Consumers must use bounded streams rather than size-then-arrayBuffer/text.
54
+ */
55
+ export function snapshotBlob(value, maximum = Number.MAX_SAFE_INTEGER) {
56
+ requireCondition(Number.isSafeInteger(maximum) && maximum >= 0, "invalid_resource_budget", "A Blob snapshot requires a bounded trusted byte budget.");
57
+ if (!value || typeof value !== "object" || types.isProxy(value))
58
+ return null;
59
+ let prototype = Object.getPrototypeOf(value), isBlob = false, isFile = false;
60
+ for (let depth = 0; prototype && depth < 64; depth++) {
61
+ requireCondition(!types.isProxy(prototype), "invalid_artifact_source", "A Blob prototype cannot be a Proxy.");
62
+ if (prototype === File.prototype)
63
+ isFile = true;
64
+ if (prototype === Blob.prototype) {
65
+ isBlob = true;
66
+ break;
67
+ }
68
+ prototype = Object.getPrototypeOf(prototype);
69
+ }
70
+ if (!isBlob)
71
+ return null;
72
+ const data = (key) => {
73
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
74
+ requireCondition(descriptor && "value" in descriptor, "invalid_artifact_source", "Blob internal fields must be own data properties.");
75
+ return descriptor.value;
76
+ };
77
+ const handle = data(blobHandleKey), size = data(blobLengthKey), type = data(blobTypeKey);
78
+ requireCondition(boundedInteger(size, maximum), "resource_too_large", "The Blob exceeds the configured content-size policy.");
79
+ requireCondition(typeof type === "string" && type.length <= 256, "invalid_artifact_source", "Blob MIME metadata must be bounded text.");
80
+ requireCondition(handle &&
81
+ typeof handle === "object" &&
82
+ !types.isProxy(handle) &&
83
+ Object.getPrototypeOf(handle) === nativeHandlePrototype &&
84
+ Reflect.ownKeys(handle).length === 0 &&
85
+ Object.getOwnPropertyDescriptor(nativeHandlePrototype, "slice")?.value ===
86
+ nativeHandleSlice &&
87
+ Object.getOwnPropertyDescriptor(nativeHandlePrototype, "getReader")
88
+ ?.value === nativeHandleReader, "invalid_artifact_source", "The Blob handle must retain its native identity and methods.");
89
+ try {
90
+ // V8's receiver signature rejects Object.create(nativeHandlePrototype)
91
+ // before entering C++; no user method or source Symbol getter is invoked.
92
+ Reflect.apply(nativeHandleSlice, handle, [0, 0]);
93
+ }
94
+ catch (cause) {
95
+ throw new AgentError("invalid_artifact_source", "The Blob handle is not an actual native Blob handle.", undefined, { cause });
96
+ }
97
+ let name, lastModified;
98
+ const fileState = Object.getOwnPropertyDescriptor(value, fileStateKey);
99
+ if (isFile || fileState) {
100
+ requireCondition(fileState &&
101
+ "value" in fileState &&
102
+ fileState.value &&
103
+ typeof fileState.value === "object" &&
104
+ !types.isProxy(fileState.value) &&
105
+ Object.getPrototypeOf(fileState.value) === nativeFileStatePrototype, "invalid_artifact_source", "File metadata must retain its native data shape.");
106
+ const fields = Object.getOwnPropertyDescriptors(fileState.value);
107
+ requireCondition(Reflect.ownKeys(fields).every((key) => (key === "name" || key === "lastModified") && "value" in fields[key]) &&
108
+ typeof fields.name?.value === "string" &&
109
+ typeof fields.lastModified?.value === "number", "invalid_artifact_source", "File name and time metadata cannot use accessors.");
110
+ name = displayName(fields.name.value);
111
+ lastModified = fields.lastModified.value;
112
+ }
113
+ // Only a fresh controlled carrier reaches Node's constructor. Cloning the
114
+ // original object could execute its additional enumerable getters; slice on
115
+ // an unvalidated source would read forged Symbol fields or a custom method.
116
+ const carrier = Object.create(null);
117
+ Object.defineProperties(carrier, {
118
+ [blobHandleKey]: { value: handle },
119
+ size: { value: size },
120
+ });
121
+ const blob = new NativeBlob([carrier], { type });
122
+ return Object.freeze({
123
+ blob,
124
+ size,
125
+ mimeType: Object.getOwnPropertyDescriptor(blob, blobTypeKey).value,
126
+ ...(name === undefined ? {} : { name }),
127
+ ...(lastModified === undefined ? {} : { lastModified }),
128
+ });
129
+ }
130
+ function mime(value) {
131
+ requireCondition(typeof value === "string" &&
132
+ value.length > 0 &&
133
+ value.length <= 256 &&
134
+ !/[\0\r\n]/.test(value), "invalid_artifact_source", "The resource MIME type must be bounded media-type text.");
135
+ try {
136
+ return new MIMEType(value).toString();
137
+ }
138
+ catch (cause) {
139
+ throw new AgentError("invalid_artifact_source", "The resource MIME type is invalid.", undefined, { cause });
140
+ }
141
+ }
142
+ function displayName(value) {
143
+ requireCondition(typeof value === "string" &&
144
+ value.length > 0 &&
145
+ Buffer.byteLength(value) <= 1024 &&
146
+ !/[\0\r\n]/.test(value), "invalid_artifact_source", "The resource name must be bounded display text.");
147
+ return value;
148
+ }
149
+ export function artifactUri(agentId, id) {
150
+ requireCondition(typeof agentId === "string" &&
151
+ agentId.length > 0 &&
152
+ Buffer.byteLength(agentId) <= 256 &&
153
+ !/[\0\r\n]/.test(agentId) &&
154
+ resourceId.test(id), "invalid_resource_uri", "A resource URI needs a valid Agent and resource identity.");
155
+ return `nexum://agents/${encodeURIComponent(agentId)}/resources/${id}`;
156
+ }
157
+ export function parseArtifactUri(uri) {
158
+ const match = typeof uri === "string" &&
159
+ /^nexum:\/\/agents\/([^/]+)\/resources\/(res_[0-9a-f]{32})$/.exec(uri);
160
+ requireCondition(match && uri.length <= 2048, "invalid_resource_uri", "The resource URI is invalid.");
161
+ let agentId;
162
+ try {
163
+ agentId = decodeURIComponent(match[1]);
164
+ }
165
+ catch (cause) {
166
+ throw new AgentError("invalid_resource_uri", "The Agent identity is not correctly encoded.", undefined, { cause });
167
+ }
168
+ requireCondition(artifactUri(agentId, match[2]) === uri, "invalid_resource_uri", "The resource URI must use its canonical encoding.");
169
+ return { agentId, resourceId: match[2] };
170
+ }
171
+ function publicRecord(record) {
172
+ return Object.freeze({
173
+ resourceId: record.resourceId,
174
+ agentId: record.agentId,
175
+ uri: record.uri,
176
+ name: record.name,
177
+ mimeType: record.mimeType,
178
+ size: record.size,
179
+ sha256: record.sha256,
180
+ originRunId: record.originRunId,
181
+ createdAt: record.createdAt,
182
+ expiresAt: record.expiresAt,
183
+ });
184
+ }
185
+ function permissionDenied(cause) {
186
+ if (!cause || typeof cause !== "object" || types.isProxy(cause))
187
+ return false;
188
+ const code = Object.getOwnPropertyDescriptor(cause, "code");
189
+ return !!code && "value" in code && denied.has(code.value);
190
+ }
191
+ function authority(check) {
192
+ try {
193
+ authorizeCall(check);
194
+ }
195
+ catch (cause) {
196
+ if (cause instanceof AgentError || permissionDenied(cause))
197
+ throw cause;
198
+ throw new AgentError("authorization_failed", "The current resource authority could not be verified.", undefined, { cause });
199
+ }
200
+ }
201
+ function unavailable(cause) {
202
+ return new AgentError("resource_unavailable", "The registered resource or its fixed content is unavailable.", undefined, { cause });
203
+ }
204
+ function sameFile(a, b) {
205
+ return (a.dev === b.dev &&
206
+ a.ino === b.ino &&
207
+ a.size === b.size &&
208
+ a.mtimeMs === b.mtimeMs &&
209
+ a.ctimeMs === b.ctimeMs);
210
+ }
211
+ async function openRegular(filename, code) {
212
+ // NONBLOCK also covers a regular file replaced by a FIFO between lstat/open.
213
+ // Opening an untrusted FIFO first would wait indefinitely outside AbortSignal.
214
+ requireCondition((await lstat(filename)).isFile(), code, "The resource source or stored content must be a regular file.");
215
+ const handle = await open(filename, constants.O_RDONLY |
216
+ (constants.O_NOFOLLOW ?? 0) |
217
+ (constants.O_NONBLOCK ?? 0));
218
+ try {
219
+ requireCondition((await handle.stat()).isFile(), code, "The resource source or stored content must remain a regular file.");
220
+ return handle;
221
+ }
222
+ catch (cause) {
223
+ await handle.close();
224
+ throw cause;
225
+ }
226
+ }
227
+ /** Fixed content and its directory catalog belong to one Agent/profile. */
228
+ export class ArtifactStore {
229
+ root;
230
+ agentId;
231
+ directory;
232
+ maxFileBytes;
233
+ maxReadBytes;
234
+ retentionMs;
235
+ #now;
236
+ #retentionUntil;
237
+ #reserve;
238
+ #active = new Map();
239
+ #pending = new Set();
240
+ constructor(root, agentId, options = {}) {
241
+ this.root = realpathSync.native(root);
242
+ requireCondition(path.resolve(root) === this.root, "storage_path_escape", "The established profile root cannot redirect elsewhere.");
243
+ artifactUri(agentId, "res_00000000000000000000000000000000");
244
+ this.agentId = agentId;
245
+ this.directory = privateDirectory(this.root, "work", "resources");
246
+ this.maxFileBytes = options.maxFileBytes ?? 256 * 1024 * 1024;
247
+ this.maxReadBytes = options.maxReadBytes ?? 64 * 1024 * 1024;
248
+ this.retentionMs = options.retentionMs ?? 7 * 86400000;
249
+ this.#now = options.now ?? Date.now;
250
+ this.#retentionUntil = options.retentionUntil;
251
+ this.#reserve = options.reserve;
252
+ requireCondition(boundedInteger(this.maxFileBytes, 20 * 1024 ** 3) &&
253
+ this.maxFileBytes > 0 &&
254
+ boundedInteger(this.maxReadBytes, 128 * 1024 ** 2) &&
255
+ this.maxReadBytes > 0 &&
256
+ boundedInteger(this.retentionMs, 365 * 86400000) &&
257
+ this.retentionMs > 0, "invalid_artifact_options", "Resource size, read and retention policies must be positive bounded Agent configuration.");
258
+ }
259
+ activeSnapshot() {
260
+ return Object.freeze({
261
+ resourceIds: new Set(this.#active.keys()),
262
+ pendingPaths: new Set(this.#pending),
263
+ });
264
+ }
265
+ #pin(id) {
266
+ this.#active.set(id, (this.#active.get(id) ?? 0) + 1);
267
+ let released = false;
268
+ return () => {
269
+ if (released)
270
+ return;
271
+ released = true;
272
+ const count = (this.#active.get(id) ?? 1) - 1;
273
+ if (count)
274
+ this.#active.set(id, count);
275
+ else
276
+ this.#active.delete(id);
277
+ };
278
+ }
279
+ #assert(scope) {
280
+ scope.signal?.throwIfAborted();
281
+ authority(() => scope.assertCurrent());
282
+ requireCondition(typeof scope.ownerKey === "string" &&
283
+ scope.ownerKey.length > 0 &&
284
+ Buffer.byteLength(scope.ownerKey) <= 256 &&
285
+ path.isAbsolute(scope.pwd), "invalid_artifact_context", "Resources need the trusted owner and absolute working directory.");
286
+ }
287
+ #check(scope, target) {
288
+ this.#assert(scope);
289
+ authority(() => scope.authorize(Object.freeze(target)));
290
+ }
291
+ #root() {
292
+ try {
293
+ requireCondition(realpathSync.native(this.root) === this.root &&
294
+ lstatSync(path.join(this.root, "work")).isDirectory() &&
295
+ lstatSync(this.directory).isDirectory() &&
296
+ realpathSync.native(this.directory) === this.directory, "storage_path_escape", "The resource catalog must remain inside the bound profile.");
297
+ }
298
+ catch (cause) {
299
+ if (cause instanceof AgentError)
300
+ throw cause;
301
+ throw unavailable(cause);
302
+ }
303
+ }
304
+ #path(id) {
305
+ this.#root();
306
+ requireCondition(resourceId.test(id), "invalid_resource_uri", "The resource identity is invalid.");
307
+ return path.join(this.directory, id);
308
+ }
309
+ async #stage(directory, expected) {
310
+ this.#root();
311
+ requireCondition(path.dirname(directory) === this.directory &&
312
+ path.basename(directory).startsWith(".pending-"), "storage_path_escape", "A resource preparation directory must belong to this catalog.");
313
+ const content = path.join(directory, "content");
314
+ const info = await lstat(directory), contentInfo = await lstat(content);
315
+ requireCondition(info.isDirectory() &&
316
+ (await realpath(directory)) === directory &&
317
+ contentInfo.isDirectory() &&
318
+ (await realpath(content)) === content, "storage_path_escape", "A resource preparation directory cannot redirect elsewhere.");
319
+ if (expected) {
320
+ requireCondition(info.dev === expected.directory.dev &&
321
+ info.ino === expected.directory.ino &&
322
+ contentInfo.dev === expected.content.dev &&
323
+ contentInfo.ino === expected.content.ino, "resource_preparation_changed", "The resource preparation directories were replaced.");
324
+ for (const [filename, previous] of [
325
+ [path.join(content, "data"), expected.data],
326
+ [path.join(directory, "resource.json"), expected.metadata],
327
+ ]) {
328
+ if (!previous)
329
+ continue;
330
+ const current = await lstat(filename);
331
+ requireCondition(current.isFile() && sameFile(previous, current), "resource_preparation_changed", "The fixed resource files were replaced or changed before publication.");
332
+ }
333
+ }
334
+ return expected ?? { directory: info, content: contentInfo };
335
+ }
336
+ async #directory(id) {
337
+ const directory = this.#path(id);
338
+ try {
339
+ const info = await lstat(directory);
340
+ requireCondition(info.isDirectory() &&
341
+ (await realpath(directory)) === directory &&
342
+ contains(this.directory, directory), "storage_path_escape", "The registered resource directory cannot redirect elsewhere.");
343
+ const content = path.join(directory, "content");
344
+ requireCondition((await lstat(content)).isDirectory() &&
345
+ (await realpath(content)) === content, "storage_path_escape", "The resource content directory cannot redirect elsewhere.");
346
+ return directory;
347
+ }
348
+ catch (cause) {
349
+ if (cause instanceof AgentError)
350
+ throw cause;
351
+ throw unavailable(cause);
352
+ }
353
+ }
354
+ #id(uri) {
355
+ const target = parseArtifactUri(uri);
356
+ requireCondition(target.agentId === this.agentId, "resource_agent_mismatch", "The resource belongs to another Agent.");
357
+ return target.resourceId;
358
+ }
359
+ async #stored(uri, scope) {
360
+ this.#check(scope, { action: "read", uri });
361
+ const id = this.#id(uri), directory = await this.#directory(id);
362
+ let handle;
363
+ try {
364
+ handle = await openRegular(path.join(directory, "resource.json"), "invalid_resource_metadata");
365
+ const info = await handle.stat();
366
+ requireCondition(info.isFile() && info.size > 0 && info.size <= metadataLimit, "invalid_resource_metadata", "The local resource registration is invalid or oversized.");
367
+ const data = Buffer.alloc(info.size);
368
+ const read = await handle.read(data, 0, data.length, 0);
369
+ requireCondition(read.bytesRead === data.length, "invalid_resource_metadata", "The local resource registration changed during reading.");
370
+ const parsed = JSON.parse(data.toString("utf8"));
371
+ requireCondition(isPlainRecord(parsed), "invalid_resource_metadata", "The local resource registration is invalid.");
372
+ const record = parsed;
373
+ requireCondition(record.schemaVersion === 1 &&
374
+ record.resourceId === id &&
375
+ record.agentId === this.agentId &&
376
+ record.uri === uri &&
377
+ typeof record.ownerKey === "string" &&
378
+ record.ownerKey.length > 0 &&
379
+ Buffer.byteLength(record.ownerKey) <= 256 &&
380
+ boundedInteger(record.size, 20 * 1024 ** 3) &&
381
+ typeof record.sha256 === "string" &&
382
+ /^[0-9a-f]{64}$/.test(record.sha256) &&
383
+ (record.originRunId === null ||
384
+ typeof record.originRunId === "string") &&
385
+ typeof record.createdAt === "string" &&
386
+ typeof record.expiresAt === "string" &&
387
+ Number.isFinite(Date.parse(record.createdAt)) &&
388
+ Number.isFinite(Date.parse(record.expiresAt)) &&
389
+ Date.parse(record.expiresAt) > Date.parse(record.createdAt), "invalid_resource_metadata", "The local resource registration does not match its identity and content policy.");
390
+ displayName(record.name);
391
+ requireCondition(mime(record.mimeType) === record.mimeType, "invalid_resource_metadata", "The registered resource MIME type is invalid.");
392
+ this.#check(scope, {
393
+ action: "read",
394
+ uri,
395
+ resource: Object.freeze(record),
396
+ });
397
+ const promisedUntil = this.#retentionUntil?.(record.resourceId, record.originRunId, Date.parse(record.expiresAt)) ?? 0;
398
+ requireCondition(Number.isSafeInteger(promisedUntil) && promisedUntil >= 0, "invalid_retention", "The trusted artifact retention deadline is invalid.");
399
+ requireCondition(this.#now() < Math.max(Date.parse(record.expiresAt), promisedUntil), "resource_expired", "The registered resource has expired; it cannot be recreated from a source path.");
400
+ return record;
401
+ }
402
+ catch (cause) {
403
+ if (cause instanceof AgentError ||
404
+ permissionDenied(cause) ||
405
+ scope.signal?.aborted)
406
+ throw cause;
407
+ throw unavailable(cause);
408
+ }
409
+ finally {
410
+ await handle?.close();
411
+ }
412
+ }
413
+ async #content(record) {
414
+ const directory = await this.#directory(record.resourceId);
415
+ let handle;
416
+ try {
417
+ handle = await openRegular(path.join(directory, "content", "data"), "resource_changed");
418
+ const info = await handle.stat();
419
+ requireCondition(info.isFile() && info.size === record.size, "resource_changed", "The registered content is no longer the fixed resource that was published.");
420
+ return { handle, info };
421
+ }
422
+ catch (cause) {
423
+ await handle?.close();
424
+ if (cause instanceof AgentError)
425
+ throw cause;
426
+ throw unavailable(cause);
427
+ }
428
+ }
429
+ async register(value, scope, inspect, options = {}) {
430
+ this.#assert(scope);
431
+ const effectiveMaximum = options.maxBytes === undefined ? this.maxFileBytes : options.maxBytes;
432
+ requireCondition(boundedInteger(effectiveMaximum, this.maxFileBytes) &&
433
+ effectiveMaximum > 0, "invalid_resource_budget", "The trusted registration budget must be positive and cannot exceed the Agent file policy.");
434
+ requireCondition(isPlainRecord(value), "invalid_artifact_source", "A resource source must be ordinary data.");
435
+ const fields = Object.getOwnPropertyDescriptors(value);
436
+ requireCondition(Reflect.ownKeys(fields).every((key) => typeof key === "string" &&
437
+ ["path", "data", "name", "mimeType"].includes(key) &&
438
+ "value" in fields[key]) &&
439
+ Number(Object.hasOwn(fields, "path")) +
440
+ Number(Object.hasOwn(fields, "data")) ===
441
+ 1, "invalid_artifact_source", "A resource needs exactly one path or native binary source and data fields.");
442
+ const source = Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, field.value]));
443
+ let bytes, blob, sourcePath;
444
+ let size, name = source.name, mimeType = source.mimeType;
445
+ if (Object.hasOwn(fields, "path")) {
446
+ requireCondition(typeof source.path === "string" &&
447
+ source.path.length > 0 &&
448
+ Buffer.byteLength(source.path) <= 262144 &&
449
+ !source.path.includes("\0"), "invalid_artifact_source", "A resource source path must be nonempty bounded text.");
450
+ sourcePath = path.resolve(scope.pwd, source.path);
451
+ name ??= path.basename(sourcePath);
452
+ this.#check(scope, { action: "register", path: sourcePath });
453
+ size = 0;
454
+ }
455
+ else {
456
+ const data = source.data;
457
+ requireCondition(data && typeof data === "object" && !types.isProxy(data), "invalid_artifact_source", "A resource needs an actual native binary source.");
458
+ try {
459
+ let native;
460
+ if (types.isDataView(data)) {
461
+ size = dataSize.call(data);
462
+ native = new Uint8Array(dataBuffer.call(data), dataOffset.call(data), size);
463
+ }
464
+ else if (types.isArrayBufferView(data)) {
465
+ size = viewSize.call(data);
466
+ native = new Uint8Array(viewBuffer.call(data), viewOffset.call(data), size);
467
+ }
468
+ else if (types.isSharedArrayBuffer(data) ||
469
+ types.isArrayBuffer(data)) {
470
+ size = (types.isSharedArrayBuffer(data) ? sharedSize : arrayBufferSize).call(data);
471
+ native = new Uint8Array(data);
472
+ }
473
+ else {
474
+ const snapshot = snapshotBlob(data, effectiveMaximum);
475
+ requireCondition(snapshot, "invalid_artifact_source", "A resource source must be an actual native Blob or File.");
476
+ size = snapshot.size;
477
+ blob = snapshot.blob;
478
+ mimeType ??= snapshot.mimeType || undefined;
479
+ name ??= snapshot.name;
480
+ }
481
+ requireCondition(boundedInteger(size, effectiveMaximum), "resource_too_large", "The resource exceeds the configured file-size policy.");
482
+ // Fix a mutable native view synchronously, before any asynchronous work.
483
+ if (native)
484
+ bytes = Buffer.from(native);
485
+ }
486
+ catch (cause) {
487
+ if (cause instanceof AgentError)
488
+ throw cause;
489
+ throw new AgentError("invalid_artifact_source", "The binary source is invalid or detached.", undefined, { cause });
490
+ }
491
+ this.#check(scope, { action: "register" });
492
+ }
493
+ name = displayName(name ?? "resource.bin");
494
+ mimeType = mime(mimeType ?? "application/octet-stream");
495
+ const id = newId("res"), uri = artifactUri(this.agentId, id);
496
+ this.#root();
497
+ let temporary, input, output;
498
+ let before;
499
+ let prepared;
500
+ let reservation;
501
+ let pendingPath;
502
+ const release = this.#pin(id);
503
+ try {
504
+ if (sourcePath) {
505
+ const canonical = await realpath(sourcePath);
506
+ this.#check(scope, { action: "register", path: canonical });
507
+ input = await openRegular(canonical, "invalid_artifact_source");
508
+ before = await input.stat();
509
+ requireCondition(before.isFile(), "invalid_artifact_source", "A local resource source must be a readable regular file.");
510
+ requireCondition(boundedInteger(before.size, effectiveMaximum), "resource_too_large", "The resource exceeds the configured file-size policy.");
511
+ size = before.size;
512
+ sourcePath = canonical;
513
+ }
514
+ this.#check(scope, {
515
+ action: "register",
516
+ ...(sourcePath ? { path: sourcePath } : {}),
517
+ });
518
+ this.#root();
519
+ reservation = await this.#reserve?.(size + metadataLimit + 1024, {
520
+ control: scope.controlStorage === true,
521
+ });
522
+ temporary = await mkdtemp(path.join(this.directory, ".pending-"));
523
+ pendingPath = temporary;
524
+ this.#pending.add(temporary);
525
+ await mkdir(path.join(temporary, "content"), { mode: 0o700 });
526
+ prepared = await this.#stage(temporary);
527
+ output = await open(path.join(temporary, "content", "data"), "wx", 0o600);
528
+ const hash = createHash("sha256");
529
+ let copied = 0;
530
+ const write = async (chunk) => {
531
+ this.#check(scope, {
532
+ action: "register",
533
+ ...(sourcePath ? { path: sourcePath } : {}),
534
+ });
535
+ copied += chunk.byteLength;
536
+ requireCondition(copied <= effectiveMaximum && copied <= size, "resource_too_large", "The resource changed size or exceeds its configured policy.");
537
+ hash.update(chunk);
538
+ let offset = 0;
539
+ while (offset < chunk.byteLength) {
540
+ const result = await output.write(chunk, offset, chunk.byteLength - offset, null);
541
+ requireCondition(result.bytesWritten > 0, "resource_persistence_failed", "The fixed resource content could not be written.");
542
+ offset += result.bytesWritten;
543
+ }
544
+ };
545
+ if (input) {
546
+ while (true) {
547
+ this.#check(scope, { action: "register", path: sourcePath });
548
+ const buffer = Buffer.allocUnsafe(chunkSize);
549
+ const read = await input.read(buffer, 0, buffer.length, null);
550
+ if (!read.bytesRead)
551
+ break;
552
+ await write(buffer.subarray(0, read.bytesRead));
553
+ }
554
+ requireCondition(sameFile(before, await input.stat()) &&
555
+ (await realpath(sourcePath)) === sourcePath &&
556
+ sameFile(before, await stat(sourcePath)), "resource_source_changed", "The source file changed while its content was being fixed.");
557
+ await input.close();
558
+ input = undefined;
559
+ }
560
+ else if (bytes) {
561
+ for (let offset = 0; offset < bytes.byteLength; offset += chunkSize)
562
+ await write(bytes.subarray(offset, offset + chunkSize));
563
+ }
564
+ else {
565
+ for await (const chunk of Readable.fromWeb(Blob.prototype.stream.call(blob)))
566
+ await write(chunk);
567
+ }
568
+ requireCondition(copied === size, "resource_source_changed", "The source ended before its declared content was fixed.");
569
+ await output.sync();
570
+ prepared.data = await output.stat();
571
+ await output.close();
572
+ output = undefined;
573
+ if (inspect) {
574
+ await this.#stage(temporary, prepared);
575
+ this.#check(scope, {
576
+ action: "register",
577
+ ...(sourcePath ? { path: sourcePath } : {}),
578
+ });
579
+ const result = await inspect(Object.freeze({
580
+ path: path.join(temporary, "content", "data"),
581
+ size: copied,
582
+ name,
583
+ mimeType,
584
+ }));
585
+ requireCondition(isPlainRecord(result), "invalid_artifact_inspection", "The trusted content inspector must return metadata data.");
586
+ const fields = Object.getOwnPropertyDescriptors(result);
587
+ requireCondition(Reflect.ownKeys(fields).every((key) => key === "mimeType" && "value" in fields[key]), "invalid_artifact_inspection", "The trusted content inspector may only refine the MIME type.");
588
+ if (fields.mimeType)
589
+ mimeType = mime(fields.mimeType.value);
590
+ await this.#stage(temporary, prepared);
591
+ this.#check(scope, {
592
+ action: "register",
593
+ ...(sourcePath ? { path: sourcePath } : {}),
594
+ });
595
+ }
596
+ const now = this.#now();
597
+ requireCondition(boundedInteger(now, 253402300799999 - this.retentionMs), "invalid_artifact_clock", "The resource clock cannot represent its expiry.");
598
+ const record = Object.freeze({
599
+ schemaVersion: 1,
600
+ ownerKey: scope.ownerKey,
601
+ resourceId: id,
602
+ agentId: this.agentId,
603
+ uri,
604
+ name,
605
+ mimeType,
606
+ size: copied,
607
+ sha256: hash.digest("hex"),
608
+ originRunId: scope.runId ?? null,
609
+ createdAt: new Date(now).toISOString(),
610
+ expiresAt: new Date(now + this.retentionMs).toISOString(),
611
+ });
612
+ this.#check(scope, {
613
+ action: "register",
614
+ ...(sourcePath ? { path: sourcePath } : {}),
615
+ resource: record,
616
+ });
617
+ await this.#stage(temporary, prepared);
618
+ const metadata = await open(path.join(temporary, "resource.json"), "wx", 0o600);
619
+ try {
620
+ await metadata.writeFile(canonicalJson(record, metadataLimit));
621
+ await metadata.sync();
622
+ prepared.metadata = await metadata.stat();
623
+ }
624
+ finally {
625
+ await metadata.close();
626
+ }
627
+ this.#check(scope, {
628
+ action: "register",
629
+ ...(sourcePath ? { path: sourcePath } : {}),
630
+ resource: record,
631
+ });
632
+ await this.#stage(temporary, prepared);
633
+ this.#check(scope, {
634
+ action: "register",
635
+ ...(sourcePath ? { path: sourcePath } : {}),
636
+ resource: record,
637
+ });
638
+ await rename(temporary, this.#path(id));
639
+ temporary = undefined;
640
+ this.#check(scope, {
641
+ action: "register",
642
+ ...(sourcePath ? { path: sourcePath } : {}),
643
+ resource: record,
644
+ });
645
+ return publicRecord(record);
646
+ }
647
+ catch (cause) {
648
+ if (cause instanceof AgentError ||
649
+ permissionDenied(cause) ||
650
+ scope.signal?.aborted)
651
+ throw cause;
652
+ throw new AgentError("resource_registration_failed", "The resource could not be fixed and registered; no completed identity was published.", undefined, { cause });
653
+ }
654
+ finally {
655
+ try {
656
+ await input?.close();
657
+ await output?.close();
658
+ if (temporary) {
659
+ this.#root();
660
+ await rm(temporary, { recursive: true, force: true });
661
+ }
662
+ }
663
+ finally {
664
+ if (pendingPath)
665
+ this.#pending.delete(pendingPath);
666
+ release();
667
+ reservation?.release();
668
+ }
669
+ }
670
+ }
671
+ async metadata(uri, scope) {
672
+ const release = this.#pin(this.#id(uri));
673
+ try {
674
+ const record = await this.#stored(uri, scope), content = await this.#content(record);
675
+ await content.handle.close();
676
+ this.#check(scope, { action: "read", uri, resource: record });
677
+ return publicRecord(record);
678
+ }
679
+ finally {
680
+ release();
681
+ }
682
+ }
683
+ async list(scope, options = {}) {
684
+ this.#check(scope, { action: "list" });
685
+ this.#root();
686
+ const limit = options.limit ?? 20;
687
+ requireCondition(Number.isSafeInteger(limit) && limit > 0 && limit <= 100, "invalid_limit", "A resource list needs a limit from 1 through 100.");
688
+ const requestedMaximum = options.maxBytes;
689
+ requireCondition(requestedMaximum === undefined ||
690
+ (Number.isSafeInteger(requestedMaximum) && requestedMaximum > 0), "invalid_resource_budget", "A resource page requires a positive trusted byte budget.");
691
+ const maximum = requestedMaximum === undefined
692
+ ? undefined
693
+ : Math.min(requestedMaximum, 1024 * 1024);
694
+ let after = "";
695
+ if (options.cursor !== undefined) {
696
+ requireCondition(typeof options.cursor === "string" &&
697
+ options.cursor.length <= 2048 &&
698
+ /^[A-Za-z0-9_-]+$/.test(options.cursor), "invalid_cursor", "The resource cursor is invalid.");
699
+ let cursor;
700
+ try {
701
+ cursor = JSON.parse(Buffer.from(options.cursor, "base64url").toString("utf8"));
702
+ }
703
+ catch {
704
+ throw new AgentError("invalid_cursor", "The resource cursor is invalid.");
705
+ }
706
+ requireCondition(isPlainRecord(cursor) &&
707
+ cursor.agentId === this.agentId &&
708
+ cursor.ownerKey === scope.ownerKey &&
709
+ typeof cursor.after === "string" &&
710
+ resourceId.test(cursor.after), "invalid_cursor", "The resource cursor belongs to another caller or catalog.");
711
+ after = cursor.after;
712
+ }
713
+ const resources = [];
714
+ let scanned = 0;
715
+ const entries = await opendir(this.directory);
716
+ for await (const entry of entries) {
717
+ this.#check(scope, { action: "list" });
718
+ requireCondition(++scanned <= 100000, "resource_catalog_too_large", "The local resource catalog exceeds its bounded scan budget.");
719
+ if (!entry.isDirectory() ||
720
+ !resourceId.test(entry.name) ||
721
+ entry.name <= after)
722
+ continue;
723
+ try {
724
+ const record = await this.metadata(artifactUri(this.agentId, entry.name), scope);
725
+ resources.push(record);
726
+ resources.sort((a, b) => a.resourceId.localeCompare(b.resourceId));
727
+ if (resources.length > limit + 1)
728
+ resources.pop();
729
+ }
730
+ catch (cause) {
731
+ if (permissionDenied(cause) ||
732
+ (cause instanceof AgentError &&
733
+ ["resource_expired", "resource_unavailable"].includes(cause.code)))
734
+ continue;
735
+ throw cause;
736
+ }
737
+ }
738
+ this.#check(scope, { action: "list" });
739
+ const cursorAt = (count) => resources.length > count
740
+ ? Buffer.from(canonicalJson({
741
+ agentId: this.agentId,
742
+ ownerKey: scope.ownerKey,
743
+ after: resources[count - 1].resourceId,
744
+ })).toString("base64url")
745
+ : null;
746
+ let count = Math.min(limit, resources.length);
747
+ if (maximum !== undefined) {
748
+ let bytes = 0, selected = -1;
749
+ if (count === 0) {
750
+ if (Buffer.byteLength(JSON.stringify({ resources: [], nextCursor: null })) <= maximum)
751
+ selected = 0;
752
+ }
753
+ else {
754
+ for (let index = 0; index < count; index++) {
755
+ bytes += Buffer.byteLength(JSON.stringify(resources[index]));
756
+ // The empty array already includes its brackets; add entries and commas.
757
+ const size = Buffer.byteLength(JSON.stringify({
758
+ resources: [],
759
+ nextCursor: cursorAt(index + 1),
760
+ })) +
761
+ bytes +
762
+ index;
763
+ if (size <= maximum)
764
+ selected = index + 1;
765
+ // A final page can lose a long caller-bound cursor. Inspect all prefixes
766
+ // rather than treating an oversized earlier prefix as the final answer.
767
+ }
768
+ }
769
+ requireCondition(selected >= 0, "resource_list_too_large", "The next resource page cannot fit the current metadata budget without skipping an entry.");
770
+ count = selected;
771
+ }
772
+ return Object.freeze({
773
+ resources: Object.freeze(resources.slice(0, count)),
774
+ nextCursor: cursorAt(count),
775
+ });
776
+ }
777
+ async open(uri, scope) {
778
+ const release = this.#pin(this.#id(uri));
779
+ try {
780
+ const result = await this.#open(uri, scope);
781
+ void result.closed.then(release, release);
782
+ return result;
783
+ }
784
+ catch (cause) {
785
+ release();
786
+ throw cause;
787
+ }
788
+ }
789
+ async #open(uri, scope) {
790
+ const record = await this.#stored(uri, scope);
791
+ requireCondition(record.size <= this.maxFileBytes, "resource_too_large", "The registered resource exceeds the current file policy.");
792
+ const { handle, info } = await this.#content(record);
793
+ try {
794
+ this.#check(scope, { action: "read", uri, resource: record });
795
+ }
796
+ catch (cause) {
797
+ await handle.close();
798
+ throw cause;
799
+ }
800
+ let closing;
801
+ const close = () => (closing ??= handle.close());
802
+ const closed = Promise.withResolvers();
803
+ // The public completion remains awaitable even when the consumer observes a
804
+ // stream error first. An unobserved internal notification must not crash Node.
805
+ void closed.promise.catch(() => { });
806
+ const check = () => this.#check(scope, { action: "read", uri, resource: record });
807
+ const content = async function* () {
808
+ let count = 0;
809
+ const hash = createHash("sha256");
810
+ try {
811
+ while (true) {
812
+ check();
813
+ const buffer = Buffer.allocUnsafe(chunkSize);
814
+ const read = await handle.read(buffer, 0, buffer.length, null);
815
+ check();
816
+ if (!read.bytesRead)
817
+ break;
818
+ count += read.bytesRead;
819
+ requireCondition(count <= record.size, "resource_changed", "The registered resource changed during reading.");
820
+ const chunk = buffer.subarray(0, read.bytesRead);
821
+ hash.update(chunk);
822
+ yield chunk;
823
+ }
824
+ requireCondition(count === record.size &&
825
+ hash.digest("hex") === record.sha256 &&
826
+ sameFile(info, await handle.stat()), "resource_changed", "The registered resource no longer matches its fixed content.");
827
+ check();
828
+ }
829
+ finally {
830
+ await close();
831
+ }
832
+ };
833
+ const stream = Readable.from(content());
834
+ stream.once("close", () => {
835
+ void close().then(closed.resolve, closed.reject);
836
+ });
837
+ if (scope.signal) {
838
+ const aborted = () => stream.destroy(new AgentError("resource_read_cancelled", "The resource read was cancelled."));
839
+ scope.signal.addEventListener("abort", aborted, { once: true });
840
+ stream.once("close", () => scope.signal.removeEventListener("abort", aborted));
841
+ if (scope.signal.aborted)
842
+ aborted();
843
+ }
844
+ return Object.freeze({
845
+ resource: publicRecord(record),
846
+ stream,
847
+ closed: closed.promise,
848
+ });
849
+ }
850
+ async read(uri, scope, options) {
851
+ requireCondition(boundedInteger(options.maxBytes, this.maxReadBytes), "invalid_resource_budget", "The trusted resource-read budget cannot exceed its Agent policy.");
852
+ const resource = await this.metadata(uri, scope);
853
+ requireCondition(resource.size <= options.maxBytes, "resource_read_too_large", "The resource exceeds this response budget; use transfer.createDownload({ uri }) for a file stream.", { uri, size: resource.size });
854
+ const result = await this.open(uri, scope), chunks = [];
855
+ let count = 0;
856
+ try {
857
+ for await (const chunk of result.stream) {
858
+ count += chunk.byteLength;
859
+ requireCondition(count <= options.maxBytes, "resource_read_too_large", "The resource exceeds this response budget; use a download stream.");
860
+ chunks.push(chunk);
861
+ }
862
+ }
863
+ finally {
864
+ result.stream.destroy();
865
+ await result.closed;
866
+ }
867
+ return Object.freeze({
868
+ resource: result.resource,
869
+ data: Buffer.concat(chunks, count),
870
+ });
871
+ }
872
+ }
873
+ //# sourceMappingURL=artifacts.js.map