@nexum-hub/agent 0.0.0-stage → 0.0.1

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 +129 -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,1855 @@
1
+ import { chmodSync, lstatSync, mkdirSync, realpathSync } from "node:fs";
2
+ import { createCipheriv, createDecipheriv, randomBytes, } from "node:crypto";
3
+ import path from "node:path";
4
+ import { MIMEType } from "node:util";
5
+ import { DatabaseSync } from "node:sqlite";
6
+ import { AgentError, isAgentError, requireCondition, } from "../contracts/errors.js";
7
+ import { canonicalJson, digest, newId, requestWindow, isPlainRecord, } from "../contracts/json.js";
8
+ import { terminalStatuses, DEFAULT_CONTROL_CAPACITY, } from "../contracts/types.js";
9
+ import { migration1, migration2, migration3, migration4, migration5, migration6, migration7, schemaVersion, } from "./schema.js";
10
+ const terminalSql = "'succeeded','failed','cancelled','interrupted'";
11
+ const taskTerminal = new Set([
12
+ "completed",
13
+ "cancelled",
14
+ "failed",
15
+ ]);
16
+ const transitions = {
17
+ accepted: ["preparing_inputs", "failed"],
18
+ preparing_inputs: ["running", "failed"],
19
+ running: ["succeeded", "failed"],
20
+ waiting_input: ["failed"],
21
+ cancelling: ["cancelled", "failed"],
22
+ succeeded: [],
23
+ failed: [],
24
+ cancelled: [],
25
+ interrupted: [],
26
+ };
27
+ function decode(row) {
28
+ const value = {};
29
+ for (const [key, item] of Object.entries(row)) {
30
+ if (key.startsWith("retention_"))
31
+ continue;
32
+ const json = key.endsWith("_json");
33
+ const name = (json ? key.slice(0, -5) : key).replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
34
+ value[name] = json && item !== null ? JSON.parse(item) : item;
35
+ }
36
+ return value;
37
+ }
38
+ const maintenanceMethods = new Set([
39
+ "packages.install",
40
+ "packages.update",
41
+ "packages.remove",
42
+ "extensions.enable",
43
+ "extensions.disable",
44
+ "mcp.add",
45
+ "mcp.update",
46
+ "mcp.remove",
47
+ "api.import",
48
+ "api.update",
49
+ "api.remove",
50
+ ]);
51
+ const maintenanceRequest = /^maint_req_[A-Za-z0-9_-]{1,128}$/;
52
+ export class SqliteStore {
53
+ bootId;
54
+ root;
55
+ binding;
56
+ #db;
57
+ #cursorKey = randomBytes(32);
58
+ #closed = false;
59
+ #retention;
60
+ constructor(root, binding, now = Date.now(), bootId = newId("boot"), retention = {}) {
61
+ this.#retention = Object.freeze({
62
+ workIdleMs: retention.workIdleMs ?? 86400000,
63
+ runHistoryMs: retention.runHistoryMs ?? 30 * 86400000,
64
+ runLogsMs: retention.runLogsMs ?? 7 * 86400000,
65
+ inputAttachmentsMs: retention.inputAttachmentsMs ?? 86400000,
66
+ });
67
+ requireCondition(Object.values(this.#retention).every((value) => Number.isSafeInteger(value) && value > 0 && value <= 253402300799999), "invalid_retention_policy", "Retention periods must be positive supported millisecond durations.");
68
+ requireCondition(typeof bootId === "string" && /^boot_[0-9a-f]{32}$/.test(bootId), "invalid_boot_id", "The Agent process boot identity is invalid.");
69
+ this.bootId = bootId;
70
+ requireCondition(path.isAbsolute(root), "invalid_root", "The Agent root must be absolute.");
71
+ requireCondition(binding.agentId &&
72
+ binding.cloudEnvironment &&
73
+ ["development", "production"].includes(binding.profile), "invalid_binding", "The Agent database requires a complete binding.");
74
+ requireCondition(!lstatSync(root, { throwIfNoEntry: false })?.isSymbolicLink(), "storage_path_escape", "The Agent root must not redirect to another profile.");
75
+ mkdirSync(root, { recursive: true, mode: 0o700 });
76
+ this.root = realpathSync.native(root);
77
+ this.binding = Object.freeze({ ...binding });
78
+ const directory = path.join(this.root, "state");
79
+ requireCondition(!lstatSync(directory, { throwIfNoEntry: false })?.isSymbolicLink(), "storage_path_escape", "The lifecycle directory must not be redirected.");
80
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
81
+ const relative = path.relative(this.root, realpathSync.native(directory));
82
+ requireCondition(relative !== ".." &&
83
+ !relative.startsWith(".." + path.sep) &&
84
+ !path.isAbsolute(relative), "storage_path_escape", "The lifecycle directory must remain inside this Agent root.");
85
+ const filename = path.join(directory, "runtime.sqlite");
86
+ for (const candidate of [filename, filename + "-wal", filename + "-shm"]) {
87
+ const existing = lstatSync(candidate, { throwIfNoEntry: false });
88
+ requireCondition(!existing || (!existing.isSymbolicLink() && existing.isFile()), "storage_path_escape", "Database files must be regular files inside the lifecycle directory.");
89
+ }
90
+ this.#db = new DatabaseSync(filename, {
91
+ timeout: 100,
92
+ enableForeignKeyConstraints: true,
93
+ allowExtension: false,
94
+ });
95
+ try {
96
+ if (process.platform !== "win32")
97
+ chmodSync(filename, 0o600);
98
+ this.#db.exec("PRAGMA locking_mode=EXCLUSIVE; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON;");
99
+ for (const [pragma, expected] of [
100
+ ["locking_mode", "exclusive"],
101
+ ["journal_mode", "wal"],
102
+ ["synchronous", 2],
103
+ ["foreign_keys", 1],
104
+ ]) {
105
+ requireCondition(this.#db.prepare(`PRAGMA ${pragma}`).get()?.[pragma] === expected, "storage_configuration", `SQLite could not apply ${pragma}.`);
106
+ }
107
+ const version = this.#db.prepare("PRAGMA user_version").get()
108
+ ?.user_version;
109
+ requireCondition(version <= schemaVersion, "storage_future_version", "The database requires a newer Agent.");
110
+ this.#transaction(() => {
111
+ if (version === 0) {
112
+ this.#db.exec(migration1);
113
+ }
114
+ if (version < 2)
115
+ this.#db.exec(migration2);
116
+ if (version < 3)
117
+ this.#db.exec(migration3);
118
+ if (version < 4)
119
+ this.#db.exec(migration4);
120
+ if (version < 5)
121
+ this.#db.exec(migration5);
122
+ if (version < 6)
123
+ this.#db.exec(migration6);
124
+ if (version < 7)
125
+ this.#db.exec(migration7);
126
+ this.#db.exec(`PRAGMA user_version=${schemaVersion}`);
127
+ const metadata = this.#db
128
+ .prepare("SELECT * FROM runtime_meta WHERE singleton=1")
129
+ .get();
130
+ if (metadata) {
131
+ requireCondition(metadata.agent_id === binding.agentId &&
132
+ metadata.profile === binding.profile &&
133
+ metadata.cloud_environment === binding.cloudEnvironment, "storage_binding_mismatch", "The database belongs to a different Agent, profile, or Cloud environment.");
134
+ }
135
+ else {
136
+ // Only a newly created, empty schema may acquire its initial binding.
137
+ const count = this.#db
138
+ .prepare("SELECT count(*) n FROM runs")
139
+ .get()?.n;
140
+ requireCondition(count === 0 && version === 0, "storage_binding_missing", "The existing database binding is missing.");
141
+ this.#db
142
+ .prepare("INSERT INTO runtime_meta VALUES(1,?,?,?,?)")
143
+ .run(binding.agentId, binding.profile, binding.cloudEnvironment, this.bootId);
144
+ }
145
+ this.#db
146
+ .prepare("UPDATE runtime_meta SET boot_id=? WHERE singleton=1")
147
+ .run(this.bootId);
148
+ this.#interrupt(now);
149
+ });
150
+ }
151
+ catch (error) {
152
+ this.#db.close();
153
+ throw this.#storageError(error);
154
+ }
155
+ }
156
+ #storageError(error) {
157
+ if (error instanceof AgentError)
158
+ return error;
159
+ const code = error?.errcode;
160
+ return new AgentError(code === 5 || code === 6 ? "storage_busy" : "storage_error", "The local lifecycle database operation failed.", undefined, { cause: error });
161
+ }
162
+ #transaction(operation) {
163
+ requireCondition(!this.#closed, "storage_closed", "The local store is closed.");
164
+ try {
165
+ this.#db.exec("BEGIN IMMEDIATE");
166
+ try {
167
+ const value = operation();
168
+ this.#db.exec("COMMIT");
169
+ return value;
170
+ }
171
+ catch (error) {
172
+ if (this.#db.isTransaction)
173
+ this.#db.exec("ROLLBACK");
174
+ throw error;
175
+ }
176
+ }
177
+ catch (error) {
178
+ throw this.#storageError(error);
179
+ }
180
+ }
181
+ #interrupt(now) {
182
+ const reason = canonicalJson({
183
+ code: "agent_restarted",
184
+ message: "The Agent restarted; execution was not restored.",
185
+ });
186
+ this.#db
187
+ .prepare("UPDATE work_contexts SET status='expired' WHERE status='open'")
188
+ .run();
189
+ this.#db
190
+ .prepare(`UPDATE runs SET status='interrupted',ended_at=?,updated_at=?,error_json=?,revision=revision+1
191
+ WHERE status NOT IN (${terminalSql})`)
192
+ .run(now, now, reason);
193
+ this.#db
194
+ .prepare("UPDATE run_waits SET status='cancelled',revision=revision+1 WHERE status='waiting'")
195
+ .run();
196
+ this.#db
197
+ .prepare(`UPDATE managed_resources SET status='unavailable',
198
+ diagnostic_json=json_set(json_patch(diagnostic_json,?),'$.osStopped',NULL,'$.unavailableAt',
199
+ CASE WHEN json_type(diagnostic_json,'$.unavailableAt') IN ('integer','real') THEN CAST(json_extract(diagnostic_json,'$.unavailableAt') AS INTEGER) ELSE CAST(? AS INTEGER) END),revision=revision+1 WHERE closed_at IS NULL`)
200
+ .run(canonicalJson({ code: "agent_restarted", controlAvailable: false }), now);
201
+ this.#db
202
+ .prepare(`UPDATE transfers SET status='interrupted',ended_at=?,revision=revision+1
203
+ WHERE status NOT IN ('succeeded','failed','cancelled','expired','interrupted')`)
204
+ .run(now);
205
+ this.#db
206
+ .prepare("UPDATE operations SET status='interrupted',ended_at=?,updated_at=?,error_json=?,revision=revision+1 WHERE ended_at IS NULL")
207
+ .run(now, now, reason);
208
+ }
209
+ close() {
210
+ if (!this.#closed) {
211
+ this.#db.close();
212
+ this.#closed = true;
213
+ }
214
+ }
215
+ #get(table, column, id, errorCode) {
216
+ const row = this.#db
217
+ .prepare(`SELECT * FROM ${table} WHERE ${column}=?`)
218
+ .get(id);
219
+ requireCondition(row, errorCode, "The requested local record does not exist.");
220
+ return decode(row);
221
+ }
222
+ getWork(id) {
223
+ return this.#get("work_contexts", "context_id", id, "context_not_found");
224
+ }
225
+ activeWork(id, callerKey, now = Date.now()) {
226
+ return this.#activeWork(id, callerKey, now);
227
+ }
228
+ getRun(id) {
229
+ return this.#get("runs", "run_id", id, "run_not_found");
230
+ }
231
+ /** Bind an existing, authorized run before a Task handle can leave the Agent. */
232
+ createTask(input, now = Date.now()) {
233
+ requireCondition(/^nx_task_[A-Za-z0-9_-]{1,1016}$/.test(input.taskId) &&
234
+ typeof input.callerKey === "string" &&
235
+ input.callerKey.length > 0 &&
236
+ Number.isSafeInteger(input.ttlMs) &&
237
+ input.ttlMs > 0 &&
238
+ Number.isSafeInteger(now) &&
239
+ now >= 0 &&
240
+ Number.isSafeInteger(now + input.ttlMs) &&
241
+ now + input.ttlMs <= 253402300799999, "invalid_task", "The Task identity or retention deadline is invalid.");
242
+ return this.#transaction(() => {
243
+ const run = this.getRun(input.runId);
244
+ requireCondition(run.callerKey === input.callerKey, "task_not_found", "The Task run is unavailable to this caller.");
245
+ const previous = this.#db
246
+ .prepare("SELECT * FROM mcp_tasks WHERE caller_key=? AND run_id=? AND expires_at>? ORDER BY created_at,task_id LIMIT 1")
247
+ .get(input.callerKey, input.runId, now);
248
+ // A retried create never renews a published promise.
249
+ if (previous)
250
+ return decode(previous);
251
+ this.#db
252
+ .prepare("INSERT INTO mcp_tasks(task_id,caller_key,run_id,status,created_at,updated_at,expires_at) VALUES(?,?,?,'working',?,?,?)")
253
+ .run(input.taskId, input.callerKey, input.runId, now, now, now + input.ttlMs);
254
+ return this.getTask(input.taskId, input.callerKey, now);
255
+ });
256
+ }
257
+ getTask(taskId, key, now = Date.now()) {
258
+ const row = this.#db
259
+ .prepare("SELECT * FROM mcp_tasks WHERE task_id=? AND caller_key=?")
260
+ .get(taskId, key);
261
+ requireCondition(row, "task_not_found", "The Task does not exist for this caller.");
262
+ const task = decode(row);
263
+ requireCondition(task.expiresAt > now, "task_expired", "The Task retention promise has expired.");
264
+ return task;
265
+ }
266
+ taskForRun(runId, key, now = Date.now()) {
267
+ requireCondition(!this.#closed, "storage_closed", "The local store is closed.");
268
+ const row = this.#db
269
+ .prepare("SELECT * FROM mcp_tasks WHERE run_id=? AND caller_key=? AND expires_at>? ORDER BY created_at,task_id LIMIT 1")
270
+ .get(runId, key, now);
271
+ return row ? decode(row) : null;
272
+ }
273
+ updateTask(taskId, key, patch, now = Date.now()) {
274
+ requireCondition([
275
+ "working",
276
+ "input_required",
277
+ "completed",
278
+ "cancelled",
279
+ "failed",
280
+ ].includes(patch.status), "invalid_task", "The Task status is invalid.");
281
+ if (taskTerminal.has(patch.status)) {
282
+ requireCondition(typeof patch.resultRef === "string" &&
283
+ /^state\/tasks\/[0-9a-f]{64}\/result_[0-9a-f]{32}\.json$/.test(patch.resultRef), "invalid_task_result", "A terminal Task requires its already fixed local method-result snapshot.");
284
+ }
285
+ else
286
+ requireCondition(patch.resultRef === undefined && patch.error === undefined, "invalid_task_result", "A working Task cannot publish a terminal result.");
287
+ if (patch.status === "failed")
288
+ requireCondition(patch.error &&
289
+ Number.isSafeInteger(patch.error.code) &&
290
+ typeof patch.error.message === "string" &&
291
+ Buffer.byteLength(patch.error.message) <= 4096, "invalid_task_error", "A failed Task requires a bounded JSON-RPC error.");
292
+ else
293
+ requireCondition(patch.error === undefined, "invalid_task_error", "Only a failed Task can carry a JSON-RPC error.");
294
+ return this.#transaction(() => {
295
+ const previous = this.getTask(taskId, key, now);
296
+ if (taskTerminal.has(previous.status))
297
+ return previous;
298
+ if (previous.status === patch.status)
299
+ return previous;
300
+ this.#db
301
+ .prepare("UPDATE mcp_tasks SET status=?,result_ref=?,error_json=?,updated_at=? WHERE task_id=?")
302
+ .run(patch.status, patch.resultRef ?? null, patch.error ? canonicalJson(patch.error, 16384) : null, now, taskId);
303
+ return this.getTask(taskId, key, now);
304
+ });
305
+ }
306
+ pinTaskRunArtifacts(runId, ids, now = Date.now()) {
307
+ requireCondition(ids.length <= 16384 && ids.every((id) => /^res_[0-9a-f]{32}$/.test(id)), "invalid_task_resource", "Task artifact references must be bounded local resource identities.");
308
+ if (!ids.length)
309
+ return;
310
+ this.#transaction(() => {
311
+ const tasks = this.#db
312
+ .prepare("SELECT task_id FROM mcp_tasks WHERE run_id=? AND expires_at>?")
313
+ .all(runId, now);
314
+ const insert = this.#db.prepare("INSERT OR IGNORE INTO task_artifacts(task_id,resource_id) VALUES(?,?)");
315
+ for (const task of tasks)
316
+ for (const id of new Set(ids))
317
+ insert.run(task.task_id, id);
318
+ });
319
+ }
320
+ taskArtifactRetentionUntil(id, originRunId, now = Date.now(), originalExpiresAt = 0) {
321
+ requireCondition(/^res_[0-9a-f]{32}$/.test(id), "invalid_task_resource", "The artifact identity is invalid.");
322
+ const row = this.#db
323
+ .prepare(`SELECT max(t.expires_at) expires_at FROM mcp_tasks t
324
+ WHERE t.expires_at>? AND ((t.run_id=? AND (?=0 OR t.created_at<?)) OR EXISTS
325
+ (SELECT 1 FROM task_artifacts a WHERE a.task_id=t.task_id AND a.resource_id=?))`)
326
+ .get(now, originRunId, originalExpiresAt, originalExpiresAt, id);
327
+ return typeof row?.expires_at === "number" ? row.expires_at : 0;
328
+ }
329
+ /** Coarse source protection is intentional: loss is preferable to guessing liveness. */
330
+ activeRunIds() {
331
+ const rows = this.#db
332
+ .prepare(`SELECT run_id FROM runs WHERE ended_at IS NULL
333
+ UNION SELECT origin_run_id FROM managed_resources WHERE boot_id=? AND closed_at IS NULL AND status!='unavailable' AND origin_run_id IS NOT NULL
334
+ UNION SELECT origin_run_id FROM operations WHERE ended_at IS NULL AND origin_run_id IS NOT NULL
335
+ UNION SELECT origin_run_id FROM transfers WHERE ended_at IS NULL AND origin_run_id IS NOT NULL
336
+ UNION SELECT json_extract(source_json,'$.replayRunId') FROM runs WHERE ended_at IS NULL AND json_type(source_json,'$.replayRunId')='text'`)
337
+ .all(this.bootId);
338
+ return new Set(rows.map((row) => row.run_id));
339
+ }
340
+ workSnapshotRefs(now = Date.now()) {
341
+ return new Set(this.#db
342
+ .prepare(`SELECT snapshot_ref FROM work_contexts c
343
+ WHERE (c.status='open' AND c.expires_at>?) OR EXISTS
344
+ (SELECT 1 FROM runs r WHERE r.context_id=c.context_id AND r.ended_at IS NULL)`)
345
+ .all(now)
346
+ .map((row) => row.snapshot_ref));
347
+ }
348
+ protectedArtifactIds(now = Date.now()) {
349
+ const ids = new Set(this.#db
350
+ .prepare(`SELECT DISTINCT a.resource_id FROM task_artifacts a
351
+ JOIN mcp_tasks t ON t.task_id=a.task_id WHERE t.expires_at>?`)
352
+ .all(now)
353
+ .map((row) => row.resource_id));
354
+ const prefix = `nexum://agents/${encodeURIComponent(this.binding.agentId)}/resources/`;
355
+ for (const row of this.#db
356
+ .prepare("SELECT json_extract(metadata_json,'$.target.resourceUri') uri FROM transfers WHERE ended_at IS NULL")
357
+ .all()) {
358
+ const uri = row.uri;
359
+ if (typeof uri === "string" &&
360
+ uri.startsWith(prefix) &&
361
+ /^res_[0-9a-f]{32}$/.test(uri.slice(prefix.length)))
362
+ ids.add(uri.slice(prefix.length));
363
+ }
364
+ return ids;
365
+ }
366
+ completeInputsCleanup(runId, now = Date.now()) {
367
+ this.#transaction(() => {
368
+ const row = this.#db
369
+ .prepare("SELECT * FROM runs WHERE run_id=?")
370
+ .get(runId);
371
+ if (!row)
372
+ return;
373
+ const run = decode(row);
374
+ requireCondition(run.endedAt !== null &&
375
+ run.endedAt <= now - row.retention_inputs_ms &&
376
+ !this.activeRunIds().has(runId), "cleanup_protected", "Temporary inputs are still protected by live work.");
377
+ this.#db
378
+ .prepare("UPDATE runs SET cleanup_json=json_set(cleanup_json,'$.temporaryInputsExpiredAt',?) WHERE run_id=?")
379
+ .run(now, runId);
380
+ });
381
+ }
382
+ /** One bounded metadata transaction. File removal is deliberately outside SQLite. */
383
+ cleanupBatch(options = {}) {
384
+ const now = options.now ?? Date.now(), limit = options.limit ?? 100;
385
+ requireCondition(Number.isSafeInteger(now) &&
386
+ now >= 0 &&
387
+ Number.isSafeInteger(limit) &&
388
+ limit >= 1 &&
389
+ limit <= 100, "invalid_cleanup", "A cleanup batch must use a valid clock and at most 100 records.");
390
+ return this.#transaction(() => {
391
+ let processed = 0;
392
+ const deleted = {}, files = [];
393
+ const remove = (table, key, where, parameters = [], file) => {
394
+ if (processed >= limit)
395
+ return;
396
+ const rows = this.#db
397
+ .prepare(`SELECT * FROM ${table} WHERE ${where} LIMIT ?`)
398
+ .all(...parameters, limit - processed);
399
+ const statement = this.#db.prepare(`DELETE FROM ${table} WHERE ${key}=?`);
400
+ for (const row of rows) {
401
+ statement.run(row[key]);
402
+ file?.(row);
403
+ processed++;
404
+ deleted[table] = (deleted[table] ?? 0) + 1;
405
+ }
406
+ };
407
+ // Pins are small reference rows, but still count toward the same hard batch bound.
408
+ if (processed < limit) {
409
+ const rows = this.#db
410
+ .prepare("SELECT a.task_id,a.resource_id FROM task_artifacts a JOIN mcp_tasks t ON t.task_id=a.task_id WHERE t.expires_at<=? LIMIT ?")
411
+ .all(now, limit - processed);
412
+ const statement = this.#db.prepare("DELETE FROM task_artifacts WHERE task_id=? AND resource_id=?");
413
+ for (const row of rows) {
414
+ statement.run(row.task_id, row.resource_id);
415
+ processed++;
416
+ deleted.task_artifacts = (deleted.task_artifacts ?? 0) + 1;
417
+ }
418
+ }
419
+ remove("mcp_tasks", "task_id", "expires_at<=? AND NOT EXISTS(SELECT 1 FROM task_artifacts a WHERE a.task_id=mcp_tasks.task_id)", [now], (row) => {
420
+ if (typeof row.result_ref === "string")
421
+ files.push({ kind: "task", ref: row.result_ref });
422
+ });
423
+ // run_requests has a compound primary key; rowid is local to this transaction.
424
+ if (processed < limit) {
425
+ const rows = this.#db
426
+ .prepare("SELECT rowid FROM run_requests WHERE expires_at<=? LIMIT ?")
427
+ .all(now, limit - processed);
428
+ for (const row of rows) {
429
+ this.#db
430
+ .prepare("DELETE FROM run_requests WHERE rowid=?")
431
+ .run(row.rowid);
432
+ processed++;
433
+ deleted.run_requests = (deleted.run_requests ?? 0) + 1;
434
+ }
435
+ }
436
+ remove("close_receipts", "context_id", "expires_at<=?", [now]);
437
+ remove("project_closures", "project_id", "expires_at<=?", [now]);
438
+ remove("transfers", "transfer_id", "ended_at IS NOT NULL AND ended_at<=?-retention_history_ms", [now]);
439
+ remove("operations", "operation_id", "ended_at IS NOT NULL AND ended_at<=?-retention_history_ms", [now]);
440
+ remove("managed_resources", "resource_id", `NOT EXISTS(SELECT 1 FROM transfers t WHERE t.resource_id=managed_resources.resource_id)
441
+ AND ((closed_at IS NOT NULL AND closed_at<=?-retention_history_ms) OR (status='unavailable' AND boot_id!=? AND
442
+ json_type(diagnostic_json,'$.unavailableAt') IN ('integer','real') AND json_extract(diagnostic_json,'$.unavailableAt')<=?-retention_history_ms))
443
+ AND NOT EXISTS(SELECT 1 FROM runs r WHERE r.run_id=managed_resources.owner_run_id AND r.ended_at IS NULL)`, [now, this.bootId, now], (row) => {
444
+ if (row.kind === "sh.process" && typeof row.resource_id === "string")
445
+ files.push({
446
+ kind: "process_log",
447
+ ref: `logs/processes/${row.resource_id}.output`,
448
+ });
449
+ });
450
+ const eligible = `ended_at IS NOT NULL AND ended_at<=?-runs.retention_history_ms
451
+ AND (logs_ref IS NULL OR ended_at<=?-runs.retention_logs_ms)
452
+ AND ended_at<=?-runs.retention_inputs_ms
453
+ AND NOT EXISTS(SELECT 1 FROM mcp_tasks t WHERE t.run_id=runs.run_id)
454
+ AND NOT EXISTS(SELECT 1 FROM run_requests q WHERE q.run_id=runs.run_id)
455
+ AND NOT EXISTS(SELECT 1 FROM managed_resources m WHERE m.owner_run_id=runs.run_id OR m.origin_run_id=runs.run_id)
456
+ AND NOT EXISTS(SELECT 1 FROM operations o WHERE o.origin_run_id=runs.run_id)
457
+ AND NOT EXISTS(SELECT 1 FROM transfers t WHERE t.origin_run_id=runs.run_id)
458
+ AND NOT EXISTS(SELECT 1 FROM runs live WHERE live.ended_at IS NULL AND json_extract(live.source_json,'$.replayRunId')=runs.run_id)`;
459
+ remove("run_waits", "wait_id", `status!='waiting' AND run_id IN(SELECT run_id FROM runs WHERE ${eligible})`, [now, now, now]);
460
+ remove("runs", "run_id", `${eligible} AND NOT EXISTS(SELECT 1 FROM run_waits w WHERE w.run_id=runs.run_id)`, [now, now, now], (row) => {
461
+ files.push({ kind: "run", ref: `work/tmp/runs/${row.run_id}` });
462
+ files.push({
463
+ kind: "log",
464
+ ref: `logs/runs/${row.run_id}/console.log`,
465
+ });
466
+ });
467
+ // Reading logs does not extend their independent seven-day retention.
468
+ if (processed < limit) {
469
+ const rows = this.#db
470
+ .prepare("SELECT run_id FROM runs WHERE ended_at IS NOT NULL AND ended_at<=?-retention_logs_ms AND logs_ref IS NOT NULL LIMIT ?")
471
+ .all(now, limit - processed);
472
+ for (const row of rows) {
473
+ this.#db
474
+ .prepare("UPDATE runs SET logs_ref=NULL WHERE run_id=?")
475
+ .run(row.run_id);
476
+ files.push({
477
+ kind: "log",
478
+ ref: `logs/runs/${row.run_id}/console.log`,
479
+ });
480
+ processed++;
481
+ deleted.logs = (deleted.logs ?? 0) + 1;
482
+ }
483
+ }
484
+ if (processed < limit) {
485
+ const rows = this.#db
486
+ .prepare(`SELECT run_id FROM runs WHERE ended_at IS NOT NULL AND ended_at<=?-retention_inputs_ms
487
+ AND json_type(cleanup_json,'$.temporaryInputsExpiredAt') IS NULL
488
+ AND NOT EXISTS(SELECT 1 FROM managed_resources m WHERE m.origin_run_id=runs.run_id AND m.boot_id=? AND m.closed_at IS NULL AND m.status!='unavailable')
489
+ AND NOT EXISTS(SELECT 1 FROM operations o WHERE o.origin_run_id=runs.run_id AND o.ended_at IS NULL)
490
+ AND NOT EXISTS(SELECT 1 FROM transfers t WHERE t.origin_run_id=runs.run_id AND t.ended_at IS NULL)
491
+ AND NOT EXISTS(SELECT 1 FROM runs live WHERE live.ended_at IS NULL AND json_extract(live.source_json,'$.replayRunId')=runs.run_id) LIMIT ?`)
492
+ .all(now, this.bootId, limit - processed);
493
+ for (const row of rows) {
494
+ files.push({
495
+ kind: "inputs",
496
+ ref: `work/tmp/runs/${row.run_id}/inputs`,
497
+ });
498
+ processed++;
499
+ deleted.input_candidates = (deleted.input_candidates ?? 0) + 1;
500
+ }
501
+ }
502
+ if (processed < limit) {
503
+ const rows = this.#db
504
+ .prepare(`SELECT resource_id FROM managed_resources WHERE kind='sh.process'
505
+ AND json_type(diagnostic_json,'$.logsExpiredAt') IS NULL AND
506
+ ((closed_at IS NOT NULL AND closed_at<=?-retention_logs_ms) OR (status='unavailable' AND boot_id!=? AND
507
+ json_type(diagnostic_json,'$.unavailableAt') IN ('integer','real') AND json_extract(diagnostic_json,'$.unavailableAt')<=?-retention_logs_ms)) LIMIT ?`)
508
+ .all(now, this.bootId, now, limit - processed);
509
+ for (const row of rows) {
510
+ this.#db
511
+ .prepare("UPDATE managed_resources SET diagnostic_json=json_set(diagnostic_json,'$.logsExpiredAt',?) WHERE resource_id=?")
512
+ .run(now, row.resource_id);
513
+ files.push({
514
+ kind: "process_log",
515
+ ref: `logs/processes/${row.resource_id}.output`,
516
+ });
517
+ processed++;
518
+ deleted.expired_process_logs =
519
+ (deleted.expired_process_logs ?? 0) + 1;
520
+ }
521
+ }
522
+ if (processed < limit) {
523
+ const rows = this.#db
524
+ .prepare("SELECT context_id FROM work_contexts c WHERE status='open' AND expires_at<=? AND NOT EXISTS(SELECT 1 FROM runs r WHERE r.context_id=c.context_id AND r.ended_at IS NULL) LIMIT ?")
525
+ .all(now, limit - processed);
526
+ for (const row of rows) {
527
+ this.#db
528
+ .prepare("UPDATE work_contexts SET status='expired' WHERE context_id=?")
529
+ .run(row.context_id);
530
+ processed++;
531
+ deleted.expired_contexts = (deleted.expired_contexts ?? 0) + 1;
532
+ }
533
+ }
534
+ return { processed, deleted, files };
535
+ });
536
+ }
537
+ getWait(id) {
538
+ return this.#get("run_waits", "wait_id", id, "wait_not_found");
539
+ }
540
+ getResource(id) {
541
+ return this.#get("managed_resources", "resource_id", id, "resource_not_found");
542
+ }
543
+ getOperation(id) {
544
+ return this.#get("operations", "operation_id", id, "operation_not_found");
545
+ }
546
+ startOperation(runId, origin, method, now = Date.now()) {
547
+ requireCondition(origin.namespace &&
548
+ origin.owner &&
549
+ origin.version &&
550
+ origin.revision &&
551
+ ["platform", "extension"].includes(origin.type) &&
552
+ typeof method === "string" &&
553
+ method.length > 0 &&
554
+ Buffer.byteLength(method) <= 1024, "invalid_operation", "An SDK operation needs its actual source/version, namespace and method.");
555
+ const source = {
556
+ origin: {
557
+ type: origin.type,
558
+ owner: origin.owner,
559
+ namespace: origin.namespace,
560
+ version: origin.version,
561
+ revision: origin.revision,
562
+ },
563
+ };
564
+ return this.#transaction(() => {
565
+ const run = this.getRun(runId);
566
+ requireCondition(run.bootId === this.bootId &&
567
+ ["preparing_inputs", "running", "waiting_input"].includes(run.status) &&
568
+ !run.stop, "run_stopping", "The run no longer admits managed operations.");
569
+ const id = newId("op");
570
+ this.#db
571
+ .prepare(`INSERT INTO operations(operation_id,origin_run_id,caller_key,boot_id,namespace,method,source_json,status,created_at,updated_at,retention_history_ms)
572
+ VALUES(?,?,?,?,?,?,?,'running',?,?,?)`)
573
+ .run(id, runId, run.callerKey, this.bootId, origin.namespace, method, canonicalJson(source), now, now, this.#retention.runHistoryMs);
574
+ return this.getOperation(id);
575
+ });
576
+ }
577
+ getMaintenanceOperation(requestId) {
578
+ requireCondition(typeof requestId === "string" && maintenanceRequest.test(requestId), "invalid_maintenance_request", "The maintenance request identity is invalid.");
579
+ const row = this.#db
580
+ .prepare("SELECT * FROM operations WHERE maintenance_request_id=?")
581
+ .get(requestId);
582
+ return row ? decode(row) : null;
583
+ }
584
+ /** Trusted approved execution admission; no package/network/filesystem effects run in this transaction. */
585
+ startMaintenanceOperation(input, now = Date.now()) {
586
+ requireCondition(typeof input.requestId === "string" &&
587
+ maintenanceRequest.test(input.requestId) &&
588
+ typeof input.approvedRevision === "string" &&
589
+ /^[0-9a-f]{64}$/.test(input.approvedRevision) &&
590
+ typeof input.callerKey === "string" &&
591
+ input.callerKey.length > 0 &&
592
+ input.callerKey.length <= 256 &&
593
+ maintenanceMethods.has(input.method) &&
594
+ (input.originRunId == null ||
595
+ (typeof input.originRunId === "string" &&
596
+ /^run_[0-9a-f]{32}$/.test(input.originRunId))) &&
597
+ input.detailRef ===
598
+ `state/maintenance/${input.requestId}/execution.json` &&
599
+ Number.isSafeInteger(now) &&
600
+ now >= 0, "invalid_maintenance_operation", "Maintenance execution needs its approved identity, action and fixed private detail reference.");
601
+ const source = JSON.parse(canonicalJson(input.source, 16384));
602
+ const origin = source.origin;
603
+ const safeText = (value) => typeof value === "string" && value.length > 0 && value.length <= 256;
604
+ requireCondition(Object.keys(source).every((key) => [
605
+ "origin",
606
+ "target",
607
+ "name",
608
+ "objectId",
609
+ "baseRevision",
610
+ "candidateRevision",
611
+ ].includes(key)) &&
612
+ origin &&
613
+ typeof origin === "object" &&
614
+ !Array.isArray(origin) &&
615
+ Object.keys(origin).length === 5 &&
616
+ Object.keys(origin).every((key) => ["type", "owner", "namespace", "version", "revision"].includes(key)) &&
617
+ origin.type === "platform" &&
618
+ origin.namespace === "maintenance" &&
619
+ safeText(origin.owner) &&
620
+ safeText(origin.version) &&
621
+ safeText(origin.revision) &&
622
+ source.target ===
623
+ {
624
+ packages: "package",
625
+ extensions: "extension",
626
+ mcp: "mcp",
627
+ api: "api",
628
+ }[input.method.split(".")[0]] &&
629
+ safeText(source.name) &&
630
+ (source.objectId === null || safeText(source.objectId)) &&
631
+ (source.baseRevision === null || safeText(source.baseRevision)) &&
632
+ source.candidateRevision === input.approvedRevision, "invalid_maintenance_operation", "Maintenance operation metadata must contain only its actual safe approved target and platform origin.");
633
+ return this.#transaction(() => {
634
+ const previous = this.getMaintenanceOperation(input.requestId);
635
+ if (previous) {
636
+ requireCondition(previous.callerKey === input.callerKey &&
637
+ previous.approvedRevision === input.approvedRevision &&
638
+ previous.method === input.method &&
639
+ canonicalJson(previous.source) === canonicalJson(source) &&
640
+ previous.originRunId === (input.originRunId ?? null) &&
641
+ previous.detailRef === input.detailRef, "maintenance_execution_conflict", "The request already belongs to another approved execution identity.");
642
+ return { operation: previous, duplicate: true };
643
+ }
644
+ if (input.originRunId) {
645
+ const run = this.getRun(input.originRunId);
646
+ requireCondition(run.callerKey === input.callerKey, "maintenance_execution_conflict", "The source run belongs to another caller.");
647
+ }
648
+ const id = newId("op");
649
+ this.#db
650
+ .prepare(`INSERT INTO operations(operation_id,origin_run_id,caller_key,boot_id,namespace,method,source_json,maintenance_request_id,approved_revision,status,detail_ref,created_at,updated_at,retention_history_ms)
651
+ VALUES(?,?,?,?,?,?,?,?,?,'running',?,?,?,?)`)
652
+ .run(id, input.originRunId ?? null, input.callerKey, this.bootId, "maintenance", input.method, canonicalJson(source, 16384), input.requestId, input.approvedRevision, input.detailRef, now, now, this.#retention.runHistoryMs);
653
+ return { operation: this.getOperation(id), duplicate: false };
654
+ });
655
+ }
656
+ finishOperation(id, status, error, now = Date.now()) {
657
+ requireCondition(["succeeded", "failed"].includes(status) &&
658
+ !(status === "succeeded" && error !== undefined), "invalid_operation_outcome", "An operation outcome must preserve its actual success or failure.");
659
+ return this.#transaction(() => {
660
+ const operation = this.getOperation(id);
661
+ requireCondition(operation.bootId === this.bootId &&
662
+ operation.endedAt === null &&
663
+ operation.status === "running", "operation_state_conflict", "Only an unsettled operation from this Agent boot may finish.");
664
+ this.#db
665
+ .prepare("UPDATE operations SET status=?,error_json=?,ended_at=?,updated_at=?,revision=revision+1 WHERE operation_id=? AND ended_at IS NULL")
666
+ .run(status, error ? canonicalJson(error) : null, now, now, id);
667
+ return this.getOperation(id);
668
+ });
669
+ }
670
+ operationsForRun(runId, limit = 64) {
671
+ requireCondition(Number.isSafeInteger(limit) && limit > 0 && limit <= 1000, "invalid_limit", "An operation query needs a bounded limit.");
672
+ return this.#db
673
+ .prepare("SELECT * FROM operations WHERE origin_run_id=? ORDER BY created_at DESC,operation_id DESC LIMIT ?")
674
+ .all(runId, limit)
675
+ .map((row) => decode(row));
676
+ }
677
+ #activeWork(id, callerKey, now) {
678
+ const work = this.getWork(id);
679
+ requireCondition(work.callerKey === callerKey, "context_forbidden", "This work belongs to another caller.");
680
+ const protectedByRun = this.#db
681
+ .prepare("SELECT 1 FROM runs WHERE context_id=? AND ended_at IS NULL LIMIT 1")
682
+ .get(id);
683
+ requireCondition(work.bootId === this.bootId &&
684
+ work.status === "open" &&
685
+ (work.expiresAt > now || protectedByRun), "context_closed", "This work is closed or expired; open a new work context.");
686
+ return work;
687
+ }
688
+ openWork(input, now = Date.now()) {
689
+ requireCondition(path.isAbsolute(input.pwd), "invalid_pwd", "The work directory must be absolute.");
690
+ const id = newId("ctx");
691
+ return this.#transaction(() => {
692
+ if (input.projectId)
693
+ requireCondition(!this.#db
694
+ .prepare(`SELECT 1 FROM project_closures WHERE project_id=? AND expires_at>?
695
+ UNION ALL SELECT 1 FROM close_receipts WHERE project_id=? AND expires_at>? LIMIT 1`)
696
+ .get(input.projectId, now, input.projectId, now), "project_closed", "This project was closed; resolve a new catalog identity before opening work.");
697
+ this.#db
698
+ .prepare(`INSERT INTO work_contexts VALUES(?,?,?,?,1,'open',?,?,?,?,?,NULL)`)
699
+ .run(id, input.callerKey, input.projectId ?? null, this.bootId, input.pwd, input.snapshotRef, now, now, now + this.#retention.workIdleMs);
700
+ return this.getWork(id);
701
+ });
702
+ }
703
+ refreshWork(id, callerKey, revision, snapshotRef, now = Date.now()) {
704
+ return this.#transaction(() => {
705
+ this.#activeWork(id, callerKey, now);
706
+ const changed = this.#db
707
+ .prepare(`UPDATE work_contexts SET revision=revision+1,snapshot_ref=?,last_used_at=?,expires_at=?
708
+ WHERE context_id=? AND revision=? AND status='open'`)
709
+ .run(snapshotRef, now, now + this.#retention.workIdleMs, id, revision).changes;
710
+ requireCondition(changed === 1, "revision_conflict", "The work was refreshed or closed concurrently.");
711
+ return this.getWork(id);
712
+ });
713
+ }
714
+ #closeProject(projectId, now) {
715
+ this.#db
716
+ .prepare(`INSERT INTO project_closures VALUES(?,?,?)
717
+ ON CONFLICT(project_id) DO UPDATE SET expires_at=MAX(expires_at,excluded.expires_at)`)
718
+ .run(projectId, now, now + 86_400_000);
719
+ const affected = this.#db
720
+ .prepare("SELECT context_id FROM work_contexts WHERE project_id=? AND status='open'")
721
+ .all(projectId);
722
+ this.#db
723
+ .prepare("UPDATE work_contexts SET status='closed',closed_at=?,revision=revision+1 WHERE project_id=? AND status='open'")
724
+ .run(now, projectId);
725
+ return affected.map((entry) => entry.context_id);
726
+ }
727
+ closeProject(projectId, now = Date.now()) {
728
+ requireCondition(typeof projectId === "string" && projectId.length > 0, "project_not_found", "Project close requires its verified catalog identity.");
729
+ return this.#transaction(() => {
730
+ const affected = this.#closeProject(projectId, now), receipt = this.#db
731
+ .prepare("SELECT closed_at FROM project_closures WHERE project_id=?")
732
+ .get(projectId);
733
+ return {
734
+ projectId,
735
+ agentConfirmed: true,
736
+ affectedContextCount: affected.length,
737
+ closedAt: receipt.closed_at,
738
+ };
739
+ });
740
+ }
741
+ closeWork(id, callerKey, now = Date.now()) {
742
+ return this.#transaction(() => {
743
+ const previous = this.#db
744
+ .prepare("SELECT * FROM close_receipts WHERE context_id=? AND expires_at>?")
745
+ .get(id, now);
746
+ if (previous) {
747
+ requireCondition(previous.caller_key === callerKey, "context_forbidden", "The close receipt belongs to another caller.");
748
+ return JSON.parse(previous.receipt_json);
749
+ }
750
+ const work = this.#activeWork(id, callerKey, now);
751
+ const affected = work.projectId
752
+ ? this.#closeProject(work.projectId, now)
753
+ : [id];
754
+ if (!work.projectId)
755
+ this.#db
756
+ .prepare("UPDATE work_contexts SET status='closed',closed_at=?,revision=revision+1 WHERE context_id=?")
757
+ .run(now, id);
758
+ const receipt = {
759
+ contextId: id,
760
+ projectId: work.projectId,
761
+ agentConfirmed: true,
762
+ affectedContextIds: affected,
763
+ closedAt: now,
764
+ };
765
+ this.#db
766
+ .prepare("INSERT INTO close_receipts VALUES(?,?,?,?,?,?,?)")
767
+ .run(id, work.projectId, callerKey, work.revision + 1, canonicalJson(receipt), now, now + 86_400_000);
768
+ return receipt;
769
+ });
770
+ }
771
+ #matchingSubmission(callerKey, requestId, intentDigest) {
772
+ const previous = this.#db
773
+ .prepare("SELECT * FROM run_requests WHERE caller_key=? AND request_id=?")
774
+ .get(callerKey, requestId);
775
+ if (!previous)
776
+ return null;
777
+ requireCondition(previous.intent_digest === intentDigest, "submission_conflict", "The submission identifier belongs to a different intent.");
778
+ try {
779
+ return this.getRun(previous.run_id);
780
+ }
781
+ catch (cause) {
782
+ throw new AgentError("submission_unknown", "The original accepted run is unavailable.", undefined, { cause });
783
+ }
784
+ }
785
+ /** Read before any current-source inspection; acceptRun rechecks atomically. */
786
+ findMatchingSubmission(callerKey, requestId, intentDigest, now = Date.now()) {
787
+ requireCondition(!this.#closed, "storage_closed", "The local store is closed.");
788
+ requestWindow(requestId, now);
789
+ requireCondition(typeof intentDigest === "string" && intentDigest.length > 0, "invalid_submission", "A submission requires its fixed intent digest.");
790
+ return this.#matchingSubmission(callerKey, requestId, intentDigest);
791
+ }
792
+ acceptRun(input, now = Date.now()) {
793
+ const request = input.requestId
794
+ ? requestWindow(input.requestId, now)
795
+ : undefined;
796
+ if (request)
797
+ requireCondition(input.intentDigest, "invalid_submission", "A submission requires its fixed intent digest.");
798
+ const timeout = input.timeoutMs ?? 1_800_000;
799
+ requireCondition(Number.isSafeInteger(timeout) &&
800
+ timeout > 0 &&
801
+ Number.isSafeInteger(now + timeout) &&
802
+ now + timeout <= 253402300799999, "invalid_timeout", "The runtime deadline is invalid.");
803
+ return this.#transaction(() => {
804
+ if (input.requestId) {
805
+ const previous = this.#matchingSubmission(input.callerKey, input.requestId, input.intentDigest);
806
+ if (previous)
807
+ return { run: previous, duplicate: true };
808
+ }
809
+ const work = this.#activeWork(input.contextId, input.callerKey, now);
810
+ const capacity = input.capacity ?? 256;
811
+ const controlCapacity = input.controlCapacity ?? DEFAULT_CONTROL_CAPACITY;
812
+ requireCondition(Number.isSafeInteger(capacity) &&
813
+ capacity > 0 &&
814
+ Number.isSafeInteger(controlCapacity) &&
815
+ controlCapacity >= 0 &&
816
+ (input.controlEligible === undefined ||
817
+ typeof input.controlEligible === "boolean") &&
818
+ (!input.controlEligible ||
819
+ (input.sourceKind === "script" &&
820
+ typeof input.scriptName === "string")), "invalid_capacity", "The configured run capacity is invalid.");
821
+ const active = this.#db
822
+ .prepare(`SELECT
823
+ count(*) FILTER (WHERE admission_class='ordinary') ordinary,
824
+ count(*) FILTER (WHERE admission_class='control') control
825
+ FROM runs WHERE ended_at IS NULL`)
826
+ .get();
827
+ const admissionClass = active.ordinary < capacity ? "ordinary" : "control";
828
+ requireCondition(admissionClass === "ordinary" ||
829
+ (input.controlEligible && active.control < controlCapacity), "runtime_busy", "The Agent has no free run slot for this submission.", {
830
+ ordinaryCapacity: capacity,
831
+ controlCapacity,
832
+ ordinaryActive: active.ordinary,
833
+ controlActive: active.control,
834
+ });
835
+ const runId = newId("run");
836
+ this.#db
837
+ .prepare(`INSERT INTO runs(run_id,caller_key,context_id,project_id,boot_id,status,source_kind,script_name,
838
+ source_json,accepted_at,deadline_at,updated_at,admission_class,retention_history_ms,retention_logs_ms,retention_inputs_ms) VALUES(?,?,?,?,?,'accepted',?,?,?,?,?,?,?,?,?,?)`)
839
+ .run(runId, input.callerKey, input.contextId, work.projectId, this.bootId, input.sourceKind, input.scriptName ?? null, canonicalJson(input.source), now, now + timeout, now, admissionClass, this.#retention.runHistoryMs, this.#retention.runLogsMs, this.#retention.inputAttachmentsMs);
840
+ if (request)
841
+ this.#db
842
+ .prepare("INSERT INTO run_requests VALUES(?,?,?,?,?)")
843
+ .run(input.callerKey, input.requestId, input.intentDigest, runId, request.expiresAt);
844
+ this.#db
845
+ .prepare("UPDATE work_contexts SET last_used_at=?,expires_at=? WHERE context_id=?")
846
+ .run(now, now + this.#retention.workIdleMs, work.contextId);
847
+ return { run: this.getRun(runId), duplicate: false };
848
+ });
849
+ }
850
+ findSubmission(callerKey, requestId, now = Date.now()) {
851
+ requestWindow(requestId, now);
852
+ const row = this.#db
853
+ .prepare("SELECT run_id FROM run_requests WHERE caller_key=? AND request_id=?")
854
+ .get(callerKey, requestId);
855
+ requireCondition(row, "submission_unknown", "No accepted submission can be confirmed.");
856
+ try {
857
+ return this.getRun(row.run_id);
858
+ }
859
+ catch (cause) {
860
+ if (!isAgentError(cause) || cause.code !== "run_not_found")
861
+ throw cause;
862
+ throw new AgentError("submission_unknown", "The original accepted run is unavailable.", undefined, { cause });
863
+ }
864
+ }
865
+ transitionRun(id, revision, status, patch = {}, now = Date.now()) {
866
+ return this.#transaction(() => {
867
+ const run = this.getRun(id);
868
+ requireCondition(run.revision === revision && transitions[run.status].includes(status), "run_state_conflict", "The run state changed or the transition is not allowed.");
869
+ if (status === "succeeded")
870
+ requireCondition(run.stop === null, "run_stopping", "The run has already accepted a stop reason.");
871
+ if (status === "succeeded")
872
+ requireCondition(now < run.deadlineAt, "run_deadline_exceeded", "The runtime deadline has passed.");
873
+ const ended = terminalStatuses.has(status);
874
+ if (ended && run.stop)
875
+ requireCondition(status === (run.stop.kind === "cancel" ? "cancelled" : "failed"), "run_state_conflict", "The first accepted stop reason determines the terminal outcome.");
876
+ if (ended)
877
+ requireCondition(!this.#db
878
+ .prepare("SELECT 1 FROM operations WHERE origin_run_id=? AND maintenance_request_id IS NULL AND ended_at IS NULL LIMIT 1")
879
+ .get(id), "run_operations_pending", "Managed operations have not actually settled.");
880
+ if (ended)
881
+ requireCondition(!this.#db
882
+ .prepare("SELECT 1 FROM managed_resources WHERE owner_run_id=? AND closed_at IS NULL LIMIT 1")
883
+ .get(id), "run_cleanup_pending", "Run-owned managed resources have not confirmed closure.");
884
+ this.#db
885
+ .prepare(`UPDATE runs SET status=?,revision=revision+1,code_ref=?,input_ref=?,result_ref=?,logs_ref=?,script_name=?,
886
+ source_json=?,error_json=?,cleanup_json=?,started_at=?,ended_at=?,updated_at=? WHERE run_id=? AND revision=? AND ended_at IS NULL`)
887
+ .run(status, patch.codeRef ?? run.codeRef, patch.inputRef ?? run.inputRef, patch.resultRef ?? run.resultRef, patch.logsRef ?? run.logsRef, patch.scriptName ?? run.scriptName, canonicalJson(patch.source ?? run.source), patch.error
888
+ ? canonicalJson(patch.error)
889
+ : run.error
890
+ ? canonicalJson(run.error)
891
+ : null, canonicalJson(patch.cleanup ?? run.cleanup), run.startedAt ?? (status === "running" ? now : null), ended ? now : null, now, id, revision);
892
+ if (ended)
893
+ this.#db
894
+ .prepare("UPDATE run_waits SET status='cancelled',revision=revision+1 WHERE run_id=? AND status='waiting'")
895
+ .run(id);
896
+ return this.getRun(id);
897
+ });
898
+ }
899
+ requestStop(id, reason, now = Date.now()) {
900
+ return this.#transaction(() => {
901
+ const run = this.getRun(id);
902
+ if (terminalStatuses.has(run.status) || run.stop)
903
+ return { accepted: false, run };
904
+ this.#db
905
+ .prepare("UPDATE runs SET status='cancelling',stop_json=?,updated_at=?,revision=revision+1 WHERE run_id=? AND revision=? AND ended_at IS NULL")
906
+ .run(canonicalJson(reason), now, id, run.revision);
907
+ this.#db
908
+ .prepare("UPDATE run_waits SET status='cancelled',revision=revision+1 WHERE run_id=? AND status='waiting'")
909
+ .run(id);
910
+ return { accepted: true, run: this.getRun(id) };
911
+ });
912
+ }
913
+ savePreparation(id, revision, patch) {
914
+ return this.#transaction(() => {
915
+ const run = this.getRun(id);
916
+ requireCondition(run.status === "preparing_inputs" &&
917
+ !run.stop &&
918
+ run.revision === revision, "run_state_conflict", "Preparation is no longer current.");
919
+ this.#db
920
+ .prepare(`UPDATE runs SET code_ref=?,input_ref=?,logs_ref=?,source_json=?,script_name=?,revision=revision+1
921
+ WHERE run_id=? AND revision=? AND status='preparing_inputs'`)
922
+ .run(patch.codeRef, patch.inputRef ?? run.inputRef, patch.logsRef ?? run.logsRef, canonicalJson(patch.source), patch.scriptName ?? run.scriptName, id, revision);
923
+ return this.getRun(id);
924
+ });
925
+ }
926
+ createWait(runId, request, deadlineAt, now = Date.now()) {
927
+ return this.#transaction(() => {
928
+ const run = this.getRun(runId);
929
+ requireCondition(run.status === "running" &&
930
+ !run.stop &&
931
+ now < deadlineAt &&
932
+ deadlineAt <= run.deadlineAt, "invalid_wait", "An input wait requires a running run and a valid deadline.");
933
+ requireCondition(!this.activeWait(runId), "input_already_waiting", "Only one active input wait is allowed per run.");
934
+ const id = newId("wait");
935
+ this.#db
936
+ .prepare(`INSERT INTO run_waits(wait_id,run_id,status,delivery_state,request_json,created_at,deadline_at)
937
+ VALUES(?,?,'waiting','none',?,?,?)`)
938
+ .run(id, runId, canonicalJson(request), now, deadlineAt);
939
+ this.#db
940
+ .prepare("UPDATE runs SET status='waiting_input',updated_at=?,revision=revision+1 WHERE run_id=? AND revision=?")
941
+ .run(now, runId, run.revision);
942
+ return this.getWait(id);
943
+ });
944
+ }
945
+ activeWait(runId) {
946
+ const row = this.#db
947
+ .prepare("SELECT * FROM run_waits WHERE run_id=? AND status='waiting'")
948
+ .get(runId);
949
+ return row ? decode(row) : null;
950
+ }
951
+ #inputTarget(runId, waitId, inputDigest, now) {
952
+ const wait = this.getWait(waitId);
953
+ requireCondition(wait.runId === runId, "wait_mismatch", "This wait belongs to another run.");
954
+ if (wait.status === "consumed") {
955
+ requireCondition(wait.inputDigest === inputDigest, "input_conflict", "This wait already consumed a different input.");
956
+ return wait;
957
+ }
958
+ const run = this.getRun(runId);
959
+ requireCondition(wait.status === "waiting" &&
960
+ wait.deadlineAt > now &&
961
+ run.deadlineAt > now &&
962
+ run.status === "waiting_input" &&
963
+ !run.stop, "input_closed", "This input wait is no longer available.");
964
+ return wait;
965
+ }
966
+ reserveInput(runId, waitId, inputDigest, now = Date.now()) {
967
+ return this.#transaction(() => {
968
+ const wait = this.#inputTarget(runId, waitId, inputDigest, now);
969
+ if (wait.status === "consumed")
970
+ return { duplicate: true, wait };
971
+ if (wait.deliveryState === "preparing") {
972
+ requireCondition(wait.inputDigest === inputDigest, "input_conflict", "A different input is already being prepared.");
973
+ return { duplicate: true, wait };
974
+ }
975
+ this.#db
976
+ .prepare("UPDATE run_waits SET delivery_state='preparing',input_digest=?,error_json=NULL,revision=revision+1 WHERE wait_id=? AND revision=?")
977
+ .run(inputDigest, waitId, wait.revision);
978
+ return { duplicate: false, wait: this.getWait(waitId) };
979
+ });
980
+ }
981
+ failInput(waitId, revision, error) {
982
+ return this.#transaction(() => {
983
+ const changed = this.#db
984
+ .prepare(`UPDATE run_waits SET delivery_state='failed',error_json=?,revision=revision+1
985
+ WHERE wait_id=? AND revision=? AND status='waiting' AND delivery_state='preparing'`)
986
+ .run(canonicalJson(error), waitId, revision).changes;
987
+ requireCondition(changed === 1, "input_state_conflict", "The input reservation is no longer current.");
988
+ return this.getWait(waitId);
989
+ });
990
+ }
991
+ consumeInput(runId, waitId, inputDigest, revision, inputRef, receipt, now = Date.now()) {
992
+ return this.#transaction(() => {
993
+ const wait = this.#inputTarget(runId, waitId, inputDigest, now);
994
+ if (wait.status === "consumed")
995
+ return wait;
996
+ requireCondition(wait.deliveryState === "preparing" &&
997
+ wait.inputDigest === inputDigest &&
998
+ wait.revision === revision, "input_state_conflict", "The input reservation is no longer current.");
999
+ this.#db
1000
+ .prepare("UPDATE run_waits SET status='consumed',delivery_state='consumed',input_ref=?,receipt_json=?,consumed_at=?,revision=revision+1 WHERE wait_id=? AND revision=?")
1001
+ .run(inputRef, canonicalJson(receipt), now, waitId, revision);
1002
+ this.#db
1003
+ .prepare("UPDATE runs SET status='running',updated_at=?,revision=revision+1 WHERE run_id=? AND status='waiting_input'")
1004
+ .run(now, runId);
1005
+ return this.getWait(waitId);
1006
+ });
1007
+ }
1008
+ expireWait(waitId, now = Date.now()) {
1009
+ return this.#transaction(() => {
1010
+ const wait = this.getWait(waitId);
1011
+ requireCondition(wait.status === "waiting" && now >= wait.deadlineAt, "input_state_conflict", "This wait has not expired.");
1012
+ this.#db
1013
+ .prepare("UPDATE run_waits SET status='expired',revision=revision+1 WHERE wait_id=? AND status='waiting'")
1014
+ .run(waitId);
1015
+ this.#db
1016
+ .prepare("UPDATE runs SET status='running',updated_at=?,revision=revision+1 WHERE run_id=? AND status='waiting_input'")
1017
+ .run(now, wait.runId);
1018
+ return this.getWait(waitId);
1019
+ });
1020
+ }
1021
+ registerResource(input, now = Date.now()) {
1022
+ return this.#transaction(() => {
1023
+ if (input.runId) {
1024
+ const run = this.getRun(input.runId);
1025
+ requireCondition(["preparing_inputs", "running", "waiting_input"].includes(run.status) && !run.stop, "run_stopping", "This run cannot acquire a new managed resource.");
1026
+ }
1027
+ const id = newId("res");
1028
+ this.#db
1029
+ .prepare(`INSERT INTO managed_resources(resource_id,origin_run_id,owner_run_id,caller_key,boot_id,kind,lifetime,source_json,status,created_at,retention_history_ms,retention_logs_ms)
1030
+ VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`)
1031
+ .run(id, input.runId ?? null, input.runId ?? null, input.callerKey, this.bootId, input.kind, input.runId ? "run" : "instance", canonicalJson(input.source), input.status ?? "active", now, this.#retention.runHistoryMs, this.#retention.runLogsMs);
1032
+ return this.getResource(id);
1033
+ });
1034
+ }
1035
+ handoff(resourceId, runId, revision, now = Date.now()) {
1036
+ return this.#transaction(() => {
1037
+ requireCondition(!this.#db
1038
+ .prepare("SELECT 1 FROM transfers WHERE resource_id=?")
1039
+ .get(resourceId), "transfer_handoff_required", "A transfer must publish pending and hand off through its fixed domain command.");
1040
+ return this.#handoffResource(resourceId, runId, revision, now);
1041
+ });
1042
+ }
1043
+ /** Shared fixed SQL, called only from an existing transaction. */
1044
+ #handoffResource(resourceId, runId, revision, now) {
1045
+ const resource = this.getResource(resourceId);
1046
+ const run = this.getRun(runId);
1047
+ requireCondition(resource.bootId === this.bootId &&
1048
+ resource.ownerRunId === runId &&
1049
+ resource.revision === revision &&
1050
+ resource.closedAt === null, "resource_state_conflict", "This resource cannot be handed off.");
1051
+ requireCondition((run.status === "running" || run.status === "waiting_input") && !run.stop, "run_stopping", "The creator already started finishing or stopping.");
1052
+ const active = this.#db
1053
+ .prepare("SELECT count(*) n FROM managed_resources WHERE boot_id=? AND lifetime='background' AND closed_at IS NULL")
1054
+ .get(this.bootId)?.n;
1055
+ requireCondition(active < 32, "background_busy", "No independent background resource slot is available.");
1056
+ this.#db
1057
+ .prepare("UPDATE managed_resources SET lifetime='background',owner_run_id=NULL,handed_off_at=?,revision=revision+1 WHERE resource_id=? AND revision=?")
1058
+ .run(now, resourceId, revision);
1059
+ return this.getResource(resourceId);
1060
+ }
1061
+ #transferOwner(scope) {
1062
+ requireCondition(scope &&
1063
+ typeof scope.callerKey === "string" &&
1064
+ scope.callerKey.length > 0 &&
1065
+ scope.owner &&
1066
+ ["platform", "extension"].includes(scope.owner.type) &&
1067
+ typeof scope.owner.owner === "string" &&
1068
+ scope.owner.owner.length > 0 &&
1069
+ typeof scope.owner.namespace === "string" &&
1070
+ scope.owner.namespace.length > 0, "invalid_transfer_owner", "Transfers require a verified caller and fixed Core source binding.");
1071
+ }
1072
+ #transferMetadata(value) {
1073
+ const data = JSON.parse(canonicalJson(value, 64 * 1024));
1074
+ requireCondition(isPlainRecord(data) &&
1075
+ Object.keys(data).every((key) => [
1076
+ "target",
1077
+ "origin",
1078
+ "maxBytes",
1079
+ "startedAt",
1080
+ "fileCommitted",
1081
+ "file",
1082
+ "cleanupConfirmed",
1083
+ "stop",
1084
+ "error",
1085
+ "outcome",
1086
+ ].includes(key)) &&
1087
+ isPlainRecord(data.target) &&
1088
+ Object.keys(data.target).every((key) => [
1089
+ "path",
1090
+ "resourceUri",
1091
+ "name",
1092
+ "mimeType",
1093
+ "size",
1094
+ "sha256",
1095
+ "expectedSize",
1096
+ "expectedSha256",
1097
+ ].includes(key)), "invalid_transfer_metadata", "Transfer history accepts fixed safe target and outcome fields, never request URLs or credentials.");
1098
+ const target = data.target;
1099
+ requireCondition((data.maxBytes === undefined ||
1100
+ data.maxBytes === null ||
1101
+ (typeof data.maxBytes === "number" &&
1102
+ Number.isSafeInteger(data.maxBytes) &&
1103
+ data.maxBytes > 0)) &&
1104
+ (data.startedAt === undefined ||
1105
+ data.startedAt === null ||
1106
+ (typeof data.startedAt === "number" &&
1107
+ Number.isSafeInteger(data.startedAt) &&
1108
+ data.startedAt >= 0)), "invalid_transfer_metadata", "A transfer keeps only its fixed accepted budget and actual claim time.");
1109
+ if (data.origin !== undefined && data.origin !== null) {
1110
+ const origin = data.origin;
1111
+ requireCondition(isPlainRecord(origin) &&
1112
+ Object.keys(origin).length === 2 &&
1113
+ typeof origin.contextId === "string" &&
1114
+ origin.contextId.length > 0 &&
1115
+ origin.contextId.length <= 256 &&
1116
+ (origin.projectId === null ||
1117
+ (typeof origin.projectId === "string" &&
1118
+ origin.projectId.length > 0 &&
1119
+ origin.projectId.length <= 256)), "invalid_transfer_origin", "The retained creator association must contain only its actual context and project identities.");
1120
+ }
1121
+ for (const field of ["path", "name", "mimeType", "resourceUri"])
1122
+ requireCondition(target[field] === undefined ||
1123
+ (typeof target[field] === "string" &&
1124
+ target[field].length > 0 &&
1125
+ !target[field].includes("\0")), "invalid_transfer_metadata", "Transfer target text is invalid.");
1126
+ requireCondition((target.path === undefined ||
1127
+ (typeof target.path === "string" && path.isAbsolute(target.path))) &&
1128
+ (target.resourceUri === undefined ||
1129
+ (typeof target.resourceUri === "string" &&
1130
+ /^nexum:\/\/agents\/[^/]+\/resources\/res_[0-9a-f]{32}$/.test(target.resourceUri))), "invalid_transfer_metadata", "Any confirmed target must be a canonical local path or registered Nexum resource coordinate.");
1131
+ for (const field of ["size", "expectedSize"])
1132
+ requireCondition(target[field] === undefined ||
1133
+ (typeof target[field] === "number" &&
1134
+ Number.isSafeInteger(target[field]) &&
1135
+ target[field] >= 0), "invalid_transfer_metadata", "Transfer sizes must be non-negative safe byte counts.");
1136
+ for (const field of ["sha256", "expectedSha256"])
1137
+ requireCondition(target[field] === undefined ||
1138
+ (typeof target[field] === "string" &&
1139
+ /^[0-9a-f]{64}$/.test(target[field])), "invalid_transfer_metadata", "Transfer checksums must be actual SHA-256 hex values.");
1140
+ for (const field of ["fileCommitted", "cleanupConfirmed"])
1141
+ requireCondition(data[field] === undefined || typeof data[field] === "boolean", "invalid_transfer_metadata", "Transfer cleanup and publication facts must be boolean.");
1142
+ if (data.file !== undefined) {
1143
+ const file = data.file;
1144
+ requireCondition(isPlainRecord(file) &&
1145
+ Object.keys(file).length === 6 &&
1146
+ ["path", "name", "size", "mimeType", "sha256", "revision"].every((key) => Object.hasOwn(file, key)) &&
1147
+ typeof file.path === "string" &&
1148
+ path.isAbsolute(file.path) &&
1149
+ file.path === target.path &&
1150
+ typeof file.name === "string" &&
1151
+ file.name === path.basename(file.path) &&
1152
+ typeof file.size === "number" &&
1153
+ Number.isSafeInteger(file.size) &&
1154
+ file.size >= 0 &&
1155
+ typeof file.mimeType === "string" &&
1156
+ file.mimeType.length > 0 &&
1157
+ !file.mimeType.includes("\0") &&
1158
+ typeof file.sha256 === "string" &&
1159
+ /^[0-9a-f]{64}$/.test(file.sha256) &&
1160
+ typeof file.revision === "string" &&
1161
+ /^[0-9a-f]{64}$/.test(file.revision), "invalid_transfer_file", "The upload receipt must retain its actual safe file facts and target.");
1162
+ try {
1163
+ new MIMEType(file.mimeType);
1164
+ }
1165
+ catch {
1166
+ throw new AgentError("invalid_transfer_file", "The upload receipt MIME type is invalid.");
1167
+ }
1168
+ }
1169
+ if (data.stop !== undefined)
1170
+ this.#transferStop(data.stop);
1171
+ if (data.error !== undefined) {
1172
+ requireCondition(isPlainRecord(data.error) &&
1173
+ Object.keys(data.error).every((key) => ["code", "message", "details"].includes(key)) &&
1174
+ typeof data.error.code === "string" &&
1175
+ data.error.code.length > 0 &&
1176
+ data.error.code.length <= 256 &&
1177
+ typeof data.error.message === "string" &&
1178
+ data.error.message.length <= 4096 &&
1179
+ (data.error.details === undefined ||
1180
+ isPlainRecord(data.error.details)), "invalid_transfer_metadata", "Transfer failures must be safe error data.");
1181
+ canonicalJson(data.error, 12 * 1024);
1182
+ }
1183
+ requireCondition(data.outcome === undefined ||
1184
+ ["succeeded", "failed", "cancelled", "expired"].includes(data.outcome), "invalid_transfer_metadata", "The retained transfer outcome is invalid.");
1185
+ return data;
1186
+ }
1187
+ #transferStop(reason) {
1188
+ requireCondition(isPlainRecord(reason) &&
1189
+ Object.keys(reason).every((key) => ["kind", "code"].includes(key)) &&
1190
+ ["cancel", "expired", "timeout", "permission", "failure"].includes(reason.kind) &&
1191
+ typeof reason.code === "string" &&
1192
+ reason.code.length > 0 &&
1193
+ reason.code.length <= 256, "invalid_transfer_stop", "A transfer stop needs a fixed reason and safe code.");
1194
+ }
1195
+ getTransfer(id, scope) {
1196
+ this.#transferOwner(scope);
1197
+ requireCondition(typeof id === "string" && /^tr_[0-9a-f]{32}$/.test(id), "invalid_transfer_id", "A transfer needs its retained identity.");
1198
+ const row = this.#get("transfers", "transfer_id", id, "transfer_not_found");
1199
+ const resource = this.getResource(row.resourceId);
1200
+ requireCondition(row.callerKey === scope.callerKey &&
1201
+ resource.callerKey === row.callerKey &&
1202
+ resource.originRunId === row.originRunId &&
1203
+ resource.source.type === scope.owner.type &&
1204
+ resource.source.owner === scope.owner.owner &&
1205
+ resource.source.namespace === scope.owner.namespace, "transfer_not_found", "The transfer does not belong to this caller and Core source.");
1206
+ return this.#transferOrigin(row);
1207
+ }
1208
+ #transferOrigin(row) {
1209
+ // Old records remain explicitly unknown; never infer history from a new run/project.
1210
+ return {
1211
+ ...row,
1212
+ metadata: {
1213
+ ...row.metadata,
1214
+ origin: row.metadata.origin ?? null,
1215
+ maxBytes: row.metadata.maxBytes ?? null,
1216
+ startedAt: row.metadata.startedAt ?? null,
1217
+ },
1218
+ };
1219
+ }
1220
+ #currentTransfer(id, scope, revision) {
1221
+ const row = this.getTransfer(id, scope), resource = this.getResource(row.resourceId);
1222
+ requireCondition(Number.isSafeInteger(revision) &&
1223
+ revision > 0 &&
1224
+ row.revision === revision &&
1225
+ row.endedAt === null &&
1226
+ resource.bootId === this.bootId, "transfer_state_conflict", "The transfer changed or its original live control is unavailable.");
1227
+ return row;
1228
+ }
1229
+ createTransfer(scope, input, now = Date.now()) {
1230
+ this.#transferOwner(scope);
1231
+ const metadata = this.#transferMetadata(input.metadata);
1232
+ requireCondition(["upload", "download"].includes(input.direction) &&
1233
+ Object.keys(metadata).every((key) => key === "target") &&
1234
+ Number.isSafeInteger(input.maxBytes) &&
1235
+ input.maxBytes > 0, "invalid_transfer", "A new transfer has only its accepted target, not a fabricated outcome.");
1236
+ requireCondition((metadata.target.size === undefined ||
1237
+ metadata.target.size <= input.maxBytes) &&
1238
+ (metadata.target.expectedSize === undefined ||
1239
+ metadata.target.expectedSize <= input.maxBytes), "resource_exhausted", "The target exceeds the accepted transfer payload budget.");
1240
+ return this.#transaction(() => {
1241
+ const resource = this.getResource(input.resourceId), run = this.getRun(input.runId);
1242
+ requireCondition(resource.bootId === this.bootId &&
1243
+ run.bootId === this.bootId &&
1244
+ resource.callerKey === scope.callerKey &&
1245
+ run.callerKey === scope.callerKey &&
1246
+ resource.source.type === scope.owner.type &&
1247
+ resource.source.owner === scope.owner.owner &&
1248
+ resource.source.namespace === scope.owner.namespace &&
1249
+ resource.originRunId === input.runId &&
1250
+ resource.ownerRunId === input.runId &&
1251
+ resource.lifetime === "run" &&
1252
+ resource.closedAt === null &&
1253
+ ["preparing_inputs", "running", "waiting_input"].includes(run.status) &&
1254
+ !run.stop, "transfer_state_conflict", "A transfer must originate from the verified live run and its registered resource.");
1255
+ const id = newId("tr");
1256
+ const captured = this.#transferMetadata({
1257
+ ...metadata,
1258
+ origin: { contextId: run.contextId, projectId: run.projectId },
1259
+ maxBytes: input.maxBytes,
1260
+ startedAt: null,
1261
+ });
1262
+ this.#db
1263
+ .prepare(`INSERT INTO transfers(transfer_id,resource_id,caller_key,origin_run_id,direction,status,metadata_json,created_at,retention_history_ms)
1264
+ VALUES(?,?,?,?,?,'preparing',?,?,?)`)
1265
+ .run(id, input.resourceId, scope.callerKey, input.runId, input.direction, canonicalJson(captured), now, this.#retention.runHistoryMs);
1266
+ return this.getTransfer(id, scope);
1267
+ });
1268
+ }
1269
+ publishTransferPending(id, scope, input, now = Date.now()) {
1270
+ requireCondition(Number.isSafeInteger(input.claimDeadlineAt) &&
1271
+ input.claimDeadlineAt > now, "invalid_transfer_deadline", "A pending offer needs its actual future claim deadline.");
1272
+ return this.#transaction(() => {
1273
+ const row = this.#currentTransfer(id, scope, input.revision);
1274
+ requireCondition(row.status === "preparing" && row.originRunId, "transfer_state_conflict", "Only the original preparing transfer can publish an offer.");
1275
+ const supplied = input.metadata
1276
+ ? this.#transferMetadata(input.metadata)
1277
+ : row.metadata;
1278
+ requireCondition(supplied.origin === undefined ||
1279
+ canonicalJson(supplied.origin) ===
1280
+ canonicalJson(row.metadata.origin ?? null), "invalid_transfer_origin", "Publishing an offer cannot replace its original creator association.");
1281
+ const metadata = this.#transferMetadata({
1282
+ ...supplied,
1283
+ origin: row.metadata.origin ?? null,
1284
+ maxBytes: row.metadata.maxBytes ?? null,
1285
+ startedAt: row.metadata.startedAt ?? null,
1286
+ });
1287
+ const unchangedTarget = Object.entries(row.metadata.target).every(([field, value]) => metadata.target[field] === value);
1288
+ requireCondition((supplied.maxBytes === undefined ||
1289
+ supplied.maxBytes === row.metadata.maxBytes) &&
1290
+ (supplied.startedAt === undefined ||
1291
+ supplied.startedAt === row.metadata.startedAt), "invalid_transfer_metadata", "Publishing an offer cannot change its accepted budget or actual claim time.");
1292
+ requireCondition(Object.keys(metadata).every((key) => ["target", "origin", "maxBytes", "startedAt"].includes(key)) &&
1293
+ unchangedTarget &&
1294
+ (row.direction === "upload"
1295
+ ? metadata.target.path !== undefined &&
1296
+ (row.metadata.target.path === undefined ||
1297
+ metadata.target.path === row.metadata.target.path)
1298
+ : metadata.target.resourceUri !== undefined &&
1299
+ metadata.target.size !== undefined &&
1300
+ metadata.target.sha256 !== undefined), "invalid_transfer_metadata", "A pending download must reference its actual fixed artifact.");
1301
+ requireCondition(typeof metadata.maxBytes === "number" &&
1302
+ (metadata.target.size === undefined ||
1303
+ metadata.target.size <= metadata.maxBytes) &&
1304
+ (metadata.target.expectedSize === undefined ||
1305
+ metadata.target.expectedSize <= metadata.maxBytes), "resource_exhausted", "The prepared target exceeds the originally accepted payload budget.");
1306
+ const resource = this.#handoffResource(row.resourceId, row.originRunId, input.resourceRevision, now);
1307
+ this.#db
1308
+ .prepare(`UPDATE transfers SET status='pending',claim_deadline_at=?,metadata_json=?,revision=revision+1
1309
+ WHERE transfer_id=? AND revision=?`)
1310
+ .run(input.claimDeadlineAt, canonicalJson(metadata), id, input.revision);
1311
+ return { transfer: this.getTransfer(id, scope), resource };
1312
+ });
1313
+ }
1314
+ claimTransfer(id, scope, input, now = Date.now()) {
1315
+ requireCondition(Number.isSafeInteger(input.transferDeadlineAt) &&
1316
+ input.transferDeadlineAt > now, "invalid_transfer_deadline", "A claimed stream needs its actual future transfer deadline.");
1317
+ return this.#transaction(() => {
1318
+ const row = this.#currentTransfer(id, scope, input.revision), resource = this.getResource(row.resourceId);
1319
+ requireCondition(row.status === "pending" &&
1320
+ row.claimDeadlineAt !== null &&
1321
+ now < row.claimDeadlineAt, "transfer_not_claimable", "The offer is not pending or its claim deadline passed; do not reuse its URL.");
1322
+ requireCondition(resource.lifetime === "background" &&
1323
+ resource.closedAt === null &&
1324
+ !["stopping", "unconfirmed", "unavailable"].includes(resource.status), "resource_unavailable", "The actual transfer resource cannot start a new stream.");
1325
+ requireCondition(typeof row.metadata.maxBytes === "number" &&
1326
+ row.metadata.maxBytes > 0 &&
1327
+ row.metadata.startedAt === null, "transfer_state_conflict", "A new claim needs its original accepted budget and no prior claim time.");
1328
+ const metadata = this.#transferMetadata({
1329
+ ...row.metadata,
1330
+ startedAt: now,
1331
+ });
1332
+ this.#db
1333
+ .prepare(`UPDATE transfers SET status='transferring',transfer_deadline_at=?,metadata_json=?,revision=revision+1
1334
+ WHERE transfer_id=? AND revision=?`)
1335
+ .run(input.transferDeadlineAt, canonicalJson(metadata), id, input.revision);
1336
+ return this.getTransfer(id, scope);
1337
+ });
1338
+ }
1339
+ #transferResultRef(value) {
1340
+ requireCondition(typeof value === "string" &&
1341
+ value.length > 0 &&
1342
+ Buffer.byteLength(value) <= 8192 &&
1343
+ !value.includes("\0") &&
1344
+ (!/^[a-z][a-z0-9+.-]*:/i.test(value) ||
1345
+ /^[a-z]:[\\/]/i.test(value) ||
1346
+ /^nexum:\/\/agents\/[^/]+\/resources\/res_[0-9a-f]{32}$/.test(value)), "invalid_transfer_result", "A result reference is a retained local coordinate, never a request URL or token.");
1347
+ }
1348
+ #transferFileFacts(row, metadata, bytes) {
1349
+ if (metadata.fileCommitted === true || metadata.file !== undefined) {
1350
+ requireCondition(row.direction === "upload" &&
1351
+ row.transferDeadlineAt !== null &&
1352
+ metadata.fileCommitted === true &&
1353
+ (metadata.target.expectedSize === undefined ||
1354
+ metadata.target.expectedSize === bytes) &&
1355
+ (metadata.file === undefined ||
1356
+ (metadata.file.size === bytes &&
1357
+ (metadata.target.expectedSha256 === undefined ||
1358
+ metadata.target.expectedSha256 === metadata.file.sha256))), "invalid_transfer_file", "Committed upload facts and any confirmed file receipt must match the actual stream.");
1359
+ }
1360
+ requireCondition(row.metadata.file === undefined ||
1361
+ canonicalJson(row.metadata.file) === canonicalJson(metadata.file), "transfer_state_conflict", "A committed upload receipt cannot be replaced or withdrawn.");
1362
+ }
1363
+ progressTransfer(id, scope, input, now = Date.now()) {
1364
+ requireCondition(Number.isSafeInteger(input.bytesTransferred) &&
1365
+ input.bytesTransferred >= 0 &&
1366
+ (input.fileCommitted === undefined ||
1367
+ typeof input.fileCommitted === "boolean"), "invalid_transfer_progress", "Progress is an actual non-negative byte count and publication fact.");
1368
+ if (input.resultRef !== undefined)
1369
+ this.#transferResultRef(input.resultRef);
1370
+ return this.#transaction(() => {
1371
+ const row = this.#currentTransfer(id, scope, input.revision);
1372
+ requireCondition(typeof row.metadata.maxBytes === "number" &&
1373
+ input.bytesTransferred <= row.metadata.maxBytes, "resource_exhausted", "Actual transfer bytes exceed the originally accepted payload budget.");
1374
+ requireCondition(input.bytesTransferred >= row.bytesTransferred &&
1375
+ (input.bytesTransferred === row.bytesTransferred ||
1376
+ (row.transferDeadlineAt !== null &&
1377
+ ["transferring", "cancelling"].includes(row.status))) &&
1378
+ (input.resultRef === undefined ||
1379
+ row.resultRef === null ||
1380
+ row.resultRef === input.resultRef), "transfer_state_conflict", "Actual progress and a committed result cannot be rolled back or replaced.");
1381
+ const metadata = this.#transferMetadata({
1382
+ ...row.metadata,
1383
+ ...(input.fileCommitted === undefined
1384
+ ? {}
1385
+ : {
1386
+ fileCommitted: row.metadata.fileCommitted === true || input.fileCommitted,
1387
+ }),
1388
+ ...(input.file === undefined ? {} : { file: input.file }),
1389
+ });
1390
+ this.#transferFileFacts(row, metadata, input.bytesTransferred);
1391
+ this.#db
1392
+ .prepare(`UPDATE transfers SET bytes_transferred=?,metadata_json=?,result_ref=COALESCE(?,result_ref),revision=revision+1
1393
+ WHERE transfer_id=? AND revision=?`)
1394
+ .run(input.bytesTransferred, canonicalJson(metadata), input.resultRef ?? null, id, input.revision);
1395
+ return this.getTransfer(id, scope);
1396
+ });
1397
+ }
1398
+ requestTransferCancel(id, scope, input, now = Date.now()) {
1399
+ this.#transferStop(input.reason);
1400
+ return this.#transaction(() => {
1401
+ const previous = this.getTransfer(id, scope);
1402
+ if (previous.endedAt !== null)
1403
+ return { accepted: false, transfer: previous };
1404
+ if (previous.status === "cancelling")
1405
+ return {
1406
+ accepted: previous.metadata.stop?.kind === input.reason.kind,
1407
+ transfer: previous,
1408
+ };
1409
+ const row = this.#currentTransfer(id, scope, input.revision);
1410
+ requireCondition((input.reason.kind !== "expired" ||
1411
+ (row.status === "pending" &&
1412
+ row.claimDeadlineAt !== null &&
1413
+ now >= row.claimDeadlineAt)) &&
1414
+ (input.reason.kind !== "timeout" ||
1415
+ (row.status === "transferring" &&
1416
+ row.transferDeadlineAt !== null &&
1417
+ now >= row.transferDeadlineAt)), "transfer_state_conflict", "A deadline stop requires the corresponding actual phase and elapsed deadline.");
1418
+ const metadata = this.#transferMetadata({
1419
+ ...row.metadata,
1420
+ stop: row.metadata.stop ?? input.reason,
1421
+ });
1422
+ this.#db
1423
+ .prepare(`UPDATE transfers SET status='cancelling',metadata_json=?,revision=revision+1
1424
+ WHERE transfer_id=? AND revision=?`)
1425
+ .run(canonicalJson(metadata), id, input.revision);
1426
+ return { accepted: true, transfer: this.getTransfer(id, scope) };
1427
+ });
1428
+ }
1429
+ finishTransfer(id, scope, input, now = Date.now()) {
1430
+ requireCondition(["succeeded", "failed", "cancelled", "expired"].includes(input.status) &&
1431
+ typeof input.cleanupConfirmed === "boolean" &&
1432
+ (input.fileCommitted === undefined ||
1433
+ typeof input.fileCommitted === "boolean"), "invalid_transfer_outcome", "Only actual I/O and cleanup facts can settle a transfer.");
1434
+ if (input.resultRef !== undefined)
1435
+ this.#transferResultRef(input.resultRef);
1436
+ return this.#transaction(() => {
1437
+ const row = this.#currentTransfer(id, scope, input.revision), resource = this.getResource(row.resourceId);
1438
+ requireCondition(input.resultRef === undefined ||
1439
+ row.resultRef === null ||
1440
+ row.resultRef === input.resultRef, "transfer_state_conflict", "A committed transfer result cannot be replaced.");
1441
+ requireCondition((input.status !== "succeeded" ||
1442
+ (["transferring", "cancelling"].includes(row.status) &&
1443
+ row.transferDeadlineAt !== null &&
1444
+ (row.direction === "upload"
1445
+ ? (row.metadata.fileCommitted === true ||
1446
+ input.fileCommitted === true) &&
1447
+ (row.metadata.file !== undefined || input.file !== undefined)
1448
+ : row.metadata.target.size === row.bytesTransferred))) &&
1449
+ (input.status !== "cancelled" ||
1450
+ row.metadata.stop?.kind === "cancel") &&
1451
+ (input.status !== "expired" || row.metadata.stop?.kind === "expired"), "invalid_transfer_outcome", "The final outcome must match the actual stream or accepted stop.");
1452
+ const confirmed = input.cleanupConfirmed && resource.closedAt !== null;
1453
+ const metadata = this.#transferMetadata({
1454
+ ...row.metadata,
1455
+ fileCommitted: row.metadata.fileCommitted === true || input.fileCommitted === true,
1456
+ ...(input.file === undefined ? {} : { file: input.file }),
1457
+ cleanupConfirmed: confirmed,
1458
+ outcome: input.status,
1459
+ ...(input.error === undefined ? {} : { error: input.error }),
1460
+ });
1461
+ this.#transferFileFacts(row, metadata, row.bytesTransferred);
1462
+ this.#db
1463
+ .prepare(`UPDATE transfers SET status=?,ended_at=?,metadata_json=?,result_ref=COALESCE(?,result_ref),revision=revision+1
1464
+ WHERE transfer_id=? AND revision=?`)
1465
+ .run(confirmed ? input.status : row.status, confirmed ? now : null, canonicalJson(metadata), input.resultRef ?? null, id, input.revision);
1466
+ return this.getTransfer(id, scope);
1467
+ });
1468
+ }
1469
+ scanTransfers(scope, filter = {}, limit = 100, cursor) {
1470
+ this.#transferOwner(scope);
1471
+ requireCondition(Number.isSafeInteger(limit) &&
1472
+ limit > 0 &&
1473
+ limit <= 1000 &&
1474
+ isPlainRecord(filter) &&
1475
+ Object.keys(filter).every((key) => ["direction", "status", "runId"].includes(key)), "invalid_transfer_query", "Transfer history needs bounded known equality filters.");
1476
+ const statuses = [
1477
+ "preparing",
1478
+ "pending",
1479
+ "transferring",
1480
+ "cancelling",
1481
+ "succeeded",
1482
+ "failed",
1483
+ "cancelled",
1484
+ "expired",
1485
+ "interrupted",
1486
+ ];
1487
+ requireCondition((filter.direction === undefined ||
1488
+ (typeof filter.direction === "string" &&
1489
+ ["upload", "download"].includes(filter.direction))) &&
1490
+ (filter.status === undefined ||
1491
+ (typeof filter.status === "string" &&
1492
+ statuses.includes(filter.status))) &&
1493
+ (filter.runId === undefined ||
1494
+ (typeof filter.runId === "string" &&
1495
+ filter.runId.length > 0 &&
1496
+ filter.runId.length <= 256)), "invalid_transfer_query", "The transfer history filter is invalid.");
1497
+ const query = digest({
1498
+ mode: "transfers",
1499
+ binding: this.binding,
1500
+ scope,
1501
+ filter: Object.fromEntries(Object.entries(filter).filter(([, value]) => value !== undefined)),
1502
+ });
1503
+ const where = [
1504
+ "t.caller_key=?",
1505
+ "json_extract(m.source_json,'$.type')=?",
1506
+ "json_extract(m.source_json,'$.owner')=?",
1507
+ "json_extract(m.source_json,'$.namespace')=?",
1508
+ ];
1509
+ const values = [
1510
+ scope.callerKey,
1511
+ scope.owner.type,
1512
+ scope.owner.owner,
1513
+ scope.owner.namespace,
1514
+ ];
1515
+ for (const [field, column] of [
1516
+ ["direction", "t.direction"],
1517
+ ["status", "t.status"],
1518
+ ["runId", "t.origin_run_id"],
1519
+ ])
1520
+ if (typeof filter[field] === "string") {
1521
+ where.push(`${column}=?`);
1522
+ values.push(filter[field]);
1523
+ }
1524
+ if (cursor !== undefined) {
1525
+ try {
1526
+ requireCondition(typeof cursor === "string" &&
1527
+ cursor.length > 0 &&
1528
+ cursor.length <= 4096 &&
1529
+ /^[A-Za-z0-9_-]+$/.test(cursor), "invalid_cursor", "The transfer history cursor is invalid.");
1530
+ const envelope = Buffer.from(cursor, "base64url");
1531
+ requireCondition(envelope.length > 28, "invalid_cursor", "The transfer cursor has no authenticated position.");
1532
+ const decipher = createDecipheriv("aes-256-gcm", this.#cursorKey, envelope.subarray(0, 12));
1533
+ decipher.setAAD(Buffer.from(query));
1534
+ decipher.setAuthTag(envelope.subarray(-16));
1535
+ const position = JSON.parse(Buffer.concat([
1536
+ decipher.update(envelope.subarray(12, -16)),
1537
+ decipher.final(),
1538
+ ]).toString("utf8"));
1539
+ requireCondition(Number.isSafeInteger(position.time) &&
1540
+ position.time >= 0 &&
1541
+ typeof position.id === "string" &&
1542
+ /^tr_[0-9a-f]{32}$/.test(position.id), "invalid_cursor", "The transfer cursor belongs to another caller or filter.");
1543
+ where.push("(t.created_at<? OR (t.created_at=? AND t.transfer_id<?))");
1544
+ values.push(position.time, position.time, position.id);
1545
+ }
1546
+ catch (cause) {
1547
+ throw new AgentError("invalid_cursor", "The transfer history cursor is invalid or no longer current.", undefined, { cause });
1548
+ }
1549
+ }
1550
+ const rows = this.#db
1551
+ .prepare(`SELECT t.* FROM transfers t JOIN managed_resources m ON m.resource_id=t.resource_id
1552
+ WHERE ${where.join(" AND ")} ORDER BY t.created_at DESC,t.transfer_id DESC LIMIT ?`)
1553
+ .all(...values, limit + 1);
1554
+ return {
1555
+ more: rows.length > limit,
1556
+ items: rows.slice(0, limit).map((raw) => {
1557
+ const record = this.#transferOrigin(decode(raw));
1558
+ const iv = randomBytes(12), cipher = createCipheriv("aes-256-gcm", this.#cursorKey, iv);
1559
+ cipher.setAAD(Buffer.from(query));
1560
+ const ciphertext = Buffer.concat([
1561
+ cipher.update(JSON.stringify({ time: record.createdAt, id: record.transferId })),
1562
+ cipher.final(),
1563
+ ]);
1564
+ return {
1565
+ record,
1566
+ cursor: Buffer.concat([iv, ciphertext, cipher.getAuthTag()]).toString("base64url"),
1567
+ };
1568
+ }),
1569
+ };
1570
+ }
1571
+ closeResource(id, revision, diagnostic = {}, now = Date.now()) {
1572
+ return this.#transaction(() => {
1573
+ const resource = this.getResource(id);
1574
+ requireCondition(resource.bootId === this.bootId, "resource_unavailable", "The old Agent resource cannot be controlled.");
1575
+ if (resource.closedAt !== null)
1576
+ return resource;
1577
+ requireCondition(resource.revision === revision, "resource_state_conflict", "The resource changed concurrently.");
1578
+ this.#db
1579
+ .prepare("UPDATE managed_resources SET status='closed',closed_at=?,diagnostic_json=?,revision=revision+1 WHERE resource_id=? AND revision=?")
1580
+ .run(now, canonicalJson(diagnostic), id, revision);
1581
+ return this.getResource(id);
1582
+ });
1583
+ }
1584
+ resourceDiagnostic(id, status, diagnostic) {
1585
+ requireCondition(["registered", "stopping", "unconfirmed"].includes(status), "invalid_resource_diagnostic", "Diagnostic updates cannot assert physical closure.");
1586
+ return this.#transaction(() => {
1587
+ const resource = this.getResource(id);
1588
+ requireCondition(resource.bootId === this.bootId, "resource_unavailable", "The old Agent resource cannot be controlled.");
1589
+ if (resource.closedAt !== null)
1590
+ return resource;
1591
+ this.#db
1592
+ .prepare("UPDATE managed_resources SET status=?,diagnostic_json=?,revision=revision+1 WHERE resource_id=? AND closed_at IS NULL")
1593
+ .run(status, canonicalJson(diagnostic), id);
1594
+ return this.getResource(id);
1595
+ });
1596
+ }
1597
+ saveCleanup(id, cleanup, now = Date.now()) {
1598
+ return this.#transaction(() => {
1599
+ const run = this.getRun(id);
1600
+ requireCondition(run.bootId === this.bootId && run.endedAt === null, "run_state_conflict", "Only a live run can update its unfinished cleanup facts.");
1601
+ this.#db
1602
+ .prepare("UPDATE runs SET cleanup_json=?,revision=revision+1,updated_at=? WHERE run_id=? AND ended_at IS NULL")
1603
+ .run(canonicalJson(cleanup), now, id);
1604
+ return this.getRun(id);
1605
+ });
1606
+ }
1607
+ resourcesForRun(runId, limit) {
1608
+ requireCondition(limit === undefined ||
1609
+ (Number.isSafeInteger(limit) && limit > 0 && limit <= 1000), "invalid_limit", "A resource summary needs a bounded limit.");
1610
+ return this.#db
1611
+ .prepare(limit === undefined
1612
+ ? "SELECT * FROM managed_resources WHERE origin_run_id=? ORDER BY created_at,resource_id"
1613
+ : "SELECT * FROM managed_resources WHERE origin_run_id=? ORDER BY created_at DESC,resource_id DESC LIMIT ?")
1614
+ .all(...(limit === undefined ? [runId] : [runId, limit]))
1615
+ .map((row) => decode(row));
1616
+ }
1617
+ resourceHistory(id) {
1618
+ const row = this.#db
1619
+ .prepare(`SELECT m.*, r.context_id FROM managed_resources m
1620
+ LEFT JOIN runs r ON r.run_id=m.origin_run_id WHERE m.resource_id=?`)
1621
+ .get(id);
1622
+ requireCondition(row, "resource_not_found", "The resource history does not exist.");
1623
+ return decode(row);
1624
+ }
1625
+ /** Internal bounded scan. Per-row cursors let the manager filter authority without skipping rows. */
1626
+ scanResourceHistory(filter, caller, limit = 100, cursor) {
1627
+ requireCondition(Number.isSafeInteger(limit) && limit > 0 && limit <= 1000, "invalid_limit", "A resource history scan must contain between 1 and 1000 rows.");
1628
+ const query = digest({
1629
+ mode: "resource-history",
1630
+ binding: this.binding,
1631
+ caller,
1632
+ filter: Object.fromEntries(Object.entries(filter).filter(([, value]) => value !== undefined)),
1633
+ });
1634
+ const where = [
1635
+ "json_extract(m.source_json,'$.owner')=?",
1636
+ "json_extract(m.source_json,'$.namespace')=?",
1637
+ "json_extract(m.source_json,'$.type')=?",
1638
+ ];
1639
+ const values = [
1640
+ filter.owner,
1641
+ filter.namespace,
1642
+ filter.type,
1643
+ ];
1644
+ for (const [field, expression] of [
1645
+ ["kind", "m.kind"],
1646
+ ["status", "m.status"],
1647
+ ["state", "json_extract(m.diagnostic_json,'$.details.state')"],
1648
+ ["runId", "m.origin_run_id"],
1649
+ ["contextId", "r.context_id"],
1650
+ ]) {
1651
+ if (filter[field] !== undefined) {
1652
+ if (field === "state")
1653
+ where.push("json_type(m.diagnostic_json,'$.details.state')='text'");
1654
+ where.push(`${expression}=?`);
1655
+ values.push(filter[field]);
1656
+ }
1657
+ }
1658
+ if (cursor !== undefined) {
1659
+ try {
1660
+ requireCondition(typeof cursor === "string" &&
1661
+ cursor.length > 0 &&
1662
+ cursor.length <= 4096 &&
1663
+ /^[A-Za-z0-9_-]+$/.test(cursor), "invalid_cursor", "The resource history cursor is invalid.");
1664
+ const envelope = Buffer.from(cursor, "base64url");
1665
+ requireCondition(envelope.length > 28, "invalid_cursor", "The resource history cursor is invalid.");
1666
+ const decipher = createDecipheriv("aes-256-gcm", this.#cursorKey, envelope.subarray(0, 12));
1667
+ decipher.setAAD(Buffer.from(query));
1668
+ decipher.setAuthTag(envelope.subarray(-16));
1669
+ const page = JSON.parse(Buffer.concat([
1670
+ decipher.update(envelope.subarray(12, -16)),
1671
+ decipher.final(),
1672
+ ]).toString("utf8"));
1673
+ requireCondition(Number.isSafeInteger(page.time) &&
1674
+ page.time >= 0 &&
1675
+ typeof page.id === "string" &&
1676
+ /^res_[0-9a-f]{32}$/.test(page.id), "invalid_cursor", "The resource history cursor has no valid position.");
1677
+ where.push("(m.created_at<? OR (m.created_at=? AND m.resource_id<?))");
1678
+ values.push(page.time, page.time, page.id);
1679
+ }
1680
+ catch (cause) {
1681
+ throw new AgentError("invalid_cursor", "The resource history cursor is invalid or belongs to another caller, source or filter.", undefined, { cause });
1682
+ }
1683
+ }
1684
+ const rows = this.#db
1685
+ .prepare(`SELECT m.*, r.context_id FROM managed_resources m
1686
+ LEFT JOIN runs r ON r.run_id=m.origin_run_id WHERE ${where.join(" AND ")}
1687
+ ORDER BY m.created_at DESC,m.resource_id DESC LIMIT ?`)
1688
+ .all(...values, limit + 1);
1689
+ return {
1690
+ more: rows.length > limit,
1691
+ items: rows.slice(0, limit).map((row) => {
1692
+ const record = decode(row);
1693
+ const iv = randomBytes(12), cipher = createCipheriv("aes-256-gcm", this.#cursorKey, iv);
1694
+ cipher.setAAD(Buffer.from(query));
1695
+ const ciphertext = Buffer.concat([
1696
+ cipher.update(JSON.stringify({ time: record.createdAt, id: record.resourceId })),
1697
+ cipher.final(),
1698
+ ]);
1699
+ return {
1700
+ record,
1701
+ cursor: Buffer.concat([iv, ciphertext, cipher.getAuthTag()]).toString("base64url"),
1702
+ };
1703
+ }),
1704
+ };
1705
+ }
1706
+ scriptUsage(callerKey) {
1707
+ return this.#db
1708
+ .prepare(`SELECT json_extract(source_json,'$.origin.owner') owner,
1709
+ script_name scriptName,count(*) count,max(started_at) lastStartedAt FROM runs
1710
+ WHERE caller_key=? AND started_at IS NOT NULL AND script_name IS NOT NULL
1711
+ AND json_type(source_json,'$.origin.owner')='text' GROUP BY owner,script_name`)
1712
+ .all(callerKey);
1713
+ }
1714
+ getState(key) {
1715
+ const row = this.#db
1716
+ .prepare("SELECT * FROM agent_state WHERE key=? AND deleted_at IS NULL")
1717
+ .get(key);
1718
+ return row
1719
+ ? {
1720
+ value: JSON.parse(row.value_json),
1721
+ version: row.version,
1722
+ updatedAt: row.updated_at,
1723
+ }
1724
+ : null;
1725
+ }
1726
+ setState(key, value, expectedVersion, now = Date.now()) {
1727
+ requireCondition(key.length > 0 && key.length <= 256, "invalid_state_key", "The state key is invalid.");
1728
+ const encoded = canonicalJson(value);
1729
+ return this.#transaction(() => {
1730
+ const previous = this.#db
1731
+ .prepare("SELECT * FROM agent_state WHERE key=?")
1732
+ .get(key);
1733
+ const currentVersion = previous && previous.deleted_at === null
1734
+ ? previous.version
1735
+ : null;
1736
+ requireCondition(currentVersion === expectedVersion, "state_version_conflict", "The shared value changed concurrently.");
1737
+ requireCondition(!previous || Number(previous.version) < Number.MAX_SAFE_INTEGER, "state_version_exhausted", "The shared key's revision cannot advance safely.");
1738
+ if (previous) {
1739
+ const changed = this.#db
1740
+ .prepare("UPDATE agent_state SET value_json=?,version=version+1,updated_at=?,deleted_at=NULL WHERE key=? AND version=?")
1741
+ .run(encoded, now, key, previous.version);
1742
+ requireCondition(changed.changes === 1, "state_version_conflict", "The shared value changed concurrently.");
1743
+ }
1744
+ else
1745
+ this.#db
1746
+ .prepare("INSERT INTO agent_state(key,value_json,version,updated_at) VALUES(?,?,1,?)")
1747
+ .run(key, encoded, now);
1748
+ return this.getState(key);
1749
+ });
1750
+ }
1751
+ deleteState(key, expectedVersion, now = Date.now()) {
1752
+ requireCondition(typeof key === "string" &&
1753
+ key.length > 0 &&
1754
+ key.length <= 256 &&
1755
+ Number.isSafeInteger(expectedVersion) &&
1756
+ expectedVersion > 0, "invalid_state_delete", "Deleting a shared value requires its actual key and positive revision.");
1757
+ return this.#transaction(() => {
1758
+ const current = this.getState(key);
1759
+ requireCondition(current?.version === expectedVersion, "state_version_conflict", "The shared value changed concurrently.");
1760
+ requireCondition(expectedVersion < Number.MAX_SAFE_INTEGER, "state_version_exhausted", "The shared key's revision cannot advance safely.");
1761
+ const changed = this.#db
1762
+ .prepare("UPDATE agent_state SET value_json='null',version=version+1,updated_at=?,deleted_at=? WHERE key=? AND version=? AND deleted_at IS NULL")
1763
+ .run(now, now, key, expectedVersion);
1764
+ requireCondition(changed.changes === 1, "state_version_conflict", "The shared value changed concurrently.");
1765
+ return { deleted: true, version: expectedVersion + 1, updatedAt: now };
1766
+ });
1767
+ }
1768
+ /** Internal bounded scan; cursors hide even records denied by the current policy. */
1769
+ scanRuns(filter, scopeKey, limit = 20, cursor) {
1770
+ requireCondition(Number.isInteger(limit) && limit >= 1 && limit <= 100, "invalid_limit", "The history limit must be between 1 and 100.");
1771
+ requireCondition(filter.from === undefined ||
1772
+ filter.to === undefined ||
1773
+ filter.from <= filter.to, "invalid_range", "The history start must not exceed the end.");
1774
+ const query = digest({
1775
+ scopeKey,
1776
+ binding: this.binding,
1777
+ filter: Object.fromEntries(Object.entries(filter).filter(([, value]) => value !== undefined)),
1778
+ });
1779
+ const where = [];
1780
+ const values = [];
1781
+ for (const [field, column] of [
1782
+ ["status", "status"],
1783
+ ["scriptName", "script_name"],
1784
+ ["sourceKind", "source_kind"],
1785
+ ["projectId", "project_id"],
1786
+ ["contextId", "context_id"],
1787
+ ]) {
1788
+ if (filter[field] !== undefined) {
1789
+ where.push(`${column}=?`);
1790
+ values.push(filter[field]);
1791
+ }
1792
+ }
1793
+ if (filter.from !== undefined) {
1794
+ where.push("accepted_at>=?");
1795
+ values.push(filter.from);
1796
+ }
1797
+ if (filter.to !== undefined) {
1798
+ where.push("accepted_at<?");
1799
+ values.push(filter.to);
1800
+ }
1801
+ if (cursor !== undefined) {
1802
+ try {
1803
+ requireCondition(typeof cursor === "string" &&
1804
+ cursor.length > 0 &&
1805
+ cursor.length <= 4096 &&
1806
+ /^[A-Za-z0-9_-]+$/.test(cursor), "invalid_cursor", "The history cursor is invalid.");
1807
+ const envelope = Buffer.from(cursor, "base64url");
1808
+ requireCondition(envelope.length > 28, "invalid_cursor", "The history cursor is invalid.");
1809
+ const decipher = createDecipheriv("aes-256-gcm", this.#cursorKey, envelope.subarray(0, 12));
1810
+ decipher.setAAD(Buffer.from(query));
1811
+ decipher.setAuthTag(envelope.subarray(-16));
1812
+ const page = JSON.parse(Buffer.concat([
1813
+ decipher.update(envelope.subarray(12, -16)),
1814
+ decipher.final(),
1815
+ ]).toString("utf8"));
1816
+ requireCondition(Number.isSafeInteger(page.time) &&
1817
+ page.time >= 0 &&
1818
+ typeof page.id === "string" &&
1819
+ /^run_[0-9a-f]{32}$/.test(page.id), "invalid_cursor", "The cursor belongs to another query or scope.");
1820
+ where.push("(accepted_at<? OR (accepted_at=? AND run_id<?))");
1821
+ values.push(page.time, page.time, page.id);
1822
+ }
1823
+ catch (cause) {
1824
+ throw new AgentError("invalid_cursor", "The history cursor is invalid or no longer current.", undefined, { cause });
1825
+ }
1826
+ }
1827
+ const rows = this.#db
1828
+ .prepare(`SELECT * FROM runs ${where.length ? "WHERE " + where.join(" AND ") : ""} ORDER BY accepted_at DESC,run_id DESC LIMIT ?`)
1829
+ .all(...values, limit + 1);
1830
+ return {
1831
+ more: rows.length > limit,
1832
+ items: rows.slice(0, limit).map((row) => {
1833
+ const record = decode(row);
1834
+ const iv = randomBytes(12), cipher = createCipheriv("aes-256-gcm", this.#cursorKey, iv);
1835
+ cipher.setAAD(Buffer.from(query));
1836
+ const ciphertext = Buffer.concat([
1837
+ cipher.update(JSON.stringify({ time: record.acceptedAt, id: record.runId })),
1838
+ cipher.final(),
1839
+ ]);
1840
+ return {
1841
+ record,
1842
+ cursor: Buffer.concat([iv, ciphertext, cipher.getAuthTag()]).toString("base64url"),
1843
+ };
1844
+ }),
1845
+ };
1846
+ }
1847
+ listRuns(filter, scopeKey, limit = 20, cursor) {
1848
+ const page = this.scanRuns(filter, scopeKey, limit, cursor);
1849
+ return {
1850
+ runs: page.items.map((item) => item.record),
1851
+ nextCursor: page.more ? page.items.at(-1).cursor : null,
1852
+ };
1853
+ }
1854
+ }
1855
+ //# sourceMappingURL=sqlite.js.map