@nexum-hub/agent 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (343) hide show
  1. package/README.md +133 -2
  2. package/contracts/v2/common.schema.json +262 -0
  3. package/contracts/v2/fixtures/inputs.json +244 -0
  4. package/contracts/v2/fixtures/wire.json +6493 -0
  5. package/contracts/v2/model/agent.close.input.schema.json +14 -0
  6. package/contracts/v2/model/agent.close.output.schema.json +101 -0
  7. package/contracts/v2/model/agent.list.input.schema.json +57 -0
  8. package/contracts/v2/model/agent.list.output.schema.json +220 -0
  9. package/contracts/v2/model/agent.open.input.schema.json +35 -0
  10. package/contracts/v2/model/agent.open.output.schema.json +41 -0
  11. package/contracts/v2/model/agent.run.cancel.input.schema.json +18 -0
  12. package/contracts/v2/model/agent.run.cancel.output.schema.json +100 -0
  13. package/contracts/v2/model/agent.run.get.input.schema.json +41 -0
  14. package/contracts/v2/model/agent.run.get.output.schema.json +100 -0
  15. package/contracts/v2/model/agent.run.input.input.schema.json +30 -0
  16. package/contracts/v2/model/agent.run.input.output.schema.json +100 -0
  17. package/contracts/v2/model/agent.run.list.input.schema.json +47 -0
  18. package/contracts/v2/model/agent.run.list.output.schema.json +41 -0
  19. package/contracts/v2/model/agent.run.start.input.schema.json +73 -0
  20. package/contracts/v2/model/agent.run.start.output.schema.json +100 -0
  21. package/contracts/v2/wire/bodies.schema.json +383 -0
  22. package/contracts/v2/wire/envelope.schema.json +2280 -0
  23. package/contracts/v2/wire/events.schema.json +242 -0
  24. package/contracts/v2/wire/maintenance.schema.json +308 -0
  25. package/contracts/v2/wire/operations.schema.json +1791 -0
  26. package/contracts/v2/wire/stream.schema.json +74 -0
  27. package/contracts/v2/wire/types.schema.json +2616 -0
  28. package/dist/adapters/mcp-http.d.ts +22 -0
  29. package/dist/adapters/mcp-http.js +472 -0
  30. package/dist/adapters/mcp-http.js.map +1 -0
  31. package/dist/adapters/mcp-oauth.d.ts +29 -0
  32. package/dist/adapters/mcp-oauth.js +653 -0
  33. package/dist/adapters/mcp-oauth.js.map +1 -0
  34. package/dist/adapters/mcp-wire.d.ts +21 -0
  35. package/dist/adapters/mcp-wire.js +307 -0
  36. package/dist/adapters/mcp-wire.js.map +1 -0
  37. package/dist/adapters/mcp.d.ts +56 -0
  38. package/dist/adapters/mcp.js +1989 -0
  39. package/dist/adapters/mcp.js.map +1 -0
  40. package/dist/adapters/openapi-http.d.ts +29 -0
  41. package/dist/adapters/openapi-http.js +504 -0
  42. package/dist/adapters/openapi-http.js.map +1 -0
  43. package/dist/adapters/openapi-request.d.ts +26 -0
  44. package/dist/adapters/openapi-request.js +597 -0
  45. package/dist/adapters/openapi-request.js.map +1 -0
  46. package/dist/adapters/openapi-schema.d.ts +22 -0
  47. package/dist/adapters/openapi-schema.js +471 -0
  48. package/dist/adapters/openapi-schema.js.map +1 -0
  49. package/dist/adapters/openapi-typegen.d.ts +11 -0
  50. package/dist/adapters/openapi-typegen.js +185 -0
  51. package/dist/adapters/openapi-typegen.js.map +1 -0
  52. package/dist/adapters/openapi-types.d.ts +99 -0
  53. package/dist/adapters/openapi-types.js +2 -0
  54. package/dist/adapters/openapi-types.js.map +1 -0
  55. package/dist/adapters/openapi.d.ts +7 -0
  56. package/dist/adapters/openapi.js +768 -0
  57. package/dist/adapters/openapi.js.map +1 -0
  58. package/dist/application/activation.d.ts +28 -0
  59. package/dist/application/activation.js +289 -0
  60. package/dist/application/activation.js.map +1 -0
  61. package/dist/application/attachments.d.ts +24 -0
  62. package/dist/application/attachments.js +87 -0
  63. package/dist/application/attachments.js.map +1 -0
  64. package/dist/application/authority.d.ts +32 -0
  65. package/dist/application/authority.js +213 -0
  66. package/dist/application/authority.js.map +1 -0
  67. package/dist/application/catalog.d.ts +11 -0
  68. package/dist/application/catalog.js +177 -0
  69. package/dist/application/catalog.js.map +1 -0
  70. package/dist/application/config.d.ts +24 -0
  71. package/dist/application/config.js +140 -0
  72. package/dist/application/config.js.map +1 -0
  73. package/dist/application/connection.d.ts +35 -0
  74. package/dist/application/connection.js +465 -0
  75. package/dist/application/connection.js.map +1 -0
  76. package/dist/application/data-plane.d.ts +35 -0
  77. package/dist/application/data-plane.js +437 -0
  78. package/dist/application/data-plane.js.map +1 -0
  79. package/dist/application/diagnostics.d.ts +4 -0
  80. package/dist/application/diagnostics.js +65 -0
  81. package/dist/application/diagnostics.js.map +1 -0
  82. package/dist/application/dispatcher.d.ts +4 -0
  83. package/dist/application/dispatcher.js +16 -0
  84. package/dist/application/dispatcher.js.map +1 -0
  85. package/dist/application/main.d.ts +12 -0
  86. package/dist/application/main.js +167 -0
  87. package/dist/application/main.js.map +1 -0
  88. package/dist/application/maintenance.d.ts +27 -0
  89. package/dist/application/maintenance.js +244 -0
  90. package/dist/application/maintenance.js.map +1 -0
  91. package/dist/application/packages.d.ts +25 -0
  92. package/dist/application/packages.js +208 -0
  93. package/dist/application/packages.js.map +1 -0
  94. package/dist/application/processes.d.ts +49 -0
  95. package/dist/application/processes.js +180 -0
  96. package/dist/application/processes.js.map +1 -0
  97. package/dist/application/run-view.d.ts +17 -0
  98. package/dist/application/run-view.js +286 -0
  99. package/dist/application/run-view.js.map +1 -0
  100. package/dist/application/runtime.d.ts +78 -0
  101. package/dist/application/runtime.js +1747 -0
  102. package/dist/application/runtime.js.map +1 -0
  103. package/dist/application/tasks.d.ts +38 -0
  104. package/dist/application/tasks.js +23 -0
  105. package/dist/application/tasks.js.map +1 -0
  106. package/dist/application/user-state.d.ts +20 -0
  107. package/dist/application/user-state.js +52 -0
  108. package/dist/application/user-state.js.map +1 -0
  109. package/dist/application/work-git.d.ts +14 -0
  110. package/dist/application/work-git.js +67 -0
  111. package/dist/application/work-git.js.map +1 -0
  112. package/dist/cli.d.ts +2 -0
  113. package/dist/cli.js +40 -0
  114. package/dist/cli.js.map +1 -0
  115. package/dist/contracts/caller.d.ts +51 -0
  116. package/dist/contracts/caller.js +95 -0
  117. package/dist/contracts/caller.js.map +1 -0
  118. package/dist/contracts/error-data.d.ts +6 -0
  119. package/dist/contracts/error-data.js +51 -0
  120. package/dist/contracts/error-data.js.map +1 -0
  121. package/dist/contracts/errors.d.ts +10 -0
  122. package/dist/contracts/errors.js +28 -0
  123. package/dist/contracts/errors.js.map +1 -0
  124. package/dist/contracts/json.d.ts +9 -0
  125. package/dist/contracts/json.js +104 -0
  126. package/dist/contracts/json.js.map +1 -0
  127. package/dist/contracts/types.d.ts +122 -0
  128. package/dist/contracts/types.js +19 -0
  129. package/dist/contracts/types.js.map +1 -0
  130. package/dist/contracts/validation.d.ts +4 -0
  131. package/dist/contracts/validation.js +157 -0
  132. package/dist/contracts/validation.js.map +1 -0
  133. package/dist/contracts/wire-validation.d.ts +9 -0
  134. package/dist/contracts/wire-validation.js +399 -0
  135. package/dist/contracts/wire-validation.js.map +1 -0
  136. package/dist/contracts/wire.d.ts +1083 -0
  137. package/dist/contracts/wire.js +62 -0
  138. package/dist/contracts/wire.js.map +1 -0
  139. package/dist/extension-api.d.ts +12 -0
  140. package/dist/extension-api.js +2 -0
  141. package/dist/extension-api.js.map +1 -0
  142. package/dist/extensions/api.d.ts +72 -0
  143. package/dist/extensions/api.js +2 -0
  144. package/dist/extensions/api.js.map +1 -0
  145. package/dist/extensions/host-requests.d.ts +23 -0
  146. package/dist/extensions/host-requests.js +60 -0
  147. package/dist/extensions/host-requests.js.map +1 -0
  148. package/dist/extensions/materials.d.ts +37 -0
  149. package/dist/extensions/materials.js +691 -0
  150. package/dist/extensions/materials.js.map +1 -0
  151. package/dist/extensions/package-loader.d.ts +28 -0
  152. package/dist/extensions/package-loader.js +177 -0
  153. package/dist/extensions/package-loader.js.map +1 -0
  154. package/dist/extensions/packages.d.ts +73 -0
  155. package/dist/extensions/packages.js +441 -0
  156. package/dist/extensions/packages.js.map +1 -0
  157. package/dist/extensions/registry.d.ts +92 -0
  158. package/dist/extensions/registry.js +1540 -0
  159. package/dist/extensions/registry.js.map +1 -0
  160. package/dist/extensions/resources.d.ts +105 -0
  161. package/dist/extensions/resources.js +595 -0
  162. package/dist/extensions/resources.js.map +1 -0
  163. package/dist/extensions/state.d.ts +25 -0
  164. package/dist/extensions/state.js +10 -0
  165. package/dist/extensions/state.js.map +1 -0
  166. package/dist/extensions/transfer.d.ts +81 -0
  167. package/dist/extensions/transfer.js +16 -0
  168. package/dist/extensions/transfer.js.map +1 -0
  169. package/dist/index.d.ts +7 -0
  170. package/dist/index.js +25 -0
  171. package/dist/index.js.map +1 -0
  172. package/dist/maintenance/configuration.d.ts +79 -0
  173. package/dist/maintenance/configuration.js +1503 -0
  174. package/dist/maintenance/configuration.js.map +1 -0
  175. package/dist/maintenance/credentials.d.ts +23 -0
  176. package/dist/maintenance/credentials.js +177 -0
  177. package/dist/maintenance/credentials.js.map +1 -0
  178. package/dist/maintenance/files.d.ts +2 -0
  179. package/dist/maintenance/files.js +40 -0
  180. package/dist/maintenance/files.js.map +1 -0
  181. package/dist/maintenance/npm.d.ts +71 -0
  182. package/dist/maintenance/npm.js +1013 -0
  183. package/dist/maintenance/npm.js.map +1 -0
  184. package/dist/maintenance/oauth.d.ts +45 -0
  185. package/dist/maintenance/oauth.js +686 -0
  186. package/dist/maintenance/oauth.js.map +1 -0
  187. package/dist/maintenance/requests.d.ts +347 -0
  188. package/dist/maintenance/requests.js +959 -0
  189. package/dist/maintenance/requests.js.map +1 -0
  190. package/dist/maintenance/work-git.d.ts +29 -0
  191. package/dist/maintenance/work-git.js +776 -0
  192. package/dist/maintenance/work-git.js.map +1 -0
  193. package/dist/process/backend.d.ts +54 -0
  194. package/dist/process/backend.js +39 -0
  195. package/dist/process/backend.js.map +1 -0
  196. package/dist/process/environment-windows.d.ts +15 -0
  197. package/dist/process/environment-windows.js +151 -0
  198. package/dist/process/environment-windows.js.map +1 -0
  199. package/dist/process/environment.d.ts +28 -0
  200. package/dist/process/environment.js +410 -0
  201. package/dist/process/environment.js.map +1 -0
  202. package/dist/process/launch.d.ts +31 -0
  203. package/dist/process/launch.js +281 -0
  204. package/dist/process/launch.js.map +1 -0
  205. package/dist/process/managed.d.ts +36 -0
  206. package/dist/process/managed.js +459 -0
  207. package/dist/process/managed.js.map +1 -0
  208. package/dist/process/output-log.d.ts +50 -0
  209. package/dist/process/output-log.js +552 -0
  210. package/dist/process/output-log.js.map +1 -0
  211. package/dist/process/pipes.d.ts +16 -0
  212. package/dist/process/pipes.js +588 -0
  213. package/dist/process/pipes.js.map +1 -0
  214. package/dist/process/pty.d.ts +22 -0
  215. package/dist/process/pty.js +512 -0
  216. package/dist/process/pty.js.map +1 -0
  217. package/dist/process/windows-conout-worker.d.ts +1 -0
  218. package/dist/process/windows-conout-worker.js +90 -0
  219. package/dist/process/windows-conout-worker.js.map +1 -0
  220. package/dist/process/windows-conout.d.ts +46 -0
  221. package/dist/process/windows-conout.js +140 -0
  222. package/dist/process/windows-conout.js.map +1 -0
  223. package/dist/process/windows-helper.d.ts +43 -0
  224. package/dist/process/windows-helper.js +255 -0
  225. package/dist/process/windows-helper.js.map +1 -0
  226. package/dist/process/windows-job.d.ts +39 -0
  227. package/dist/process/windows-job.js +224 -0
  228. package/dist/process/windows-job.js.map +1 -0
  229. package/dist/process/windows-pipes.d.ts +16 -0
  230. package/dist/process/windows-pipes.js +475 -0
  231. package/dist/process/windows-pipes.js.map +1 -0
  232. package/dist/results/artifacts.d.ts +118 -0
  233. package/dist/results/artifacts.js +873 -0
  234. package/dist/results/artifacts.js.map +1 -0
  235. package/dist/results/encoder.d.ts +57 -0
  236. package/dist/results/encoder.js +1179 -0
  237. package/dist/results/encoder.js.map +1 -0
  238. package/dist/results/mcp.d.ts +95 -0
  239. package/dist/results/mcp.js +656 -0
  240. package/dist/results/mcp.js.map +1 -0
  241. package/dist/results/media.d.ts +19 -0
  242. package/dist/results/media.js +301 -0
  243. package/dist/results/media.js.map +1 -0
  244. package/dist/results/normalize.d.ts +29 -0
  245. package/dist/results/normalize.js +464 -0
  246. package/dist/results/normalize.js.map +1 -0
  247. package/dist/runtime/control-scripts.d.ts +23 -0
  248. package/dist/runtime/control-scripts.js +242 -0
  249. package/dist/runtime/control-scripts.js.map +1 -0
  250. package/dist/runtime/engine.d.ts +177 -0
  251. package/dist/runtime/engine.js +1159 -0
  252. package/dist/runtime/engine.js.map +1 -0
  253. package/dist/runtime/globals.d.ts +1 -0
  254. package/dist/runtime/globals.js +31 -0
  255. package/dist/runtime/globals.js.map +1 -0
  256. package/dist/runtime/material-retention.d.ts +34 -0
  257. package/dist/runtime/material-retention.js +671 -0
  258. package/dist/runtime/material-retention.js.map +1 -0
  259. package/dist/runtime/modules.d.ts +50 -0
  260. package/dist/runtime/modules.js +320 -0
  261. package/dist/runtime/modules.js.map +1 -0
  262. package/dist/runtime/names.d.ts +2 -0
  263. package/dist/runtime/names.js +22 -0
  264. package/dist/runtime/names.js.map +1 -0
  265. package/dist/runtime/operations.d.ts +20 -0
  266. package/dist/runtime/operations.js +137 -0
  267. package/dist/runtime/operations.js.map +1 -0
  268. package/dist/runtime/paths.d.ts +3 -0
  269. package/dist/runtime/paths.js +38 -0
  270. package/dist/runtime/paths.js.map +1 -0
  271. package/dist/runtime/promises.d.ts +9 -0
  272. package/dist/runtime/promises.js +78 -0
  273. package/dist/runtime/promises.js.map +1 -0
  274. package/dist/runtime/retention.d.ts +88 -0
  275. package/dist/runtime/retention.js +735 -0
  276. package/dist/runtime/retention.js.map +1 -0
  277. package/dist/runtime/run-log.d.ts +30 -0
  278. package/dist/runtime/run-log.js +207 -0
  279. package/dist/runtime/run-log.js.map +1 -0
  280. package/dist/runtime/scripts.d.ts +84 -0
  281. package/dist/runtime/scripts.js +387 -0
  282. package/dist/runtime/scripts.js.map +1 -0
  283. package/dist/runtime/tasks.d.ts +54 -0
  284. package/dist/runtime/tasks.js +290 -0
  285. package/dist/runtime/tasks.js.map +1 -0
  286. package/dist/sdk/maintenance.d.ts +3 -0
  287. package/dist/sdk/maintenance.js +80 -0
  288. package/dist/sdk/maintenance.js.map +1 -0
  289. package/dist/sdk/output-extension.d.ts +3 -0
  290. package/dist/sdk/output-extension.js +44 -0
  291. package/dist/sdk/output-extension.js.map +1 -0
  292. package/dist/sdk/output.d.ts +52 -0
  293. package/dist/sdk/output.js +350 -0
  294. package/dist/sdk/output.js.map +1 -0
  295. package/dist/sdk/runtime.d.ts +3 -0
  296. package/dist/sdk/runtime.js +26 -0
  297. package/dist/sdk/runtime.js.map +1 -0
  298. package/dist/sdk/sh.d.ts +3 -0
  299. package/dist/sdk/sh.js +384 -0
  300. package/dist/sdk/sh.js.map +1 -0
  301. package/dist/sdk/state.d.ts +2 -0
  302. package/dist/sdk/state.js +69 -0
  303. package/dist/sdk/state.js.map +1 -0
  304. package/dist/sdk/transfer.d.ts +3 -0
  305. package/dist/sdk/transfer.js +141 -0
  306. package/dist/sdk/transfer.js.map +1 -0
  307. package/dist/services/extensions.d.ts +19 -0
  308. package/dist/services/extensions.js +183 -0
  309. package/dist/services/extensions.js.map +1 -0
  310. package/dist/services/state.d.ts +37 -0
  311. package/dist/services/state.js +125 -0
  312. package/dist/services/state.js.map +1 -0
  313. package/dist/services/transfer.d.ts +86 -0
  314. package/dist/services/transfer.js +948 -0
  315. package/dist/services/transfer.js.map +1 -0
  316. package/dist/storage/schema.d.ts +8 -0
  317. package/dist/storage/schema.js +241 -0
  318. package/dist/storage/schema.js.map +1 -0
  319. package/dist/storage/sqlite.d.ts +241 -0
  320. package/dist/storage/sqlite.js +1855 -0
  321. package/dist/storage/sqlite.js.map +1 -0
  322. package/dist/storage/transfers.d.ts +90 -0
  323. package/dist/storage/transfers.js +2 -0
  324. package/dist/storage/transfers.js.map +1 -0
  325. package/dist/transfer/io.d.ts +74 -0
  326. package/dist/transfer/io.js +425 -0
  327. package/dist/transfer/io.js.map +1 -0
  328. package/dist/transfer/offers.d.ts +72 -0
  329. package/dist/transfer/offers.js +380 -0
  330. package/dist/transfer/offers.js.map +1 -0
  331. package/dist/transfer/stream-slots.d.ts +12 -0
  332. package/dist/transfer/stream-slots.js +28 -0
  333. package/dist/transfer/stream-slots.js.map +1 -0
  334. package/dist/work/catalog.d.ts +43 -0
  335. package/dist/work/catalog.js +198 -0
  336. package/dist/work/catalog.js.map +1 -0
  337. package/dist/work/discovery.d.ts +70 -0
  338. package/dist/work/discovery.js +465 -0
  339. package/dist/work/discovery.js.map +1 -0
  340. package/dist/work/service.d.ts +83 -0
  341. package/dist/work/service.js +703 -0
  342. package/dist/work/service.js.map +1 -0
  343. package/package.json +66 -4
@@ -0,0 +1,1747 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { createHash } from "node:crypto";
3
+ import { Readable } from "node:stream";
4
+ import { existsSync, realpathSync, statSync } from "node:fs";
5
+ import { appendFile } from "node:fs/promises";
6
+ import { homedir } from "node:os";
7
+ import path from "node:path";
8
+ import { AgentError, isAgentError, requireCondition, } from "../contracts/errors.js";
9
+ import { callerKey } from "../contracts/caller.js";
10
+ import { canonicalJson, digest, newId, isPlainRecord, } from "../contracts/json.js";
11
+ import { validateContract } from "../contracts/validation.js";
12
+ import { validateConnectionV2 } from "../contracts/wire-validation.js";
13
+ import { terminalStatuses } from "../contracts/types.js";
14
+ import { SqliteStore } from "../storage/sqlite.js";
15
+ import { defaultBuiltins, ModuleLoader, } from "../runtime/modules.js";
16
+ import { RunEngine, } from "../runtime/engine.js";
17
+ import { ScriptCatalog } from "../runtime/scripts.js";
18
+ import { RuntimeTasks, localTaskArtifactIds } from "../runtime/tasks.js";
19
+ import { ProfileRetention } from "../runtime/retention.js";
20
+ import { MaterialRetention } from "../runtime/material-retention.js";
21
+ import { taskHandlers } from "./tasks.js";
22
+ import { ApprovedPackageCatalog } from "./packages.js";
23
+ import { atomicText, contains, privateDirectory } from "../runtime/paths.js";
24
+ import { CONTROL_OWNER, CONTROL_VERSION, materializeManagedControlScripts, } from "../runtime/control-scripts.js";
25
+ import { ExtensionRegistry, } from "../extensions/registry.js";
26
+ import { ResourceManager } from "../extensions/resources.js";
27
+ import { ExtensionMaterials } from "../extensions/materials.js";
28
+ import { ExtensionPackageLoader } from "../extensions/package-loader.js";
29
+ import { ArtifactStore } from "../results/artifacts.js";
30
+ import { ResultEncoder } from "../results/encoder.js";
31
+ import { McpResultResources } from "../results/mcp.js";
32
+ import { TransferOfferDelivery } from "../transfer/offers.js";
33
+ import { TransferStreamSlots } from "../transfer/stream-slots.js";
34
+ import { TransferIoError } from "../transfer/io.js";
35
+ import { StateServices } from "../services/state.js";
36
+ import { TransferServices, } from "../services/transfer.js";
37
+ import { ExtensionServices } from "../services/extensions.js";
38
+ import { ExtensionEnablement } from "../maintenance/npm.js";
39
+ import { maintenanceMethods, unavailableMaintenance, } from "../maintenance/requests.js";
40
+ import { runtimeExtension } from "../sdk/runtime.js";
41
+ import { stateExtension } from "../sdk/state.js";
42
+ import { outputExtension } from "../sdk/output-extension.js";
43
+ import { shExtension } from "../sdk/sh.js";
44
+ import { transferExtension } from "../sdk/transfer.js";
45
+ import { maintenanceExtension } from "../sdk/maintenance.js";
46
+ import { DocumentCatalog } from "../work/catalog.js";
47
+ import { WorkService } from "../work/service.js";
48
+ import { AgentAuthority } from "./authority.js";
49
+ import { ConfigurationSources } from "./activation.js";
50
+ import { CredentialVault } from "../maintenance/credentials.js";
51
+ import { ConfigurationMaintenanceBackend } from "../maintenance/configuration.js";
52
+ import { OAuthProvider, OAuthSessionService } from "../maintenance/oauth.js";
53
+ import { McpOAuthService } from "../adapters/mcp-oauth.js";
54
+ import { AgentDataPlane } from "./data-plane.js";
55
+ import { CloudUserStateBackend } from "./user-state.js";
56
+ import { AgentCatalog } from "./catalog.js";
57
+ import { ApplicationProcesses } from "./processes.js";
58
+ import { prepareRunAttachments } from "./attachments.js";
59
+ import { dispatchApplication } from "./dispatcher.js";
60
+ import { projectRunView, projectRunRecord } from "./run-view.js";
61
+ const copy = (value, max = 1024 * 1024) => JSON.parse(canonicalJson(value, max));
62
+ const iso = (value) => new Date(value).toISOString();
63
+ const platformOrigin = (namespace) => ({
64
+ type: "platform",
65
+ owner: CONTROL_OWNER,
66
+ namespace,
67
+ version: CONTROL_VERSION,
68
+ revision: CONTROL_VERSION,
69
+ });
70
+ /** One process boot's actual Core composition. A control reconnect never creates another engine. */
71
+ export class AgentRuntime {
72
+ #connection;
73
+ #config;
74
+ #options;
75
+ #authority;
76
+ #store;
77
+ #modules;
78
+ #scripts;
79
+ #documents;
80
+ #work;
81
+ #engine;
82
+ #tasks;
83
+ #approvedPackages;
84
+ #resources;
85
+ #processes;
86
+ #artifacts;
87
+ #retention;
88
+ #materialRetention;
89
+ #registry;
90
+ #materials;
91
+ #extensions;
92
+ #enablement;
93
+ #state;
94
+ #offers;
95
+ #transfers;
96
+ #encoder;
97
+ #maintenance;
98
+ #configuration;
99
+ #configurationOpening;
100
+ #configurationSources;
101
+ #restoredOwners = new Set();
102
+ #restoringOwners = new Map();
103
+ #platform = [];
104
+ #platformMaterials = {
105
+ instructions: [],
106
+ skills: [],
107
+ docs: [],
108
+ };
109
+ #slots = new TransferStreamSlots();
110
+ #lifetime = new AbortController();
111
+ #stopping = new AbortController();
112
+ #leases = new Set();
113
+ #shutdownJoins = new Set();
114
+ #invocation = new AsyncLocalStorage();
115
+ #runs = new Map();
116
+ #reservations = new Map();
117
+ #channels = new Map();
118
+ #announcements = new WeakMap();
119
+ #streams = new Set();
120
+ #logTail = Promise.resolve();
121
+ #pendingLogBytes = 0;
122
+ #pendingLogEntries = 0;
123
+ #logErrorCode = null;
124
+ #logWriterClosed = false;
125
+ #catalog;
126
+ #refreshTimer;
127
+ #closing = false;
128
+ #closed = false;
129
+ #closeTask;
130
+ constructor(config, connection, bootId, options) {
131
+ requireCondition(config.profile === connection.binding.profile &&
132
+ bootId === connection.binding.bootId, "runtime_binding_mismatch", "The authenticated connection does not match this process profile and boot.");
133
+ this.#config = config;
134
+ this.#connection = connection;
135
+ this.#options = options;
136
+ requireCondition(options.shutdownWaitMs === undefined ||
137
+ (Number.isSafeInteger(options.shutdownWaitMs) &&
138
+ options.shutdownWaitMs >= 1 &&
139
+ options.shutdownWaitMs <= 30000), "invalid_configuration", "The shutdown observation must be bounded by thirty seconds.");
140
+ const root = realpathSync.native(config.root), work = privateDirectory(root, "work");
141
+ for (const directory of ["modules", "tmp"])
142
+ privateDirectory(work, directory);
143
+ privateDirectory(root, "logs");
144
+ if (!existsSync(path.join(work, "package.json")))
145
+ atomicText(path.join(work, "package.json"), '{"private":true,"type":"module"}\n');
146
+ this.#store = new SqliteStore(root, connection.binding, Date.now(), bootId, {
147
+ workIdleMs: config.retention?.work_idle_ms,
148
+ runHistoryMs: config.retention?.run_history_ms,
149
+ runLogsMs: config.retention?.run_logs_ms,
150
+ inputAttachmentsMs: config.retention?.input_attachments_ms,
151
+ });
152
+ this.#resources = new ResourceManager(this.#store);
153
+ this.#processes = new ApplicationProcesses(this.#resources, {
154
+ authorize: (caller, record, action) => this.#processAuthority(caller, record, action),
155
+ });
156
+ this.#authority = new AgentAuthority({ ...this.#store.binding, bootId }, work);
157
+ this.#authority.connect(connection.binding);
158
+ this.#materialRetention = new MaterialRetention(root, {
159
+ reserve: (bytes) => this.#retention.reserve(bytes),
160
+ retentionMs: config.retention?.material_copies_ms,
161
+ liveSnapshotRefs: () => new Set([
162
+ ...this.#store.workSnapshotRefs(Date.now()),
163
+ ...(this.#engine?.activeSnapshotRefs() ?? []),
164
+ ]),
165
+ publishedDirectories: () => new Set([
166
+ ...(this.#materials?.activeDirectories() ?? []),
167
+ ...(this.#documents?.activeDirectories() ?? []),
168
+ ]),
169
+ });
170
+ this.#materials = new ExtensionMaterials(work, {
171
+ reserve: (bytes) => this.#retention.reserve(bytes),
172
+ materialRetention: this.#materialRetention,
173
+ });
174
+ this.#artifacts = new ArtifactStore(root, connection.binding.agentId, {
175
+ maxFileBytes: 256 * 1024 * 1024,
176
+ maxReadBytes: 64 * 1024 * 1024,
177
+ retentionMs: config.retention?.artifact_ms,
178
+ reserve: (bytes, options) => this.#retention.reserve(bytes, options),
179
+ retentionUntil: (id, runId, originalExpiresAt) => this.#store.taskArtifactRetentionUntil(id, runId, Date.now(), originalExpiresAt),
180
+ });
181
+ this.#retention = new ProfileRetention(this.#store, this.#artifacts, {
182
+ maxManagedBytes: config.storage?.max_managed_bytes,
183
+ materialRetention: this.#materialRetention,
184
+ });
185
+ this.#state = new StateServices(this.#store, options.userState ??
186
+ new CloudUserStateBackend({
187
+ control: () => this.#control(),
188
+ context: (identity) => this.#context(identity),
189
+ }), { reserve: (bytes) => this.#retention.reserve(bytes) });
190
+ this.#catalog = new AgentCatalog((data) => this.#connection.send({
191
+ type: "event",
192
+ name: "agent.catalog.changed",
193
+ connection: this.#connection.binding,
194
+ data,
195
+ }));
196
+ }
197
+ static async create(config, connection, bootId, options = {}) {
198
+ const runtime = new AgentRuntime(config, connection, bootId, options);
199
+ try {
200
+ await runtime.#initialize();
201
+ return runtime;
202
+ }
203
+ catch (cause) {
204
+ await runtime.close().catch(() => { });
205
+ throw cause;
206
+ }
207
+ }
208
+ #components() {
209
+ return {
210
+ store: this.#store,
211
+ engine: this.#engine,
212
+ artifacts: this.#artifacts,
213
+ encoder: this.#encoder,
214
+ resources: this.#resources,
215
+ modules: this.#modules,
216
+ extensions: this.#extensions,
217
+ enablement: this.#enablement,
218
+ registry: this.#registry,
219
+ streams: this.#slots,
220
+ reserve: (bytes, options) => this.#retention.reserve(bytes, options),
221
+ signal: this.#stopping.signal,
222
+ control: () => this.#control(),
223
+ data: () => this.#data(),
224
+ context: (caller, projectId) => this.#context(caller, projectId),
225
+ scope: (caller, signal, runId) => this.#scope(caller, signal, runId),
226
+ startLease: (caller, source, signal) => this.#startLease(caller, source, signal),
227
+ onShutdown: (join) => {
228
+ this.#shutdownJoins.add(join);
229
+ return () => {
230
+ this.#shutdownJoins.delete(join);
231
+ };
232
+ },
233
+ shipJson: (value, purpose, signal, context, origin, runId) => this.#shipJson(value, purpose, signal, context, origin, runId),
234
+ configurationBackend: () => this.#configurationBackend(),
235
+ refreshPackages: async (snapshot) => {
236
+ if (snapshot)
237
+ await this.#approvedPackages.accept(snapshot);
238
+ await this.#documents.refresh(this.#published().docs);
239
+ },
240
+ };
241
+ }
242
+ async #initialize() {
243
+ const work = path.join(this.#store.root, "work");
244
+ await this.#retention.start();
245
+ this.#approvedPackages = await ApprovedPackageCatalog.open(this.#store.root, this.#store.binding, { reserve: (bytes) => this.#retention.reserve(bytes) });
246
+ const policy = this.#options.modulePolicy ?? {
247
+ builtins: () => defaultBuiltins,
248
+ approvedPackages: () => this.#approvedPackages.approvedPackages(),
249
+ };
250
+ const importer = await this.#retention.reserve(65536, { control: true });
251
+ try {
252
+ this.#modules = await ModuleLoader.create(work, this.#store.bootId, policy);
253
+ }
254
+ finally {
255
+ importer.release();
256
+ }
257
+ this.#enablement = await ExtensionEnablement.open(this.#store.root, {
258
+ reserve: (bytes) => this.#retention.reserve(bytes),
259
+ });
260
+ const controls = await materializeManagedControlScripts(work, (bytes, options) => this.#retention.reserve(bytes, options));
261
+ this.#scripts = new ScriptCatalog(work, this.#store.binding.agentId, () => [
262
+ ...controls,
263
+ ...this.#materials.scriptSources(),
264
+ ]);
265
+ this.#documents = new DocumentCatalog(work, this.#scripts, policy, {
266
+ reserve: (bytes) => this.#retention.reserve(bytes),
267
+ materialRetention: this.#materialRetention,
268
+ });
269
+ const permissions = new Set([
270
+ "connection",
271
+ "path",
272
+ "resource",
273
+ "url",
274
+ "runtime.input",
275
+ "storage.reserve",
276
+ "output",
277
+ "sh.execute",
278
+ "sh.read",
279
+ "sh.control",
280
+ "mcp.use",
281
+ "api.use",
282
+ ...["agent", "user"].flatMap((scope) => ["read", "write"].map((action) => `state.${scope}.${action}`)),
283
+ ...["createUpload", "createDownload", "get", "list", "cancel"].map((action) => `transfer.${action}`),
284
+ ...[...maintenanceMethods, "get", "list", "cancel"].map((action) => `maintenance.${action}`),
285
+ ...(this.#options.extensionPermissions ?? []),
286
+ ]);
287
+ this.#registry = new ExtensionRegistry(this.#resources, {
288
+ permissions,
289
+ authorize: (policy) => this.#registryAuthority(policy),
290
+ log: (origin, entry, runId, operationId) => {
291
+ requireCondition(!this.#logWriterClosed, "log_closed", "The extension log writer has finished its actual lifecycle.");
292
+ const bytes = Buffer.from(canonicalJson({
293
+ origin,
294
+ ...entry,
295
+ runId: runId ?? null,
296
+ operationId: operationId ?? null,
297
+ }, 65536) + "\n");
298
+ requireCondition(this.#pendingLogEntries < 128 &&
299
+ this.#pendingLogBytes + bytes.length <= 4 * 1024 * 1024, "log_busy", "The bounded extension log writer is busy.");
300
+ this.#pendingLogBytes += bytes.length;
301
+ this.#pendingLogEntries++;
302
+ const task = this.#logTail
303
+ .then(async () => {
304
+ const ticket = await this.#retention.reserve(bytes.length);
305
+ try {
306
+ await appendFile(path.join(this.#store.root, "logs", "extensions.log"), bytes, { mode: 0o600 });
307
+ }
308
+ finally {
309
+ ticket.release();
310
+ }
311
+ })
312
+ .finally(() => {
313
+ this.#pendingLogBytes -= bytes.length;
314
+ this.#pendingLogEntries--;
315
+ });
316
+ this.#logTail = task.catch((cause) => {
317
+ this.#logErrorCode = isAgentError(cause)
318
+ ? cause.code
319
+ : "extension_log_failed";
320
+ });
321
+ this.#track(task);
322
+ },
323
+ progress: (_origin, runId) => this.#runs.get(runId)?.notify(),
324
+ storage: { reserve: (bytes) => this.#retention.reserve(bytes) },
325
+ state: (scope) => this.#state.bind(scope),
326
+ transfer: (scope) => this.#transfers.bind(scope),
327
+ maintenance: (scope) => this.#maintenance?.bind(scope) ??
328
+ unavailableMaintenance(scope.assertCurrent),
329
+ hostRequests: (scope) => this.#hostRequests(scope),
330
+ });
331
+ this.#configurationSources = new ConfigurationSources(work, this.#registry, (bytes) => this.#retention.reserve(bytes), this.#materialRetention);
332
+ const packages = new ExtensionPackageLoader(this.#registry, this.#modules, {
333
+ policy,
334
+ permissions,
335
+ enabled: () => this.#enablement.enabled(),
336
+ });
337
+ this.#extensions = new ExtensionServices(this.#registry, packages, this.#materials);
338
+ this.#offers = new TransferOfferDelivery({
339
+ agentId: this.#store.binding.agentId,
340
+ profileRoot: this.#store.root,
341
+ authorize: (scope, snapshot) => this.#transfers.authorizeDelivery(scope, snapshot),
342
+ });
343
+ this.#transfers = new TransferServices(this.#store, this.#resources, this.#artifacts, this.#offers, {
344
+ prepare: (binding, signal) => this.#prepareTransfer(binding, signal),
345
+ revoke: (binding, reason) => this.#revokeTransfer(binding, reason),
346
+ }, { origin: platformOrigin("transfer"), streams: this.#slots });
347
+ const mcp = new McpResultResources({
348
+ agentId: this.#store.binding.agentId,
349
+ profileRoot: this.#store.root,
350
+ resolveResource: (source, scope) => this.#registry.resolveMcpResource(source, scope),
351
+ });
352
+ this.#encoder = new ResultEncoder(this.#artifacts, {}, this.#offers, mcp);
353
+ this.#work = new WorkService(this.#store, this.#scripts, this.#documents, {
354
+ reserve: (bytes) => this.#retention.reserve(bytes),
355
+ materialRetention: this.#materialRetention,
356
+ home: this.#options.home === undefined ? homedir() : this.#options.home,
357
+ agent: {
358
+ name: "Nexum Agent",
359
+ version: this.#options.version ?? CONTROL_VERSION,
360
+ protocolVersion: "2",
361
+ extensionApiVersion: "1",
362
+ },
363
+ authorize: (caller, target) => this.#authorize(caller, target),
364
+ resolveProject: async (caller, target) => {
365
+ const policy = this.#authority.current(caller, this.#projectFor(caller));
366
+ requireCondition(policy.projectId &&
367
+ policy.projectRoot &&
368
+ (!target.projectId || target.projectId === policy.projectId) &&
369
+ (!target.path ||
370
+ realpathSync.native(target.path) === policy.projectRoot), "project_not_found", "The project requires its current Cloud identity and canonical root.");
371
+ return {
372
+ project: {
373
+ projectId: policy.projectId,
374
+ root: policy.projectRoot,
375
+ name: policy.projectName ?? path.basename(policy.projectRoot),
376
+ ...(policy.projectDescription === undefined
377
+ ? {}
378
+ : { description: policy.projectDescription }),
379
+ },
380
+ disabledItems: policy.projectContextVisibility?.disabledItems ?? [],
381
+ };
382
+ },
383
+ materials: () => this.#published(),
384
+ scriptUsage: (caller) => this.#store.scriptUsage(callerKey(caller)),
385
+ canUseScript: (caller) => {
386
+ try {
387
+ this.#authorizeCaller(caller);
388
+ return true;
389
+ }
390
+ catch {
391
+ return false;
392
+ }
393
+ },
394
+ });
395
+ this.#engine = new RunEngine(this.#store, this.#modules, this.#scripts, {
396
+ reserve: (bytes, options) => this.#retention.reserve(bytes, options),
397
+ authorize: (caller, target) => this.#authorize(caller, target),
398
+ loadWork: (work) => this.#work.load(work),
399
+ resources: this.#resources,
400
+ leaseScript: (origin) => origin.type === "extension" ? this.#registry.lease(origin) : () => { },
401
+ bindings: (services) => {
402
+ this.#accepted(services);
403
+ return this.#registry.bindings(services);
404
+ },
405
+ prepareAttachments: (references, directory, services) => {
406
+ this.#accepted(services);
407
+ return prepareRunAttachments({
408
+ work,
409
+ slots: this.#slots,
410
+ reserve: (bytes) => this.#retention.reserve(bytes),
411
+ resolve: (ref, scope) => this.#attachment(ref, scope),
412
+ }, references, directory, services);
413
+ },
414
+ encodeResult: async (value, services) => {
415
+ const run = this.#accepted(services);
416
+ const stored = await this.#encoder.encode(value, {
417
+ ...this.#resultScope(run.context.caller, this.#store.getRun(services.runId), services.signal),
418
+ controlStorage: services.controlStorage,
419
+ });
420
+ this.#store.pinTaskRunArtifacts(services.runId, localTaskArtifactIds(stored, this.#store.binding.agentId));
421
+ return stored;
422
+ },
423
+ });
424
+ this.#tasks = new RuntimeTasks(this.#store, this.#engine, {
425
+ reserve: (bytes, options) => this.#retention.reserve(bytes, options),
426
+ });
427
+ for (const [namespace, factory] of Object.entries({
428
+ runtime: runtimeExtension,
429
+ state: stateExtension,
430
+ output: outputExtension,
431
+ sh: shExtension,
432
+ transfer: transferExtension,
433
+ maintenance: maintenanceExtension,
434
+ })) {
435
+ const handle = await this.#registry.prepare({
436
+ apiVersion: 1,
437
+ origin: platformOrigin(namespace),
438
+ permissions: [...permissions],
439
+ }, factory);
440
+ this.#registry.publish(handle);
441
+ this.#platform.push(handle);
442
+ const directory = privateDirectory(work, "docs", "platform");
443
+ const filename = path.join(directory, namespace + ".md");
444
+ const text = `# ${namespace} SDK\n\n` +
445
+ handle.methods
446
+ .map((method) => "```json\n" + canonicalJson(method, 65536) + "\n```\n")
447
+ .join("\n");
448
+ const ticket = await this.#retention.reserve(Buffer.byteLength(text) + 1024, { control: true });
449
+ try {
450
+ atomicText(filename, text);
451
+ }
452
+ finally {
453
+ ticket.release();
454
+ }
455
+ this.#platformMaterials.docs = [
456
+ ...this.#platformMaterials.docs,
457
+ {
458
+ name: namespace,
459
+ description: `${namespace} SDK 参数和返回约定`,
460
+ path: filename,
461
+ owner: CONTROL_OWNER,
462
+ version: CONTROL_VERSION,
463
+ },
464
+ ];
465
+ }
466
+ const instruction = "本地文件和操作系统基础能力使用当前允许的 Node/npm。SDK 原子能力由 runtime、state、output、sh、transfer、maintenance 提供,参数以 work/docs/platform 文档为准。脚本返回真实值或 output 包装,由平台适配 MCP;本地路径字符串不会自动变成图片。长任务用现有运行和资源身份继续控制,观察等待结束不代表任务已停止。";
467
+ this.#platformMaterials.instructions = [
468
+ {
469
+ instructionId: "platform-runtime",
470
+ kind: "platform",
471
+ path: null,
472
+ scope: { type: "agent", root: work },
473
+ origin: { ...platformOrigin("nexum"), revision: digest(instruction) },
474
+ content: instruction,
475
+ truncated: false,
476
+ },
477
+ ];
478
+ if (this.#options.configureMaintenance)
479
+ this.#maintenance = await this.#options.configureMaintenance(this.#components());
480
+ for (const name of this.#enablement.enabled())
481
+ await this.#extensions.enable(name, this.#enablement.get(name)?.config ?? {});
482
+ await this.#documents.refresh(this.#published().docs);
483
+ this.#refreshTimer = setInterval(() => {
484
+ for (const entry of this.#runs.values())
485
+ if (!terminalStatuses.has(this.#store.getRun(entry.services.runId).status))
486
+ void this.#refresh(entry).catch(() => { });
487
+ for (const entry of this.#leases)
488
+ void this.#refreshLease(entry).catch(() => { });
489
+ }, 10000);
490
+ this.#refreshTimer.unref();
491
+ }
492
+ #published() {
493
+ const extra = this.#materials.published();
494
+ const adapters = this.#configurationSources?.published() ?? {
495
+ instructions: [],
496
+ docs: [],
497
+ skills: [],
498
+ };
499
+ return {
500
+ instructions: [
501
+ ...this.#platformMaterials.instructions,
502
+ ...extra.instructions,
503
+ ...adapters.instructions,
504
+ ],
505
+ skills: [...this.#platformMaterials.skills, ...extra.skills],
506
+ docs: [...this.#platformMaterials.docs, ...extra.docs, ...adapters.docs],
507
+ };
508
+ }
509
+ #configurationBackend() {
510
+ return (this.#configurationOpening ??= (async () => {
511
+ const credentials = await CredentialVault.open(this.#store.root, {
512
+ reserve: (bytes) => this.#retention.reserve(bytes),
513
+ });
514
+ const oauth = new OAuthProvider(credentials);
515
+ const backend = await ConfigurationMaintenanceBackend.open({
516
+ root: this.#store.root,
517
+ agentId: this.#store.binding.agentId,
518
+ profile: this.#store.binding.profile,
519
+ credentials,
520
+ reserve: (bytes) => this.#retention.reserve(bytes),
521
+ oauth,
522
+ oauthSessions: new OAuthSessionService(oauth, {
523
+ root: this.#store.root,
524
+ reserve: (bytes) => this.#retention.reserve(bytes),
525
+ }),
526
+ mcpOAuth: new McpOAuthService(credentials),
527
+ activation: this.#configurationSources,
528
+ runtimeScope: (request) => ({
529
+ ...this.#scope(request.context.caller, request.signal, typeof request.context.runId === "string"
530
+ ? request.context.runId
531
+ : undefined),
532
+ signal: request.signal,
533
+ operationId: request.operationId,
534
+ }),
535
+ });
536
+ this.#configuration = backend;
537
+ return backend;
538
+ })().catch((cause) => {
539
+ this.#configurationOpening = undefined;
540
+ throw cause;
541
+ }));
542
+ }
543
+ async #restoreConfigurations(caller) {
544
+ if (!this.#configuration || this.#restoredOwners.has(caller.principalId))
545
+ return;
546
+ const pending = this.#restoringOwners.get(caller.principalId);
547
+ if (pending)
548
+ return pending;
549
+ const task = (async () => {
550
+ const result = await this.#configuration.restore(this.#scope(caller, this.#stopping.signal));
551
+ if (result.every((value) => value.state === "ready"))
552
+ this.#restoredOwners.add(caller.principalId);
553
+ await this.#documents.refresh(this.#published().docs);
554
+ })();
555
+ this.#restoringOwners.set(caller.principalId, task);
556
+ try {
557
+ await task;
558
+ }
559
+ finally {
560
+ this.#restoringOwners.delete(caller.principalId);
561
+ }
562
+ }
563
+ #control() {
564
+ requireCondition(!this.#closed && !this.#connection.signal.aborted, "connection_closed", "The authenticated control observation is unavailable.");
565
+ return this.#connection;
566
+ }
567
+ #data(connection = this.#connection) {
568
+ return new AgentDataPlane({
569
+ serverUrl: this.#config.serverUrl,
570
+ token: this.#config.token,
571
+ binding: connection.binding,
572
+ maxJsonBytes: 128 * 1024 * 1024,
573
+ assertCurrent: () => {
574
+ requireCondition(!this.#closed && connection.binding.bootId === this.#store.bootId, "runtime_closed", "The original Agent boot has closed.");
575
+ },
576
+ });
577
+ }
578
+ #processAuthority(caller, record, action) {
579
+ requireCondition(caller.source === "owner_session", "forbidden", "Managed process control requires the current owner session.");
580
+ this.#authorizeCaller(caller);
581
+ if (!record)
582
+ return;
583
+ requireCondition(record.originRunId, "process_unavailable", "The process lacks its actual accepted Run identity.");
584
+ const run = this.#store.getRun(record.originRunId);
585
+ let scope;
586
+ try {
587
+ scope = this.#boundProject(caller, run.projectId);
588
+ }
589
+ catch (cause) {
590
+ if (String(this.#invocation.getStore()?.operation) ===
591
+ "agent.process.list" &&
592
+ isAgentError(cause) &&
593
+ cause.code === "authorization_scope_mismatch")
594
+ throw new AgentError("forbidden", "This process is outside the current Project inspection scope.");
595
+ throw cause;
596
+ }
597
+ const work = this.#store.getWork(run.contextId);
598
+ this.#authority.authorize(caller, { type: "path", value: work.pwd, access: "read" }, scope);
599
+ const details = record.diagnostic.details ?? {};
600
+ requireCondition(isPlainRecord(details), "process_unavailable", "The registered process facts must remain an ordinary data object.");
601
+ const cwd = details.cwd;
602
+ if (cwd !== undefined) {
603
+ requireCondition(typeof cwd === "string" && path.isAbsolute(cwd), "process_unavailable", "The registered process has invalid working-directory facts.");
604
+ this.#authority.authorize(caller, { type: "path", value: cwd, access: "read" }, scope);
605
+ }
606
+ this.#authority.authorize(caller, { type: "resource", value: record.resourceId, access: action }, scope);
607
+ }
608
+ #ownerRunInspection(caller, runId) {
609
+ const invoke = this.#invocation.getStore();
610
+ return (caller.source === "owner_session" &&
611
+ invoke?.context.caller.source === "owner_session" &&
612
+ String(invoke.operation) === "agent.run.inspect" &&
613
+ invoke.input.runId === runId &&
614
+ invoke.context.caller.sessionRef === caller.sessionRef &&
615
+ callerKey(invoke.context.caller) === callerKey(caller));
616
+ }
617
+ #boundProject(caller, projectId) {
618
+ const invoke = this.#invocation.getStore();
619
+ if (invoke &&
620
+ callerKey(invoke.context.caller) === callerKey(caller) &&
621
+ invoke.context.caller.grantId === caller.grantId &&
622
+ invoke.context.caller.source === caller.source) {
623
+ const current = invoke.context.authorization.projectId ?? null;
624
+ requireCondition(current === null || current === projectId, "authorization_scope_mismatch", "An explicit Project scope cannot control a different retained Project.");
625
+ return current;
626
+ }
627
+ return projectId;
628
+ }
629
+ #projectFor(caller, runId) {
630
+ if (runId) {
631
+ const run = this.#store.getRun(runId);
632
+ requireCondition(run.callerKey === callerKey(caller) ||
633
+ this.#ownerRunInspection(caller, runId), "forbidden", "The runtime scope belongs to another caller.");
634
+ return this.#boundProject(caller, run.projectId);
635
+ }
636
+ const invoke = this.#invocation.getStore();
637
+ return invoke &&
638
+ callerKey(invoke.context.caller) === callerKey(caller) &&
639
+ invoke.context.caller.grantId === caller.grantId
640
+ ? (invoke.context.authorization.projectId ?? null)
641
+ : null;
642
+ }
643
+ #authorizeCaller(caller, target, projectId = this.#projectFor(caller)) {
644
+ this.#authority.authorize(caller, target, projectId);
645
+ }
646
+ #context(caller, projectId = this.#projectFor(caller)) {
647
+ return this.#authority.context(caller, projectId);
648
+ }
649
+ #scope(caller, signal, runId, projectId = this.#projectFor(caller, runId)) {
650
+ const bound = copy(caller), scoped = AbortSignal.any([signal, this.#stopping.signal]);
651
+ const run = runId ? this.#store.getRun(runId) : undefined;
652
+ const pwd = run
653
+ ? this.#store.getWork(run.contextId).pwd
654
+ : path.join(this.#store.root, "work");
655
+ const check = () => {
656
+ scoped.throwIfAborted();
657
+ this.#authorizeCaller(bound, undefined, projectId);
658
+ if (run)
659
+ this.#authorizeCaller(bound, { type: "path", value: pwd, access: "read" }, projectId);
660
+ };
661
+ check();
662
+ return {
663
+ caller: bound,
664
+ operationId: this.#invocation.getStore()?.id ?? newId("scope"),
665
+ ...(runId ? { runId } : {}),
666
+ pwd,
667
+ signal: scoped,
668
+ assertCurrent: check,
669
+ authorize: (target) => {
670
+ check();
671
+ this.#authorizeCaller(bound, target, projectId);
672
+ },
673
+ };
674
+ }
675
+ #startLease(caller, source, signal, projectId = this.#projectFor(caller)) {
676
+ validateContract("wire.input:authorization.refresh", source);
677
+ const controller = new AbortController();
678
+ const scope = this.#scope(caller, AbortSignal.any([signal, controller.signal]), source.runId, projectId);
679
+ const entry = {
680
+ caller: copy(caller),
681
+ projectId,
682
+ source: copy(source),
683
+ signal: scope.signal,
684
+ controller,
685
+ active: true,
686
+ close: () => {
687
+ if (!entry.active)
688
+ return;
689
+ entry.active = false;
690
+ clearTimeout(entry.timer);
691
+ entry.signal.removeEventListener("abort", entry.close);
692
+ this.#leases.delete(entry);
693
+ },
694
+ };
695
+ entry.signal.addEventListener("abort", entry.close, { once: true });
696
+ this.#leases.add(entry);
697
+ if (entry.signal.aborted)
698
+ entry.close();
699
+ else
700
+ this.#scheduleLease(entry);
701
+ return {
702
+ scope,
703
+ refresh: () => this.#refreshLease(entry),
704
+ close: entry.close,
705
+ };
706
+ }
707
+ #scheduleLease(entry) {
708
+ clearTimeout(entry.timer);
709
+ if (!entry.active)
710
+ return;
711
+ try {
712
+ const policy = this.#authority.current(entry.caller, entry.projectId);
713
+ if (entry.source.runId)
714
+ this.#authority.authorize(entry.caller, {
715
+ type: "path",
716
+ value: this.#store.getWork(this.#store.getRun(entry.source.runId).contextId).pwd,
717
+ access: "read",
718
+ }, entry.projectId);
719
+ const remaining = Date.parse(policy.expiresAt) - Date.now();
720
+ if (remaining <= 0)
721
+ throw new AgentError("authorization_expired", "The current authorization lease has expired.");
722
+ entry.timer = setTimeout(() => this.#scheduleLease(entry), Math.min(remaining + 1, 2_147_483_647));
723
+ entry.timer.unref();
724
+ }
725
+ catch (cause) {
726
+ entry.controller.abort(cause);
727
+ }
728
+ }
729
+ #revokeLeases(caller) {
730
+ const cause = new AgentError("authorization_revoked", "The authenticated Cloud revoked this caller's authorization.");
731
+ for (const entry of this.#leases)
732
+ if (callerKey(entry.caller) === callerKey(caller) &&
733
+ entry.caller.grantId === caller.grantId)
734
+ entry.controller.abort(cause);
735
+ }
736
+ async #refreshLease(entry) {
737
+ if (!entry.active)
738
+ return;
739
+ if (entry.refreshing)
740
+ return entry.refreshing;
741
+ entry.refreshing = (async () => {
742
+ const observed = this.#authority.capture(entry.caller, entry.projectId);
743
+ if (Date.parse(observed.context.authorization.expiresAt) - Date.now() >
744
+ 15000)
745
+ return;
746
+ const fresh = await this.#control().request("authorization.refresh", observed.context, entry.source, entry.signal, 10000);
747
+ if (entry.active) {
748
+ this.#authority.refresh(observed, fresh.authorization);
749
+ this.#scheduleLease(entry);
750
+ }
751
+ })();
752
+ try {
753
+ await entry.refreshing;
754
+ }
755
+ catch (cause) {
756
+ if (isAgentError(cause) &&
757
+ [
758
+ "forbidden",
759
+ "unauthorized",
760
+ "grant_revoked",
761
+ "grant_expired",
762
+ "authorization_denied",
763
+ "authorization_revoked",
764
+ "authorization_expired",
765
+ ].includes(cause.code))
766
+ entry.controller.abort(cause);
767
+ throw cause;
768
+ }
769
+ finally {
770
+ entry.refreshing = undefined;
771
+ }
772
+ }
773
+ #authorize(caller, target) {
774
+ if (target.run &&
775
+ target.action === "get" &&
776
+ this.#ownerRunInspection(caller, target.run.runId)) {
777
+ const scope = this.#boundProject(caller, target.run.projectId);
778
+ this.#authority.authorize(caller, {
779
+ type: "path",
780
+ value: this.#store.getWork(target.run.contextId).pwd,
781
+ access: "read",
782
+ }, scope);
783
+ return;
784
+ }
785
+ if (this.#closing) {
786
+ requireCondition(target.run &&
787
+ target.run.callerKey === callerKey(caller) &&
788
+ ["cancel", "get"].includes(target.action), "runtime_closed", "The Agent is no longer admitting business work.");
789
+ return;
790
+ }
791
+ const projectId = target.run
792
+ ? this.#boundProject(caller, target.run.projectId)
793
+ : target.work
794
+ ? this.#boundProject(caller, target.work.projectId)
795
+ : this.#projectFor(caller);
796
+ this.#authorizeCaller(caller, undefined, projectId);
797
+ const work = target.work ??
798
+ (target.run ? this.#store.getWork(target.run.contextId) : undefined);
799
+ if (work) {
800
+ requireCondition(work.callerKey === callerKey(caller), "forbidden", "This work or run belongs to another caller.");
801
+ this.#authorizeCaller(caller, {
802
+ type: "path",
803
+ value: work.pwd,
804
+ access: "read",
805
+ }, projectId);
806
+ }
807
+ if (target.path || target.project)
808
+ this.#authorizeCaller(caller, {
809
+ type: "path",
810
+ value: target.path ?? target.project.root,
811
+ access: "read",
812
+ }, projectId);
813
+ }
814
+ #registryAuthority(policy) {
815
+ if (policy.context) {
816
+ const caller = policy.context.caller;
817
+ this.#authorizeCaller(caller, policy.target, this.#projectFor(caller, policy.runId));
818
+ return;
819
+ }
820
+ requireCondition(!this.#closing || policy.action === "disable", "runtime_closed", "The Agent extension environment is stopping.");
821
+ if (policy.target?.type === "path")
822
+ requireCondition(this.#configurationSources?.authorizeInstance(policy.origin, policy.target) ||
823
+ (path.isAbsolute(policy.target.value) &&
824
+ (contains(path.join(this.#store.root, "work"), path.resolve(policy.target.value)) ||
825
+ contains(path.join(this.#store.root, "logs"), path.resolve(policy.target.value)))), "path_not_allowed", "Instance filesystem access stays in its own public work and logs.");
826
+ }
827
+ #resultScope(caller, run, signal = this.#lifetime.signal) {
828
+ const projectId = this.#projectFor(caller, run?.runId);
829
+ const pwd = run
830
+ ? this.#store.getWork(run.contextId).pwd
831
+ : path.join(this.#store.root, "work");
832
+ return {
833
+ pwd,
834
+ ownerKey: callerKey(caller),
835
+ grantId: caller.grantId,
836
+ signal,
837
+ ...(run ? { runId: run.runId } : {}),
838
+ assertCurrent: () => this.#authorizeCaller(caller, undefined, projectId),
839
+ authorizeTarget: (target) => this.#authorizeCaller(caller, target, projectId),
840
+ authorize: (target) => {
841
+ this.#authorizeCaller(caller, undefined, projectId);
842
+ if (target.path)
843
+ this.#authorizeCaller(caller, {
844
+ type: "path",
845
+ value: target.path,
846
+ access: target.action === "register" ? "read" : target.action,
847
+ }, projectId);
848
+ if (target.resource?.originRunId)
849
+ this.#authorize(caller, {
850
+ action: "get",
851
+ run: this.#store.getRun(target.resource.originRunId),
852
+ });
853
+ },
854
+ };
855
+ }
856
+ #accepted(services) {
857
+ const previous = this.#runs.get(services.runId);
858
+ if (previous)
859
+ return previous;
860
+ const origin = this.#invocation.getStore();
861
+ requireCondition(origin, "run_origin_unavailable", "The accepted run needs its actual original authenticated invocation.");
862
+ const context = copy(origin.context);
863
+ requireCondition((context.authorization.projectId ?? null) ===
864
+ this.#store.getRun(services.runId).projectId, "authorization_scope_mismatch", "The accepted run origin must retain its actual work Project scope.");
865
+ const lease = this.#startLease(context.caller, { runId: services.runId, originInvocationId: origin.id }, services.signal, context.authorization.projectId ?? null);
866
+ const stop = () => {
867
+ if (!this.#closing && !services.signal.aborted) {
868
+ const cause = lease.scope.signal.reason;
869
+ this.#engine.stopAcceptedRun(services.runId, {
870
+ code: isAgentError(cause) ? cause.code : "authorization_revoked",
871
+ });
872
+ }
873
+ };
874
+ if (lease.scope.signal.aborted)
875
+ stop();
876
+ else
877
+ lease.scope.signal.addEventListener("abort", stop, { once: true });
878
+ const announce = this.#connection.send({
879
+ type: "event",
880
+ name: "agent.run.changed",
881
+ connection: this.#connection.binding,
882
+ data: {
883
+ originInvocationId: origin.id,
884
+ runId: services.runId,
885
+ revision: this.#store.getRun(services.runId).revision,
886
+ status: this.#store.getRun(services.runId).status,
887
+ observedAt: new Date().toISOString(),
888
+ },
889
+ });
890
+ void announce.catch(() => { });
891
+ this.#announcements.set(origin, announce);
892
+ const entry = {
893
+ originInvocationId: origin.id,
894
+ context,
895
+ services,
896
+ announced: announce,
897
+ lease,
898
+ notify: () => {
899
+ if (this.#closed)
900
+ return;
901
+ const row = this.#store.getRun(services.runId);
902
+ if (!this.#connection.signal.aborted)
903
+ void this.#connection
904
+ .send({
905
+ type: "event",
906
+ name: "agent.run.changed",
907
+ connection: this.#connection.binding,
908
+ data: {
909
+ runId: row.runId,
910
+ revision: row.revision,
911
+ status: row.status,
912
+ observedAt: new Date().toISOString(),
913
+ },
914
+ })
915
+ .catch(() => { });
916
+ if (terminalStatuses.has(row.status)) {
917
+ lease.close();
918
+ this.#engine.off(services.runId, entry.notify);
919
+ this.#runs.delete(services.runId);
920
+ }
921
+ },
922
+ };
923
+ this.#runs.set(services.runId, entry);
924
+ this.#engine.on(services.runId, entry.notify);
925
+ return entry;
926
+ }
927
+ async #refresh(entry) {
928
+ await entry.announced;
929
+ await entry.lease.refresh();
930
+ }
931
+ #track(task) {
932
+ this.#streams.add(task);
933
+ void task.finally(() => this.#streams.delete(task)).catch(() => { });
934
+ }
935
+ async #failedStream(control, context, stream, cause) {
936
+ try {
937
+ await control.request("stream.revoke", this.#authority.cleanupContext(context.caller, context), {
938
+ streamId: stream.streamId,
939
+ reason: {
940
+ code: isAgentError(cause) ? cause.code : "stream_failed",
941
+ message: "The fixed stream producer could not complete.",
942
+ },
943
+ }, this.#lifetime.signal);
944
+ }
945
+ catch {
946
+ /* The original failure remains; a disconnected Cloud owns its expiry. */
947
+ }
948
+ throw cause;
949
+ }
950
+ async #shipJson(value, purpose, signal, supplied, originId, runId) {
951
+ const invoke = this.#invocation.getStore();
952
+ const context = supplied ?? invoke?.context;
953
+ requireCondition(context && (originId ?? invoke?.id), "invocation_origin_unavailable", "A fixed stream needs its original authenticated invocation.");
954
+ const announced = invoke ? this.#announcements.get(invoke) : undefined;
955
+ if (announced)
956
+ await announced;
957
+ const permit = this.#slots.tryAcquire();
958
+ requireCondition(permit, "transfer_busy", "All actual file stream slots are occupied.");
959
+ let prepared;
960
+ try {
961
+ const bytes = Buffer.from(canonicalJson(value, 128 * 1024 * 1024));
962
+ const control = this.#control();
963
+ const output = await control.request("stream.prepare", this.#context(context.caller, context.authorization.projectId ?? null), {
964
+ originInvocationId: originId ?? invoke.id,
965
+ ...(runId ? { runId } : {}),
966
+ purpose,
967
+ direction: "agent-to-cloud",
968
+ expiresAt: iso(Date.now() + 5 * 60_000),
969
+ maxBytes: bytes.length || 1,
970
+ mimeType: "application/json",
971
+ size: bytes.length,
972
+ sha256: createHash("sha256").update(bytes).digest("hex"),
973
+ }, signal);
974
+ prepared = { control, stream: output.stream };
975
+ const lease = this.#startLease(context.caller, {
976
+ streamId: output.stream.streamId,
977
+ originInvocationId: originId ?? invoke.id,
978
+ }, signal, context.authorization.projectId ?? null);
979
+ const task = this.#data(control)
980
+ .sendFixedBody(output.stream, bytes, lease.scope.signal)
981
+ .catch((cause) => this.#failedStream(control, context, output.stream, cause))
982
+ .finally(() => {
983
+ lease.close();
984
+ permit.release();
985
+ });
986
+ this.#track(task);
987
+ return output.stream;
988
+ }
989
+ catch (cause) {
990
+ permit.release();
991
+ if (prepared)
992
+ await this.#failedStream(prepared.control, context, prepared.stream, cause);
993
+ throw cause;
994
+ }
995
+ }
996
+ #hostRequests(binding) {
997
+ const accepted = this.#runs.get(binding.runId);
998
+ if (!accepted?.context.caller.hostRef)
999
+ return undefined;
1000
+ const caller = accepted.context.caller, capabilities = caller.hostCapabilities;
1001
+ if (!capabilities)
1002
+ return undefined;
1003
+ const request = async (action, params = {}, options) => {
1004
+ requireCondition(capabilities[action], "host_capability_unavailable", "The original Host session did not provide this capability.");
1005
+ await accepted.announced;
1006
+ await this.#refresh(accepted);
1007
+ binding.assertCurrent();
1008
+ const signal = options?.signal
1009
+ ? AbortSignal.any([binding.signal, options.signal])
1010
+ : binding.signal;
1011
+ const body = await this.#shipJson(params, "host-request", signal, accepted.context, accepted.originInvocationId, accepted.services.runId);
1012
+ const response = await this.#control().request("host.request", this.#context(caller, accepted.context.authorization.projectId ?? null), {
1013
+ runId: binding.runId,
1014
+ originInvocationId: accepted.originInvocationId,
1015
+ hostRef: caller.hostRef,
1016
+ action,
1017
+ body,
1018
+ }, signal);
1019
+ const permit = this.#slots.tryAcquire();
1020
+ requireCondition(permit, "transfer_busy", "All actual file stream slots are occupied.");
1021
+ let result;
1022
+ try {
1023
+ result = await this.#data().readJson(response.body, signal);
1024
+ }
1025
+ finally {
1026
+ permit.release();
1027
+ }
1028
+ requireCondition(result && typeof result === "object" && !Array.isArray(result), "invalid_host_response", "A Host response must be an ordinary protocol object.");
1029
+ return result;
1030
+ };
1031
+ return {
1032
+ capabilities: Object.fromEntries(["sampling", "elicitation", "roots"].flatMap((action) => capabilities[action] &&
1033
+ (caller.hostFeatures === undefined ||
1034
+ caller.hostFeatures[action] !== undefined)
1035
+ ? [
1036
+ [
1037
+ action,
1038
+ caller.hostFeatures?.[action] ??
1039
+ (action === "elicitation" ? { form: {} } : {}),
1040
+ ],
1041
+ ]
1042
+ : [])),
1043
+ assertCurrent: () => {
1044
+ binding.assertCurrent();
1045
+ this.#authorizeCaller(caller, undefined, accepted.context.authorization.projectId ?? null);
1046
+ },
1047
+ sampling: (params, options) => request("sampling", params, options),
1048
+ elicitation: (params, options) => request("elicitation", params, options),
1049
+ roots: (options) => request("roots", {}, options),
1050
+ };
1051
+ }
1052
+ async #attachment(reference, services) {
1053
+ const accepted = this.#accepted(services);
1054
+ await accepted.announced;
1055
+ await this.#refresh(accepted);
1056
+ if (typeof reference.sourceId === "string") {
1057
+ const control = this.#control();
1058
+ const controllerCaller = this.#invocation.getStore()?.context.caller ?? accepted.context.caller;
1059
+ const response = await control.request("attachment.open", this.#context(controllerCaller), {
1060
+ sourceId: reference.sourceId,
1061
+ originInvocationId: this.#invocation.getStore()?.id ?? accepted.originInvocationId,
1062
+ runId: services.runId,
1063
+ }, services.signal);
1064
+ return {
1065
+ name: response.name,
1066
+ mimeType: response.mimeType,
1067
+ size: response.size ?? response.stream.size,
1068
+ sha256: response.sha256 ?? response.stream.sha256,
1069
+ open: async () => this.#data(control).openRead(response.stream, services.signal),
1070
+ };
1071
+ }
1072
+ const scope = this.#resultScope(accepted.context.caller, this.#store.getRun(services.runId), services.signal);
1073
+ let uri;
1074
+ if (typeof reference.uri === "string")
1075
+ uri = reference.uri;
1076
+ else {
1077
+ requireCondition(typeof reference.transferId === "string", "invalid_attachment", "An attachment requires a normalized source or an owned committed resource.");
1078
+ const transfer = await this.#transfers
1079
+ .bind({
1080
+ context: services.context,
1081
+ runId: services.runId,
1082
+ signal: services.signal,
1083
+ deadline: services.deadlineAt,
1084
+ assertCurrent: services.assertCurrent,
1085
+ authorize: (target) => this.#authorizeCaller(accepted.context.caller, target, this.#store.getRun(services.runId).projectId),
1086
+ })
1087
+ .get(reference.transferId);
1088
+ requireCondition(transfer.status === "succeeded" &&
1089
+ transfer.direction === "upload" &&
1090
+ transfer.file, "attachment_unavailable", "The upload has not committed its actual input file.");
1091
+ const fixed = await this.#artifacts.register({
1092
+ path: transfer.file.path,
1093
+ name: transfer.file.name,
1094
+ mimeType: transfer.file.mimeType,
1095
+ }, scope);
1096
+ requireCondition(fixed.size === transfer.file.size &&
1097
+ fixed.sha256 === transfer.file.sha256, "file_changed", "The committed upload changed before this input preparation.");
1098
+ uri = fixed.uri;
1099
+ }
1100
+ const metadata = await this.#artifacts.metadata(uri, scope);
1101
+ return {
1102
+ name: metadata.name,
1103
+ mimeType: metadata.mimeType,
1104
+ size: metadata.size,
1105
+ sha256: metadata.sha256,
1106
+ open: async () => {
1107
+ const input = await this.#artifacts.open(uri, scope);
1108
+ return { readable: input.stream, closed: input.closed };
1109
+ },
1110
+ };
1111
+ }
1112
+ async #prepareTransfer(binding, signal) {
1113
+ const runId = this.#store.getResource(binding.resourceId).originRunId;
1114
+ requireCondition(runId, "run_origin_unavailable", "The transfer resource has no accepted creator run.");
1115
+ const accepted = this.#runs.get(runId);
1116
+ requireCondition(accepted, "run_origin_unavailable", "The transfer needs its accepted run origin.");
1117
+ await accepted.announced;
1118
+ await this.#refresh(accepted);
1119
+ const context = this.#context(binding.caller, accepted.context.authorization.projectId ?? null);
1120
+ this.#channels.set(binding.transferId, {
1121
+ context,
1122
+ originInvocationId: accepted.originInvocationId,
1123
+ });
1124
+ const result = await this.#control().request("transfer.prepare", context, {
1125
+ transferId: binding.transferId,
1126
+ resourceId: binding.resourceId,
1127
+ runId,
1128
+ contextId: this.#store.getRun(runId).contextId,
1129
+ projectId: this.#store.getRun(runId).projectId,
1130
+ direction: binding.direction,
1131
+ claimDeadlineAt: iso(binding.claimDeadlineAt),
1132
+ maxBytes: binding.maxBytes,
1133
+ target: binding.target,
1134
+ }, signal);
1135
+ return result.request;
1136
+ }
1137
+ async #revokeTransfer(binding, reason) {
1138
+ const previous = this.#channels.get(binding.transferId);
1139
+ if (!previous)
1140
+ return;
1141
+ const control = this.#control();
1142
+ const context = this.#authority.cleanupContext(binding.caller, previous.context);
1143
+ await control.request("transfer.revoke", context, { transferId: binding.transferId, reason }, this.#lifetime.signal);
1144
+ this.#channels.delete(binding.transferId);
1145
+ }
1146
+ async attachConnection(connection) {
1147
+ requireCondition(!this.#closing, "runtime_closed", "The Agent runtime is stopping.");
1148
+ this.#authority.connect(connection.binding);
1149
+ this.#connection = connection;
1150
+ }
1151
+ async event(message, signal) {
1152
+ validateContract("wire", message);
1153
+ validateConnectionV2(message.connection, this.#connection.binding);
1154
+ if (message.name === "agent.catalog.sync")
1155
+ await this.#catalog.sync(message.data, signal);
1156
+ else if (message.name === "agent.authorization.changed") {
1157
+ if (message.data.authorization === null) {
1158
+ this.#authority.revoke(message.data.caller);
1159
+ this.#revokeLeases(message.data.caller);
1160
+ }
1161
+ else {
1162
+ this.#authority.observe({
1163
+ caller: message.data.caller,
1164
+ authorization: message.data.authorization,
1165
+ connection: message.connection,
1166
+ });
1167
+ for (const lease of this.#leases)
1168
+ if (callerKey(lease.caller) === callerKey(message.data.caller))
1169
+ this.#scheduleLease(lease);
1170
+ }
1171
+ }
1172
+ else
1173
+ throw new AgentError("invalid_control_direction", "This event is not an Agent application entry.");
1174
+ }
1175
+ async dispatch(message, signal) {
1176
+ requireCondition(!this.#closing, "runtime_closed", "The Agent runtime is stopping.");
1177
+ validateContract("wire", message);
1178
+ validateConnectionV2(message.context.connection, this.#connection.binding);
1179
+ if (message.context.caller.source === "owner_session")
1180
+ requireCondition([
1181
+ "agent.project.resolve",
1182
+ "agent.project.inspect",
1183
+ "agent.project.close",
1184
+ "agent.run.inspect",
1185
+ "agent.context.read",
1186
+ "agent.process.list",
1187
+ "agent.process.get",
1188
+ "agent.process.stop",
1189
+ ].includes(message.operation), "invalid_control_direction", "An owner Console session has only its declared Project and managed-process operations.");
1190
+ this.#authority.observe(message.context);
1191
+ for (const lease of this.#leases)
1192
+ if (callerKey(lease.caller) === callerKey(message.context.caller))
1193
+ this.#scheduleLease(lease);
1194
+ return this.#invocation.run(copy(message), async () => {
1195
+ if (message.context.caller.source !== "owner_session")
1196
+ await this.#restoreConfigurations(message.context.caller);
1197
+ return dispatchApplication(message, this.#connection.binding, this.#handlers(message, signal));
1198
+ });
1199
+ }
1200
+ #handlers(message, signal) {
1201
+ const caller = message.context.caller;
1202
+ const view = (value) => projectRunView(value, {
1203
+ encoder: this.#encoder,
1204
+ scope: this.#resultScope(caller, value.run, signal),
1205
+ budgets: this.#authority.current(caller, this.#projectFor(caller))
1206
+ .budgets,
1207
+ shipJson: (value, purpose) => this.#shipJson(value, purpose, this.#lifetime.signal),
1208
+ });
1209
+ const handlers = {
1210
+ ...taskHandlers(this.#tasks, {
1211
+ caller,
1212
+ signal,
1213
+ project: view,
1214
+ beforeInput: async (runId) => {
1215
+ const run = this.#store.getRun(runId);
1216
+ this.#authorize(caller, { action: "input", run });
1217
+ await this.#control().send({
1218
+ type: "event",
1219
+ name: "agent.run.changed",
1220
+ connection: this.#connection.binding,
1221
+ data: {
1222
+ originInvocationId: message.id,
1223
+ runId,
1224
+ revision: run.revision,
1225
+ status: run.status,
1226
+ observedAt: new Date().toISOString(),
1227
+ },
1228
+ });
1229
+ },
1230
+ }),
1231
+ "agent.project.resolve": (input) => {
1232
+ const root = realpathSync.native(input.path);
1233
+ requireCondition(statSync(root).isDirectory(), "project_not_found", "A project root must be a real directory.");
1234
+ try {
1235
+ this.#authorizeCaller(caller, {
1236
+ type: "path",
1237
+ value: root,
1238
+ access: "read",
1239
+ });
1240
+ }
1241
+ catch (cause) {
1242
+ if (isAgentError(cause) && cause.code === "path_not_allowed")
1243
+ throw new AgentError("project_not_allowed", "The canonical project directory requires current owner approval.", { canonicalPath: root });
1244
+ throw cause;
1245
+ }
1246
+ return { root, name: path.basename(root) };
1247
+ },
1248
+ "agent.open": (input) => this.#work.open(caller, input, signal),
1249
+ "agent.project.close": async (input) => {
1250
+ const result = await this.#work.closeProject(caller, input.projectId, signal);
1251
+ return { ...result, closedAt: iso(result.closedAt) };
1252
+ },
1253
+ "agent.project.inspect": (input) => this.#work.inspect(caller, {
1254
+ agentId: this.#store.binding.agentId,
1255
+ projectId: input.projectId,
1256
+ ...(input.contextId ? { contextId: input.contextId } : {}),
1257
+ }, signal),
1258
+ "agent.close": (input) => {
1259
+ const result = this.#work.close(caller, input.contextId);
1260
+ return { ...result, closedAt: iso(result.closedAt) };
1261
+ },
1262
+ "agent.run.start": async (input) => {
1263
+ const work = this.#store.activeWork(input.contextId, callerKey(caller));
1264
+ requireCondition((message.context.authorization.projectId ?? null) === work.projectId, "authorization_scope_mismatch", "A new Run must use its actual work Project authorization.");
1265
+ const { submission: _submission, ...normalized } = input;
1266
+ return view(await this.#engine.start(caller, normalized, signal));
1267
+ },
1268
+ "agent.run.get": async (input) => view(await this.#engine.get(caller, input, signal)),
1269
+ "agent.run.inspect": async (input) => {
1270
+ requireCondition(caller.source === "owner_session", "forbidden", "Only a current owner Console session may inspect retained Run facts.");
1271
+ const retained = await this.#engine.get(caller, {
1272
+ agentId: this.#store.binding.agentId,
1273
+ runId: input.runId,
1274
+ waitMs: 0,
1275
+ }, signal);
1276
+ return projectRunView(retained, {
1277
+ encoder: this.#encoder,
1278
+ scope: this.#resultScope(caller, retained.run, signal),
1279
+ budgets: this.#authority.current(caller, this.#projectFor(caller, retained.run.runId)).budgets,
1280
+ readOnly: true,
1281
+ shipJson: async () => {
1282
+ throw new AgentError("read_only_view", "A retained Console inspection cannot allocate a new data stream.");
1283
+ },
1284
+ });
1285
+ },
1286
+ "agent.run.input": async (input) => {
1287
+ const run = this.#store.getRun(input.runId);
1288
+ this.#authorize(caller, { action: "input", run });
1289
+ await this.#control().send({
1290
+ type: "event",
1291
+ name: "agent.run.changed",
1292
+ connection: this.#connection.binding,
1293
+ data: {
1294
+ originInvocationId: message.id,
1295
+ runId: run.runId,
1296
+ revision: run.revision,
1297
+ status: run.status,
1298
+ observedAt: new Date().toISOString(),
1299
+ },
1300
+ });
1301
+ return view(await this.#engine.input(caller, input, signal));
1302
+ },
1303
+ "agent.run.cancel": async (input) => {
1304
+ const result = this.#engine.cancel(caller, input.runId);
1305
+ return { accepted: result.accepted, view: await view(result) };
1306
+ },
1307
+ "agent.run.list": (input) => {
1308
+ const page = this.#engine.list(caller, input);
1309
+ return {
1310
+ runs: page.runs.map((row) => projectRunRecord(this.#store.getRun(row.runId), {
1311
+ root: this.#store.root,
1312
+ availability: Object.fromEntries(["code", "input", "result", "logs"].map((key) => [
1313
+ key,
1314
+ ["available", "too_large"].includes(String(row.availability[key])),
1315
+ ])),
1316
+ })),
1317
+ nextCursor: page.nextCursor,
1318
+ observedAt: new Date().toISOString(),
1319
+ };
1320
+ },
1321
+ "agent.context.read": (input) => this.#readContext(caller, input, signal),
1322
+ "agent.process.list": (input) => {
1323
+ if (input.projectId !== undefined)
1324
+ this.#boundProject(caller, input.projectId);
1325
+ return this.#processes.list(caller, input);
1326
+ },
1327
+ "agent.process.get": (input) => this.#processes.get(caller, input),
1328
+ "agent.process.stop": (input) => this.#processes.stop(caller, input),
1329
+ "agent.resources.list": (input) => this.#listResources(caller, input, signal),
1330
+ "agent.resources.read": (input) => this.#readResource(caller, input, signal),
1331
+ "agent.transfer.reserveClaim": (input) => this.#reserve(caller, input.transferId),
1332
+ "agent.transfer.releaseReservation": (input) => {
1333
+ const reservation = this.#reservation(caller, input);
1334
+ this.#transfers.releaseReservation(reservation.core);
1335
+ this.#reservations.delete(input.reservationId);
1336
+ return { transferId: input.transferId, released: true };
1337
+ },
1338
+ "agent.transfer.commitClaim": (input) => this.#commit(caller, input),
1339
+ };
1340
+ for (const operation of [
1341
+ "agent.maintenance.draft.read",
1342
+ "agent.maintenance.draft.prepare",
1343
+ "agent.maintenance.draft.verify",
1344
+ "agent.maintenance.draft.notify",
1345
+ "agent.maintenance.oauth.start",
1346
+ "agent.maintenance.oauth.complete",
1347
+ "agent.maintenance.execute",
1348
+ "agent.maintenance.get",
1349
+ "agent.maintenance.cancel",
1350
+ ])
1351
+ handlers[operation] = async (input) => {
1352
+ requireCondition(this.#maintenance, "maintenance_unavailable", "This process has no configured maintenance backend.");
1353
+ const scope = this.#scope(caller, this.#stopping.signal);
1354
+ if (this.#options.dispatchMaintenance)
1355
+ return this.#options.dispatchMaintenance(message, scope, this.#components(), this.#maintenance, signal);
1356
+ if (operation === "agent.maintenance.get")
1357
+ return this.#maintenance.get(input.requestId, scope);
1358
+ if (operation === "agent.maintenance.cancel")
1359
+ return this.#maintenance.cancel(input.requestId, scope);
1360
+ if (operation === "agent.maintenance.execute")
1361
+ return this.#maintenance.execute(input.requestId, scope);
1362
+ throw new AgentError("maintenance_unavailable", "This process has no configured maintenance body adapter.");
1363
+ };
1364
+ return handlers;
1365
+ }
1366
+ async #readContext(caller, input, signal) {
1367
+ const work = this.#store.activeWork(input.contextId, callerKey(caller));
1368
+ requireCondition(work.revision === input.revision, "context_revision_mismatch", "The work materials changed; refresh the work first.");
1369
+ if (input.includeEntries) {
1370
+ requireCondition(!input.cursor, "invalid_cursor", "A complete bounded Skill tree has no byte cursor.");
1371
+ const { entries } = await this.#work.readMaterialEntries(caller, input.contextId, input.itemId, input.relativePath, signal);
1372
+ const bytes = canonicalJson(entries, 65536);
1373
+ requireCondition(Buffer.byteLength(bytes) <=
1374
+ Math.min(input.maxBytes, this.#authority.current(caller, this.#projectFor(caller)).budgets
1375
+ .textBytes ?? 65536), "context_budget_exceeded", "The complete Skill tree exceeds the current metadata budget.");
1376
+ return {
1377
+ contextId: input.contextId,
1378
+ revision: input.revision,
1379
+ itemId: input.itemId,
1380
+ contentRevision: digest(bytes),
1381
+ text: "",
1382
+ complete: true,
1383
+ nextCursor: null,
1384
+ entries,
1385
+ treeTruncated: false,
1386
+ };
1387
+ }
1388
+ const material = await this.#work.readMaterial(caller, input.contextId, input.itemId, input.relativePath, signal);
1389
+ let offset = 0;
1390
+ requireCondition(!input.cursor || input.startLine === undefined, "invalid_cursor", "A continuation cannot switch its original line position.");
1391
+ if (input.startLine !== undefined && input.startLine > 1) {
1392
+ let line = 1;
1393
+ while (offset < material.bytes.length && line < input.startLine)
1394
+ if (material.bytes[offset++] === 10)
1395
+ line++;
1396
+ requireCondition(line === input.startLine, "context_line_out_of_range", "The requested line is beyond this actual material.");
1397
+ }
1398
+ if (input.cursor) {
1399
+ const cursor = JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8"));
1400
+ requireCondition(cursor.contextId === input.contextId &&
1401
+ cursor.itemId === input.itemId &&
1402
+ (cursor.relativePath ?? null) === (input.relativePath ?? null) &&
1403
+ cursor.revision === material.revision &&
1404
+ Number.isSafeInteger(cursor.offset) &&
1405
+ cursor.offset >= 0 &&
1406
+ cursor.offset <= material.bytes.length, "invalid_cursor", "The material cursor is stale or invalid.");
1407
+ offset = cursor.offset;
1408
+ }
1409
+ const maximum = Math.min(input.maxBytes, this.#authority.current(caller, this.#projectFor(caller)).budgets
1410
+ .textBytes ?? 65536, 65536);
1411
+ let end = Math.min(material.bytes.length, offset + maximum);
1412
+ const maximumLines = input.maxLines ?? 1000;
1413
+ let selectedLines = 0;
1414
+ for (let position = offset; position < end; position++)
1415
+ if (material.bytes[position] === 10 && ++selectedLines >= maximumLines) {
1416
+ end = position + 1;
1417
+ break;
1418
+ }
1419
+ while (end > offset &&
1420
+ end < material.bytes.length &&
1421
+ (material.bytes[end] & 0xc0) === 0x80)
1422
+ end--;
1423
+ requireCondition(end > offset || end === material.bytes.length, "context_budget_exceeded", "The current material budget cannot contain its next UTF-8 character.");
1424
+ const complete = end === material.bytes.length;
1425
+ let startLine = 1, lineBreaks = 0;
1426
+ for (let position = 0; position < offset; position++)
1427
+ if (material.bytes[position] === 10)
1428
+ startLine++;
1429
+ for (let position = offset; position < end; position++)
1430
+ if (material.bytes[position] === 10)
1431
+ lineBreaks++;
1432
+ return {
1433
+ contextId: input.contextId,
1434
+ revision: input.revision,
1435
+ itemId: input.itemId,
1436
+ contentRevision: material.revision,
1437
+ text: new TextDecoder("utf-8", { fatal: true }).decode(material.bytes.subarray(offset, end)),
1438
+ startLine,
1439
+ endLine: startLine +
1440
+ lineBreaks -
1441
+ (end > offset && material.bytes[end - 1] === 10 ? 1 : 0),
1442
+ startsMidLine: offset > 0 && material.bytes[offset - 1] !== 10,
1443
+ endsMidLine: end < material.bytes.length &&
1444
+ (end === offset || material.bytes[end - 1] !== 10),
1445
+ complete,
1446
+ nextCursor: complete
1447
+ ? null
1448
+ : Buffer.from(canonicalJson({
1449
+ contextId: input.contextId,
1450
+ itemId: input.itemId,
1451
+ ...(input.relativePath !== undefined
1452
+ ? { relativePath: input.relativePath }
1453
+ : {}),
1454
+ revision: material.revision,
1455
+ offset: end,
1456
+ })).toString("base64url"),
1457
+ };
1458
+ }
1459
+ async #listResources(caller, input, signal) {
1460
+ const page = await this.#artifacts.list(this.#resultScope(caller, undefined, signal), {
1461
+ ...input,
1462
+ maxBytes: Math.max(1, (this.#authority.current(caller, this.#projectFor(caller)).budgets
1463
+ .textBytes ?? 65536) - 1024),
1464
+ });
1465
+ return {
1466
+ resources: page.resources.map(({ uri, name, mimeType, size }) => ({
1467
+ uri,
1468
+ name,
1469
+ mimeType,
1470
+ size,
1471
+ })),
1472
+ nextCursor: page.nextCursor,
1473
+ };
1474
+ }
1475
+ async #readResource(caller, input, signal) {
1476
+ const scope = this.#resultScope(caller, undefined, signal);
1477
+ if (/^nexum:\/\/agents\/[^/]+\/mcp\//.test(input.uri)) {
1478
+ requireCondition(this.#encoder.mcp, "mcp_source_unavailable", "The registered MCP resource source is unavailable.");
1479
+ const budgets = this.#authority.current(caller, this.#projectFor(caller)).budgets;
1480
+ const limits = { ...this.#encoder.limits };
1481
+ for (const key of [
1482
+ "textBytes",
1483
+ "imageBytes",
1484
+ "audioBytes",
1485
+ "inlineBytes",
1486
+ "responseBytes",
1487
+ ])
1488
+ if (budgets[key] !== undefined)
1489
+ limits[key] = Math.min(limits[key], budgets[key]);
1490
+ limits.inlineBytes = Math.min(limits.inlineBytes, input.maxBytes);
1491
+ const result = await this.#encoder.mcp.readResource(input.uri, scope, limits);
1492
+ validateContract("wire.body:ResourcesRead", result);
1493
+ return {
1494
+ body: await this.#shipJson(result, "result-meta", this.#lifetime.signal),
1495
+ };
1496
+ }
1497
+ const metadata = await this.#artifacts.metadata(input.uri, scope);
1498
+ requireCondition(metadata.size <=
1499
+ Math.min(input.maxBytes, this.#authority.current(caller, this.#projectFor(caller)).budgets
1500
+ .fileBytes ?? 256 * 1024 * 1024), "resource_too_large", "The resource exceeds its current read budget.");
1501
+ const text = /^(text\/|application\/(json|javascript|xml|yaml)(;|$))/.test(metadata.mimeType);
1502
+ if (text &&
1503
+ metadata.size <=
1504
+ Math.min(65536, this.#authority.current(caller, this.#projectFor(caller)).budgets
1505
+ .textBytes ?? 65536)) {
1506
+ const resource = await this.#artifacts.open(input.uri, scope);
1507
+ const chunks = [];
1508
+ try {
1509
+ for await (const chunk of resource.stream)
1510
+ chunks.push(chunk);
1511
+ await resource.closed;
1512
+ return {
1513
+ contents: [
1514
+ {
1515
+ uri: input.uri,
1516
+ mimeType: metadata.mimeType,
1517
+ text: new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)),
1518
+ },
1519
+ ],
1520
+ };
1521
+ }
1522
+ finally {
1523
+ resource.stream.destroy();
1524
+ await resource.closed.catch(() => { });
1525
+ }
1526
+ }
1527
+ const invoke = this.#invocation.getStore(), control = this.#control();
1528
+ const permit = this.#slots.tryAcquire();
1529
+ requireCondition(permit, "transfer_busy", "All actual file stream slots are occupied.");
1530
+ let prepared;
1531
+ try {
1532
+ const context = this.#context(caller);
1533
+ const { stream } = await control.request("stream.prepare", context, {
1534
+ originInvocationId: invoke.id,
1535
+ resourceUri: input.uri,
1536
+ purpose: "resource",
1537
+ direction: "agent-to-cloud",
1538
+ expiresAt: iso(Math.min(Date.parse(metadata.expiresAt), Date.now() + 5 * 60_000)),
1539
+ maxBytes: metadata.size || 1,
1540
+ mimeType: metadata.mimeType,
1541
+ size: metadata.size,
1542
+ sha256: metadata.sha256,
1543
+ }, signal);
1544
+ prepared = { context, stream };
1545
+ const lease = this.#startLease(caller, { streamId: stream.streamId, originInvocationId: invoke.id }, this.#lifetime.signal);
1546
+ const task = (async () => {
1547
+ let source;
1548
+ try {
1549
+ source = await this.#artifacts.open(input.uri, {
1550
+ ...scope,
1551
+ signal: lease.scope.signal,
1552
+ });
1553
+ await this.#data(control).sendFixedBody(stream, source.stream, lease.scope.signal);
1554
+ await source.closed;
1555
+ }
1556
+ finally {
1557
+ source?.stream.destroy();
1558
+ await source?.closed.catch(() => { });
1559
+ }
1560
+ })()
1561
+ .catch((cause) => this.#failedStream(control, context, stream, cause))
1562
+ .finally(() => {
1563
+ lease.close();
1564
+ permit.release();
1565
+ });
1566
+ this.#track(task);
1567
+ return {
1568
+ contents: [{ uri: input.uri, mimeType: metadata.mimeType, stream }],
1569
+ };
1570
+ }
1571
+ catch (cause) {
1572
+ permit.release();
1573
+ if (prepared)
1574
+ await this.#failedStream(control, prepared.context, prepared.stream, cause);
1575
+ throw cause;
1576
+ }
1577
+ }
1578
+ #reserve(caller, transferId) {
1579
+ for (const [id, value] of this.#reservations)
1580
+ if (!value.consumed && value.expiresAt <= Date.now())
1581
+ this.#reservations.delete(id);
1582
+ requireCondition(this.#reservations.size < 512, "transfer_busy", "Too many transfer observations are pending.");
1583
+ const context = this.#context(caller);
1584
+ const projectId = context.authorization.projectId ?? null;
1585
+ const core = this.#transfers.reserveClaim(transferId, {
1586
+ binding: { ...this.#store.binding, bootId: this.#store.bootId },
1587
+ caller,
1588
+ signal: this.#lifetime.signal,
1589
+ assertCurrent: () => this.#authorizeCaller(caller, undefined, projectId),
1590
+ authorize: (target) => this.#authorizeCaller(caller, target, projectId),
1591
+ });
1592
+ const reservationId = newId("reservation");
1593
+ this.#reservations.set(reservationId, {
1594
+ core,
1595
+ transferId,
1596
+ context,
1597
+ consumed: false,
1598
+ expiresAt: Date.now() + 5000,
1599
+ });
1600
+ const record = this.#store.getTransfer(transferId, {
1601
+ callerKey: callerKey(caller),
1602
+ owner: platformOrigin("transfer"),
1603
+ });
1604
+ return {
1605
+ transferId,
1606
+ reservationId,
1607
+ expiresAt: iso(Math.min(record.claimDeadlineAt ?? Date.now() + 5000, Date.now() + 5000)),
1608
+ direction: record.direction,
1609
+ maxBytes: record.metadata.maxBytes,
1610
+ };
1611
+ }
1612
+ #reservation(caller, input) {
1613
+ const reservation = this.#reservations.get(input.reservationId);
1614
+ requireCondition(reservation &&
1615
+ !reservation.consumed &&
1616
+ reservation.transferId === input.transferId &&
1617
+ callerKey(reservation.context.caller) === callerKey(caller) &&
1618
+ reservation.context.caller.grantId === caller.grantId, "invalid_transfer_reservation", "The claim must use its actual original Core reservation.");
1619
+ return reservation;
1620
+ }
1621
+ async #commit(caller, input) {
1622
+ const reservation = this.#reservation(caller, input);
1623
+ reservation.consumed = true;
1624
+ const claim = {
1625
+ transferId: input.transferId,
1626
+ reservationId: input.reservationId,
1627
+ };
1628
+ const controller = new AbortController();
1629
+ const signal = AbortSignal.any([this.#lifetime.signal, controller.signal]);
1630
+ let lease;
1631
+ let transportClosed;
1632
+ let enteredCore = false;
1633
+ const knownClosure = (closed) => {
1634
+ transportClosed = closed;
1635
+ const observed = closed.catch((cause) => {
1636
+ throw new TransferIoError(isAgentError(cause) ? cause.code : "transfer_failed", "The authenticated data stream failed after physical closure.", false, true, undefined, cause);
1637
+ });
1638
+ void observed.catch(() => { });
1639
+ return observed;
1640
+ };
1641
+ try {
1642
+ const control = this.#control(), data = this.#data(control);
1643
+ const source = this.#channels.get(input.transferId);
1644
+ requireCondition(source, "transfer_origin_unavailable", "The transfer has no original approved channel source.");
1645
+ lease = this.#startLease(caller, {
1646
+ transferId: input.transferId,
1647
+ originInvocationId: source.originInvocationId,
1648
+ }, signal, reservation.context.authorization.projectId ?? null);
1649
+ if (input.stream.direction === "agent-to-cloud") {
1650
+ const stream = data.openWrite(input.stream, lease.scope.signal, claim);
1651
+ enteredCore = true;
1652
+ return await this.#transfers.commitClaim(reservation.core, {
1653
+ download: stream.writable,
1654
+ closed: knownClosure(stream.closed),
1655
+ });
1656
+ }
1657
+ // The existing reservation is consumed before waiting for response headers
1658
+ // or the Host's first upload byte. A native Readable supplies the deferred I/O.
1659
+ const opening = data.openRead(input.stream, lease.scope.signal, claim);
1660
+ void opening.catch(() => { });
1661
+ let actual;
1662
+ const readable = Readable.from((async function* () {
1663
+ actual = await opening;
1664
+ yield* actual.readable;
1665
+ })());
1666
+ const closed = opening.then((stream) => stream.closed);
1667
+ void closed.catch(() => { });
1668
+ readable.once("close", () => {
1669
+ if (!readable.readableEnded)
1670
+ controller.abort();
1671
+ actual?.readable.destroy();
1672
+ void opening.then((stream) => stream.readable.destroy(), () => { });
1673
+ });
1674
+ enteredCore = true;
1675
+ return await this.#transfers.commitClaim(reservation.core, {
1676
+ upload: readable,
1677
+ closed: knownClosure(closed),
1678
+ ...(input.contentLength === undefined
1679
+ ? {}
1680
+ : { contentLength: input.contentLength }),
1681
+ });
1682
+ }
1683
+ catch (cause) {
1684
+ controller.abort(cause);
1685
+ await transportClosed?.catch(() => { });
1686
+ if (!enteredCore) {
1687
+ try {
1688
+ this.#transfers.releaseReservation(reservation.core);
1689
+ }
1690
+ catch {
1691
+ /* Core's own expiration may already have released it. */
1692
+ }
1693
+ }
1694
+ throw cause;
1695
+ }
1696
+ finally {
1697
+ lease?.close();
1698
+ this.#reservations.delete(input.reservationId);
1699
+ }
1700
+ }
1701
+ close() {
1702
+ return (this.#closeTask ??= (async () => {
1703
+ if (this.#closed)
1704
+ return;
1705
+ this.#closing = true;
1706
+ this.#stopping.abort(new AgentError("runtime_closed", "The Agent process is stopping."));
1707
+ await Promise.all([...this.#shutdownJoins].map((join) => join()));
1708
+ clearInterval(this.#refreshTimer);
1709
+ await this.#catalog.close();
1710
+ if (this.#engine)
1711
+ for (const entry of this.#runs.values())
1712
+ if (!terminalStatuses.has(this.#store.getRun(entry.services.runId).status))
1713
+ this.#engine.cancel(entry.context.caller, entry.services.runId);
1714
+ const cleanup = await this.#resources.shutdown({
1715
+ code: "agent_shutdown",
1716
+ });
1717
+ requireCondition(cleanup.unconfirmed.length === 0, "shutdown_unconfirmed", "Some actual native resources have not confirmed closure.");
1718
+ this.#lifetime.abort(new AgentError("runtime_closed", "The Agent process is stopping."));
1719
+ await Promise.allSettled([...this.#streams]);
1720
+ if (this.#engine)
1721
+ for (const entry of this.#runs.values()) {
1722
+ const observed = await this.#engine.observe(entry.context.caller, entry.services.runId, this.#options.shutdownWaitMs ?? 30000);
1723
+ requireCondition(terminalStatuses.has(observed.run.status), "shutdown_unconfirmed", "An accepted JavaScript execution has not actually settled.");
1724
+ this.#engine.off(entry.services.runId, entry.notify);
1725
+ }
1726
+ await this.#configurationSources?.close();
1727
+ if (this.#extensions)
1728
+ for (const item of this.#extensions.list())
1729
+ requireCondition((await this.#extensions.disable(item.name)).status ===
1730
+ "disabled", "shutdown_unconfirmed", "An enabled extension has not confirmed closure.");
1731
+ if (this.#registry)
1732
+ for (const handle of [...this.#platform].reverse())
1733
+ requireCondition((await this.#registry.disable(handle)).status === "disabled", "shutdown_unconfirmed", "A platform extension has not confirmed closure.");
1734
+ this.#logWriterClosed = true;
1735
+ await this.#logTail;
1736
+ await Promise.allSettled([...this.#streams]);
1737
+ await this.#work?.drain();
1738
+ await this.#retention.stop();
1739
+ this.#closed = true;
1740
+ this.#store.close();
1741
+ })().catch((cause) => {
1742
+ this.#closeTask = undefined;
1743
+ throw cause;
1744
+ }));
1745
+ }
1746
+ }
1747
+ //# sourceMappingURL=runtime.js.map