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,89 @@
1
+ /**
2
+ * `PromptOrigin` — a structured tag on a journaled message record saying WHERE the message
3
+ * came from. It is the persistence-layer replacement for parsing intent back out of rendered
4
+ * text: a settle notification carries `{kind:'background_task', …}` so a reducer reads the entity
5
+ * id/status structurally instead of regexing a `<background-task-done>` tag.
6
+ *
7
+ * Lives at the store layer (below `loop`) so `AgentRecordBody` can carry it without a layer
8
+ * inversion. Fields are primitives only — no import of capabilities/background types — so this
9
+ * stays a leaf module. `status` is a plain string (the domain's own vocabulary).
10
+ *
11
+ * Pragmatic subset: only the kinds agent-framework produces today. Extensible by adding a
12
+ * member when a new kind appears — kept a CLOSED discriminated union (no open `kind`) so
13
+ * `origin.kind === '…'` narrows and exhaustiveness is checkable.
14
+ */
15
+ export interface UserPromptOrigin {
16
+ readonly kind: "user";
17
+ /** Present when the message arrived via the SteerBus: the enqueue-time correlation id. */
18
+ readonly steerId?: string;
19
+ }
20
+ export interface UserFollowUpPromptOrigin {
21
+ readonly kind: "user_follow_up";
22
+ /** Present when the message arrived via the SteerBus: the enqueue-time correlation id. */
23
+ readonly steerId?: string;
24
+ }
25
+ export interface InjectionOrigin {
26
+ readonly kind: "injection";
27
+ /** Stable injector identity used to restore its cadence after replay. Absent on legacy records. */
28
+ readonly injectorId?: string;
29
+ /** The emitted form/state (e.g. "full", "sparse", "todo_reminder"). */
30
+ readonly variant: string;
31
+ }
32
+ export interface BackgroundTaskOrigin {
33
+ readonly kind: "background_task";
34
+ readonly taskId: string;
35
+ /** The background task's terminal status, or the entity's finer status when it reports one. */
36
+ readonly status?: string;
37
+ readonly agentId?: string;
38
+ readonly runId?: string;
39
+ /** Present when the message arrived via the SteerBus: the enqueue-time correlation id. */
40
+ readonly steerId?: string;
41
+ }
42
+ /** A message an extension enqueued (cron fires, quota warnings, …). */
43
+ export interface ExtensionMessageOrigin {
44
+ readonly kind: "extension";
45
+ readonly extensionId: string;
46
+ readonly metadata?: Readonly<Record<string, string | number | boolean>>;
47
+ /** Present when the message arrived via the SteerBus: the enqueue-time correlation id. */
48
+ readonly steerId?: string;
49
+ }
50
+ /** LEGACY (pre-extension cron): kept so journals written by the cron capability still parse. */
51
+ export interface CronJobOrigin {
52
+ readonly kind: "cron_job";
53
+ readonly jobId: string;
54
+ readonly cron: string;
55
+ readonly recurring: boolean;
56
+ readonly coalescedCount: number;
57
+ readonly stale: boolean;
58
+ /** Present when the message arrived via the SteerBus: the enqueue-time correlation id. */
59
+ readonly steerId?: string;
60
+ }
61
+ export interface CronMissedOrigin {
62
+ readonly kind: "cron_missed";
63
+ readonly count: number;
64
+ /** Present when the message arrived via the SteerBus: the enqueue-time correlation id. */
65
+ readonly steerId?: string;
66
+ }
67
+ export interface CompactionSummaryOrigin {
68
+ readonly kind: "compaction_summary";
69
+ }
70
+ /** A message copied into a fresh conversation shard when ownership is handed to another agent. */
71
+ export interface HandoffSeedOrigin {
72
+ readonly kind: "handoff_seed";
73
+ readonly handoffId: string;
74
+ readonly fromAddress: string;
75
+ }
76
+ export type ExternalOriginMetadataValue = string | number | boolean | null;
77
+ /** A prompt delivered by another agent/application through the host delivery API. */
78
+ export interface ExternalPromptOrigin {
79
+ readonly kind: "external";
80
+ readonly source: string;
81
+ readonly deliveryId: string;
82
+ readonly actor?: string;
83
+ readonly metadata?: Readonly<Record<string, ExternalOriginMetadataValue>>;
84
+ /** Present when the message was queued through the SteerBus. */
85
+ readonly steerId?: string;
86
+ }
87
+ export type PromptOrigin = UserPromptOrigin | UserFollowUpPromptOrigin | InjectionOrigin | BackgroundTaskOrigin | ExtensionMessageOrigin | CronJobOrigin | CronMissedOrigin | CompactionSummaryOrigin | HandoffSeedOrigin | ExternalPromptOrigin;
88
+ export declare const USER_PROMPT_ORIGIN: UserPromptOrigin;
89
+ //# sourceMappingURL=origin.d.ts.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `PromptOrigin` — a structured tag on a journaled message record saying WHERE the message
3
+ * came from. It is the persistence-layer replacement for parsing intent back out of rendered
4
+ * text: a settle notification carries `{kind:'background_task', …}` so a reducer reads the entity
5
+ * id/status structurally instead of regexing a `<background-task-done>` tag.
6
+ *
7
+ * Lives at the store layer (below `loop`) so `AgentRecordBody` can carry it without a layer
8
+ * inversion. Fields are primitives only — no import of capabilities/background types — so this
9
+ * stays a leaf module. `status` is a plain string (the domain's own vocabulary).
10
+ *
11
+ * Pragmatic subset: only the kinds agent-framework produces today. Extensible by adding a
12
+ * member when a new kind appears — kept a CLOSED discriminated union (no open `kind`) so
13
+ * `origin.kind === '…'` narrows and exhaustiveness is checkable.
14
+ */
15
+ export const USER_PROMPT_ORIGIN = { kind: "user" };
16
+ //# sourceMappingURL=origin.js.map
@@ -0,0 +1,90 @@
1
+ import { LogSessionStore, type ReadLinesPageOptions, type StoredLogLine } from "./log-store.ts";
2
+ import { type CreateSessionInput, type ForkSessionInput, type ListSessionsFilter, type OpenSessionOptions, type DeleteSessionOptions, type SessionHandle, type SessionRepository, type SessionSummary } from "./repository.ts";
3
+ import { type SessionStorage } from "./storage.ts";
4
+ import type { SessionStore, StateKey } from "./store.ts";
5
+ /** The slice of `pg.Pool` this backing uses — a real `pg.Pool` satisfies it structurally. */
6
+ /** Anything that can run a statement — the pool itself, or a connection pinned to a transaction. */
7
+ export interface PgExecutor {
8
+ query(text: string, params?: readonly unknown[]): Promise<{
9
+ rows: Array<Record<string, unknown>>;
10
+ }>;
11
+ }
12
+ /** A connection pinned out of the pool, so BEGIN/COMMIT apply to the statements in between. */
13
+ export interface PgClient extends PgExecutor {
14
+ release(): void;
15
+ }
16
+ export interface PgPool extends PgExecutor {
17
+ /**
18
+ * Pin a connection. `pg.Pool` provides exactly this; a minimal duck-typed pool may not, and
19
+ * multi-statement writes then fall back to running unwrapped (see {@link PgSessionRepository}).
20
+ */
21
+ connect?(): Promise<PgClient>;
22
+ end?(): Promise<void>;
23
+ }
24
+ export interface PgStorageOptions {
25
+ /** A constructed `pg.Pool` (or compatible). Shared by all sessions. */
26
+ readonly pool: PgPool;
27
+ /** When true, `storage.close()` ends the pool. Default false (you constructed it; you close it). */
28
+ readonly ownsPool?: boolean;
29
+ }
30
+ /** Tree session store for one session over a shared pool. Tree/migration/blobs live in LogSessionStore. */
31
+ export declare class PgSessionStore extends LogSessionStore {
32
+ private readonly pool;
33
+ private readonly id;
34
+ constructor(pool: PgExecutor, id: string);
35
+ protected appendLine(address: string, line: string): Promise<string>;
36
+ protected readLines(address: string): AsyncIterable<StoredLogLine>;
37
+ /** A range read on `session_log_sess_addr_seq`: the page, and nothing before or after it. */
38
+ protected readLinesPage(address: string, options: ReadLinesPageOptions): Promise<readonly StoredLogLine[]>;
39
+ protected rewriteLines(address: string, lines: readonly StoredLogLine[]): Promise<void>;
40
+ protected listShardAddresses(): Promise<readonly string[]>;
41
+ getState(key: StateKey): Promise<unknown | null>;
42
+ putState(key: StateKey, value: unknown): Promise<void>;
43
+ deleteState(key: StateKey): Promise<void>;
44
+ listStateKeys(): Promise<readonly StateKey[]>;
45
+ protected readBlobBytes(sha: string): Promise<Buffer | undefined>;
46
+ protected writeBlobBytes(sha: string, bytes: Buffer): Promise<void>;
47
+ }
48
+ /** One transaction in progress. Statements on `exec` and writes through `store(id)` share it. */
49
+ export interface PgTransaction {
50
+ readonly exec: PgExecutor;
51
+ store(id: string): SessionStore;
52
+ }
53
+ export declare class PgSessionRepository implements SessionRepository {
54
+ private readonly pool;
55
+ private readonly ownsPool;
56
+ private schemaReady?;
57
+ constructor(pool: PgPool, ownsPool?: boolean);
58
+ /** Create the tables on first use (idempotent); memoized so it runs once per repository. */
59
+ private ready;
60
+ /**
61
+ * Run `fn` inside BEGIN/COMMIT on a pinned connection, rolling back on any throw.
62
+ *
63
+ * Falls back to running unwrapped when the injected pool exposes no `connect()` — a minimal
64
+ * duck-typed pool still works, it just keeps the old non-atomic behaviour. That is the one
65
+ * place this class degrades, and it degrades loudly only in the sense that the caller chose
66
+ * the pool: `pg.Pool` has `connect`, so a real deployment always gets the transaction.
67
+ */
68
+ private inTransaction;
69
+ /**
70
+ * Run `fn` as one transaction: everything it does through `tx` commits together or not at all.
71
+ *
72
+ * This is how a host makes a session write and a write of its own atomic — a record appended
73
+ * to the log and a row in the host's own table, with no moment in between where one exists
74
+ * without the other. Same fallback as the repository's own multi-statement operations: a pool
75
+ * with no `connect()` runs `fn` unwrapped.
76
+ */
77
+ transaction<T>(fn: (tx: PgTransaction) => Promise<T>): Promise<T>;
78
+ private storeFor;
79
+ create(input: CreateSessionInput): Promise<SessionHandle>;
80
+ open(id: string, options?: OpenSessionOptions): Promise<SessionHandle | undefined>;
81
+ get(id: string): Promise<SessionSummary | undefined>;
82
+ list(filter?: ListSessionsFilter): Promise<readonly SessionSummary[]>;
83
+ fork(sourceId: string, input?: ForkSessionInput): Promise<SessionHandle>;
84
+ delete(id: string, options?: DeleteSessionOptions): Promise<void>;
85
+ restore(id: string): Promise<void>;
86
+ close(): Promise<void>;
87
+ }
88
+ /** Postgres-backed {@link SessionStorage}. Inject a `pg.Pool`; tables are created on first use. */
89
+ export declare function pgStorage(options: PgStorageOptions): SessionStorage;
90
+ //# sourceMappingURL=pg.d.ts.map
@@ -0,0 +1,344 @@
1
+ import { LogSessionStore } from "./log-store.js";
2
+ import { CatalogSessionStore } from "./catalog-store.js";
3
+ import { generateSessionId, SessionRepositoryConflictError, SessionRepositoryNotFoundError, } from "./repository.js";
4
+ import { storageOver } from "./storage.js";
5
+ import { normalizeWorkDir } from "./workdir-key.js";
6
+ /**
7
+ * Postgres backing for {@link SessionStorage}. You inject a constructed `pg.Pool` (the driver is
8
+ * never imported here, so core stays dependency-free); the pool is shared across every session.
9
+ * Logs/state/blobs/catalog live in four tables; blobs are content-addressed and global, so a fork
10
+ * shares them (no copy). Log lines are stored as `text` (not jsonb) on purpose — jsonb rejects
11
+ * `NUL`, which can appear in tool output. The log is flat and linear (one append-only record
12
+ * stream per address); {@link LogSessionStore} reduces it to conversation state on read.
13
+ *
14
+ * import { Pool } from "pg";
15
+ * const storage = pgStorage({ pool: new Pool({ connectionString: process.env.DATABASE_URL }), ownsPool: true });
16
+ */
17
+ const SESSION_ID_RE = /^[a-zA-Z0-9_-]+$/;
18
+ function assertSafeSessionId(id) {
19
+ if (!SESSION_ID_RE.test(id))
20
+ throw new Error(`invalid session id "${id}" — only [A-Za-z0-9_-] allowed`);
21
+ }
22
+ // Separate statements (not one multi-statement string) — a single `create ... if not exists` per call works everywhere.
23
+ const SCHEMA_STATEMENTS = [
24
+ `create table if not exists session_log (
25
+ session_id text not null,
26
+ address text not null,
27
+ seq bigint generated always as identity,
28
+ line text not null,
29
+ primary key (seq)
30
+ )`,
31
+ `create index if not exists session_log_sess_addr_seq on session_log (session_id, address, seq)`,
32
+ `create table if not exists session_state (
33
+ session_id text not null,
34
+ key text not null,
35
+ value jsonb,
36
+ primary key (session_id, key)
37
+ )`,
38
+ `create table if not exists session_blob (
39
+ sha text primary key,
40
+ bytes bytea not null
41
+ )`,
42
+ `create table if not exists session_meta (
43
+ id text primary key,
44
+ work_dir text not null,
45
+ owner_key text,
46
+ deleted_at bigint,
47
+ title text,
48
+ created_at bigint not null,
49
+ updated_at bigint not null
50
+ )`,
51
+ `create index if not exists session_meta_workdir on session_meta (work_dir)`,
52
+ // Ordered to match list()'s `order by updated_at desc, id desc`, so an owner-filtered
53
+ // listing is an index scan rather than a filter + sort over the whole fleet.
54
+ `create index if not exists session_meta_owner on session_meta (owner_key, updated_at desc, id desc)`,
55
+ // Soft-deleted rows are retained for audit, so every listing filters them out; a partial
56
+ // index keeps that predicate from touching them at all.
57
+ `create index if not exists session_meta_live on session_meta (updated_at desc, id desc) where deleted_at is null`,
58
+ `create index if not exists session_meta_recency on session_meta (updated_at desc, id desc)`,
59
+ ];
60
+ /** Tree session store for one session over a shared pool. Tree/migration/blobs live in LogSessionStore. */
61
+ export class PgSessionStore extends LogSessionStore {
62
+ pool;
63
+ id;
64
+ constructor(pool, id) {
65
+ super();
66
+ this.pool = pool;
67
+ this.id = id;
68
+ }
69
+ async appendLine(address, line) {
70
+ const { rows } = await this.pool.query(`insert into session_log(session_id, address, line) values($1, $2, $3) returning seq`, [this.id, address, line]);
71
+ // Advance the activity stamp so list() ("most recently active" first) is honest — stamped
72
+ // once at create otherwise. No-op (0 rows) when meta doesn't exist (a store used standalone).
73
+ await this.pool.query(`update session_meta set updated_at = $2 where id = $1`, [this.id, Date.now()]);
74
+ return String(rows[0].seq);
75
+ }
76
+ async *readLines(address) {
77
+ const { rows } = await this.pool.query(`select seq, line from session_log where session_id=$1 and address=$2 order by seq`, [this.id, address]);
78
+ for (const row of rows)
79
+ yield { sequence: String(row.seq), line: row.line };
80
+ }
81
+ /** A range read on `session_log_sess_addr_seq`: the page, and nothing before or after it. */
82
+ async readLinesPage(address, options) {
83
+ const beyond = options.order === "asc" ? ">" : "<";
84
+ const { rows } = await this.pool.query(`select seq, line from session_log
85
+ where session_id=$1 and address=$2${options.after !== undefined ? ` and seq ${beyond} $4` : ""}
86
+ order by seq ${options.order} limit $3`, [this.id, address, options.limit, ...(options.after !== undefined ? [options.after] : [])]);
87
+ return rows.map((row) => ({ sequence: String(row.seq), line: row.line }));
88
+ }
89
+ async rewriteLines(address, lines) {
90
+ // Rewrites update the existing physical rows and remove migration-dropped rows. Their
91
+ // store-assigned sequence is never regenerated, so already-issued cursors stay valid.
92
+ for (const entry of lines) {
93
+ await this.pool.query(`update session_log set line=$4 where session_id=$1 and address=$2 and seq=$3`, [this.id, address, entry.sequence, entry.line]);
94
+ }
95
+ await this.pool.query(`delete from session_log where session_id=$1 and address=$2 and not (seq = any($3::bigint[]))`, [this.id, address, lines.map((entry) => entry.sequence)]);
96
+ }
97
+ async listShardAddresses() {
98
+ const { rows } = await this.pool.query(`select distinct address from session_log where session_id=$1`, [this.id]);
99
+ return rows.map((r) => r.address);
100
+ }
101
+ async getState(key) {
102
+ const { rows } = await this.pool.query(`select value from session_state where session_id=$1 and key=$2`, [this.id, key]);
103
+ return rows.length > 0 ? (rows[0].value ?? null) : null;
104
+ }
105
+ async putState(key, value) {
106
+ await this.pool.query(`insert into session_state(session_id, key, value) values($1, $2, $3::jsonb)
107
+ on conflict (session_id, key) do update set value = excluded.value`, [this.id, key, JSON.stringify(value ?? null)]);
108
+ }
109
+ async deleteState(key) {
110
+ await this.pool.query(`delete from session_state where session_id=$1 and key=$2`, [this.id, key]);
111
+ }
112
+ async listStateKeys() {
113
+ const { rows } = await this.pool.query(`select key from session_state where session_id=$1`, [this.id]);
114
+ return rows.map((r) => r.key);
115
+ }
116
+ async readBlobBytes(sha) {
117
+ const { rows } = await this.pool.query(`select bytes from session_blob where sha=$1`, [sha]);
118
+ // `bytea` comes back as a Buffer from node-pg but a Uint8Array from some drivers; normalize.
119
+ return rows.length > 0 ? Buffer.from(rows[0].bytes) : undefined;
120
+ }
121
+ async writeBlobBytes(sha, bytes) {
122
+ await this.pool.query(`insert into session_blob(sha, bytes) values($1, $2) on conflict (sha) do nothing`, [sha, bytes]);
123
+ }
124
+ }
125
+ export class PgSessionRepository {
126
+ pool;
127
+ ownsPool;
128
+ schemaReady;
129
+ constructor(pool, ownsPool = false) {
130
+ this.pool = pool;
131
+ this.ownsPool = ownsPool;
132
+ }
133
+ /** Create the tables on first use (idempotent); memoized so it runs once per repository. */
134
+ ready() {
135
+ return (this.schemaReady ??= (async () => {
136
+ for (const stmt of SCHEMA_STATEMENTS)
137
+ await this.pool.query(stmt);
138
+ })());
139
+ }
140
+ /**
141
+ * Run `fn` inside BEGIN/COMMIT on a pinned connection, rolling back on any throw.
142
+ *
143
+ * Falls back to running unwrapped when the injected pool exposes no `connect()` — a minimal
144
+ * duck-typed pool still works, it just keeps the old non-atomic behaviour. That is the one
145
+ * place this class degrades, and it degrades loudly only in the sense that the caller chose
146
+ * the pool: `pg.Pool` has `connect`, so a real deployment always gets the transaction.
147
+ */
148
+ async inTransaction(fn) {
149
+ const client = await this.pool.connect?.();
150
+ if (client === undefined)
151
+ return fn(this.pool);
152
+ try {
153
+ await client.query("begin");
154
+ const result = await fn(client);
155
+ await client.query("commit");
156
+ return result;
157
+ }
158
+ catch (error) {
159
+ await client.query("rollback").catch(() => undefined);
160
+ throw error;
161
+ }
162
+ finally {
163
+ client.release();
164
+ }
165
+ }
166
+ /**
167
+ * Run `fn` as one transaction: everything it does through `tx` commits together or not at all.
168
+ *
169
+ * This is how a host makes a session write and a write of its own atomic — a record appended
170
+ * to the log and a row in the host's own table, with no moment in between where one exists
171
+ * without the other. Same fallback as the repository's own multi-statement operations: a pool
172
+ * with no `connect()` runs `fn` unwrapped.
173
+ */
174
+ async transaction(fn) {
175
+ await this.ready();
176
+ return this.inTransaction((exec) => fn({ exec, store: (id) => this.storeFor(id, exec) }));
177
+ }
178
+ storeFor(id, exec = this.pool) {
179
+ const raw = new PgSessionStore(exec, id);
180
+ const patch = async (values) => {
181
+ await exec.query(values.durableState === undefined
182
+ ? `update session_meta set updated_at=$2 where id=$1`
183
+ : `update session_meta set durable_state=$2, updated_at=$3 where id=$1`, values.durableState === undefined
184
+ ? [id, values.updatedAt]
185
+ : [id, values.durableState, values.updatedAt]);
186
+ };
187
+ const observer = {
188
+ // appendLine and interruption state transitions already advance metadata atomically.
189
+ activity: (updatedAt, source) => source === "state" ? patch({ updatedAt }) : undefined,
190
+ durableState: (_durableState, updatedAt) => patch({ updatedAt }),
191
+ metadata: async (value, updatedAt) => {
192
+ const title = sessionMetaTitle(value);
193
+ if (title === undefined)
194
+ return patch({ updatedAt });
195
+ await exec.query(`update session_meta set title=$2, updated_at=$3 where id=$1`, [id, title, updatedAt]);
196
+ },
197
+ };
198
+ return new CatalogSessionStore(raw, observer);
199
+ }
200
+ // create/fork/purge are multi-statement, so they run inside BEGIN/COMMIT on a pinned connection
201
+ // (`inTransaction`). With a pool that exposes no `connect()` they degrade to the old unwrapped
202
+ // behaviour: a mid-sequence failure can leave a partial session (meta row without the meta state;
203
+ // a fork with a partly copied log). The meta row is inserted first and gates existence, so even
204
+ // then a partial is inert (open() still resolves) rather than corrupt, and recovery is
205
+ // delete-then-recreate. Inject a real `pg.Pool` and none of that applies.
206
+ async create(input) {
207
+ await this.ready();
208
+ const id = input.id ?? generateSessionId();
209
+ assertSafeSessionId(id);
210
+ const workDir = normalizeWorkDir(input.workDir);
211
+ const now = Date.now();
212
+ await this.inTransaction(async (exec) => {
213
+ const { rows } = await exec.query(`insert into session_meta(id, work_dir, owner_key, title, created_at, updated_at) values($1, $2, $3, $4, $5, $5)
214
+ on conflict (id) do nothing returning id`, [id, workDir, input.ownerKey ?? null, input.title ?? null, now]);
215
+ // Rolls the (empty) transaction back and propagates — the id was already taken.
216
+ if (rows.length === 0)
217
+ throw new SessionRepositoryConflictError(id);
218
+ await this.storeFor(id, exec).putState("meta", { id, workDir, ownerKey: input.ownerKey, title: input.title, createdAt: now, updatedAt: now });
219
+ });
220
+ return { id, workDir, createdAt: now, store: this.storeFor(id) };
221
+ }
222
+ async open(id, options) {
223
+ await this.ready();
224
+ const { rows } = await this.pool.query(options?.includeDeleted === true
225
+ ? `select work_dir, created_at from session_meta where id=$1`
226
+ : `select work_dir, created_at from session_meta where id=$1 and deleted_at is null`, [id]);
227
+ if (rows.length === 0)
228
+ return undefined;
229
+ return { id, workDir: rows[0].work_dir, createdAt: Number(rows[0].created_at), store: this.storeFor(id) };
230
+ }
231
+ async get(id) {
232
+ await this.ready();
233
+ const { rows } = await this.pool.query(`select m.id, m.work_dir, m.owner_key, m.deleted_at, m.title, m.created_at, m.updated_at,
234
+ case when s.session_id is null then 'idle' else 'interrupted' end as durable_state
235
+ from session_meta m left join session_state s on s.session_id=m.id and s.key='interrupt'
236
+ where m.id=$1`, [id]);
237
+ const row = rows[0];
238
+ return row === undefined
239
+ ? undefined
240
+ : {
241
+ id: row.id,
242
+ workDir: row.work_dir,
243
+ ownerKey: row.owner_key ?? undefined,
244
+ deletedAt: row.deleted_at === null || row.deleted_at === undefined ? undefined : Number(row.deleted_at),
245
+ title: row.title ?? undefined,
246
+ createdAt: Number(row.created_at),
247
+ updatedAt: Number(row.updated_at),
248
+ durableState: parseDurableState(row.durable_state),
249
+ };
250
+ }
251
+ async list(filter) {
252
+ await this.ready();
253
+ const wanted = filter?.workDir !== undefined ? normalizeWorkDir(filter.workDir) : undefined;
254
+ const params = [];
255
+ const conditions = [];
256
+ if (wanted !== undefined) {
257
+ params.push(wanted);
258
+ conditions.push(`m.work_dir=$${params.length}`);
259
+ }
260
+ if (filter?.ownerKey !== undefined) {
261
+ params.push(filter.ownerKey);
262
+ conditions.push(`m.owner_key=$${params.length}`);
263
+ }
264
+ if (filter?.includeDeleted !== true)
265
+ conditions.push("m.deleted_at is null");
266
+ const where = conditions.length === 0 ? "" : `where ${conditions.join(" and ")} `;
267
+ const { rows } = await this.pool.query(`select m.id, m.work_dir, m.owner_key, m.deleted_at, m.title, m.created_at, m.updated_at,
268
+ case when s.session_id is null then 'idle' else 'interrupted' end as durable_state
269
+ from session_meta m left join session_state s on s.session_id=m.id and s.key='interrupt'
270
+ ${where}order by m.updated_at desc, m.id desc`, params);
271
+ return rows.map((r) => ({
272
+ id: r.id,
273
+ workDir: r.work_dir,
274
+ ownerKey: r.owner_key ?? undefined,
275
+ deletedAt: r.deleted_at === null || r.deleted_at === undefined ? undefined : Number(r.deleted_at),
276
+ title: r.title ?? undefined,
277
+ createdAt: Number(r.created_at),
278
+ updatedAt: Number(r.updated_at),
279
+ durableState: parseDurableState(r.durable_state),
280
+ }));
281
+ }
282
+ async fork(sourceId, input) {
283
+ await this.ready();
284
+ const src = await this.pool.query(`select m.work_dir, m.owner_key, m.title,
285
+ case when s.session_id is null then 'idle' else 'interrupted' end as durable_state
286
+ from session_meta m left join session_state s on s.session_id=m.id and s.key='interrupt'
287
+ where m.id=$1 and m.deleted_at is null`, [sourceId]);
288
+ if (src.rows.length === 0)
289
+ throw new SessionRepositoryNotFoundError(sourceId);
290
+ const workDir = src.rows[0].work_dir;
291
+ const ownerKey = input?.ownerKey ?? (src.rows[0].owner_key ?? undefined);
292
+ const id = input?.id ?? generateSessionId();
293
+ assertSafeSessionId(id);
294
+ const now = Date.now();
295
+ const title = input?.title ?? (src.rows[0].title ?? undefined);
296
+ const durableState = parseDurableState(src.rows[0].durable_state);
297
+ await this.inTransaction(async (exec) => {
298
+ const ins = await exec.query(`insert into session_meta(id, work_dir, owner_key, title, created_at, updated_at) values($1, $2, $3, $4, $5, $5)
299
+ on conflict (id) do nothing returning id`, [id, workDir, ownerKey ?? null, title ?? null, now]);
300
+ if (ins.rows.length === 0)
301
+ throw new SessionRepositoryConflictError(id);
302
+ // Copy log + state into the new id; blobs are content-addressed + global, so they're shared.
303
+ await exec.query(`insert into session_log(session_id, address, line) select $1, address, line from session_log where session_id=$2 order by seq`, [id, sourceId]);
304
+ await exec.query(`insert into session_state(session_id, key, value) select $1, key, value from session_state where session_id=$2`, [id, sourceId]);
305
+ await this.storeFor(id, exec).putState("meta", { id, workDir, ownerKey, title, createdAt: now, updatedAt: now, durableState });
306
+ });
307
+ return { id, workDir, createdAt: now, store: this.storeFor(id) };
308
+ }
309
+ async delete(id, options) {
310
+ await this.ready();
311
+ if (options?.purge !== true) {
312
+ await this.pool.query(`update session_meta set deleted_at=$2, updated_at=$2 where id=$1 and deleted_at is null`, [id, Date.now()]);
313
+ return;
314
+ }
315
+ await this.inTransaction(async (exec) => {
316
+ await exec.query(`delete from session_log where session_id=$1`, [id]);
317
+ await exec.query(`delete from session_state where session_id=$1`, [id]);
318
+ await exec.query(`delete from session_meta where id=$1`, [id]);
319
+ });
320
+ // Blobs are content-addressed and possibly shared across sessions; left in place (no GC).
321
+ }
322
+ async restore(id) {
323
+ await this.ready();
324
+ await this.pool.query(`update session_meta set deleted_at=null, updated_at=$2 where id=$1 and deleted_at is not null`, [id, Date.now()]);
325
+ }
326
+ async close() {
327
+ if (this.ownsPool)
328
+ await this.pool.end?.();
329
+ }
330
+ }
331
+ /** Postgres-backed {@link SessionStorage}. Inject a `pg.Pool`; tables are created on first use. */
332
+ export function pgStorage(options) {
333
+ return storageOver(new PgSessionRepository(options.pool, options.ownsPool ?? false));
334
+ }
335
+ function parseDurableState(value) {
336
+ return value === "interrupted" ? "interrupted" : "idle";
337
+ }
338
+ function sessionMetaTitle(value) {
339
+ if (typeof value !== "object" || value === null || !("title" in value))
340
+ return undefined;
341
+ const title = value.title;
342
+ return typeof title === "string" ? title : title === undefined ? null : undefined;
343
+ }
344
+ //# sourceMappingURL=pg.js.map
@@ -0,0 +1,21 @@
1
+ import { type RedactOptions } from "../logging/redact.ts";
2
+ import type { AgentRecord, ReadRecordPageOptions, ReadRecordsFilter, RecordPage, SessionStore, StateKey } from "./store.ts";
3
+ export interface RedactingStoreOptions extends RedactOptions {
4
+ readonly redactState?: boolean;
5
+ }
6
+ export declare class RedactingSessionStore implements SessionStore {
7
+ private readonly inner;
8
+ private readonly options;
9
+ constructor(inner: SessionStore, options?: RedactingStoreOptions);
10
+ appendRecord(record: AgentRecord): Promise<string>;
11
+ readRecords(filter?: ReadRecordsFilter): AsyncIterable<AgentRecord>;
12
+ readRecordPage(options: ReadRecordPageOptions): Promise<RecordPage>;
13
+ putState(key: StateKey, value: unknown): Promise<void>;
14
+ getState(key: StateKey): Promise<unknown | null>;
15
+ deleteState(key: StateKey): Promise<void>;
16
+ flush(): Promise<void>;
17
+ close(): Promise<void>;
18
+ rewrite(address?: string): Promise<void>;
19
+ storageDir(): string | undefined;
20
+ }
21
+ //# sourceMappingURL=redacting-store.d.ts.map
@@ -0,0 +1,46 @@
1
+ import { redactDeep } from "../logging/redact.js";
2
+ export class RedactingSessionStore {
3
+ inner;
4
+ options;
5
+ constructor(inner, options = {}) {
6
+ this.inner = inner;
7
+ this.options = options;
8
+ }
9
+ appendRecord(record) {
10
+ return this.inner.appendRecord(redactRecord(record, this.options));
11
+ }
12
+ readRecords(filter) {
13
+ // Records were redacted on the way in, so the inner store already holds safe data.
14
+ return this.inner.readRecords(filter);
15
+ }
16
+ readRecordPage(options) {
17
+ return this.inner.readRecordPage(options);
18
+ }
19
+ async putState(key, value) {
20
+ await this.inner.putState(key, this.options.redactState ? redactDeep(value, this.options) : value);
21
+ }
22
+ getState(key) {
23
+ return this.inner.getState(key);
24
+ }
25
+ deleteState(key) {
26
+ return this.inner.deleteState(key);
27
+ }
28
+ flush() {
29
+ return this.inner.flush?.() ?? Promise.resolve();
30
+ }
31
+ close() {
32
+ return this.inner.close?.() ?? Promise.resolve();
33
+ }
34
+ rewrite(address) {
35
+ return this.inner.rewrite?.(address) ?? Promise.resolve();
36
+ }
37
+ storageDir() {
38
+ return this.inner.storageDir?.();
39
+ }
40
+ }
41
+ function redactRecord(record, options) {
42
+ const { type, eventId, time, address, ...body } = record;
43
+ const safeBody = redactDeep(body, options);
44
+ return { type, eventId, time, address, ...safeBody };
45
+ }
46
+ //# sourceMappingURL=redacting-store.js.map