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,937 @@
1
+ import { FileFreshnessLedger } from "../tool/file-freshness.js";
2
+ import { PermissionManager } from "../permission/manager.js";
3
+ import { STAGED_POLICY_SLOTS } from "../permission/policies.js";
4
+ import { NullMachine } from "../tool/machine-null.js";
5
+ import { joinAddress, ListenerSink, SessionEventPublisher, } from "../events/index.js";
6
+ import { envLogger, noopLogger } from "../logging/index.js";
7
+ import { DEFAULT_ADDRESS } from "../store/index.js";
8
+ import { eventSinkTracingBridge } from "../tracing/index.js";
9
+ import { ConversationContext } from "../loop/context.js";
10
+ import { readLog } from "../capabilities/capability-state.js";
11
+ import { SteerBus, steerOriginToPromptOrigin } from "../loop/steer.js";
12
+ import {} from "./subagent.js";
13
+ import { SystemPromptContextCache } from "./instruction-context.js";
14
+ let CLOSE_TIMEOUT_MS = 5_000;
15
+ /** store.flush persists data (vs. telemetry), so it gets a longer grace. The run journal
16
+ * is already settled by settleRun's context.flush() before close — this is only a
17
+ * best-effort tail sync of whatever the store implementation buffers itself. */
18
+ let STORE_FLUSH_TIMEOUT_MS = 15_000;
19
+ /** Test-only (exported via `operon-agents-core/internal`): shrink the close deadlines
20
+ * so hang-isolation tests don't wait wall-clock seconds. */
21
+ export function setSessionCloseTimeoutsForTest(ms) {
22
+ if (ms.close !== undefined)
23
+ CLOSE_TIMEOUT_MS = ms.close;
24
+ if (ms.storeFlush !== undefined)
25
+ STORE_FLUSH_TIMEOUT_MS = ms.storeFlush;
26
+ }
27
+ let sessionCounter = 0;
28
+ export function newSessionId() {
29
+ sessionCounter += 1;
30
+ return `s${Date.now().toString(36)}-${sessionCounter.toString(36)}`;
31
+ }
32
+ /**
33
+ * Thrown by `Session`'s capability-backed convenience methods when the capability they
34
+ * wrap is not open on this session. Detect with `instanceof`; `capability` names the
35
+ * missing one. The probe tier never throws — the getters (`session.cron`, `.goal`, …)
36
+ * return `undefined` instead.
37
+ */
38
+ export class CapabilityMissingError extends Error {
39
+ capability;
40
+ constructor(capability) {
41
+ super(`Session has no open "${capability}" capability.`);
42
+ this.name = "CapabilityMissingError";
43
+ this.capability = capability;
44
+ }
45
+ }
46
+ /**
47
+ * Capability access on a session has two tiers, one rule each:
48
+ * - PROBE — the service getters (`session.cron`, `.goal`, `.plan`, `.backgroundManager`,
49
+ * `.mcp`, …) return `undefined` when that capability is not open. Use these to feature-test.
50
+ * - REQUIRE — the convenience wrappers (`createCronTask()`, `compact()`, `listSkills()`, …)
51
+ * assume the capability and throw {@link CapabilityMissingError} when it is missing.
52
+ * The only exceptions are list views documented as degrading to empty when the capability
53
+ * is off (`listWorkflows`, `listSubagents`, `listMcpServers`) — views over durable state
54
+ * that stay meaningful on a session opened without the capability.
55
+ */
56
+ export class Session {
57
+ id;
58
+ machine;
59
+ store;
60
+ events;
61
+ eventPublisher;
62
+ responder;
63
+ permissionOptions;
64
+ /** Session-lived permission manager: one policy chain + approval memory +
65
+ * mode for the whole session. Constructed in `openCapabilities` (needs capability policy
66
+ * slots and the replayed log); runs reference it instead of building their own. */
67
+ _permission;
68
+ steer;
69
+ signal;
70
+ /** Upstream of `signal`. Fires only via `abort()`; a host signal aborts independently. */
71
+ ownController;
72
+ logger;
73
+ tracing;
74
+ unsubscribeTracing;
75
+ injectedBackground;
76
+ allCapabilities;
77
+ services = new Map();
78
+ // Runtime prompt data is live-Session state, not Agent state: machine identity + cwd isolate
79
+ // root/subagent/worktree frames, and the date stays fixed for the Session's lifetime.
80
+ systemPromptContexts = new SystemPromptContextCache();
81
+ // Live in-memory conversation context per address, kept across turns so a long-lived session
82
+ // appends instead of replaying the whole log each turn. Invalidated when the log is rewritten.
83
+ liveContexts = new Map();
84
+ /** Inboxes of frames currently running under this session, keyed by journal address. */
85
+ frameBuses = new Map();
86
+ // Rebuildable cache of the leaf reached by following durable `agent.handoff` records from
87
+ // `main`. Storeless sessions keep the same state here for their in-memory lifetime.
88
+ activeConversationHead;
89
+ // File freshness ledger per address (mirrors liveContexts): each agent line — main agent and
90
+ // every subagent — has its own read-before-write state, persisted across turns/runs. A subagent
91
+ // has not "read" what its parent read, so ledgers are never shared across addresses.
92
+ fileLedgers = new Map();
93
+ modelOverride;
94
+ /** Caller-supplied one-shot log for open (see SessionConfig.preloadedLog); cleared after
95
+ * openCapabilities so the array itself is not pinned for the session's lifetime. */
96
+ preloadedLog;
97
+ thinkingOverride;
98
+ openedCapabilities = [];
99
+ isOpen = false;
100
+ runChain = Promise.resolve();
101
+ pendingDiagnostics = [];
102
+ // Most-recent per-turn context-window breakdown, stamped by the Runner at each turn boundary.
103
+ // Undefined until the first turn assembles a request.
104
+ lastContextBreakdown;
105
+ constructor(cfg, id, eventPublisher, steer, signal, machine, ownController) {
106
+ this.id = id;
107
+ this.machine = machine;
108
+ this.ownController = ownController;
109
+ this.eventPublisher = eventPublisher;
110
+ this.store = eventPublisher.store;
111
+ this.events = eventPublisher;
112
+ this.tracing = cfg.tracing;
113
+ this.unsubscribeTracing = cfg.tracing === undefined ? undefined : eventSinkTracingBridge(this.events, cfg.tracing);
114
+ this.responder = cfg.responder;
115
+ this.permissionOptions = cfg.permission;
116
+ this.steer = steer;
117
+ // Every enqueue — user steer/follow-up, cron fire, background settle — surfaces on the
118
+ // event stream, so clients can render a pending queue and later match `origin.steerId`
119
+ // on the consuming `message.appended` to know when the model actually saw it.
120
+ steer.setEnqueueListener((item, channel) => {
121
+ void this.events.emit({
122
+ type: "steer.queued",
123
+ steerId: item.id,
124
+ channel,
125
+ origin: steerOriginToPromptOrigin(item.origin, item.id),
126
+ message: item.message,
127
+ address: "main",
128
+ sessionId: id,
129
+ });
130
+ });
131
+ this.injectedBackground = cfg.background;
132
+ this.signal = signal;
133
+ // Env fallback (`AGENTS_LOG`) is resolved here so every entry point — direct `Session.open`,
134
+ // the Runner's ephemeral session, or the harness — honors it from one place.
135
+ this.logger = cfg.logger ?? envLogger() ?? noopLogger;
136
+ this.allCapabilities = cfg.capabilities ?? [];
137
+ this.preloadedLog = cfg.preloadedLog;
138
+ }
139
+ static async open(cfg) {
140
+ const events = cfg.events ?? new ListenerSink();
141
+ const steer = cfg.steer ?? new SteerBus();
142
+ // The session owns a cancel handle of its own, downstream of whatever the host passed in:
143
+ // `session.abort()` stops the session without taking the host's signal away from it, and a
144
+ // host abort still propagates. `AbortSignal.any` owns the listener lifetime for us.
145
+ const ownController = new AbortController();
146
+ const signal = cfg.signal === undefined
147
+ ? ownController.signal
148
+ : AbortSignal.any([cfg.signal, ownController.signal]);
149
+ const id = cfg.sessionId ?? newSessionId();
150
+ const eventPublisher = new SessionEventPublisher(id, events, cfg.store, cfg.eventPublication ?? "immediate");
151
+ const machine = await resolveMachine(cfg, { sessionId: id, signal });
152
+ const session = new Session(cfg, id, eventPublisher, steer, signal, machine, ownController);
153
+ await session.openCapabilities();
154
+ return session;
155
+ }
156
+ async openCapabilities() {
157
+ // Shared restore: read the log at most once and
158
+ // let every log-fold capability (goal/plan/todo) reconstruct from that one read via
159
+ // `readSessionLog(ctx)`, then reuse it to pre-build the main conversation context — instead
160
+ // of each capability, plus the first run's `replayContext`, re-reading the log separately.
161
+ // A caller-preloaded log (SessionConfig.preloadedLog) IS that one read, done outside.
162
+ let log = this.preloadedLog;
163
+ this.preloadedLog = undefined;
164
+ const logRecords = async () => {
165
+ if (log === undefined)
166
+ log = await readLog(this.store);
167
+ return log;
168
+ };
169
+ const ctx = {
170
+ sessionId: this.id,
171
+ machine: this.machine,
172
+ store: this.store,
173
+ events: this.events,
174
+ signal: this.signal,
175
+ steer: this.steer,
176
+ controls: this.controls(),
177
+ logRecords,
178
+ };
179
+ const opened = [];
180
+ const seen = new Set();
181
+ for (const cap of this.allCapabilities) {
182
+ if (seen.has(cap.name)) {
183
+ this.pendingDiagnostics.push({
184
+ capability: cap.name,
185
+ phase: "register",
186
+ level: "error",
187
+ message: `duplicate capability name "${cap.name}"; second registration skipped.`,
188
+ });
189
+ continue;
190
+ }
191
+ seen.add(cap.name);
192
+ try {
193
+ if (cap.openSession)
194
+ await cap.openSession(ctx);
195
+ }
196
+ catch (error) {
197
+ // per-run assembly too, since it isn't pushed onto `opened`.
198
+ this.pendingDiagnostics.push({
199
+ capability: cap.name,
200
+ phase: "start",
201
+ level: "error",
202
+ message: `openSession failed; capability absent for the session: ${messageOf(error)}`,
203
+ });
204
+ this.logger.log("error", `capability "${cap.name}" openSession failed`, { capability: cap.name, phase: "start", error: messageOf(error) });
205
+ continue;
206
+ }
207
+ opened.push(cap);
208
+ if (cap.service !== undefined)
209
+ this.services.set(cap.name, cap.service);
210
+ }
211
+ this.openedCapabilities = opened;
212
+ await this.buildPermissionManager(opened, logRecords);
213
+ // If a capability triggered the log read, reuse those records to seed the main live
214
+ // context so the first run appends to it instead of replaying the log a second time.
215
+ if (log !== undefined && this.store !== undefined && this.liveContext(DEFAULT_ADDRESS) === undefined) {
216
+ const context = new ConversationContext({
217
+ store: this.store,
218
+ address: DEFAULT_ADDRESS,
219
+ });
220
+ context.loadFromRecords([...log]);
221
+ this.setLiveContext(DEFAULT_ADDRESS, context);
222
+ }
223
+ this.isOpen = true;
224
+ }
225
+ /**
226
+ * Construct the session-lived PermissionManager: capability policy slots are collected from
227
+ * the opened capabilities' static `policies` (session-tier fault isolation: a capability whose
228
+ * `openSession` failed contributes nothing; a per-run `start()` failure does NOT retract its
229
+ * policies — they are pure evaluators over session-lived state). Then runtime permission
230
+ * state is folded back from the log — `permission.set_mode` (last wins) and approve-for-session
231
+ * grants (`permission.record_approval` with scope "session").
232
+ */
233
+ async buildPermissionManager(opened, logRecords) {
234
+ const overrides = new Map();
235
+ for (const capability of opened) {
236
+ for (const policy of capability.policies ?? []) {
237
+ if (!STAGED_POLICY_SLOTS.has(policy.name)) {
238
+ this.pendingDiagnostics.push({
239
+ capability: capability.name,
240
+ phase: "register",
241
+ level: "warn",
242
+ message: `policy "${policy.name}" matches no reserved staged slot; ignored.`,
243
+ });
244
+ continue;
245
+ }
246
+ if (overrides.has(policy.name)) {
247
+ this.pendingDiagnostics.push({
248
+ capability: capability.name,
249
+ phase: "register",
250
+ level: "warn",
251
+ message: `policy slot "${policy.name}" already filled; "${capability.name}" duplicate ignored.`,
252
+ });
253
+ continue;
254
+ }
255
+ overrides.set(policy.name, policy);
256
+ }
257
+ }
258
+ this._permission = new PermissionManager({
259
+ ...this.permissionOptions,
260
+ mode: this.permissionOptions?.mode,
261
+ // The Runner-driven path answers approvals via interrupt/resume (or the live responder
262
+ // in onInterrupt) — never inline through the manager, so it gets no responder here.
263
+ responder: undefined,
264
+ cwd: this.permissionOptions?.cwd ?? safeCwd(this.machine),
265
+ pathClass: this.permissionOptions?.pathClass ?? this.machine.pathClass(),
266
+ machine: this.permissionOptions?.machine ?? this.machine,
267
+ policyOverrides: overrides,
268
+ logger: this.logger,
269
+ });
270
+ if (this.store === undefined)
271
+ return;
272
+ for (const record of await logRecords()) {
273
+ if (record.type === "permission.set_mode") {
274
+ this._permission.setMode(record.mode);
275
+ }
276
+ else if (record.type === "permission.record_approval" &&
277
+ record.decision === "approved" &&
278
+ record.scope === "session" &&
279
+ record.approvalRule !== undefined) {
280
+ this._permission.applyApproval(record.approvalRule, { decision: "approved", scope: "session" });
281
+ }
282
+ }
283
+ }
284
+ /** The session-lived permission manager (policy chain + mode + approval memory). */
285
+ get permission() {
286
+ return this._permission;
287
+ }
288
+ get capabilities() {
289
+ return this.openedCapabilities;
290
+ }
291
+ service(name) {
292
+ return this.services.get(name);
293
+ }
294
+ /** The REQUIRE tier (see the class doc): unwrap a probed service or throw the typed error. */
295
+ requireCapability(service, name) {
296
+ if (service === undefined)
297
+ throw new CapabilityMissingError(name);
298
+ return service;
299
+ }
300
+ get goal() {
301
+ return this.services.get("goal");
302
+ }
303
+ get workflow() {
304
+ return this.services.get("workflow");
305
+ }
306
+ get skills() {
307
+ return this.services.get("skills");
308
+ }
309
+ get plugins() {
310
+ return this.services.get("plugins");
311
+ }
312
+ get backgroundManager() {
313
+ return this.services.get("background");
314
+ }
315
+ get plan() {
316
+ return this.services.get("plan");
317
+ }
318
+ get compaction() {
319
+ return this.services.get("compaction");
320
+ }
321
+ get mcp() {
322
+ return this.services.get("mcp");
323
+ }
324
+ get background() {
325
+ return this.services.get("background") ?? this.injectedBackground;
326
+ }
327
+ async listBackgroundTasks(options = {}) {
328
+ const background = this.requireCapability(this.backgroundManager, "background");
329
+ return background.list(options.activeOnly ?? false, options.limit);
330
+ }
331
+ /** Past BACKGROUND workflow runs (newest first), from the durable task store. A foreground
332
+ * workflow is a plain `Workflow` tool call — its record is the conversation plus its journal
333
+ * shard — so it is not listed here (its shard stays resumable by runId). */
334
+ async listWorkflows() {
335
+ const manager = this.backgroundManager;
336
+ if (manager === undefined)
337
+ return [];
338
+ const runs = [];
339
+ for (const info of manager.list(false)) {
340
+ const snap = taskToWorkflowSnapshot(info);
341
+ if (snap !== undefined)
342
+ runs.push(snap);
343
+ }
344
+ runs.sort((a, b) => (a.startedAt < b.startedAt ? 1 : a.startedAt > b.startedAt ? -1 : 0));
345
+ return runs;
346
+ }
347
+ /** One background workflow run's snapshot by runId, or undefined if unknown. */
348
+ async getWorkflow(runId) {
349
+ return (await this.listWorkflows()).find((run) => run.runId === runId);
350
+ }
351
+ /** The most-recent context-window breakdown (system/tools/messages/injections/free), stamped
352
+ * by the Runner at each turn boundary — or undefined if no turn has assembled a request yet.
353
+ * A read-only snapshot: it reflects the last turn sent, not a fresh recomputation. */
354
+ getContextBreakdown() {
355
+ return this.lastContextBreakdown;
356
+ }
357
+ /** Runner-internal: record the breakdown assembled for the turn about to be sent. */
358
+ recordContextBreakdown(breakdown) {
359
+ this.lastContextBreakdown = breakdown;
360
+ }
361
+ /** The background subagents of this session, from the durable task store (live + reconciled
362
+ * ghosts). Foreground subagents are plain `Agent` tool calls — their record is the conversation
363
+ * plus their own shard — so they are not listed here (their shard stays resumable by id). */
364
+ async listSubagents() {
365
+ const manager = this.backgroundManager;
366
+ if (manager === undefined)
367
+ return [];
368
+ const records = [];
369
+ for (const info of manager.list(false)) {
370
+ const record = taskToSubagentRecord(info);
371
+ if (record !== undefined)
372
+ records.push(record);
373
+ }
374
+ return records;
375
+ }
376
+ /**
377
+ * Reclassify orphaned background work (spawned by a dead process, never settled) as `lost`
378
+ * through the task store: the manager writes the terminal status back and steers the lost
379
+ * notification (the durable settle record), so later opens won't re-report. Also emits a warning
380
+ * per reclassified subagent. Call when reopening an existing session. Returns the lost subagents
381
+ * (resume any with `Agent(resume="<id>", ...)`).
382
+ */
383
+ async reconcileSubagents() {
384
+ const manager = this.backgroundManager;
385
+ if (manager === undefined || this.store === undefined)
386
+ return [];
387
+ const lost = [];
388
+ for (const info of await manager.reconcile()) {
389
+ const record = taskToSubagentRecord(info);
390
+ if (record === undefined)
391
+ continue;
392
+ lost.push(record);
393
+ await this.emitControlEvent({
394
+ type: "warning",
395
+ message: `Background subagent "${record.agentId}" (${record.type}) was running when the previous process exited; marked lost. Resume with Agent(resume="${record.agentId}", ...).`,
396
+ });
397
+ }
398
+ return lost;
399
+ }
400
+ // ── Conversation log (flat, linear) ──────────────────────────────────────────────────────
401
+ // The log is a single append-only record stream per address (no branching). `getRecords`
402
+ // exposes it read-only for inspection / transcript rendering.
403
+ /** Every record of an address in append order (for rendering the transcript). */
404
+ async getRecords(address) {
405
+ if (this.store === undefined) {
406
+ throw new Error("Session has no store; the conversation log requires a durable store.");
407
+ }
408
+ const records = [];
409
+ for await (const record of this.store.readRecords({ ...(address !== undefined ? { address } : {}) }))
410
+ records.push(record);
411
+ return records;
412
+ }
413
+ // ── live context cache (perf: append across turns instead of replaying the log) ──
414
+ /** @internal The kept live context for an address, or undefined (cold → caller replays). */
415
+ liveContext(address) {
416
+ return this.liveContexts.get(address);
417
+ }
418
+ /** @internal Cache the live context so the next turn on this address reuses it. */
419
+ setLiveContext(address, ctx) {
420
+ this.liveContexts.set(address, ctx);
421
+ }
422
+ /**
423
+ * @internal Register a running frame's inbox so `steerTo` can reach it.
424
+ *
425
+ * Called when a subagent frame is forked; the returned function unregisters. Guarded by identity
426
+ * so a late unregister from a finished run cannot evict a newer frame that reused the address.
427
+ */
428
+ registerFrameBus(address, bus) {
429
+ this.frameBuses.set(address, bus);
430
+ return () => {
431
+ if (this.frameBuses.get(address) === bus)
432
+ this.frameBuses.delete(address);
433
+ };
434
+ }
435
+ /**
436
+ * Hand a message to the frame running at `address`; `false` when nobody is there.
437
+ *
438
+ * This is the whole seam an external coordinator needs in order to address a subagent: it can
439
+ * already learn who exists from `agent.started` / `agent.ended` (both carry `address`), but it
440
+ * has no way to reach a child's inbox — every frame owns a private `SteerBus`. Deliberately
441
+ * knows nothing about peers, rosters or visibility: those are policy, and policy belongs to
442
+ * whoever is coordinating, not to the engine.
443
+ */
444
+ steerTo(address, content, origin) {
445
+ const bus = address === DEFAULT_ADDRESS ? this.steer : this.frameBuses.get(address);
446
+ if (bus === undefined)
447
+ return false;
448
+ bus.steer(content, origin);
449
+ return true;
450
+ }
451
+ /** @internal Cached conversation owner. Durable sessions can always rebuild it from the log. */
452
+ conversationHead() {
453
+ return this.activeConversationHead;
454
+ }
455
+ /** @internal Update the cache only after the source-side handoff commit has been flushed. */
456
+ setConversationHead(head) {
457
+ this.activeConversationHead = head;
458
+ }
459
+ /** @internal Force the next prompt to fold the handoff chain again. */
460
+ invalidateConversationHead() {
461
+ this.activeConversationHead = undefined;
462
+ }
463
+ /** Drop the cached live context(s) so the next turn replays from the store (e.g. after a log
464
+ * rewrite, or an out-of-band store mutation). Omit `address` to clear all. */
465
+ invalidateLiveContext(address) {
466
+ if (address === undefined)
467
+ this.liveContexts.clear();
468
+ else
469
+ this.liveContexts.delete(address);
470
+ this.invalidateConversationHead();
471
+ }
472
+ /** The file freshness ledger for one agent line (address); created on first use and kept for
473
+ * the session lifetime, so read-before-write state survives across turns and run() calls. */
474
+ fileLedgerFor(address) {
475
+ let ledger = this.fileLedgers.get(address);
476
+ if (ledger === undefined) {
477
+ ledger = new FileFreshnessLedger();
478
+ this.fileLedgers.set(address, ledger);
479
+ }
480
+ return ledger;
481
+ }
482
+ /** Resolve environment + AGENTS.md for the active runtime frame, cached for this Session. */
483
+ resolveSystemPromptContext(machine) {
484
+ return this.systemPromptContexts.resolve(machine, this.compaction?.revision ?? 0);
485
+ }
486
+ /** A bounded view of the task's authoritative output, with explicit size/truncation metadata. */
487
+ async readBackgroundTaskOutput(taskId, options = {}) {
488
+ const background = this.requireCapability(this.backgroundManager, "background");
489
+ return background.readOutput(taskId, options.maxBytes ?? 16 * 1024);
490
+ }
491
+ /**
492
+ * Everything a task appended since `cursor` — what a live panel polls so each tick
493
+ * carries only what is new, instead of re-fetching the same window. `followable: false`
494
+ * means this task keeps no byte-addressable output; use `readBackgroundTaskOutput` instead.
495
+ */
496
+ async readBackgroundTaskOutputDelta(taskId, options) {
497
+ const background = this.requireCapability(this.backgroundManager, "background");
498
+ return background.readOutputDelta(taskId, options.cursor, options.maxBytes);
499
+ }
500
+ async stopBackgroundTask(taskId, reason) {
501
+ const background = this.requireCapability(this.backgroundManager, "background");
502
+ return background.stop(taskId, reason);
503
+ }
504
+ /**
505
+ * Move a running, detachable tool call (bash / subagent / workflow) from the foreground into
506
+ * a background task — the "move to background" action. Returns false if no such call is
507
+ * currently in its detachable window (already finished, or not a detachable tool).
508
+ */
509
+ detachTool(toolCallId) {
510
+ const background = this.requireCapability(this.backgroundManager, "background");
511
+ return background.detach(toolCallId);
512
+ }
513
+ /** Connected MCP servers and their status. Empty when no MCP capability is open. */
514
+ listMcpServers() {
515
+ return this.mcp?.list() ?? [];
516
+ }
517
+ /** Force-reconnect one MCP server by name. Throws if no MCP capability is open. */
518
+ async reconnectMcpServer(name) {
519
+ const mcp = this.requireCapability(this.mcp, "mcp");
520
+ await mcp.reconnect(name);
521
+ }
522
+ async createGoal(input) {
523
+ const goal = this.requireCapability(this.goal, "goal");
524
+ if (input.objective.trim().length === 0)
525
+ throw new Error("Goal objective cannot be empty.");
526
+ if (goal.has())
527
+ goal.update({ status: "complete" });
528
+ let snapshot = goal.update({
529
+ objective: input.objective.trim(),
530
+ completionCriterion: input.completionCriterion?.trim(),
531
+ status: "active",
532
+ });
533
+ if (input.budget !== undefined)
534
+ snapshot = goal.setBudget(normalizeGoalBudget(input.budget));
535
+ if (snapshot === null)
536
+ throw new Error("Goal was not created.");
537
+ await this.emitControlEvent({ type: "goal.updated", snapshot });
538
+ return snapshot;
539
+ }
540
+ async getGoal() {
541
+ const goal = this.requireCapability(this.goal, "goal");
542
+ return goal.snapshot();
543
+ }
544
+ async pauseGoal(options = {}) {
545
+ return this.updateExistingGoal("paused", options.reason);
546
+ }
547
+ async resumeGoal(options = {}) {
548
+ return this.updateExistingGoal("active", options.reason);
549
+ }
550
+ async cancelGoal(options = {}) {
551
+ const goal = this.requireCapability(this.goal, "goal");
552
+ const previous = goal.snapshot();
553
+ if (previous === null)
554
+ return null;
555
+ goal.update({ status: "complete", reason: options.reason });
556
+ await this.emitControlEvent({ type: "goal.updated", snapshot: null });
557
+ return previous;
558
+ }
559
+ async setGoalBudget(budget) {
560
+ const goal = this.requireCapability(this.goal, "goal");
561
+ const snapshot = goal.setBudget(normalizeGoalBudget(budget));
562
+ await this.emitControlEvent({ type: "goal.updated", snapshot });
563
+ return snapshot;
564
+ }
565
+ async setPlanMode(enabled, options = {}) {
566
+ const plan = this.requireCapability(this.plan, "plan");
567
+ if (enabled && !plan.isActive) {
568
+ await plan.enter(options.createFile ?? true);
569
+ }
570
+ else if (!enabled && plan.isActive) {
571
+ plan.exit();
572
+ }
573
+ const snapshot = await plan.data();
574
+ await this.emitControlEvent({ type: "plan.updated", snapshot });
575
+ return snapshot;
576
+ }
577
+ async getPlan() {
578
+ const plan = this.requireCapability(this.plan, "plan");
579
+ return plan.data();
580
+ }
581
+ async clearPlan() {
582
+ return this.setPlanMode(false);
583
+ }
584
+ /**
585
+ * The `SessionControls` view handed to capabilities that act on the session (the extension
586
+ * runtime's `ctx.actions`). Bound methods over the same public operations a host would call —
587
+ * no new reach, just a typed handle that does not leak the whole Session.
588
+ */
589
+ controls() {
590
+ return {
591
+ abort: (reason) => this.abort(reason),
592
+ compact: (options) => this.compact(options),
593
+ getContextBreakdown: () => this.getContextBreakdown(),
594
+ setModel: (model) => this.setModel(model),
595
+ setThinking: (level) => this.setThinking(level),
596
+ };
597
+ }
598
+ /**
599
+ * Cancel the session: every run riding `session.signal` unwinds as `status: "aborted"`.
600
+ * The reason is shaped as an `AbortError` so the loop classifies it as cancellation rather
601
+ * than as a failure (see `isAbortError`). Idempotent — a second call is a no-op.
602
+ */
603
+ abort(reason) {
604
+ if (this.ownController.signal.aborted)
605
+ return;
606
+ this.ownController.abort(abortReason(reason ?? "session aborted"));
607
+ }
608
+ async compact(options = {}) {
609
+ const compaction = this.requireCapability(this.compaction, "compaction");
610
+ return compaction.request(options);
611
+ }
612
+ async pendingCompaction() {
613
+ const compaction = this.requireCapability(this.compaction, "compaction");
614
+ return compaction.pending();
615
+ }
616
+ async cancelCompaction() {
617
+ const compaction = this.requireCapability(this.compaction, "compaction");
618
+ return compaction.cancel();
619
+ }
620
+ async updateExistingGoal(status, reason) {
621
+ const goal = this.requireCapability(this.goal, "goal");
622
+ if (goal.snapshot() === null)
623
+ return null;
624
+ const snapshot = goal.update({ status, reason });
625
+ await this.emitControlEvent({ type: "goal.updated", snapshot });
626
+ return snapshot;
627
+ }
628
+ async emitControlEvent(body) {
629
+ await this.events.emit({ ...body, address: "main", sessionId: this.id });
630
+ }
631
+ async listSkills() {
632
+ const skills = this.requireCapability(this.skills, "skills");
633
+ return skills.listSkills();
634
+ }
635
+ async activateSkill(nameOrRequest, args) {
636
+ const skills = this.requireCapability(this.skills, "skills");
637
+ const request = typeof nameOrRequest === "string" ? { name: nameOrRequest, ...(args !== undefined ? { args } : {}) } : nameOrRequest;
638
+ return skills.activateSkill(request);
639
+ }
640
+ async listPlugins() {
641
+ const plugins = this.requireCapability(this.plugins, "plugins");
642
+ return plugins.summaries();
643
+ }
644
+ async getPluginInfo(id) {
645
+ const plugins = this.requireCapability(this.plugins, "plugins");
646
+ return plugins.info(id);
647
+ }
648
+ async installPlugin(source) {
649
+ const plugins = this.requireCapability(this.plugins, "plugins");
650
+ const record = await plugins.install(source);
651
+ const summary = plugins.summaries().find((plugin) => plugin.id === record.id);
652
+ if (summary === undefined)
653
+ throw new Error(`Plugin "${record.id}" was installed but no summary was produced.`);
654
+ return summary;
655
+ }
656
+ async setPluginEnabled(id, enabled) {
657
+ const plugins = this.requireCapability(this.plugins, "plugins");
658
+ await plugins.setEnabled(id, enabled);
659
+ }
660
+ async setPluginMcpServerEnabled(id, server, enabled) {
661
+ const plugins = this.requireCapability(this.plugins, "plugins");
662
+ await plugins.setMcpServerEnabled(id, server, enabled);
663
+ }
664
+ async removePlugin(id) {
665
+ const plugins = this.requireCapability(this.plugins, "plugins");
666
+ await plugins.remove(id);
667
+ }
668
+ async reloadPlugins() {
669
+ const plugins = this.requireCapability(this.plugins, "plugins");
670
+ return plugins.reload();
671
+ }
672
+ setModel(model) {
673
+ this.modelOverride = model;
674
+ }
675
+ setThinking(level) {
676
+ this.thinkingOverride = level;
677
+ }
678
+ /**
679
+ * Switch the permission mode. Takes effect in memory immediately — policies read the
680
+ * manager's mode lazily at each tool authorization, so the next tool call (mid-turn
681
+ * included) sees it. The returned promise settles when the mode is also journaled
682
+ * (so it survives reopen) and REJECTS if that persistence fails, so callers who care
683
+ * about durability can surface the failure. Fire-and-forget callers may ignore it:
684
+ * the in-memory switch has already happened, and the failure is still logged (the
685
+ * rejection is pre-handled internally, so ignoring it never trips unhandledRejection).
686
+ */
687
+ setPermissionMode(mode) {
688
+ this._permission.setMode(mode);
689
+ if (this.store === undefined)
690
+ return Promise.resolve();
691
+ const persisted = this.store.appendRecord({ type: "permission.set_mode", mode, address: DEFAULT_ADDRESS });
692
+ persisted.catch((error) => {
693
+ this.logger.log("warn", "failed to journal permission.set_mode", { error: error instanceof Error ? error.message : String(error) });
694
+ });
695
+ return persisted.then(() => undefined);
696
+ }
697
+ get modelSetting() {
698
+ return this.modelOverride;
699
+ }
700
+ get thinkingSetting() {
701
+ return this.thinkingOverride;
702
+ }
703
+ get permissionModeSetting() {
704
+ return this._permission.mode;
705
+ }
706
+ drainDiagnostics() {
707
+ return this.pendingDiagnostics.splice(0, this.pendingDiagnostics.length);
708
+ }
709
+ async withRunLock(body) {
710
+ const prev = this.runChain;
711
+ let release;
712
+ this.runChain = new Promise((resolve) => (release = resolve));
713
+ await prev;
714
+ try {
715
+ return await body();
716
+ }
717
+ finally {
718
+ release();
719
+ }
720
+ }
721
+ flushEvents() {
722
+ return this.eventPublisher.flush();
723
+ }
724
+ async close() {
725
+ if (!this.isOpen)
726
+ return;
727
+ this.isOpen = false;
728
+ this.systemPromptContexts.clear();
729
+ this.unsubscribeTracing?.();
730
+ for (const cap of [...this.openedCapabilities].reverse()) {
731
+ if (!cap.closeSession)
732
+ continue;
733
+ try {
734
+ await withTimeout(Promise.resolve(cap.closeSession()), CLOSE_TIMEOUT_MS);
735
+ }
736
+ catch (error) {
737
+ this.pendingDiagnostics.push({
738
+ capability: cap.name,
739
+ phase: "stop",
740
+ level: "warn",
741
+ message: `closeSession failed/timed out: ${messageOf(error)}`,
742
+ });
743
+ this.logger.log("warn", `capability "${cap.name}" closeSession failed/timed out`, { capability: cap.name, phase: "stop", error: messageOf(error) });
744
+ }
745
+ }
746
+ this.openedCapabilities = [];
747
+ try {
748
+ await withTimeout(Promise.resolve(this.tracing?.forceFlush()), CLOSE_TIMEOUT_MS);
749
+ }
750
+ catch (error) {
751
+ this.pendingDiagnostics.push({
752
+ capability: "tracing",
753
+ phase: "stop",
754
+ level: "warn",
755
+ message: `forceFlush failed/timed out: ${messageOf(error)}`,
756
+ });
757
+ this.logger.log("warn", "tracing forceFlush failed/timed out", { capability: "tracing", phase: "stop", error: messageOf(error) });
758
+ }
759
+ try {
760
+ await withTimeout(this.eventPublisher.flush(), STORE_FLUSH_TIMEOUT_MS);
761
+ await withTimeout(Promise.resolve(this.store?.flush?.()), STORE_FLUSH_TIMEOUT_MS);
762
+ }
763
+ catch (error) {
764
+ this.pendingDiagnostics.push({
765
+ capability: "store",
766
+ phase: "stop",
767
+ level: "warn",
768
+ message: `store flush failed/timed out: ${messageOf(error)}`,
769
+ });
770
+ this.logger.log("warn", "store flush failed/timed out", { capability: "store", phase: "stop", error: messageOf(error) });
771
+ }
772
+ // The machine is deliberately NOT closed here: its lifetime belongs to whoever created
773
+ // it (see `MachineFactory`). A sandbox usually outlives any one session, so closing it
774
+ // on session.close would pull the workspace out from under the user's other sessions.
775
+ }
776
+ /** Public URL for a port inside the machine, or undefined when the backend can't expose one. */
777
+ async resolveExposedPort(port) {
778
+ return await this.machine.exposedPortUrl?.(port);
779
+ }
780
+ }
781
+ function normalizeGoalBudget(input) {
782
+ let fields = 0;
783
+ const budget = {};
784
+ if (input.turns !== undefined) {
785
+ budget.turns = positiveInt("turns", input.turns);
786
+ fields += 1;
787
+ }
788
+ if (input.tokens !== undefined) {
789
+ budget.tokens = positiveInt("tokens", input.tokens);
790
+ fields += 1;
791
+ }
792
+ if (input.wallClockMs !== undefined) {
793
+ budget.wallClockMs = positiveInt("wallClockMs", input.wallClockMs);
794
+ fields += 1;
795
+ }
796
+ if (fields === 0)
797
+ throw new Error("At least one goal budget field is required.");
798
+ return budget;
799
+ }
800
+ function positiveInt(name, value) {
801
+ if (!Number.isInteger(value) || value <= 0)
802
+ throw new Error(`Goal budget ${name} must be a positive integer.`);
803
+ return value;
804
+ }
805
+ async function resolveMachine(cfg, ctx) {
806
+ // No machine configured → stateless session with no filesystem. A NullMachine
807
+ // answers metadata but refuses all I/O, so a stray file tool fails loudly
808
+ // rather than silently touching the host disk.
809
+ if (!cfg.machine)
810
+ return new NullMachine();
811
+ return typeof cfg.machine === "function" ? await cfg.machine(ctx) : cfg.machine;
812
+ }
813
+ function safeCwd(machine) {
814
+ try {
815
+ return machine.getcwd();
816
+ }
817
+ catch {
818
+ return "";
819
+ }
820
+ }
821
+ function messageOf(error) {
822
+ return error instanceof Error ? error.message : String(error);
823
+ }
824
+ /** Plain text of a message content (string, or the text parts of a content array). */
825
+ /**
826
+ * `AbortController.abort(x)` stores `x` verbatim as `signal.reason`, and `throwIfAborted()`
827
+ * rethrows exactly that. The loop classifies cancellation by `error.name === "AbortError"`
828
+ * (`isAbortError`), so a caller-supplied reason has to be wrapped, or an intentional abort
829
+ * would surface as a run failure.
830
+ */
831
+ export function abortReason(message) {
832
+ const error = new Error(message);
833
+ error.name = "AbortError";
834
+ return error;
835
+ }
836
+ function withTimeout(promise, ms) {
837
+ return new Promise((resolve, reject) => {
838
+ const timer = setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms);
839
+ promise.then((value) => {
840
+ clearTimeout(timer);
841
+ resolve(value);
842
+ }, (error) => {
843
+ clearTimeout(timer);
844
+ reject(error);
845
+ });
846
+ });
847
+ }
848
+ // ── Background agent-task → SubagentRecord projection ──────────────────────────
849
+ // A background subagent is a task of kind "agent"; its SubagentRecord view is derived from
850
+ // the task's persisted info, replacing the old conversation fold.
851
+ const SUBAGENT_STATUS_SET = new Set([
852
+ "running",
853
+ "completed",
854
+ "error",
855
+ "paused",
856
+ "cancelled",
857
+ "lost",
858
+ ]);
859
+ function taskToSubagentRecord(info) {
860
+ if (info.kind !== "agent" || info.agentId === undefined)
861
+ return undefined;
862
+ if (info.outputRef?.kind !== "conversation")
863
+ return undefined;
864
+ const address = info.outputRef.address;
865
+ return {
866
+ agentId: info.agentId,
867
+ type: info.subagentType ?? "unknown",
868
+ address,
869
+ description: info.description,
870
+ background: true,
871
+ taskId: info.taskId,
872
+ createdAt: info.startedAt,
873
+ status: subagentStatusFromTask(info.status, info.agentStatus),
874
+ updatedAt: info.endedAt ?? info.startedAt,
875
+ };
876
+ }
877
+ /** Map a background task status to the finer subagent status, preferring the run's own
878
+ * `agentStatus` (e.g. "paused") when it reported one. */
879
+ function subagentStatusFromTask(status, agentStatus) {
880
+ if (agentStatus !== undefined && SUBAGENT_STATUS_SET.has(agentStatus))
881
+ return agentStatus;
882
+ switch (status) {
883
+ case "completed":
884
+ return "completed";
885
+ case "killed":
886
+ return "cancelled";
887
+ case "paused":
888
+ return "paused";
889
+ case "lost":
890
+ return "lost";
891
+ case "running":
892
+ return "running";
893
+ default:
894
+ return "error"; // failed / timed_out
895
+ }
896
+ }
897
+ // ── Background workflow-task → WorkflowSnapshot projection ─────────────────────
898
+ // A background workflow run is a task of kind "workflow"; its discovery row is derived from the
899
+ // task's persisted info, replacing the old conversation fold (WorkflowSnapshotStore).
900
+ const WORKFLOW_STATUS_SET = new Set([
901
+ "running",
902
+ "completed",
903
+ "failed",
904
+ "aborted",
905
+ ]);
906
+ function taskToWorkflowSnapshot(info) {
907
+ if (info.kind !== "workflow" || info.runId === undefined)
908
+ return undefined;
909
+ return {
910
+ runId: info.runId,
911
+ workflowName: info.workflowName ?? "unknown",
912
+ description: info.description,
913
+ status: workflowStatusFromTask(info.status, info.runStatus),
914
+ background: true,
915
+ taskId: info.taskId,
916
+ startedAt: new Date(info.startedAt).toISOString(),
917
+ endedAt: info.endedAt !== null ? new Date(info.endedAt).toISOString() : undefined,
918
+ };
919
+ }
920
+ /** Map a background task status to the workflow discovery status, preferring the run's own
921
+ * `runStatus` (e.g. "failed") when it reported one. */
922
+ function workflowStatusFromTask(status, runStatus) {
923
+ if (runStatus !== undefined && WORKFLOW_STATUS_SET.has(runStatus))
924
+ return runStatus;
925
+ switch (status) {
926
+ case "completed":
927
+ return "completed";
928
+ case "killed":
929
+ case "lost":
930
+ return "aborted";
931
+ case "running":
932
+ return "running";
933
+ default:
934
+ return "failed"; // failed / timed_out
935
+ }
936
+ }
937
+ //# sourceMappingURL=session.js.map