operon-agents-core 0.1.0-alpha.0

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 (511) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +7 -0
  3. package/dist/agent/agent.d.ts +65 -0
  4. package/dist/agent/agent.js +39 -0
  5. package/dist/agent/compose-hooks.d.ts +13 -0
  6. package/dist/agent/compose-hooks.js +197 -0
  7. package/dist/agent/concurrency.d.ts +22 -0
  8. package/dist/agent/concurrency.js +70 -0
  9. package/dist/agent/context-report.d.ts +60 -0
  10. package/dist/agent/context-report.js +45 -0
  11. package/dist/agent/graph.d.ts +48 -0
  12. package/dist/agent/graph.js +129 -0
  13. package/dist/agent/guardrail.d.ts +105 -0
  14. package/dist/agent/guardrail.js +314 -0
  15. package/dist/agent/handoff-executor.d.ts +21 -0
  16. package/dist/agent/handoff-executor.js +95 -0
  17. package/dist/agent/handoff.d.ts +42 -0
  18. package/dist/agent/handoff.js +70 -0
  19. package/dist/agent/index.d.ts +25 -0
  20. package/dist/agent/index.js +19 -0
  21. package/dist/agent/instruction-context.d.ts +33 -0
  22. package/dist/agent/instruction-context.js +100 -0
  23. package/dist/agent/pause.d.ts +12 -0
  24. package/dist/agent/pause.js +82 -0
  25. package/dist/agent/profile-builtins.d.ts +8 -0
  26. package/dist/agent/profile-builtins.js +130 -0
  27. package/dist/agent/profiles.d.ts +94 -0
  28. package/dist/agent/profiles.js +264 -0
  29. package/dist/agent/recovery.d.ts +10 -0
  30. package/dist/agent/recovery.js +151 -0
  31. package/dist/agent/run-support.d.ts +79 -0
  32. package/dist/agent/run-support.js +211 -0
  33. package/dist/agent/runner.d.ts +246 -0
  34. package/dist/agent/runner.js +786 -0
  35. package/dist/agent/session.d.ts +363 -0
  36. package/dist/agent/session.js +937 -0
  37. package/dist/agent/subagent-tools.d.ts +18 -0
  38. package/dist/agent/subagent-tools.js +650 -0
  39. package/dist/agent/subagent.d.ts +56 -0
  40. package/dist/agent/subagent.js +50 -0
  41. package/dist/agent/toolset.d.ts +24 -0
  42. package/dist/agent/toolset.js +112 -0
  43. package/dist/agent/workflow/index.d.ts +9 -0
  44. package/dist/agent/workflow/index.js +8 -0
  45. package/dist/agent/workflow/journal.d.ts +180 -0
  46. package/dist/agent/workflow/journal.js +224 -0
  47. package/dist/agent/workflow/manager.d.ts +27 -0
  48. package/dist/agent/workflow/manager.js +33 -0
  49. package/dist/agent/workflow/parse.d.ts +17 -0
  50. package/dist/agent/workflow/parse.js +174 -0
  51. package/dist/agent/workflow/prompt.d.ts +8 -0
  52. package/dist/agent/workflow/prompt.js +84 -0
  53. package/dist/agent/workflow/runtime.d.ts +64 -0
  54. package/dist/agent/workflow/runtime.js +380 -0
  55. package/dist/agent/workflow/sandbox.d.ts +35 -0
  56. package/dist/agent/workflow/sandbox.js +90 -0
  57. package/dist/agent/workflow/snapshot.d.ts +36 -0
  58. package/dist/agent/workflow/snapshot.js +9 -0
  59. package/dist/agent/workflow/structured.d.ts +35 -0
  60. package/dist/agent/workflow/structured.js +79 -0
  61. package/dist/agent/workflow/tool.d.ts +14 -0
  62. package/dist/agent/workflow/tool.js +569 -0
  63. package/dist/agent/workflow/types.d.ts +100 -0
  64. package/dist/agent/workflow/types.js +17 -0
  65. package/dist/agent/worktree.d.ts +38 -0
  66. package/dist/agent/worktree.js +56 -0
  67. package/dist/capabilities/assembler.d.ts +39 -0
  68. package/dist/capabilities/assembler.js +171 -0
  69. package/dist/capabilities/background/agent-task.d.ts +51 -0
  70. package/dist/capabilities/background/agent-task.js +101 -0
  71. package/dist/capabilities/background/command-task.d.ts +43 -0
  72. package/dist/capabilities/background/command-task.js +86 -0
  73. package/dist/capabilities/background/index.d.ts +20 -0
  74. package/dist/capabilities/background/index.js +57 -0
  75. package/dist/capabilities/background/manager.d.ts +194 -0
  76. package/dist/capabilities/background/manager.js +1131 -0
  77. package/dist/capabilities/background/persist-disk.d.ts +17 -0
  78. package/dist/capabilities/background/persist-disk.js +66 -0
  79. package/dist/capabilities/background/persist.d.ts +61 -0
  80. package/dist/capabilities/background/persist.js +117 -0
  81. package/dist/capabilities/background/question-task.d.ts +32 -0
  82. package/dist/capabilities/background/question-task.js +56 -0
  83. package/dist/capabilities/background/registrar.d.ts +12 -0
  84. package/dist/capabilities/background/registrar.js +9 -0
  85. package/dist/capabilities/background/swappable-sink.d.ts +20 -0
  86. package/dist/capabilities/background/swappable-sink.js +20 -0
  87. package/dist/capabilities/background/task.d.ts +114 -0
  88. package/dist/capabilities/background/task.js +20 -0
  89. package/dist/capabilities/background/tools.d.ts +6 -0
  90. package/dist/capabilities/background/tools.js +190 -0
  91. package/dist/capabilities/background/workflow-task.d.ts +48 -0
  92. package/dist/capabilities/background/workflow-task.js +91 -0
  93. package/dist/capabilities/capability-state.d.ts +13 -0
  94. package/dist/capabilities/capability-state.js +37 -0
  95. package/dist/capabilities/capability.d.ts +145 -0
  96. package/dist/capabilities/capability.js +2 -0
  97. package/dist/capabilities/compaction/full.d.ts +27 -0
  98. package/dist/capabilities/compaction/full.js +155 -0
  99. package/dist/capabilities/compaction/index.d.ts +17 -0
  100. package/dist/capabilities/compaction/index.js +145 -0
  101. package/dist/capabilities/compaction/instruction.d.ts +2 -0
  102. package/dist/capabilities/compaction/instruction.js +31 -0
  103. package/dist/capabilities/compaction/micro.d.ts +17 -0
  104. package/dist/capabilities/compaction/micro.js +57 -0
  105. package/dist/capabilities/compaction/service.d.ts +28 -0
  106. package/dist/capabilities/compaction/service.js +52 -0
  107. package/dist/capabilities/compaction/strategy.d.ts +43 -0
  108. package/dist/capabilities/compaction/strategy.js +116 -0
  109. package/dist/capabilities/compaction/tokens.d.ts +5 -0
  110. package/dist/capabilities/compaction/tokens.js +28 -0
  111. package/dist/capabilities/goal/goal-store.d.ts +69 -0
  112. package/dist/capabilities/goal/goal-store.js +172 -0
  113. package/dist/capabilities/goal/index.d.ts +6 -0
  114. package/dist/capabilities/goal/index.js +31 -0
  115. package/dist/capabilities/goal/injector.d.ts +9 -0
  116. package/dist/capabilities/goal/injector.js +79 -0
  117. package/dist/capabilities/goal/tools.d.ts +6 -0
  118. package/dist/capabilities/goal/tools.js +86 -0
  119. package/dist/capabilities/index.d.ts +25 -0
  120. package/dist/capabilities/index.js +22 -0
  121. package/dist/capabilities/injection.d.ts +44 -0
  122. package/dist/capabilities/injection.js +112 -0
  123. package/dist/capabilities/plan/index.d.ts +6 -0
  124. package/dist/capabilities/plan/index.js +25 -0
  125. package/dist/capabilities/plan/injector.d.ts +13 -0
  126. package/dist/capabilities/plan/injector.js +83 -0
  127. package/dist/capabilities/plan/plan-mode.d.ts +38 -0
  128. package/dist/capabilities/plan/plan-mode.js +113 -0
  129. package/dist/capabilities/plan/policies.d.ts +6 -0
  130. package/dist/capabilities/plan/policies.js +89 -0
  131. package/dist/capabilities/plan/tools.d.ts +15 -0
  132. package/dist/capabilities/plan/tools.js +87 -0
  133. package/dist/capabilities/skills/flow-provider.d.ts +6 -0
  134. package/dist/capabilities/skills/flow-provider.js +50 -0
  135. package/dist/capabilities/skills/index.d.ts +43 -0
  136. package/dist/capabilities/skills/index.js +48 -0
  137. package/dist/capabilities/skills/injector.d.ts +11 -0
  138. package/dist/capabilities/skills/injector.js +27 -0
  139. package/dist/capabilities/skills/parser.d.ts +36 -0
  140. package/dist/capabilities/skills/parser.js +334 -0
  141. package/dist/capabilities/skills/registry.d.ts +33 -0
  142. package/dist/capabilities/skills/registry.js +118 -0
  143. package/dist/capabilities/skills/scanner.d.ts +26 -0
  144. package/dist/capabilities/skills/scanner.js +154 -0
  145. package/dist/capabilities/skills/service.d.ts +39 -0
  146. package/dist/capabilities/skills/service.js +68 -0
  147. package/dist/capabilities/skills/skill-tool.d.ts +13 -0
  148. package/dist/capabilities/skills/skill-tool.js +72 -0
  149. package/dist/capabilities/skills/types.d.ts +62 -0
  150. package/dist/capabilities/skills/types.js +26 -0
  151. package/dist/capabilities/task/index.d.ts +23 -0
  152. package/dist/capabilities/task/index.js +38 -0
  153. package/dist/capabilities/task/injector.d.ts +9 -0
  154. package/dist/capabilities/task/injector.js +62 -0
  155. package/dist/capabilities/task/persist-disk.d.ts +19 -0
  156. package/dist/capabilities/task/persist-disk.js +84 -0
  157. package/dist/capabilities/task/persist.d.ts +52 -0
  158. package/dist/capabilities/task/persist.js +84 -0
  159. package/dist/capabilities/task/task-store.d.ts +44 -0
  160. package/dist/capabilities/task/task-store.js +106 -0
  161. package/dist/capabilities/task/tools.d.ts +12 -0
  162. package/dist/capabilities/task/tools.js +164 -0
  163. package/dist/capabilities/todo/index.d.ts +8 -0
  164. package/dist/capabilities/todo/index.js +21 -0
  165. package/dist/capabilities/todo/injector.d.ts +9 -0
  166. package/dist/capabilities/todo/injector.js +68 -0
  167. package/dist/capabilities/todo/todo-store.d.ts +19 -0
  168. package/dist/capabilities/todo/todo-store.js +36 -0
  169. package/dist/capabilities/todo/tools.d.ts +6 -0
  170. package/dist/capabilities/todo/tools.js +70 -0
  171. package/dist/capabilities/tool-provider.d.ts +12 -0
  172. package/dist/capabilities/tool-provider.js +20 -0
  173. package/dist/capabilities/user-hooks/engine.d.ts +22 -0
  174. package/dist/capabilities/user-hooks/engine.js +105 -0
  175. package/dist/capabilities/user-hooks/index.d.ts +13 -0
  176. package/dist/capabilities/user-hooks/index.js +126 -0
  177. package/dist/capabilities/user-hooks/types.d.ts +26 -0
  178. package/dist/capabilities/user-hooks/types.js +19 -0
  179. package/dist/capabilities/workflow/index.d.ts +16 -0
  180. package/dist/capabilities/workflow/index.js +15 -0
  181. package/dist/commands/index.d.ts +31 -0
  182. package/dist/commands/index.js +318 -0
  183. package/dist/config/config-store.d.ts +29 -0
  184. package/dist/config/config-store.js +103 -0
  185. package/dist/config/file-source.d.ts +40 -0
  186. package/dist/config/file-source.js +78 -0
  187. package/dist/config/flags.d.ts +13 -0
  188. package/dist/config/flags.js +25 -0
  189. package/dist/config/index.d.ts +17 -0
  190. package/dist/config/index.js +10 -0
  191. package/dist/config/merge.d.ts +5 -0
  192. package/dist/config/merge.js +57 -0
  193. package/dist/config/model-catalog.d.ts +17 -0
  194. package/dist/config/model-catalog.js +37 -0
  195. package/dist/config/paths.d.ts +31 -0
  196. package/dist/config/paths.js +28 -0
  197. package/dist/config/provider-manager.d.ts +57 -0
  198. package/dist/config/provider-manager.js +344 -0
  199. package/dist/config/resolver.d.ts +40 -0
  200. package/dist/config/resolver.js +52 -0
  201. package/dist/config/schema.d.ts +389 -0
  202. package/dist/config/schema.js +132 -0
  203. package/dist/events/events.d.ts +348 -0
  204. package/dist/events/events.js +146 -0
  205. package/dist/events/index.d.ts +10 -0
  206. package/dist/events/index.js +5 -0
  207. package/dist/events/projection.d.ts +207 -0
  208. package/dist/events/projection.js +438 -0
  209. package/dist/events/publisher.d.ts +48 -0
  210. package/dist/events/publisher.js +404 -0
  211. package/dist/events/redacting-sink.d.ts +11 -0
  212. package/dist/events/redacting-sink.js +31 -0
  213. package/dist/home.d.ts +16 -0
  214. package/dist/home.js +20 -0
  215. package/dist/index.d.ts +22 -0
  216. package/dist/index.js +22 -0
  217. package/dist/internal.d.ts +33 -0
  218. package/dist/internal.js +29 -0
  219. package/dist/llm/auth.d.ts +22 -0
  220. package/dist/llm/auth.js +112 -0
  221. package/dist/llm/capability.d.ts +13 -0
  222. package/dist/llm/capability.js +45 -0
  223. package/dist/llm/define-model.d.ts +110 -0
  224. package/dist/llm/define-model.js +252 -0
  225. package/dist/llm/errors.d.ts +33 -0
  226. package/dist/llm/errors.js +154 -0
  227. package/dist/llm/index.d.ts +14 -0
  228. package/dist/llm/index.js +8 -0
  229. package/dist/llm/model.d.ts +43 -0
  230. package/dist/llm/model.js +9 -0
  231. package/dist/llm/retry.d.ts +35 -0
  232. package/dist/llm/retry.js +160 -0
  233. package/dist/llm/runtime.d.ts +25 -0
  234. package/dist/llm/runtime.js +38 -0
  235. package/dist/logging/diagnostics.d.ts +21 -0
  236. package/dist/logging/diagnostics.js +46 -0
  237. package/dist/logging/index.d.ts +11 -0
  238. package/dist/logging/index.js +7 -0
  239. package/dist/logging/logger.d.ts +25 -0
  240. package/dist/logging/logger.js +54 -0
  241. package/dist/logging/paths.d.ts +11 -0
  242. package/dist/logging/paths.js +20 -0
  243. package/dist/logging/policy.d.ts +5 -0
  244. package/dist/logging/policy.js +19 -0
  245. package/dist/logging/redact.d.ts +10 -0
  246. package/dist/logging/redact.js +95 -0
  247. package/dist/logging/sinks.d.ts +67 -0
  248. package/dist/logging/sinks.js +117 -0
  249. package/dist/loop/context.d.ts +69 -0
  250. package/dist/loop/context.js +129 -0
  251. package/dist/loop/errors.d.ts +8 -0
  252. package/dist/loop/errors.js +27 -0
  253. package/dist/loop/events.d.ts +14 -0
  254. package/dist/loop/events.js +2 -0
  255. package/dist/loop/index.d.ts +10 -0
  256. package/dist/loop/index.js +7 -0
  257. package/dist/loop/interruption.d.ts +118 -0
  258. package/dist/loop/interruption.js +191 -0
  259. package/dist/loop/run-turn.d.ts +54 -0
  260. package/dist/loop/run-turn.js +203 -0
  261. package/dist/loop/scheduler.d.ts +18 -0
  262. package/dist/loop/scheduler.js +71 -0
  263. package/dist/loop/steer.d.ts +122 -0
  264. package/dist/loop/steer.js +209 -0
  265. package/dist/loop/tool-call.d.ts +41 -0
  266. package/dist/loop/tool-call.js +326 -0
  267. package/dist/loop/turn-step.d.ts +57 -0
  268. package/dist/loop/turn-step.js +298 -0
  269. package/dist/loop/types.d.ts +217 -0
  270. package/dist/loop/types.js +2 -0
  271. package/dist/loop/usage.d.ts +6 -0
  272. package/dist/loop/usage.js +44 -0
  273. package/dist/mcp/auth-tool.d.ts +12 -0
  274. package/dist/mcp/auth-tool.js +92 -0
  275. package/dist/mcp/capability.d.ts +7 -0
  276. package/dist/mcp/capability.js +91 -0
  277. package/dist/mcp/config-loader.d.ts +28 -0
  278. package/dist/mcp/config-loader.js +115 -0
  279. package/dist/mcp/filter.d.ts +18 -0
  280. package/dist/mcp/filter.js +35 -0
  281. package/dist/mcp/index.d.ts +23 -0
  282. package/dist/mcp/index.js +13 -0
  283. package/dist/mcp/manager.d.ts +51 -0
  284. package/dist/mcp/manager.js +412 -0
  285. package/dist/mcp/mock-transport.d.ts +40 -0
  286. package/dist/mcp/mock-transport.js +68 -0
  287. package/dist/mcp/oauth/callback-server.d.ts +14 -0
  288. package/dist/mcp/oauth/callback-server.js +122 -0
  289. package/dist/mcp/oauth/index.d.ts +9 -0
  290. package/dist/mcp/oauth/index.js +5 -0
  291. package/dist/mcp/oauth/provider.d.ts +39 -0
  292. package/dist/mcp/oauth/provider.js +121 -0
  293. package/dist/mcp/oauth/service.d.ts +34 -0
  294. package/dist/mcp/oauth/service.js +130 -0
  295. package/dist/mcp/oauth/store.d.ts +40 -0
  296. package/dist/mcp/oauth/store.js +134 -0
  297. package/dist/mcp/output.d.ts +12 -0
  298. package/dist/mcp/output.js +110 -0
  299. package/dist/mcp/provider.d.ts +7 -0
  300. package/dist/mcp/provider.js +56 -0
  301. package/dist/mcp/sdk-transport.d.ts +25 -0
  302. package/dist/mcp/sdk-transport.js +228 -0
  303. package/dist/mcp/server.d.ts +77 -0
  304. package/dist/mcp/server.js +120 -0
  305. package/dist/mcp/tool-naming.d.ts +4 -0
  306. package/dist/mcp/tool-naming.js +26 -0
  307. package/dist/mcp/types.d.ts +75 -0
  308. package/dist/mcp/types.js +2 -0
  309. package/dist/net/index.d.ts +3 -0
  310. package/dist/net/index.js +2 -0
  311. package/dist/net/proxy.d.ts +16 -0
  312. package/dist/net/proxy.js +42 -0
  313. package/dist/permission/auto-approver/index.d.ts +3 -0
  314. package/dist/permission/auto-approver/index.js +3 -0
  315. package/dist/permission/auto-approver/llm-auto-approver.d.ts +53 -0
  316. package/dist/permission/auto-approver/llm-auto-approver.js +122 -0
  317. package/dist/permission/auto-approver/prompts-data.d.ts +9 -0
  318. package/dist/permission/auto-approver/prompts-data.js +155 -0
  319. package/dist/permission/auto-approver/prompts.d.ts +18 -0
  320. package/dist/permission/auto-approver/prompts.js +40 -0
  321. package/dist/permission/auto-approver/transcript.d.ts +22 -0
  322. package/dist/permission/auto-approver/transcript.js +75 -0
  323. package/dist/permission/auto-approver/xml.d.ts +5 -0
  324. package/dist/permission/auto-approver/xml.js +25 -0
  325. package/dist/permission/index.d.ts +7 -0
  326. package/dist/permission/index.js +5 -0
  327. package/dist/permission/manager.d.ts +74 -0
  328. package/dist/permission/manager.js +162 -0
  329. package/dist/permission/matches-rule.d.ts +27 -0
  330. package/dist/permission/matches-rule.js +54 -0
  331. package/dist/permission/policies.d.ts +14 -0
  332. package/dist/permission/policies.js +233 -0
  333. package/dist/permission/types.d.ts +84 -0
  334. package/dist/permission/types.js +2 -0
  335. package/dist/plugins/archive.d.ts +3 -0
  336. package/dist/plugins/archive.js +58 -0
  337. package/dist/plugins/github-resolver.d.ts +13 -0
  338. package/dist/plugins/github-resolver.js +20 -0
  339. package/dist/plugins/hooks.d.ts +28 -0
  340. package/dist/plugins/hooks.js +296 -0
  341. package/dist/plugins/index.d.ts +23 -0
  342. package/dist/plugins/index.js +23 -0
  343. package/dist/plugins/injector.d.ts +11 -0
  344. package/dist/plugins/injector.js +32 -0
  345. package/dist/plugins/manager.d.ts +37 -0
  346. package/dist/plugins/manager.js +330 -0
  347. package/dist/plugins/manifest.d.ts +9 -0
  348. package/dist/plugins/manifest.js +234 -0
  349. package/dist/plugins/marketplace.d.ts +85 -0
  350. package/dist/plugins/marketplace.js +205 -0
  351. package/dist/plugins/source.d.ts +23 -0
  352. package/dist/plugins/source.js +87 -0
  353. package/dist/plugins/store.d.ts +20 -0
  354. package/dist/plugins/store.js +30 -0
  355. package/dist/plugins/types.d.ts +118 -0
  356. package/dist/plugins/types.js +5 -0
  357. package/dist/protocol/index.d.ts +4 -0
  358. package/dist/protocol/index.js +2 -0
  359. package/dist/protocol/tool-schema.d.ts +6 -0
  360. package/dist/protocol/tool-schema.js +2 -0
  361. package/dist/store/blob-store.d.ts +45 -0
  362. package/dist/store/blob-store.js +120 -0
  363. package/dist/store/catalog-store.d.ts +32 -0
  364. package/dist/store/catalog-store.js +73 -0
  365. package/dist/store/disk-store.d.ts +58 -0
  366. package/dist/store/disk-store.js +369 -0
  367. package/dist/store/index.d.ts +23 -0
  368. package/dist/store/index.js +15 -0
  369. package/dist/store/lock.d.ts +86 -0
  370. package/dist/store/lock.js +104 -0
  371. package/dist/store/log-store.d.ts +89 -0
  372. package/dist/store/log-store.js +296 -0
  373. package/dist/store/migrate.d.ts +26 -0
  374. package/dist/store/migrate.js +32 -0
  375. package/dist/store/origin.d.ts +89 -0
  376. package/dist/store/origin.js +16 -0
  377. package/dist/store/pg.d.ts +90 -0
  378. package/dist/store/pg.js +344 -0
  379. package/dist/store/redacting-store.d.ts +21 -0
  380. package/dist/store/redacting-store.js +46 -0
  381. package/dist/store/redis.d.ts +89 -0
  382. package/dist/store/redis.js +370 -0
  383. package/dist/store/repository.d.ts +150 -0
  384. package/dist/store/repository.js +508 -0
  385. package/dist/store/session-catalog.d.ts +32 -0
  386. package/dist/store/session-catalog.js +117 -0
  387. package/dist/store/storage.d.ts +27 -0
  388. package/dist/store/storage.js +54 -0
  389. package/dist/store/store.d.ts +262 -0
  390. package/dist/store/store.js +129 -0
  391. package/dist/store/workdir-key.d.ts +4 -0
  392. package/dist/store/workdir-key.js +28 -0
  393. package/dist/tool/access.d.ts +37 -0
  394. package/dist/tool/access.js +79 -0
  395. package/dist/tool/ask.d.ts +22 -0
  396. package/dist/tool/ask.js +38 -0
  397. package/dist/tool/background.d.ts +109 -0
  398. package/dist/tool/background.js +39 -0
  399. package/dist/tool/builtin/ask-user-question.d.ts +2 -0
  400. package/dist/tool/builtin/ask-user-question.js +175 -0
  401. package/dist/tool/builtin/bash.d.ts +2 -0
  402. package/dist/tool/builtin/bash.js +407 -0
  403. package/dist/tool/builtin/edit.d.ts +2 -0
  404. package/dist/tool/builtin/edit.js +202 -0
  405. package/dist/tool/builtin/glob.d.ts +3 -0
  406. package/dist/tool/builtin/glob.js +260 -0
  407. package/dist/tool/builtin/grep.d.ts +2 -0
  408. package/dist/tool/builtin/grep.js +574 -0
  409. package/dist/tool/builtin/line-endings.d.ts +10 -0
  410. package/dist/tool/builtin/line-endings.js +41 -0
  411. package/dist/tool/builtin/read.d.ts +28 -0
  412. package/dist/tool/builtin/read.js +498 -0
  413. package/dist/tool/builtin/write.d.ts +2 -0
  414. package/dist/tool/builtin/write.js +179 -0
  415. package/dist/tool/define.d.ts +46 -0
  416. package/dist/tool/define.js +45 -0
  417. package/dist/tool/file-freshness.d.ts +81 -0
  418. package/dist/tool/file-freshness.js +67 -0
  419. package/dist/tool/filesystem-tools.d.ts +16 -0
  420. package/dist/tool/filesystem-tools.js +19 -0
  421. package/dist/tool/git-context.d.ts +20 -0
  422. package/dist/tool/git-context.js +114 -0
  423. package/dist/tool/index.d.ts +37 -0
  424. package/dist/tool/index.js +34 -0
  425. package/dist/tool/machine-base.d.ts +138 -0
  426. package/dist/tool/machine-base.js +388 -0
  427. package/dist/tool/machine-local.d.ts +35 -0
  428. package/dist/tool/machine-local.js +316 -0
  429. package/dist/tool/machine-null.d.ts +36 -0
  430. package/dist/tool/machine-null.js +64 -0
  431. package/dist/tool/machine-ssh.d.ts +86 -0
  432. package/dist/tool/machine-ssh.js +576 -0
  433. package/dist/tool/machine.d.ts +333 -0
  434. package/dist/tool/machine.js +15 -0
  435. package/dist/tool/policies/path-access.d.ts +48 -0
  436. package/dist/tool/policies/path-access.js +186 -0
  437. package/dist/tool/policies/sensitive.d.ts +3 -0
  438. package/dist/tool/policies/sensitive.js +60 -0
  439. package/dist/tool/questions.d.ts +40 -0
  440. package/dist/tool/questions.js +8 -0
  441. package/dist/tool/search/activation.d.ts +13 -0
  442. package/dist/tool/search/activation.js +31 -0
  443. package/dist/tool/search/deferral.d.ts +37 -0
  444. package/dist/tool/search/deferral.js +128 -0
  445. package/dist/tool/search/search-tool.d.ts +9 -0
  446. package/dist/tool/search/search-tool.js +62 -0
  447. package/dist/tool/shell-env.d.ts +9 -0
  448. package/dist/tool/shell-env.js +34 -0
  449. package/dist/tool/support/bash-destructive.d.ts +24 -0
  450. package/dist/tool/support/bash-destructive.js +63 -0
  451. package/dist/tool/support/bash-paths.d.ts +7 -0
  452. package/dist/tool/support/bash-paths.js +247 -0
  453. package/dist/tool/support/bash-read-only.d.ts +8 -0
  454. package/dist/tool/support/bash-read-only.js +165 -0
  455. package/dist/tool/support/bash-rule-match.d.ts +20 -0
  456. package/dist/tool/support/bash-rule-match.js +191 -0
  457. package/dist/tool/support/file-type.d.ts +10 -0
  458. package/dist/tool/support/file-type.js +149 -0
  459. package/dist/tool/support/git-worktree.d.ts +10 -0
  460. package/dist/tool/support/git-worktree.js +63 -0
  461. package/dist/tool/support/image-compress.d.ts +69 -0
  462. package/dist/tool/support/image-compress.js +265 -0
  463. package/dist/tool/support/machine-ops.d.ts +34 -0
  464. package/dist/tool/support/machine-ops.js +34 -0
  465. package/dist/tool/support/path-glob-match.d.ts +12 -0
  466. package/dist/tool/support/path-glob-match.js +84 -0
  467. package/dist/tool/support/result-builder.d.ts +27 -0
  468. package/dist/tool/support/result-builder.js +108 -0
  469. package/dist/tool/support/rg-locator.d.ts +20 -0
  470. package/dist/tool/support/rg-locator.js +42 -0
  471. package/dist/tool/support/ripgrep-run.d.ts +65 -0
  472. package/dist/tool/support/ripgrep-run.js +40 -0
  473. package/dist/tool/support/rule-match.d.ts +6 -0
  474. package/dist/tool/support/rule-match.js +23 -0
  475. package/dist/tool/support/tool-path.d.ts +8 -0
  476. package/dist/tool/support/tool-path.js +28 -0
  477. package/dist/tool/support/workspace.d.ts +5 -0
  478. package/dist/tool/support/workspace.js +2 -0
  479. package/dist/tool/types.d.ts +131 -0
  480. package/dist/tool/types.js +2 -0
  481. package/dist/tool/web/fetch-url.d.ts +4 -0
  482. package/dist/tool/web/fetch-url.js +61 -0
  483. package/dist/tool/web/index.d.ts +11 -0
  484. package/dist/tool/web/index.js +7 -0
  485. package/dist/tool/web/providers/direct-fetch.d.ts +33 -0
  486. package/dist/tool/web/providers/direct-fetch.js +198 -0
  487. package/dist/tool/web/providers/firecrawl.d.ts +16 -0
  488. package/dist/tool/web/providers/firecrawl.js +59 -0
  489. package/dist/tool/web/providers/tavily.d.ts +14 -0
  490. package/dist/tool/web/providers/tavily.js +43 -0
  491. package/dist/tool/web/types.d.ts +41 -0
  492. package/dist/tool/web/types.js +7 -0
  493. package/dist/tool/web/web-search.d.ts +4 -0
  494. package/dist/tool/web/web-search.js +68 -0
  495. package/dist/tool/workspace-spec.d.ts +74 -0
  496. package/dist/tool/workspace-spec.js +177 -0
  497. package/dist/tracing/bridge.d.ts +7 -0
  498. package/dist/tracing/bridge.js +171 -0
  499. package/dist/tracing/index.d.ts +9 -0
  500. package/dist/tracing/index.js +5 -0
  501. package/dist/tracing/otel.d.ts +38 -0
  502. package/dist/tracing/otel.js +221 -0
  503. package/dist/tracing/processor.d.ts +47 -0
  504. package/dist/tracing/processor.js +94 -0
  505. package/dist/tracing/spans.d.ts +94 -0
  506. package/dist/tracing/spans.js +56 -0
  507. package/dist/ui/ai-sdk.d.ts +114 -0
  508. package/dist/ui/ai-sdk.js +175 -0
  509. package/dist/ui/index.d.ts +2 -0
  510. package/dist/ui/index.js +2 -0
  511. package/package.json +101 -0
@@ -0,0 +1,786 @@
1
+ import { addUsage, emptyUsage } from "../loop/usage.js";
2
+ import { runTurn } from "../loop/run-turn.js";
3
+ import { isAbortError } from "../loop/errors.js";
4
+ import { ConversationContext, replayContext } from "../loop/context.js";
5
+ import { PermissionManager } from "../permission/manager.js";
6
+ import { assembleCapabilities } from "../capabilities/assembler.js";
7
+ import { computeContextBreakdown } from "./context-report.js";
8
+ import { IterableSink, } from "../events/index.js";
9
+ import { DEFAULT_ADDRESS, SessionBusyError } from "../store/index.js";
10
+ import { SteerBus, steerOriginToPromptOrigin } from "../loop/steer.js";
11
+ import { INTERRUPTION_STATE_KEY, applyInterruptionAnswers, findAnchoredAssistant, newInterruptionId, parseInterruptionState, } from "../loop/interruption.js";
12
+ import { abortReason, Session } from "./session.js";
13
+ import { Agent } from "./agent.js";
14
+ import { createOutputGuardrailMonitor, runInputGuardrails, isGuardrailTripwireError, } from "./guardrail.js";
15
+ import { buildRunHooks } from "./compose-hooks.js";
16
+ import { assertGraphUnambiguous, duplicateAgentNames, findAgentByName, findAgentsByName } from "./graph.js";
17
+ import { performHandoff } from "./handoff-executor.js";
18
+ import { pauseRun } from "./pause.js";
19
+ import { buildRunTools } from "./toolset.js";
20
+ import { activeDeferredTools } from "../tool/search/activation.js";
21
+ import { emitRunEvent, finalText, historyChangeEmitter, injectAtTurnBoundary, lastAssistant, mapTerminalStatus, resolveModelParams, runCtxFor, tryParseOutput, } from "./run-support.js";
22
+ export class Runner {
23
+ config;
24
+ engine;
25
+ constructor(config = {}) {
26
+ this.config = config;
27
+ this.engine = new Engine(config);
28
+ }
29
+ async run(agent, input, opts) {
30
+ return this.withLease(opts, async (lease) => {
31
+ const { session, owned } = await this.acquireSession(opts, undefined, lease);
32
+ try {
33
+ return await session.withRunLock(() => this.execute(agent, input, opts, session));
34
+ }
35
+ finally {
36
+ if (owned)
37
+ await session.close();
38
+ }
39
+ });
40
+ }
41
+ /**
42
+ * Hold the session lease for the duration of `fn`, when a lock is configured.
43
+ *
44
+ * Taken BEFORE the session is opened: opening assembles capabilities, may connect MCP servers
45
+ * and may boot a sandbox, none of which should happen for a run that is about to be rejected.
46
+ *
47
+ * Only a session with a known id can be contended. A run that neither reuses a session nor
48
+ * names one is opening a fresh id nobody else can hold, so it skips the lease entirely.
49
+ */
50
+ async withLease(opts, fn) {
51
+ const lock = this.config.lock;
52
+ const sessionId = opts?.session?.id ?? opts?.sessionId;
53
+ if (lock === undefined || sessionId === undefined)
54
+ return fn();
55
+ const lease = await lock.acquire(sessionId, opts?.signal !== undefined ? { signal: opts.signal } : {});
56
+ if (lease === undefined)
57
+ throw new SessionBusyError(sessionId);
58
+ try {
59
+ return await fn(lease);
60
+ }
61
+ finally {
62
+ await lease.release();
63
+ }
64
+ }
65
+ runStream(agent, input, opts) {
66
+ const pull = new IterableSink();
67
+ const completed = this.withLease(opts, async (lease) => {
68
+ // One-shot pull sessions emit straight to `pull` (the bus IS the iterable). For a
69
+ // shared session, subscribe `pull` to its bus so we never replace the channel (Invariant 4).
70
+ const { session, owned } = await this.acquireSession(opts, pull, lease);
71
+ const unsub = owned ? undefined : session.events.subscribe((ev) => void pull.emit(ev));
72
+ try {
73
+ return await session.withRunLock(() => this.execute(agent, input, opts, session));
74
+ }
75
+ finally {
76
+ unsub?.();
77
+ pull.close();
78
+ if (owned)
79
+ await session.close();
80
+ }
81
+ }).catch((error) => {
82
+ // A rejected lease throws before the body runs, so nothing has closed `pull` — a consumer
83
+ // iterating the handle would hang forever waiting for a stream that never opens.
84
+ pull.close();
85
+ throw error;
86
+ });
87
+ // Avoid an unhandled rejection if the caller only iterates and never awaits `completed`.
88
+ completed.catch(() => undefined);
89
+ return {
90
+ [Symbol.asyncIterator]: () => pull[Symbol.asyncIterator](),
91
+ completed,
92
+ };
93
+ }
94
+ /** Continue an interrupted run. Mirrors `run(agent, input, opts)`: the second argument is
95
+ * the resume input (paused control tree + answers) instead of a fresh prompt. */
96
+ async resume(rootAgent, input, opts) {
97
+ const { interruption, answers } = input;
98
+ assertGraphUnambiguous(rootAgent);
99
+ const parsed = parseInterruptionState(interruption);
100
+ const rootFrame = parsed.frames[parsed.rootFrameId];
101
+ const active = findAgentByName(rootAgent, rootFrame.agent.key);
102
+ if (!active) {
103
+ throw new Error(`Cannot resume: agent "${rootFrame.agent.key}" not found in the provided agent graph.`);
104
+ }
105
+ const updated = applyInterruptionAnswers(parsed, answers);
106
+ const baseOpts = opts;
107
+ // Resuming is running: it needs the same exclusivity as a fresh prompt, or two nodes
108
+ // continue the same interrupted run and both consume its answers.
109
+ return this.withLease(baseOpts, async (lease) => {
110
+ const { session, owned } = await this.acquireSession(baseOpts, undefined, lease);
111
+ // Reopening a session: orphaned background subagents (running from a dead process) → lost.
112
+ await session.reconcileSubagents();
113
+ try {
114
+ return await session.withRunLock(async () => {
115
+ const store = session.store;
116
+ if (!store)
117
+ throw new Error("Cannot resume an interrupted run without a durable session store.");
118
+ const currentRaw = await store.getState(INTERRUPTION_STATE_KEY);
119
+ if (currentRaw === null)
120
+ throw new Error("Cannot resume: this session has no persisted interruption state.");
121
+ const current = parseInterruptionState(currentRaw);
122
+ if (current.interruptionId !== parsed.interruptionId || current.revision !== parsed.revision) {
123
+ throw new Error(`Cannot resume stale interruption state (expected ${current.interruptionId}@${current.revision}, received ${parsed.interruptionId}@${parsed.revision}).`);
124
+ }
125
+ session.setConversationHead({ agentKey: active.name, address: rootFrame.address });
126
+ const state = await this.beginRun(session, baseOpts, updated);
127
+ await store.putState(INTERRUPTION_STATE_KEY, updated);
128
+ // History is the log's job — replay it (the active agent's shard) to rebuild context.
129
+ const context = await replayContext(store, rootFrame.address);
130
+ session.setLiveContext(rootFrame.address, context);
131
+ try {
132
+ const resumeFrom = findAnchoredAssistant(context.messages, rootFrame.anchor);
133
+ const result = await this.engine.run(active, context, state, resumeFrom);
134
+ if (result.status !== "interrupted")
135
+ await store.deleteState(INTERRUPTION_STATE_KEY);
136
+ return result;
137
+ }
138
+ catch (error) {
139
+ const current = await store.getState(INTERRUPTION_STATE_KEY);
140
+ if (current !== null) {
141
+ const recovery = parseInterruptionState(current);
142
+ if (recovery.phase === "resuming") {
143
+ await store.putState(INTERRUPTION_STATE_KEY, {
144
+ ...recovery,
145
+ phase: "recovery_required",
146
+ revision: recovery.revision + 1,
147
+ updatedAt: Date.now(),
148
+ });
149
+ }
150
+ }
151
+ throw error;
152
+ }
153
+ finally {
154
+ await this.settleRun(session, state, context);
155
+ }
156
+ });
157
+ }
158
+ finally {
159
+ if (owned)
160
+ await session.close();
161
+ }
162
+ });
163
+ }
164
+ // Internals.
165
+ /** Reuse the caller's session, or open one for this run. `owned` means we created it and the
166
+ * caller of this method must close it. */
167
+ async acquireSession(opts, eventsOverride, lease) {
168
+ if (opts?.session) {
169
+ // An explicit session wins, but a contradictory sessionId is a caller bug — surface
170
+ // it instead of silently ignoring one of the two.
171
+ if (opts.sessionId !== undefined && opts.sessionId !== opts.session.id) {
172
+ throw new Error(`RunOptions.session (id "${opts.session.id}") and RunOptions.sessionId ("${opts.sessionId}") disagree; pass one of them, or make them match.`);
173
+ }
174
+ return { session: opts.session, owned: false };
175
+ }
176
+ const cfg = {
177
+ machine: this.config.machine,
178
+ store: this.config.store,
179
+ events: eventsOverride ?? this.config.events,
180
+ tracing: this.config.tracing,
181
+ responder: this.config.responder,
182
+ permission: this.config.permission,
183
+ capabilities: this.config.capabilities,
184
+ steer: this.config.steer,
185
+ background: this.config.background,
186
+ eventPublication: this.config.eventPublication,
187
+ sessionId: opts?.sessionId,
188
+ // Losing the lease cancels the run: a holder that can no longer renew has, by definition,
189
+ // been superseded, and must stop before its writes race the node that took over. Only the
190
+ // session this runner owns is wired up — a caller-supplied session keeps its own signal.
191
+ signal: mergeSignals(opts?.signal, lease?.signal),
192
+ };
193
+ const session = await Session.open(cfg);
194
+ return { session, owned: true };
195
+ }
196
+ /** Resolve the durable conversation owner by following committed handoffs from `main`. */
197
+ async resolveConversationHead(session, rootAgent) {
198
+ const cached = session.conversationHead();
199
+ if (cached !== undefined) {
200
+ const matches = findAgentsByName(rootAgent, cached.agentKey);
201
+ if (matches.length === 0) {
202
+ throw new Error(`Cannot continue session: active agent "${cached.agentKey}" is not present in the provided agent graph.`);
203
+ }
204
+ if (matches.length === 1)
205
+ return { agent: matches[0], address: cached.address };
206
+ // Several distinct agents share the cached name: the cache stores only the name, so it
207
+ // cannot say WHICH object owns the conversation. Fall through to the cold walk below —
208
+ // it resolves along committed handoff edges, which stays correct under duplicate names.
209
+ }
210
+ let head = { agentKey: rootAgent.name, address: DEFAULT_ADDRESS };
211
+ let current = rootAgent;
212
+ const store = session.store;
213
+ if (store !== undefined) {
214
+ const visited = new Set();
215
+ let expectedAcceptance;
216
+ while (true) {
217
+ if (visited.has(head.address)) {
218
+ throw new Error(`Cannot continue session: handoff chain contains a cycle at "${head.address}".`);
219
+ }
220
+ if (visited.size >= 64) {
221
+ throw new Error("Cannot continue session: handoff chain exceeds 64 transfers.");
222
+ }
223
+ visited.add(head.address);
224
+ const records = [];
225
+ for await (const record of store.readRecords({ address: head.address }))
226
+ records.push(record);
227
+ if (expectedAcceptance !== undefined &&
228
+ !records.some((record) => record.type === "agent.handoff.accepted" &&
229
+ record.handoffId === expectedAcceptance.handoffId &&
230
+ record.fromAddress === expectedAcceptance.fromAddress)) {
231
+ throw new Error(`Cannot continue session: handoff "${expectedAcceptance.handoffId}" points to uninitialized shard "${head.address}".`);
232
+ }
233
+ const committed = records.filter((record) => record.type === "agent.handoff" &&
234
+ typeof record.handoffId === "string" &&
235
+ typeof record.toAddress === "string");
236
+ if (committed.length === 0) {
237
+ // Reuse the leaf records we already read to seed the live cache; otherwise the caller
238
+ // would immediately replay the same shard a second time before appending the prompt.
239
+ if (session.liveContext(head.address) === undefined) {
240
+ const context = new ConversationContext({
241
+ store,
242
+ address: head.address,
243
+ });
244
+ context.loadFromRecords(records);
245
+ session.setLiveContext(head.address, context);
246
+ }
247
+ break;
248
+ }
249
+ if (committed.length > 1) {
250
+ throw new Error(`Cannot continue session: frozen shard "${head.address}" has multiple committed handoffs.`);
251
+ }
252
+ const transfer = committed[0];
253
+ // This shard's records were written by `current`, so the committed transfer followed one
254
+ // of its own handoff edges. Resolving along that edge (not a global graph search) retraces
255
+ // the original run, so a same-named agent elsewhere in the graph can never capture the
256
+ // conversation — target names only have to be unambiguous within one agent's handoffs.
257
+ const edges = current.handoffs.filter((h) => h.target.name === transfer.to);
258
+ const target = edges[0]?.target;
259
+ if (target === undefined) {
260
+ throw new Error(`Cannot continue session: handoff target "${transfer.to}" is not among agent "${current.name}"'s handoffs.`);
261
+ }
262
+ if (edges.some((h) => h.target !== target)) {
263
+ throw new Error(`Cannot continue session: agent "${current.name}" has multiple handoff targets named "${transfer.to}".`);
264
+ }
265
+ current = target;
266
+ expectedAcceptance = { handoffId: transfer.handoffId, fromAddress: head.address };
267
+ head = { agentKey: current.name, address: transfer.toAddress };
268
+ }
269
+ }
270
+ session.setConversationHead(head);
271
+ return { agent: current, address: head.address };
272
+ }
273
+ async execute(rootAgent, input, opts, session) {
274
+ assertGraphUnambiguous(rootAgent);
275
+ // A normal post-crash continuation is a fresh prompt (for example "continue"), not the
276
+ // HITL-specific Runner.resume path. Reconcile durable task ghosts before request recovery
277
+ // inspects them so BackgroundOutput is given the truthful terminal `lost` status.
278
+ await session.reconcileSubagents();
279
+ if (session.store && (await session.store.getState(INTERRUPTION_STATE_KEY)) !== null) {
280
+ throw new Error("This session has an interrupted run. Resume or resolve it before starting a new prompt.");
281
+ }
282
+ const head = await this.resolveConversationHead(session, rootAgent);
283
+ const agent = head.agent;
284
+ const state = await this.beginRun(session, opts, undefined, head.address);
285
+ // Live runs tolerate duplicate names (edges resolve by object), but durable name-keyed
286
+ // resolution (resume) fails closed on them — warn now, not mid-recovery.
287
+ const duplicates = duplicateAgentNames(rootAgent);
288
+ if (duplicates.length > 0) {
289
+ emitRunEvent(state, {
290
+ type: "warning",
291
+ message: `Agent graph contains duplicate agent names (${duplicates.join(", ")}). Interrupted runs referencing these names cannot be resumed — give agents unique names.`,
292
+ });
293
+ }
294
+ // Continue the conversation. A long-lived session keeps its live context, so we append to it
295
+ // (O(1)) instead of replaying the whole log every turn. Model-visible reminders are ordinary
296
+ // append-only context records, so the live prefix is exactly what a cold replay reconstructs.
297
+ // A cold run (new session, or after a log rewrite) replays the log once and caches it. No
298
+ // store means the same append-only behavior, held only in memory.
299
+ let context = session.liveContext(state.address);
300
+ if (context === undefined) {
301
+ context = state.store
302
+ ? await replayContext(state.store, state.address)
303
+ : new ConversationContext({
304
+ store: state.store,
305
+ address: state.address,
306
+ onHistoryChange: historyChangeEmitter(state.events, state.sessionId),
307
+ });
308
+ session.setLiveContext(state.address, context);
309
+ }
310
+ // Capability interception of the caller's input, BEFORE guardrails and before anything is
311
+ // journaled: a rewrite here is what the run (and its replay) sees as the prompt. Guardrails
312
+ // then judge what actually enters history, not what the caller originally sent.
313
+ const runStart = await this.applyRunStarts(state, agent.name, toMessages(input));
314
+ const messages = runStart.input;
315
+ let inputAccepted = false;
316
+ try {
317
+ // A capability answered it. Nothing is journaled — not the prompt, not a reply — so the
318
+ // session is byte-identical to before the call, and `messages` reflects that. Inside the
319
+ // try so teardown still runs through the one `settleRun` in `finally`.
320
+ if (runStart.handled !== undefined) {
321
+ return {
322
+ status: "skipped",
323
+ finalAgent: agent.name,
324
+ activeAddress: state.address,
325
+ output: runStart.handled.output ?? "",
326
+ messages: [...context.messages],
327
+ usage: emptyUsage(),
328
+ };
329
+ }
330
+ await runInputGuardrails(agent.guardrails.input ?? [], {
331
+ agent,
332
+ input: messages,
333
+ context: runCtxFor(state),
334
+ });
335
+ // Append + journal the new user input as the next turn of history, surfacing each via
336
+ // `message.appended` so consumers can rebuild the transcript uniformly (prompts get a
337
+ // signal too, not just assistant/toolResult). These fire before agent.started — the input
338
+ // exists before the agent begins — and the tracing bridge ignores non-assistant messages.
339
+ for (const message of messages)
340
+ context.appendMessage(message, opts?.inputOrigin);
341
+ inputAccepted = true;
342
+ // No input of its own ⇒ a wake run, whose prompt IS whatever is queued (a background task
343
+ // that settled after its spawning turn ended, a cron fire, a peer message). Let the first
344
+ // iteration drain, or the turn would run with nothing new in front of the model.
345
+ return await this.engine.run(agent, context, state, undefined, messages.length === 0);
346
+ }
347
+ catch (error) {
348
+ // A guardrail tripwire aborts the whole run by throwing (like OpenAI Agents). Emit a
349
+ // clean terminal frame first so streaming consumers don't see the event stream silently
350
+ // truncate; the run still rejects with the enriched GuardrailTripwireError.
351
+ if (isGuardrailTripwireError(error)) {
352
+ if (error.usage !== undefined) {
353
+ state.usage = addUsage(state.usage, error.usage);
354
+ const activeContext = session.liveContext(state.address) ?? context;
355
+ activeContext.record({ type: "usage.record", usage: error.usage, total: state.usage });
356
+ if (state.store === undefined)
357
+ void emitRunEvent(state, { type: "usage.updated", usage: state.usage });
358
+ }
359
+ const blocked = {
360
+ type: "guardrail.blocked",
361
+ stage: error.stage,
362
+ guardrail: error.guardrailName,
363
+ ...(error.agentName !== undefined ? { agent: error.agentName } : {}),
364
+ ...(error.turnId !== undefined ? { turnId: error.turnId } : {}),
365
+ ...(error.step !== undefined ? { step: error.step } : {}),
366
+ ...(error.stepId !== undefined ? { stepId: error.stepId } : {}),
367
+ message: error.message,
368
+ };
369
+ const activeContext = session.liveContext(state.address) ?? context;
370
+ activeContext.record({
371
+ ...blocked,
372
+ ...(error.stage === "input" && !inputAccepted ? { input: [...messages] } : {}),
373
+ });
374
+ if (state.store === undefined)
375
+ void emitRunEvent(state, blocked);
376
+ }
377
+ throw error;
378
+ }
379
+ finally {
380
+ await this.settleRun(session, state, context);
381
+ }
382
+ }
383
+ /**
384
+ * Chain the capabilities' run-tier input hooks. Each sees the previous one's rewrite; a hook
385
+ * that throws is skipped (fault isolation — a broken capability must not sink the prompt).
386
+ */
387
+ async applyRunStarts(state, agentName, input) {
388
+ let current = input;
389
+ for (const hook of state.capabilities.runStarts) {
390
+ try {
391
+ const result = await hook({
392
+ sessionId: state.sessionId,
393
+ address: state.address,
394
+ agent: agentName,
395
+ signal: state.signal,
396
+ input: current,
397
+ });
398
+ // First claim wins: once a hook answers the prompt there is nothing left to rewrite.
399
+ if (result?.handled !== undefined)
400
+ return { input: [...current], handled: result.handled };
401
+ if (result?.input !== undefined)
402
+ current = result.input;
403
+ }
404
+ catch (error) {
405
+ emitRunEvent(state, {
406
+ type: "warning",
407
+ message: `beforeRun hook failed; input left unchanged: ${error instanceof Error ? error.message : String(error)}`,
408
+ });
409
+ }
410
+ }
411
+ return { input: [...current] };
412
+ }
413
+ /**
414
+ * The run teardown invariant shared by execute() and resume(): flush the run's ACTIVE
415
+ * shard — not the entry `context`; a handoff during the run re-points `state.address`
416
+ * at a new shard (session.setLiveContext), and that shard's context is what holds the
417
+ * run's latest unflushed writes — then stop capabilities and surface their diagnostics.
418
+ */
419
+ async settleRun(session, state, context) {
420
+ await (session.liveContext(state.address) ?? context).flush();
421
+ await state.capabilities.stop();
422
+ await session.flushEvents();
423
+ this.reportDiagnostics(state);
424
+ }
425
+ async beginRun(session, opts, interruption, initialAddress = DEFAULT_ADDRESS) {
426
+ // Per-run cancel handle, downstream of the caller's (or the session's) signal. Capabilities
427
+ // that abort stop THIS run — the session stays usable for the next prompt — while an
428
+ // upstream abort still tears the run down. `AbortSignal.any` owns the listener lifetime.
429
+ const runController = new AbortController();
430
+ const upstream = opts?.signal ?? session.signal;
431
+ const signal = AbortSignal.any([upstream, runController.signal]);
432
+ const ctx = {
433
+ sessionId: session.id,
434
+ machine: session.machine,
435
+ store: session.store,
436
+ events: session.events,
437
+ signal,
438
+ steer: session.steer,
439
+ responder: session.responder,
440
+ background: session.background,
441
+ logger: session.logger,
442
+ // Same session controls, except `abort` is scoped to this run rather than the session.
443
+ controls: {
444
+ ...session.controls(),
445
+ abort: (reason) => {
446
+ if (!runController.signal.aborted)
447
+ runController.abort(abortReason(reason ?? "run aborted by a capability"));
448
+ },
449
+ },
450
+ };
451
+ const capabilities = await assembleCapabilities(session.capabilities, ctx);
452
+ const permission = session.permission;
453
+ const frame = interruption?.frames[interruption.rootFrameId];
454
+ const state = {
455
+ runId: interruption?.runId ?? newInterruptionId("run"),
456
+ frameId: frame?.frameId ?? newInterruptionId("frame"),
457
+ agentInstanceId: frame?.agentInstanceId ?? "root",
458
+ sessionId: session.id,
459
+ session,
460
+ context: opts?.context,
461
+ signal,
462
+ usage: frame?.execution.usage ?? emptyUsage(),
463
+ turns: frame?.execution.turns ?? 0,
464
+ maxTurns: frame?.execution.maxTurns ?? opts?.maxTurns ?? this.config.maxTurns ?? 16,
465
+ address: frame?.address ?? initialAddress,
466
+ events: session.events,
467
+ machine: session.machine,
468
+ store: session.store,
469
+ responder: session.responder,
470
+ background: session.background,
471
+ subagentProvider: this.config.subagentProvider,
472
+ ...(this.config.maxConcurrentSubagents !== undefined ? { maxConcurrentSubagents: this.config.maxConcurrentSubagents } : {}),
473
+ workflowTool: this.config.workflowTool,
474
+ permission,
475
+ capabilities,
476
+ steer: session.steer,
477
+ answers: frame ? { ...frame.decisions } : undefined,
478
+ inputAnswers: frame?.inputAnswers,
479
+ interruption,
480
+ currentTurnId: frame?.turnId,
481
+ };
482
+ // Emit any session-tier diagnostics (openSession failures) once, on first run.
483
+ for (const diagnostic of session.drainDiagnostics()) {
484
+ const message = `[capability ${diagnostic.capability}/${diagnostic.phase}] ${diagnostic.message}`;
485
+ emitRunEvent(state, diagnostic.level === "error" ? { type: "error", message } : { type: "warning", message });
486
+ }
487
+ return state;
488
+ }
489
+ reportDiagnostics(state) {
490
+ for (const diagnostic of state.capabilities.diagnostics) {
491
+ const message = `[capability ${diagnostic.capability}/${diagnostic.phase}] ${diagnostic.message}`;
492
+ emitRunEvent(state, diagnostic.level === "error" ? { type: "error", message } : { type: "warning", message });
493
+ }
494
+ }
495
+ }
496
+ /**
497
+ * The engine that actually runs an agent. `run` is the loop; it holds no run state —
498
+ * everything flows through `(agent, context, state)`, and its only tie to the Runner is
499
+ * the shared `RunnerConfig`. `Runner.run`/`resume` build a default runtime and call
500
+ * `engine.run`; a tool (subagent / Agent / Workflow) that holds a runtime calls it too,
501
+ * so "run an agent" is one engine call, not a privilege reached out of the Runner.
502
+ */
503
+ class Engine {
504
+ config;
505
+ constructor(config) {
506
+ this.config = config;
507
+ }
508
+ async run(initial, context, state, resumeFrom,
509
+ /**
510
+ * Let the FIRST iteration drain queued follow-ups. Set only for a wake run — one started
511
+ * with no input precisely to consume what is already queued (a settled background task, a
512
+ * cron fire). The usual bar against draining on iteration one exists so a follow-up is not
513
+ * merged into the caller's prompt; with no prompt there is nothing to merge into, and
514
+ * refusing to drain would run a turn with no new input at all.
515
+ */
516
+ drainQueuedAtStart) {
517
+ let messages = context.messages; // replaced only when a handoff opens a fresh root shard
518
+ let current = initial;
519
+ let resume = resumeFrom;
520
+ let canDrainFollowUps = drainQueuedAtStart === true;
521
+ emitRunEvent(state, { type: "agent.started", agent: current.name, ...(state.parentToolCallId ? { parentToolCallId: state.parentToolCallId } : {}) });
522
+ while (true) {
523
+ state.signal.throwIfAborted();
524
+ const resumingInterruptedTurn = resume !== undefined;
525
+ if (!resumingInterruptedTurn) {
526
+ if (state.turns >= state.maxTurns) {
527
+ return this.finish(state, "max_turns", current, messages);
528
+ }
529
+ state.turns += 1;
530
+ }
531
+ // A follow-up belongs after work that has already run. In particular, never drain one
532
+ // on the first iteration (where it would be merged into the initial prompt) or at the
533
+ // start of an interrupted-turn resume. The prior iteration's terminal path decides
534
+ // whether to loop; this next iteration consumes the queued prompts as its new input.
535
+ // Deliberately NOT reset on handoff: the pre-handoff agent's turn already ran, so the
536
+ // target agent's first iteration draining a queued follow-up still honors this rule.
537
+ if (canDrainFollowUps) {
538
+ for (const { id, message, origin } of state.steer.drainFollowUps()) {
539
+ context.appendMessage(message, steerOriginToPromptOrigin(origin, id));
540
+ }
541
+ }
542
+ // Fresh turns append durable reminders to the context tail. HITL resume continues the
543
+ // already-framed model turn: injecting here would separate its assistant tool call from
544
+ // the resumed tool result and would change the cached request prefix.
545
+ const injectionTokens = resumingInterruptedTurn ? new Map() : injectAtTurnBoundary(state, context);
546
+ const model = await this.resolveModelFor(current, state);
547
+ const system = await current.resolveInstructions(runCtxFor(state));
548
+ // The engine's run loop rides into the toolset as a plain callback: the spawner the
549
+ // subagent/Agent/Workflow tools share calls it to run child agents.
550
+ const toolset = await buildRunTools(current, state, (agent, childContext, childState, childResume) => this.run(agent, childContext, childState, childResume), model);
551
+ const hooks = buildRunHooks(current, state, context, toolset.tools);
552
+ const visibleTools = activeDeferredTools(toolset.tools, toolset.deferredToolNames, context.messages);
553
+ // Stamp a context-window breakdown snapshot from exactly what this turn will send, so
554
+ // `session.getContextBreakdown()` (and the app-server RPC) can report where tokens go.
555
+ state.session.recordContextBreakdown(computeContextBreakdown({
556
+ model,
557
+ system,
558
+ tools: visibleTools,
559
+ messages: context.messages,
560
+ injectionTokens,
561
+ compactBufferTokens: state.session.compaction?.reservedContextTokens ?? 0,
562
+ capturedAt: Date.now(),
563
+ }));
564
+ const turnId = state.currentTurnId ?? `${state.sessionId}-t${state.turns}`;
565
+ const outputGuardrails = current.guardrails.output ?? [];
566
+ if (resume === undefined)
567
+ emitRunEvent(state, { type: "turn.started", turnId });
568
+ state.steer.beginTurn(turnId);
569
+ let r;
570
+ try {
571
+ r = await runTurn({
572
+ turnId,
573
+ address: state.address,
574
+ sessionId: state.sessionId,
575
+ signal: state.signal,
576
+ model,
577
+ machine: state.machine,
578
+ background: state.background,
579
+ responder: state.responder,
580
+ // Per-address ledger: main agent and each subagent line keep independent
581
+ // read-before-write state that survives across turns and run() calls.
582
+ fileLedger: state.session.fileLedgerFor(state.address),
583
+ system,
584
+ context,
585
+ tools: toolset.tools,
586
+ deferredToolNames: toolset.deferredToolNames,
587
+ hooks,
588
+ params: resolveModelParams(current.modelSettings, state.session.thinkingSetting),
589
+ createOutputGuardrailMonitor: outputGuardrails.length > 0
590
+ ? (options) => createOutputGuardrailMonitor(outputGuardrails, current, runCtxFor(state), options)
591
+ : undefined,
592
+ maxSteps: current.maxStepsPerTurn ?? this.config.maxStepsPerTurn,
593
+ maxRetriesPerStep: this.config.maxRetriesPerStep,
594
+ drainSteering: () => state.steer.drainSteering().map((s) => ({ message: s.message, origin: steerOriginToPromptOrigin(s.origin, s.id) })),
595
+ // One sink: the loop dispatches real AgentEvent bodies; we only add the envelope.
596
+ dispatchEvent: (body) => void emitRunEvent(state, body),
597
+ logger: state.session.logger,
598
+ resumeFrom: resume,
599
+ resume: resume !== undefined ? frameResume(state) : undefined,
600
+ });
601
+ }
602
+ catch (error) {
603
+ // The turn we opened above must not end without a `turn.ended` — a streaming consumer
604
+ // would otherwise see the event stream truncate with nothing to say it stopped, and a
605
+ // client waiting on this turn would wait forever. A guardrail tripwire is the one throw
606
+ // that already carries its own terminal frame (`guardrail.blocked`, emitted by the
607
+ // outer handler), so we leave it be; everything else is closed here before it propagates.
608
+ // An aborted signal is a cancel, not a failure; anything else is a genuine failure and
609
+ // carries its message so a later reader learns why, not just that it stopped.
610
+ if (!isGuardrailTripwireError(error)) {
611
+ const aborted = state.signal.aborted || isAbortError(error);
612
+ emitRunEvent(state, {
613
+ type: "turn.ended",
614
+ turnId,
615
+ reason: aborted ? "cancelled" : "failed",
616
+ ...(aborted ? {} : { error: error instanceof Error ? error.message : String(error) }),
617
+ contextWindow: model.contextWindow,
618
+ });
619
+ }
620
+ throw error;
621
+ }
622
+ finally {
623
+ state.steer.endTurn();
624
+ }
625
+ canDrainFollowUps = true;
626
+ resume = undefined;
627
+ state.currentTurnId = undefined;
628
+ state.usage = addUsage(state.usage, r.usage);
629
+ // Audit record: per-turn cost, journaled in order with the message stream (not history).
630
+ context.record({ type: "usage.record", model: model.id, usage: r.usage, total: state.usage });
631
+ if (state.store === undefined)
632
+ emitRunEvent(state, { type: "usage.updated", usage: state.usage });
633
+ if (r.stopReason === "interrupt") {
634
+ const pending = r.pending ?? [];
635
+ const suspensions = r.suspensions ?? [];
636
+ // Live: an injected Responder that answers approvals inline does so in place, then we
637
+ // resume in memory. When no responder is present, or it reports it isn't a live approver
638
+ // (`isLiveApprover() === false`), we fall through to the durable pause — this is the
639
+ // "no live responder ⇒ durable" rule. Child suspensions have already gone through the same
640
+ // responder, so a live responder only needs to answer this frame's direct approvals.
641
+ // Tool input suspensions always go durable: a tool that wanted a live answer would have
642
+ // used the responder channel instead of suspending.
643
+ const approvals = pending.filter((p) => p.kind === "approval");
644
+ if (pending.length > 0 && approvals.length === pending.length && suspensions.length === 0 && state.responder && (state.responder.isLiveApprover?.() ?? true)) {
645
+ const answers = {};
646
+ for (const p of approvals) {
647
+ // A batch can contain several approval-required tools. Stop must end the
648
+ // currently visible request without advancing to the next one in the batch.
649
+ if (state.signal.aborted)
650
+ return this.finish(state, "aborted", current, messages);
651
+ const answer = await state.responder.requestApproval({
652
+ toolCallId: p.toolCallId,
653
+ toolName: p.toolName,
654
+ approvalRule: p.approvalRule,
655
+ display: p.display,
656
+ }, { signal: state.signal });
657
+ if (state.signal.aborted)
658
+ return this.finish(state, "aborted", current, messages);
659
+ answers[p.toolCallId] = answer;
660
+ }
661
+ // Continue the SAME model turn in this loop with the pending batch pre-answered — a
662
+ // loop, not recursion, so memory stays flat across many live-approval rounds and the
663
+ // still-running agent does not re-emit `agent.started`.
664
+ state.answers = { ...state.answers, ...answers };
665
+ state.currentTurnId = turnId;
666
+ resume = lastAssistant(messages);
667
+ // Mirror the reset a fresh run() entry would have done: a resumed interrupted turn
668
+ // must not drain follow-ups at its start (see the drain rule above).
669
+ canDrainFollowUps = false;
670
+ continue;
671
+ }
672
+ return pauseRun(current, context, pending, suspensions, state, turnId);
673
+ }
674
+ emitRunEvent(state, {
675
+ type: "turn.ended",
676
+ turnId,
677
+ // A turn can settle on an error without throwing — a model that returns an error stop,
678
+ // an unclaimed context overflow. That is a failed turn, not a completed one, and saying
679
+ // "completed" would be the same silent lie a missing `turn.ended` is.
680
+ reason: r.stopReason === "error" ? "failed" : "completed",
681
+ contextWindow: model.contextWindow,
682
+ });
683
+ if (r.stopReason === "handoff" && r.handoff) {
684
+ const next = await performHandoff(current, context, r.handoff, state);
685
+ if (!next)
686
+ return this.finish(state, "error", current, messages);
687
+ current = next.agent;
688
+ context = next.context;
689
+ messages = context.messages;
690
+ continue;
691
+ }
692
+ // Terminal stop reasons.
693
+ if (r.stopReason === "end_turn") {
694
+ // A follow-up that landed during this turn (a background task finished, a cron fired)
695
+ // makes the agent run one more turn to consume it instead of stopping — the boundary
696
+ // drain above injects it. User steers can't reach here: runTurn keeps them in-turn.
697
+ if (state.steer.hasFollowUps())
698
+ continue;
699
+ // wants another turn, loop (re-injecting at the boundary) instead of finishing.
700
+ if (await this.shouldContinueAtBoundary(state, model, r.usage))
701
+ continue;
702
+ }
703
+ return this.finish(state, mapTerminalStatus(r.stopReason), current, messages);
704
+ }
705
+ }
706
+ finish(state, status, agent, history) {
707
+ // Snapshot: RunResult.messages must not alias the LIVE context array, or a later turn
708
+ // (or a caller mutating the result) would corrupt the other side.
709
+ const messages = [...history];
710
+ emitRunEvent(state, { type: "agent.ended", agent: agent.name });
711
+ const output = finalText(messages);
712
+ let outputParsed;
713
+ let outputParseError;
714
+ if (agent.outputType && output) {
715
+ const parsed = tryParseOutput(agent.outputType, output);
716
+ outputParsed = parsed.value;
717
+ outputParseError = parsed.error;
718
+ if (parsed.error !== undefined) {
719
+ emitRunEvent(state, { type: "warning", message: `Agent "${agent.name}" outputType rejected the final output: ${parsed.error}` });
720
+ }
721
+ }
722
+ return {
723
+ status,
724
+ finalAgent: agent.name,
725
+ activeAddress: state.address,
726
+ output,
727
+ outputParsed,
728
+ ...(outputParseError !== undefined ? { outputParseError } : {}),
729
+ messages,
730
+ usage: state.usage,
731
+ };
732
+ }
733
+ async shouldContinueAtBoundary(state, model, usage) {
734
+ for (const hook of state.capabilities.boundaryContinuations) {
735
+ const result = await hook({
736
+ turnId: `${state.sessionId}-t${state.turns}`,
737
+ stepNumber: state.turns,
738
+ usage,
739
+ stopReason: "end_turn",
740
+ signal: state.signal,
741
+ model,
742
+ });
743
+ if (result?.continue === true)
744
+ return true;
745
+ }
746
+ return false;
747
+ }
748
+ async resolveModelFor(agent, state) {
749
+ const model = state.session.modelSetting ?? agent.model;
750
+ if (!model)
751
+ throw new Error(`Agent "${agent.name}" has no model.`);
752
+ if (typeof model !== "string")
753
+ return model;
754
+ if (!this.config.resolveModel) {
755
+ throw new Error(`Agent "${agent.name}" uses model id "${model}" but no resolveModel was configured.`);
756
+ }
757
+ return this.config.resolveModel(model);
758
+ }
759
+ }
760
+ // Pure helpers.
761
+ /**
762
+ * The paused frame's batch-resume payload (pending entries + input answers), consumed by the
763
+ * tool-call layer when re-running the interrupted batch: answered suspended calls get their
764
+ * continuation, unanswered ones re-park. Live in-memory resumes have no reified frame → undefined.
765
+ */
766
+ function frameResume(state) {
767
+ const frame = state.interruption?.frames[state.frameId];
768
+ if (!frame)
769
+ return undefined;
770
+ return { pending: frame.pending, inputAnswers: state.inputAnswers ?? {} };
771
+ }
772
+ function toMessages(input) {
773
+ if (typeof input === "string") {
774
+ return [{ role: "user", content: [{ type: "text", text: input }], timestamp: Date.now() }];
775
+ }
776
+ return [...input];
777
+ }
778
+ /** Combine optional signals: the result aborts when either does. */
779
+ function mergeSignals(a, b) {
780
+ if (a === undefined)
781
+ return b;
782
+ if (b === undefined)
783
+ return a;
784
+ return AbortSignal.any([a, b]);
785
+ }
786
+ //# sourceMappingURL=runner.js.map