@warlock.js/ai 4.2.11 → 4.4.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 (432) hide show
  1. package/CHANGELOG.md +68 -1
  2. package/cjs/index.cjs +10155 -4626
  3. package/cjs/index.cjs.map +1 -1
  4. package/cjs/magic-string.es-BtxW4VqG.cjs +1015 -0
  5. package/cjs/magic-string.es-BtxW4VqG.cjs.map +1 -0
  6. package/cjs/matcher-logic-SBnzYohQ.cjs +217 -0
  7. package/cjs/matcher-logic-SBnzYohQ.cjs.map +1 -0
  8. package/cjs/matchers-BBh3gyB-.cjs +13739 -0
  9. package/cjs/matchers-BBh3gyB-.cjs.map +1 -0
  10. package/esm/agent/agent-config.type.d.mts +19 -6
  11. package/esm/agent/agent-config.type.d.mts.map +1 -1
  12. package/esm/agent/agent.d.mts.map +1 -1
  13. package/esm/agent/agent.mjs +17 -6
  14. package/esm/agent/agent.mjs.map +1 -1
  15. package/esm/agent/index.d.mts +2 -1
  16. package/esm/agent/index.mjs +1 -0
  17. package/esm/agent/spawn-sub-agent.d.mts +87 -0
  18. package/esm/agent/spawn-sub-agent.d.mts.map +1 -0
  19. package/esm/agent/spawn-sub-agent.mjs +68 -0
  20. package/esm/agent/spawn-sub-agent.mjs.map +1 -0
  21. package/esm/ai.d.mts +58 -3
  22. package/esm/ai.d.mts.map +1 -1
  23. package/esm/ai.mjs +58 -3
  24. package/esm/ai.mjs.map +1 -1
  25. package/esm/batch/batch.d.mts +43 -0
  26. package/esm/batch/batch.d.mts.map +1 -0
  27. package/esm/batch/batch.mjs +179 -0
  28. package/esm/batch/batch.mjs.map +1 -0
  29. package/esm/batch/batch.type.d.mts +144 -0
  30. package/esm/batch/batch.type.d.mts.map +1 -0
  31. package/esm/batch/index.mjs +3 -0
  32. package/esm/batch/run-batch-item.mjs +100 -0
  33. package/esm/batch/run-batch-item.mjs.map +1 -0
  34. package/esm/batch/run-with-concurrency.mjs +39 -0
  35. package/esm/batch/run-with-concurrency.mjs.map +1 -0
  36. package/esm/checkpoint/index.d.mts +3 -0
  37. package/esm/checkpoint/memory.d.mts +21 -0
  38. package/esm/checkpoint/memory.d.mts.map +1 -0
  39. package/esm/checkpoint/memory.mjs +0 -0
  40. package/esm/checkpoint/memory.mjs.map +1 -0
  41. package/esm/checkpoint/pg.d.mts +37 -0
  42. package/esm/checkpoint/pg.d.mts.map +1 -0
  43. package/esm/checkpoint/pg.mjs +265 -0
  44. package/esm/checkpoint/pg.mjs.map +1 -0
  45. package/esm/checkpoint/redis.d.mts +39 -0
  46. package/esm/checkpoint/redis.d.mts.map +1 -0
  47. package/esm/checkpoint/redis.mjs +200 -0
  48. package/esm/checkpoint/redis.mjs.map +1 -0
  49. package/esm/config.d.mts +61 -14
  50. package/esm/config.d.mts.map +1 -1
  51. package/esm/config.mjs +25 -6
  52. package/esm/config.mjs.map +1 -1
  53. package/esm/contracts/agent/agent.contract.d.mts +43 -0
  54. package/esm/contracts/agent/agent.contract.d.mts.map +1 -1
  55. package/esm/contracts/agent/eval.type.d.mts +143 -0
  56. package/esm/contracts/agent/eval.type.d.mts.map +1 -0
  57. package/esm/contracts/agent/index.d.mts +1 -0
  58. package/esm/contracts/events/supervisor-events.type.d.mts +3 -3
  59. package/esm/contracts/fallback-model.contract.d.mts +65 -0
  60. package/esm/contracts/fallback-model.contract.d.mts.map +1 -0
  61. package/esm/contracts/index.d.mts +32 -12
  62. package/esm/contracts/memory/index.d.mts +4 -0
  63. package/esm/contracts/memory/memory-config.type.d.mts +150 -0
  64. package/esm/contracts/memory/memory-config.type.d.mts.map +1 -0
  65. package/esm/contracts/memory/memory-item.type.d.mts +64 -0
  66. package/esm/contracts/memory/memory-item.type.d.mts.map +1 -0
  67. package/esm/contracts/memory/memory.contract.d.mts +87 -0
  68. package/esm/contracts/memory/memory.contract.d.mts.map +1 -0
  69. package/esm/contracts/memory/recall-options.type.d.mts +33 -0
  70. package/esm/contracts/memory/recall-options.type.d.mts.map +1 -0
  71. package/esm/contracts/middleware/index.d.mts +2 -2
  72. package/esm/contracts/middleware/middleware-context.type.d.mts +42 -2
  73. package/esm/contracts/middleware/middleware-context.type.d.mts.map +1 -1
  74. package/esm/contracts/middleware/middleware.contract.d.mts +46 -2
  75. package/esm/contracts/middleware/middleware.contract.d.mts.map +1 -1
  76. package/esm/contracts/model.contract.d.mts +63 -2
  77. package/esm/contracts/model.contract.d.mts.map +1 -1
  78. package/esm/contracts/orchestrator/checkpoint-store.contract.d.mts +91 -0
  79. package/esm/contracts/orchestrator/checkpoint-store.contract.d.mts.map +1 -0
  80. package/esm/contracts/orchestrator/index.d.mts +8 -0
  81. package/esm/contracts/orchestrator/orchestrator-commands.type.d.mts +43 -0
  82. package/esm/contracts/orchestrator/orchestrator-commands.type.d.mts.map +1 -0
  83. package/esm/contracts/orchestrator/orchestrator-config.type.d.mts +170 -0
  84. package/esm/contracts/orchestrator/orchestrator-config.type.d.mts.map +1 -0
  85. package/esm/contracts/orchestrator/orchestrator-event.type.d.mts +118 -0
  86. package/esm/contracts/orchestrator/orchestrator-event.type.d.mts.map +1 -0
  87. package/esm/contracts/orchestrator/orchestrator-execute-options.type.d.mts +44 -0
  88. package/esm/contracts/orchestrator/orchestrator-execute-options.type.d.mts.map +1 -0
  89. package/esm/contracts/orchestrator/orchestrator.contract.d.mts +129 -0
  90. package/esm/contracts/orchestrator/orchestrator.contract.d.mts.map +1 -0
  91. package/esm/contracts/orchestrator/session.contract.d.mts +26 -0
  92. package/esm/contracts/orchestrator/session.contract.d.mts.map +1 -0
  93. package/esm/contracts/orchestrator/snapshot-store.contract.d.mts +89 -0
  94. package/esm/contracts/orchestrator/snapshot-store.contract.d.mts.map +1 -0
  95. package/esm/contracts/planner/index.d.mts +6 -0
  96. package/esm/contracts/planner/planner-capability.type.d.mts +39 -0
  97. package/esm/contracts/planner/planner-capability.type.d.mts.map +1 -0
  98. package/esm/contracts/planner/planner-config.type.d.mts +78 -0
  99. package/esm/contracts/planner/planner-config.type.d.mts.map +1 -0
  100. package/esm/contracts/planner/planner-execute-options.type.d.mts +43 -0
  101. package/esm/contracts/planner/planner-execute-options.type.d.mts.map +1 -0
  102. package/esm/contracts/planner/planner-plan.type.d.mts +48 -0
  103. package/esm/contracts/planner/planner-plan.type.d.mts.map +1 -0
  104. package/esm/contracts/planner/planner-result.type.d.mts +88 -0
  105. package/esm/contracts/planner/planner-result.type.d.mts.map +1 -0
  106. package/esm/contracts/planner/planner.contract.d.mts +60 -0
  107. package/esm/contracts/planner/planner.contract.d.mts.map +1 -0
  108. package/esm/contracts/result/base-report.type.d.mts +7 -2
  109. package/esm/contracts/result/base-report.type.d.mts.map +1 -1
  110. package/esm/contracts/result/base-report.type.mjs.map +1 -1
  111. package/esm/contracts/result/index.d.mts +2 -1
  112. package/esm/contracts/result/model-pricing.type.d.mts +10 -0
  113. package/esm/contracts/result/model-pricing.type.d.mts.map +1 -1
  114. package/esm/contracts/result/orchestrator-result.type.d.mts +143 -0
  115. package/esm/contracts/result/orchestrator-result.type.d.mts.map +1 -0
  116. package/esm/contracts/result/session-send-result.type.d.mts +12 -3
  117. package/esm/contracts/result/session-send-result.type.d.mts.map +1 -1
  118. package/esm/contracts/result/supervisor-result.type.d.mts +2 -2
  119. package/esm/contracts/result/supervisor-result.type.d.mts.map +1 -1
  120. package/esm/contracts/result/tool-call.type.d.mts +2 -2
  121. package/esm/contracts/result/tool-call.type.d.mts.map +1 -1
  122. package/esm/contracts/result/usage.type.d.mts +24 -0
  123. package/esm/contracts/result/usage.type.d.mts.map +1 -1
  124. package/esm/contracts/result/workflow-result.type.d.mts +1 -1
  125. package/esm/contracts/result/workflow-result.type.d.mts.map +1 -1
  126. package/esm/contracts/sdk-adapter.contract.d.mts +1 -1
  127. package/esm/contracts/supervisor/dispatch-context.type.d.mts +3 -3
  128. package/esm/contracts/supervisor/evaluate-context.type.d.mts +1 -1
  129. package/esm/contracts/supervisor/index.d.mts +5 -5
  130. package/esm/contracts/supervisor/route-context.type.d.mts +2 -2
  131. package/esm/contracts/supervisor/supervisor-config.type.d.mts +55 -13
  132. package/esm/contracts/supervisor/supervisor-config.type.d.mts.map +1 -1
  133. package/esm/contracts/supervisor/supervisor-snapshot.type.d.mts +1 -1
  134. package/esm/contracts/supervisor/supervisor.contract.d.mts +9 -2
  135. package/esm/contracts/supervisor/supervisor.contract.d.mts.map +1 -1
  136. package/esm/contracts/workflow/index.d.mts +2 -2
  137. package/esm/contracts/workflow/workflow.contract.d.mts +28 -7
  138. package/esm/contracts/workflow/workflow.contract.d.mts.map +1 -1
  139. package/esm/errors/error-code.type.d.mts +1 -1
  140. package/esm/errors/index.d.mts +7 -0
  141. package/esm/errors/index.mjs +7 -0
  142. package/esm/errors/orchestrator-cancelled-error.d.mts +32 -0
  143. package/esm/errors/orchestrator-cancelled-error.d.mts.map +1 -0
  144. package/esm/errors/orchestrator-cancelled-error.mjs +31 -0
  145. package/esm/errors/orchestrator-cancelled-error.mjs.map +1 -0
  146. package/esm/errors/orchestrator-config-error.d.mts +26 -0
  147. package/esm/errors/orchestrator-config-error.d.mts.map +1 -0
  148. package/esm/errors/orchestrator-config-error.mjs +30 -0
  149. package/esm/errors/orchestrator-config-error.mjs.map +1 -0
  150. package/esm/errors/orchestrator-drift-error.d.mts +38 -0
  151. package/esm/errors/orchestrator-drift-error.d.mts.map +1 -0
  152. package/esm/errors/orchestrator-drift-error.mjs +37 -0
  153. package/esm/errors/orchestrator-drift-error.mjs.map +1 -0
  154. package/esm/errors/orchestrator-failed-error.d.mts +33 -0
  155. package/esm/errors/orchestrator-failed-error.d.mts.map +1 -0
  156. package/esm/errors/orchestrator-failed-error.mjs +36 -0
  157. package/esm/errors/orchestrator-failed-error.mjs.map +1 -0
  158. package/esm/errors/planner-cancelled-error.d.mts +33 -0
  159. package/esm/errors/planner-cancelled-error.d.mts.map +1 -0
  160. package/esm/errors/planner-cancelled-error.mjs +29 -0
  161. package/esm/errors/planner-cancelled-error.mjs.map +1 -0
  162. package/esm/errors/planner-failed-error.d.mts +40 -0
  163. package/esm/errors/planner-failed-error.d.mts.map +1 -0
  164. package/esm/errors/planner-failed-error.mjs +37 -0
  165. package/esm/errors/planner-failed-error.mjs.map +1 -0
  166. package/esm/errors/planner-plan-invalid-error.d.mts +21 -0
  167. package/esm/errors/planner-plan-invalid-error.d.mts.map +1 -0
  168. package/esm/errors/planner-plan-invalid-error.mjs +25 -0
  169. package/esm/errors/planner-plan-invalid-error.mjs.map +1 -0
  170. package/esm/eval/eval-runner.d.mts +17 -0
  171. package/esm/eval/eval-runner.d.mts.map +1 -0
  172. package/esm/eval/eval-runner.mjs +121 -0
  173. package/esm/eval/eval-runner.mjs.map +1 -0
  174. package/esm/eval/index.d.mts +29 -0
  175. package/esm/eval/index.d.mts.map +1 -0
  176. package/esm/eval/index.mjs +30 -0
  177. package/esm/eval/index.mjs.map +1 -0
  178. package/esm/eval/judge-scorer.d.mts +21 -0
  179. package/esm/eval/judge-scorer.d.mts.map +1 -0
  180. package/esm/eval/judge-scorer.mjs +87 -0
  181. package/esm/eval/judge-scorer.mjs.map +1 -0
  182. package/esm/eval/scorers.d.mts +50 -0
  183. package/esm/eval/scorers.d.mts.map +1 -0
  184. package/esm/eval/scorers.mjs +101 -0
  185. package/esm/eval/scorers.mjs.map +1 -0
  186. package/esm/index.d.mts +95 -30
  187. package/esm/index.mjs +66 -22
  188. package/esm/memory/derive-id.mjs +24 -0
  189. package/esm/memory/derive-id.mjs.map +1 -0
  190. package/esm/memory/episodic-memory.mjs +106 -0
  191. package/esm/memory/episodic-memory.mjs.map +1 -0
  192. package/esm/memory/index.d.mts +5 -0
  193. package/esm/memory/memory.d.mts +42 -0
  194. package/esm/memory/memory.d.mts.map +1 -0
  195. package/esm/memory/memory.mjs +166 -0
  196. package/esm/memory/memory.mjs.map +1 -0
  197. package/esm/memory/procedural-memory.mjs +103 -0
  198. package/esm/memory/procedural-memory.mjs.map +1 -0
  199. package/esm/memory/semantic-memory.mjs +80 -0
  200. package/esm/memory/semantic-memory.mjs.map +1 -0
  201. package/esm/memory/working-memory.mjs +62 -0
  202. package/esm/memory/working-memory.mjs.map +1 -0
  203. package/esm/middleware/builtins/budget-contract.type.d.mts +126 -0
  204. package/esm/middleware/builtins/budget-contract.type.d.mts.map +1 -0
  205. package/esm/middleware/builtins/budget.d.mts +71 -1
  206. package/esm/middleware/builtins/budget.d.mts.map +1 -1
  207. package/esm/middleware/builtins/budget.mjs +119 -4
  208. package/esm/middleware/builtins/budget.mjs.map +1 -1
  209. package/esm/middleware/builtins/semantic-cache.d.mts +1 -1
  210. package/esm/middleware/index.d.mts +2 -1
  211. package/esm/middleware/index.mjs +1 -1
  212. package/esm/middleware/pipeline.d.mts +9 -6
  213. package/esm/middleware/pipeline.d.mts.map +1 -1
  214. package/esm/middleware/pipeline.mjs.map +1 -1
  215. package/esm/mock/index.d.mts +1 -0
  216. package/esm/mock/index.mjs +1 -0
  217. package/esm/mock/mock-router.d.mts +63 -0
  218. package/esm/mock/mock-router.d.mts.map +1 -0
  219. package/esm/mock/mock-router.mjs +58 -0
  220. package/esm/mock/mock-router.mjs.map +1 -0
  221. package/esm/model/fallback-model.d.mts +45 -0
  222. package/esm/model/fallback-model.d.mts.map +1 -0
  223. package/esm/model/fallback-model.mjs +218 -0
  224. package/esm/model/fallback-model.mjs.map +1 -0
  225. package/esm/model/index.d.mts +2 -0
  226. package/esm/model/index.mjs +3 -0
  227. package/esm/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs +78 -0
  228. package/esm/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map +1 -0
  229. package/esm/node_modules/@vitest/expect/dist/index.mjs +1473 -0
  230. package/esm/node_modules/@vitest/expect/dist/index.mjs.map +1 -0
  231. package/esm/node_modules/@vitest/pretty-format/dist/index.mjs +888 -0
  232. package/esm/node_modules/@vitest/pretty-format/dist/index.mjs.map +1 -0
  233. package/esm/node_modules/@vitest/runner/dist/chunk-artifact.mjs +1533 -0
  234. package/esm/node_modules/@vitest/runner/dist/chunk-artifact.mjs.map +1 -0
  235. package/esm/node_modules/@vitest/runner/dist/index.mjs +3 -0
  236. package/esm/node_modules/@vitest/runner/dist/utils.mjs +3 -0
  237. package/esm/node_modules/@vitest/snapshot/dist/index.mjs +922 -0
  238. package/esm/node_modules/@vitest/snapshot/dist/index.mjs.map +1 -0
  239. package/esm/node_modules/@vitest/spy/dist/index.mjs +386 -0
  240. package/esm/node_modules/@vitest/spy/dist/index.mjs.map +1 -0
  241. package/esm/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.mjs +82 -0
  242. package/esm/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.mjs.map +1 -0
  243. package/esm/node_modules/@vitest/utils/dist/diff.mjs +1357 -0
  244. package/esm/node_modules/@vitest/utils/dist/diff.mjs.map +1 -0
  245. package/esm/node_modules/@vitest/utils/dist/display.mjs +559 -0
  246. package/esm/node_modules/@vitest/utils/dist/display.mjs.map +1 -0
  247. package/esm/node_modules/@vitest/utils/dist/error.mjs +38 -0
  248. package/esm/node_modules/@vitest/utils/dist/error.mjs.map +1 -0
  249. package/esm/node_modules/@vitest/utils/dist/helpers.mjs +181 -0
  250. package/esm/node_modules/@vitest/utils/dist/helpers.mjs.map +1 -0
  251. package/esm/node_modules/@vitest/utils/dist/offset.mjs +27 -0
  252. package/esm/node_modules/@vitest/utils/dist/offset.mjs.map +1 -0
  253. package/esm/node_modules/@vitest/utils/dist/serialize.mjs +77 -0
  254. package/esm/node_modules/@vitest/utils/dist/serialize.mjs.map +1 -0
  255. package/esm/node_modules/@vitest/utils/dist/source-map.mjs +374 -0
  256. package/esm/node_modules/@vitest/utils/dist/source-map.mjs.map +1 -0
  257. package/esm/node_modules/@vitest/utils/dist/timers.mjs +37 -0
  258. package/esm/node_modules/@vitest/utils/dist/timers.mjs.map +1 -0
  259. package/esm/node_modules/chai/index.mjs +2973 -0
  260. package/esm/node_modules/chai/index.mjs.map +1 -0
  261. package/esm/node_modules/magic-string/dist/magic-string.es.mjs +940 -0
  262. package/esm/node_modules/magic-string/dist/magic-string.es.mjs.map +1 -0
  263. package/esm/node_modules/tinyrainbow/dist/index.mjs +87 -0
  264. package/esm/node_modules/tinyrainbow/dist/index.mjs.map +1 -0
  265. package/esm/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.mjs +6 -0
  266. package/esm/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.mjs.map +1 -0
  267. package/esm/node_modules/vitest/dist/chunks/rpc.MzXet3jl.mjs +52 -0
  268. package/esm/node_modules/vitest/dist/chunks/rpc.MzXet3jl.mjs.map +1 -0
  269. package/esm/node_modules/vitest/dist/chunks/test.DNmyFkvJ.mjs +2697 -0
  270. package/esm/node_modules/vitest/dist/chunks/test.DNmyFkvJ.mjs.map +1 -0
  271. package/esm/node_modules/vitest/dist/chunks/utils.BX5Fg8C4.mjs +45 -0
  272. package/esm/node_modules/vitest/dist/chunks/utils.BX5Fg8C4.mjs.map +1 -0
  273. package/esm/orchestrator/as-tool.d.mts +42 -0
  274. package/esm/orchestrator/as-tool.d.mts.map +1 -0
  275. package/esm/orchestrator/as-tool.mjs +98 -0
  276. package/esm/orchestrator/as-tool.mjs.map +1 -0
  277. package/esm/orchestrator/checkpoint.mjs +75 -0
  278. package/esm/orchestrator/checkpoint.mjs.map +1 -0
  279. package/esm/orchestrator/commands.d.mts +38 -0
  280. package/esm/orchestrator/commands.d.mts.map +1 -0
  281. package/esm/orchestrator/commands.mjs +34 -0
  282. package/esm/orchestrator/commands.mjs.map +1 -0
  283. package/esm/orchestrator/compaction.mjs +206 -0
  284. package/esm/orchestrator/compaction.mjs.map +1 -0
  285. package/esm/orchestrator/dispatch.mjs +171 -0
  286. package/esm/orchestrator/dispatch.mjs.map +1 -0
  287. package/esm/orchestrator/emitter-port.type.d.mts +31 -0
  288. package/esm/orchestrator/emitter-port.type.d.mts.map +1 -0
  289. package/esm/orchestrator/emitter.d.mts +56 -0
  290. package/esm/orchestrator/emitter.d.mts.map +1 -0
  291. package/esm/orchestrator/emitter.mjs +85 -0
  292. package/esm/orchestrator/emitter.mjs.map +1 -0
  293. package/esm/orchestrator/engine-context.type.d.mts +56 -0
  294. package/esm/orchestrator/engine-context.type.d.mts.map +1 -0
  295. package/esm/orchestrator/execution.d.mts +116 -0
  296. package/esm/orchestrator/execution.d.mts.map +1 -0
  297. package/esm/orchestrator/execution.mjs +406 -0
  298. package/esm/orchestrator/execution.mjs.map +1 -0
  299. package/esm/orchestrator/index.d.mts +8 -0
  300. package/esm/orchestrator/index.mjs +10 -0
  301. package/esm/orchestrator/load.mjs +49 -0
  302. package/esm/orchestrator/load.mjs.map +1 -0
  303. package/esm/orchestrator/lock.mjs +75 -0
  304. package/esm/orchestrator/lock.mjs.map +1 -0
  305. package/esm/orchestrator/memory.d.mts +84 -0
  306. package/esm/orchestrator/memory.d.mts.map +1 -0
  307. package/esm/orchestrator/memory.mjs +141 -0
  308. package/esm/orchestrator/memory.mjs.map +1 -0
  309. package/esm/orchestrator/orchestrator-stream.d.mts +42 -0
  310. package/esm/orchestrator/orchestrator-stream.d.mts.map +1 -0
  311. package/esm/orchestrator/orchestrator-stream.mjs +98 -0
  312. package/esm/orchestrator/orchestrator-stream.mjs.map +1 -0
  313. package/esm/orchestrator/orchestrator.d.mts +38 -0
  314. package/esm/orchestrator/orchestrator.d.mts.map +1 -0
  315. package/esm/orchestrator/orchestrator.mjs +173 -0
  316. package/esm/orchestrator/orchestrator.mjs.map +1 -0
  317. package/esm/orchestrator/resume.mjs +74 -0
  318. package/esm/orchestrator/resume.mjs.map +1 -0
  319. package/esm/orchestrator/signature.d.mts +40 -0
  320. package/esm/orchestrator/signature.d.mts.map +1 -0
  321. package/esm/orchestrator/signature.mjs +120 -0
  322. package/esm/orchestrator/signature.mjs.map +1 -0
  323. package/esm/orchestrator/window.mjs +56 -0
  324. package/esm/orchestrator/window.mjs.map +1 -0
  325. package/esm/planner/index.d.mts +5 -0
  326. package/esm/planner/index.mjs +6 -0
  327. package/esm/planner/plan-prompt.d.mts +17 -0
  328. package/esm/planner/plan-prompt.d.mts.map +1 -0
  329. package/esm/planner/plan-prompt.mjs +30 -0
  330. package/esm/planner/plan-prompt.mjs.map +1 -0
  331. package/esm/planner/plan-schema.d.mts +27 -0
  332. package/esm/planner/plan-schema.d.mts.map +1 -0
  333. package/esm/planner/plan-schema.mjs +120 -0
  334. package/esm/planner/plan-schema.mjs.map +1 -0
  335. package/esm/planner/planner-run.d.mts +23 -0
  336. package/esm/planner/planner-run.d.mts.map +1 -0
  337. package/esm/planner/planner-run.mjs +344 -0
  338. package/esm/planner/planner-run.mjs.map +1 -0
  339. package/esm/planner/planner.d.mts +37 -0
  340. package/esm/planner/planner.d.mts.map +1 -0
  341. package/esm/planner/planner.mjs +120 -0
  342. package/esm/planner/planner.mjs.map +1 -0
  343. package/esm/planner/signature.d.mts +18 -0
  344. package/esm/planner/signature.d.mts.map +1 -0
  345. package/esm/planner/signature.mjs +27 -0
  346. package/esm/planner/signature.mjs.map +1 -0
  347. package/esm/snapshot/index.d.mts +3 -0
  348. package/esm/snapshot/memory.d.mts +26 -0
  349. package/esm/snapshot/memory.d.mts.map +1 -0
  350. package/esm/snapshot/memory.mjs +81 -0
  351. package/esm/snapshot/memory.mjs.map +1 -0
  352. package/esm/snapshot/pg.d.mts +41 -0
  353. package/esm/snapshot/pg.d.mts.map +1 -0
  354. package/esm/snapshot/pg.mjs +146 -0
  355. package/esm/snapshot/pg.mjs.map +1 -0
  356. package/esm/snapshot/redis.d.mts +42 -0
  357. package/esm/snapshot/redis.d.mts.map +1 -0
  358. package/esm/snapshot/redis.mjs +101 -0
  359. package/esm/snapshot/redis.mjs.map +1 -0
  360. package/esm/supervisor/as-tool.d.mts +0 -6
  361. package/esm/supervisor/as-tool.d.mts.map +1 -1
  362. package/esm/supervisor/as-tool.mjs +0 -6
  363. package/esm/supervisor/as-tool.mjs.map +1 -1
  364. package/esm/supervisor/execution.d.mts +43 -8
  365. package/esm/supervisor/execution.d.mts.map +1 -1
  366. package/esm/supervisor/execution.mjs +66 -16
  367. package/esm/supervisor/execution.mjs.map +1 -1
  368. package/esm/supervisor/fan-out.d.mts +65 -0
  369. package/esm/supervisor/fan-out.d.mts.map +1 -0
  370. package/esm/supervisor/fan-out.mjs +65 -0
  371. package/esm/supervisor/fan-out.mjs.map +1 -0
  372. package/esm/supervisor/index.d.mts +5 -3
  373. package/esm/supervisor/index.mjs +3 -1
  374. package/esm/supervisor/router-factory.d.mts +110 -0
  375. package/esm/supervisor/router-factory.d.mts.map +1 -0
  376. package/esm/supervisor/router-factory.mjs +141 -0
  377. package/esm/supervisor/router-factory.mjs.map +1 -0
  378. package/esm/supervisor/router-prompt.d.mts +1 -1
  379. package/esm/supervisor/snapshot.d.mts +4 -10
  380. package/esm/supervisor/snapshot.d.mts.map +1 -1
  381. package/esm/supervisor/snapshot.mjs +8 -16
  382. package/esm/supervisor/snapshot.mjs.map +1 -1
  383. package/esm/supervisor/supervisor.mjs +1 -0
  384. package/esm/supervisor/supervisor.mjs.map +1 -1
  385. package/esm/system-prompt/index.mjs +6 -0
  386. package/esm/system-prompt/system-prompt.d.mts +51 -3
  387. package/esm/system-prompt/system-prompt.d.mts.map +1 -1
  388. package/esm/system-prompt/system-prompt.mjs +52 -6
  389. package/esm/system-prompt/system-prompt.mjs.map +1 -1
  390. package/esm/testing/matcher-logic.d.mts +76 -0
  391. package/esm/testing/matcher-logic.d.mts.map +1 -0
  392. package/esm/testing/matcher-logic.mjs +144 -0
  393. package/esm/testing/matcher-logic.mjs.map +1 -0
  394. package/esm/testing/matchers.d.mts +48 -0
  395. package/esm/testing/matchers.d.mts.map +1 -0
  396. package/esm/testing/matchers.mjs +37 -0
  397. package/esm/testing/matchers.mjs.map +1 -0
  398. package/esm/testing/register-lazy.d.mts +20 -0
  399. package/esm/testing/register-lazy.d.mts.map +1 -0
  400. package/esm/testing/register-lazy.mjs +24 -0
  401. package/esm/testing/register-lazy.mjs.map +1 -0
  402. package/esm/tool/executable-as-tool.d.mts +87 -0
  403. package/esm/tool/executable-as-tool.d.mts.map +1 -0
  404. package/esm/tool/executable-as-tool.mjs +81 -0
  405. package/esm/tool/executable-as-tool.mjs.map +1 -0
  406. package/esm/tool/index.d.mts +2 -1
  407. package/esm/tool/index.mjs +1 -0
  408. package/esm/workflow/as-tool.mjs +0 -6
  409. package/esm/workflow/as-tool.mjs.map +1 -1
  410. package/esm/workflow/engine.mjs +2 -2
  411. package/esm/workflow/snapshot.mjs +13 -7
  412. package/esm/workflow/snapshot.mjs.map +1 -1
  413. package/esm/workflow/step-runner.mjs +1 -1
  414. package/esm/workflow/workflow.mjs +1 -0
  415. package/esm/workflow/workflow.mjs.map +1 -1
  416. package/llms-full.txt +947 -42
  417. package/llms.txt +13 -8
  418. package/package.json +3 -3
  419. package/skills/README.md +25 -5
  420. package/skills/ai-basics/SKILL.md +18 -7
  421. package/skills/ai-dx-helpers/SKILL.md +180 -0
  422. package/skills/attach-ai-middleware/SKILL.md +32 -3
  423. package/skills/handle-ai-errors/SKILL.md +20 -6
  424. package/skills/manage-ai-stores/SKILL.md +127 -0
  425. package/skills/persist-ai-data/SKILL.md +21 -10
  426. package/skills/pick-ai-provider/SKILL.md +46 -12
  427. package/skills/run-ai-agent/SKILL.md +51 -2
  428. package/skills/run-orchestrator/SKILL.md +198 -0
  429. package/skills/run-planner/SKILL.md +68 -0
  430. package/skills/run-supervisor/SKILL.md +47 -2
  431. package/skills/use-ai-memory/SKILL.md +124 -0
  432. package/skills/write-system-prompt/SKILL.md +14 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"episodic-memory.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/memory/episodic-memory.ts"],"sourcesContent":["import type { CacheDriver, CacheSimilarHit } from \"@warlock.js/cache\";\nimport type { EmbedderContract } from \"../contracts/embedder.contract\";\nimport type {\n MemoryItem,\n RecalledMemory,\n} from \"../contracts/memory/memory-item.type\";\nimport { deriveMemoryId } from \"./derive-id\";\n\n/**\n * Shape persisted per episode. `ts` is the wall-clock time the episode\n * was remembered — the basis for the recency half of the blended recall\n * score. The vector lives in the driver's index (via `set({ vector })`),\n * so it is not duplicated here.\n */\ntype StoredEpisode = {\n id: string;\n text: string;\n ts: number;\n metadata?: Record<string, unknown>;\n};\n\n/**\n * How many extra candidates to pull from `similar()` before re-ranking by\n * the recency-blended score and slicing to `k`. Recency can promote a\n * slightly-less-similar-but-recent episode past a stale exact match, so\n * the raw top-`k` by similarity alone would miss it — overscan, then\n * re-rank.\n */\nconst RECALL_OVERSCAN = 5;\n\n/**\n * Episodic recall tier (memory core M2).\n *\n * Holds a durable, timestamped log of *what happened* — events/episodes —\n * and retrieves the ones most relevant to a query, **blended with\n * recency** so recent episodes outrank stale ones at equal similarity.\n * That recency weighting is the whole difference from the {@link\n * import(\"./semantic-memory\").SemanticMemory} tier (pure similarity over\n * timeless facts): episodic memory is time-anchored.\n *\n * Like the semantic tier it delegates the similarity search to the\n * `@warlock.js/cache` driver's `similar()` and never implements ANN\n * itself; it adds a stored `ts` per entry and a decay curve at recall.\n * The blended `score` stays in `[0, 1]` so a consumer can merge episodic\n * hits with the other tiers and sort on one field.\n *\n * Internal to the `memory()` factory — never exported on the package\n * surface.\n */\nexport class EpisodicMemory {\n public constructor(\n private readonly embedder: EmbedderContract,\n private readonly store: CacheDriver<any, any>,\n private readonly namespace: string,\n private readonly recencyWeight: number,\n private readonly halfLifeMs: number,\n private readonly now: () => number,\n ) {}\n\n /**\n * Embed the episode text and index it under a namespaced, id-derived\n * key, stamping the current time. Re-remembering the same id overwrites\n * the prior entry (and refreshes its timestamp).\n */\n public async remember(item: MemoryItem): Promise<void> {\n const id = item.id ?? deriveMemoryId(item.text);\n const { vector } = await this.embedder.embed(item.text);\n\n const value: StoredEpisode = {\n id,\n text: item.text,\n ts: this.now(),\n metadata: item.metadata,\n };\n\n await this.store.set(this.keyFor(id), value, { vector });\n }\n\n /**\n * Embed `query`, pull the nearest episodes clearing the similarity\n * `threshold`, then re-rank each by a recency-blended score before\n * returning the top `k`. The similarity floor still gates relevance —\n * recency only reorders episodes that already cleared it, it never\n * surfaces an irrelevant-but-recent one.\n */\n public async recall(\n query: string,\n k: number,\n threshold: number,\n ): Promise<RecalledMemory[]> {\n const { vector } = await this.embedder.embed(query);\n\n const hits = await this.store.similar<StoredEpisode>(vector, {\n topK: Math.max(k * RECALL_OVERSCAN, k),\n threshold,\n });\n\n const prefix = `${this.namespace}.`;\n const now = this.now();\n\n return hits\n .filter((hit: CacheSimilarHit<StoredEpisode>) =>\n hit.key.startsWith(prefix),\n )\n .map((hit: CacheSimilarHit<StoredEpisode>) => ({\n id: hit.value.id,\n text: hit.value.text,\n tier: \"episodic\" as const,\n score: this.blend(hit.score, hit.value.ts, now),\n metadata: hit.value.metadata,\n }))\n .sort((first, second) => second.score - first.score)\n .slice(0, k);\n }\n\n /** Drop every episode written under this instance's namespace. */\n public async clear(): Promise<void> {\n await this.store.removeNamespace(this.namespace);\n }\n\n /**\n * Combine raw similarity with an exponential recency decay:\n * `(1 - w)·similarity + w·0.5^(age / halfLife)`. A just-remembered\n * episode contributes a recency of `1`; one `halfLife` old, `0.5`;\n * older trends toward `0`. With `recencyWeight` 0 the score is pure\n * similarity (an opt-out back to semantic-style ranking).\n */\n private blend(similarity: number, ts: number, now: number): number {\n const ageMs = Math.max(0, now - ts);\n const recency = 0.5 ** (ageMs / this.halfLifeMs);\n\n return (1 - this.recencyWeight) * similarity + this.recencyWeight * recency;\n }\n\n /**\n * Namespaced key for an entry. Mirrors the semantic tier's dot\n * separator so the prefix used here matches the `hit.key` the driver\n * returns from `similar()`.\n */\n private keyFor(id: string): string {\n return `${this.namespace}.${id}`;\n }\n}\n"],"mappings":";;;;;;;;;;AA4BA,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;AAqBxB,IAAa,iBAAb,MAA4B;CAC1B,AAAO,YACL,AAAiB,UACjB,AAAiB,OACjB,AAAiB,WACjB,AAAiB,eACjB,AAAiB,YACjB,AAAiB,KACjB;EANiB;EACA;EACA;EACA;EACA;EACA;CAChB;;;;;;CAOH,MAAa,SAAS,MAAiC;EACrD,MAAM,KAAK,KAAK,MAAM,eAAe,KAAK,IAAI;EAC9C,MAAM,EAAE,WAAW,MAAM,KAAK,SAAS,MAAM,KAAK,IAAI;EAEtD,MAAM,QAAuB;GAC3B;GACA,MAAM,KAAK;GACX,IAAI,KAAK,IAAI;GACb,UAAU,KAAK;EACjB;EAEA,MAAM,KAAK,MAAM,IAAI,KAAK,OAAO,EAAE,GAAG,OAAO,EAAE,OAAO,CAAC;CACzD;;;;;;;;CASA,MAAa,OACX,OACA,GACA,WAC2B;EAC3B,MAAM,EAAE,WAAW,MAAM,KAAK,SAAS,MAAM,KAAK;EAElD,MAAM,OAAO,MAAM,KAAK,MAAM,QAAuB,QAAQ;GAC3D,MAAM,KAAK,IAAI,IAAI,iBAAiB,CAAC;GACrC;EACF,CAAC;EAED,MAAM,SAAS,GAAG,KAAK,UAAU;EACjC,MAAM,MAAM,KAAK,IAAI;EAErB,OAAO,KACJ,QAAQ,QACP,IAAI,IAAI,WAAW,MAAM,CAC3B,CAAC,CACA,KAAK,SAAyC;GAC7C,IAAI,IAAI,MAAM;GACd,MAAM,IAAI,MAAM;GAChB,MAAM;GACN,OAAO,KAAK,MAAM,IAAI,OAAO,IAAI,MAAM,IAAI,GAAG;GAC9C,UAAU,IAAI,MAAM;EACtB,EAAE,CAAC,CACF,MAAM,OAAO,WAAW,OAAO,QAAQ,MAAM,KAAK,CAAC,CACnD,MAAM,GAAG,CAAC;CACf;;CAGA,MAAa,QAAuB;EAClC,MAAM,KAAK,MAAM,gBAAgB,KAAK,SAAS;CACjD;;;;;;;;CASA,AAAQ,MAAM,YAAoB,IAAY,KAAqB;EAEjE,MAAM,UAAU,OADF,KAAK,IAAI,GAAG,MAAM,EACJ,IAAI,KAAK;EAErC,QAAQ,IAAI,KAAK,iBAAiB,aAAa,KAAK,gBAAgB;CACtE;;;;;;CAOA,AAAQ,OAAO,IAAoB;EACjC,OAAO,GAAG,KAAK,UAAU,GAAG;CAC9B;AACF"}
@@ -0,0 +1,5 @@
1
+ import { MemoryItem, MemoryTier, RecalledMemory } from "../contracts/memory/memory-item.type.mjs";
2
+ import { RecallOptions } from "../contracts/memory/recall-options.type.mjs";
3
+ import { MemoryContract } from "../contracts/memory/memory.contract.mjs";
4
+ import { EpisodicMemoryConfig, MemoryConfig, ProceduralMemoryConfig, SemanticMemoryConfig } from "../contracts/memory/memory-config.type.mjs";
5
+ import { memory } from "./memory.mjs";
@@ -0,0 +1,42 @@
1
+ import { MemoryContract } from "../contracts/memory/memory.contract.mjs";
2
+ import { MemoryConfig } from "../contracts/memory/memory-config.type.mjs";
3
+
4
+ //#region ../@warlock.js/ai/src/memory/memory.d.ts
5
+ /**
6
+ * Create an agent memory store (memory core M2).
7
+ *
8
+ * Wires up to four tiers behind the {@link MemoryContract}: **working**
9
+ * (in-run scratch, recency), **semantic** (durable facts by cosine
10
+ * similarity), **episodic** (durable events, similarity blended with
11
+ * recency), and **procedural** (durable how-tos, similarity blended with
12
+ * reinforcement). The working tier is on by default; the other three each
13
+ * activate only when their config is supplied. The three vector tiers
14
+ * mirror how `semanticCache` delegates similarity to the cache driver's
15
+ * `.similar()`.
16
+ *
17
+ * Resolution happens once here, at construction (loud), rather than per
18
+ * call (silent until first use): a vector-tier config with no `store` and
19
+ * no `ai.config({ defaultStore })` throws now; enabling no tier at all
20
+ * throws now.
21
+ *
22
+ * Decay / forgetting (TTL-based falloff, eviction) remains deferred.
23
+ *
24
+ * @example
25
+ * import { ai } from "@warlock.js/ai";
26
+ * import { MemoryCacheDriver } from "@warlock.js/cache";
27
+ *
28
+ * const store = new MemoryCacheDriver();
29
+ * store.setOptions({});
30
+ *
31
+ * const mem = ai.memory({
32
+ * semantic: { embedder, store },
33
+ * defaultTier: "semantic",
34
+ * });
35
+ *
36
+ * await mem.remember({ text: "User prefers concise answers." });
37
+ * const hits = await mem.recall("how should I respond?", { k: 3 });
38
+ */
39
+ declare function memory(config?: MemoryConfig): MemoryContract;
40
+ //#endregion
41
+ export { memory };
42
+ //# sourceMappingURL=memory.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/memory/memory.ts"],"mappings":";;;;;;AA0DA;;;;;;;;AAAiE;;;;;;;;;;;;;;;;;;;;;;;;iBAAjD,MAAA,CAAO,MAAA,GAAQ,YAAA,GAAoB,cAAc"}
@@ -0,0 +1,166 @@
1
+ import { resolveDefaultStore } from "../config.mjs";
2
+ import { EpisodicMemory } from "./episodic-memory.mjs";
3
+ import { ProceduralMemory } from "./procedural-memory.mjs";
4
+ import { SemanticMemory } from "./semantic-memory.mjs";
5
+ import { WorkingMemory } from "./working-memory.mjs";
6
+
7
+ //#region ../@warlock.js/ai/src/memory/memory.ts
8
+ const DEFAULT_NAME = "memory";
9
+ const DEFAULT_SEMANTIC_NAMESPACE = "ai.memory.semantic";
10
+ const DEFAULT_EPISODIC_NAMESPACE = "ai.memory.episodic";
11
+ const DEFAULT_PROCEDURAL_NAMESPACE = "ai.memory.procedural";
12
+ const DEFAULT_K = 5;
13
+ const DEFAULT_THRESHOLD = .7;
14
+ const DEFAULT_RECENCY_WEIGHT = .3;
15
+ const DEFAULT_HALF_LIFE_MS = 10080 * 60 * 1e3;
16
+ const DEFAULT_REINFORCEMENT_WEIGHT = .3;
17
+ /**
18
+ * Create an agent memory store (memory core M2).
19
+ *
20
+ * Wires up to four tiers behind the {@link MemoryContract}: **working**
21
+ * (in-run scratch, recency), **semantic** (durable facts by cosine
22
+ * similarity), **episodic** (durable events, similarity blended with
23
+ * recency), and **procedural** (durable how-tos, similarity blended with
24
+ * reinforcement). The working tier is on by default; the other three each
25
+ * activate only when their config is supplied. The three vector tiers
26
+ * mirror how `semanticCache` delegates similarity to the cache driver's
27
+ * `.similar()`.
28
+ *
29
+ * Resolution happens once here, at construction (loud), rather than per
30
+ * call (silent until first use): a vector-tier config with no `store` and
31
+ * no `ai.config({ defaultStore })` throws now; enabling no tier at all
32
+ * throws now.
33
+ *
34
+ * Decay / forgetting (TTL-based falloff, eviction) remains deferred.
35
+ *
36
+ * @example
37
+ * import { ai } from "@warlock.js/ai";
38
+ * import { MemoryCacheDriver } from "@warlock.js/cache";
39
+ *
40
+ * const store = new MemoryCacheDriver();
41
+ * store.setOptions({});
42
+ *
43
+ * const mem = ai.memory({
44
+ * semantic: { embedder, store },
45
+ * defaultTier: "semantic",
46
+ * });
47
+ *
48
+ * await mem.remember({ text: "User prefers concise answers." });
49
+ * const hits = await mem.recall("how should I respond?", { k: 3 });
50
+ */
51
+ function memory(config = {}) {
52
+ const name = config.name ?? DEFAULT_NAME;
53
+ const workingEnabled = config.working ?? true;
54
+ const defaultK = config.k ?? DEFAULT_K;
55
+ const defaultThreshold = config.threshold ?? DEFAULT_THRESHOLD;
56
+ const working = workingEnabled ? new WorkingMemory() : void 0;
57
+ const semantic = config.semantic ? buildSemanticTier(config.semantic, name) : void 0;
58
+ const episodic = config.episodic ? buildEpisodicTier(config.episodic, name) : void 0;
59
+ const procedural = config.procedural ? buildProceduralTier(config.procedural, name) : void 0;
60
+ const tiers = {
61
+ working,
62
+ semantic,
63
+ episodic,
64
+ procedural
65
+ };
66
+ if (!working && !semantic && !episodic && !procedural) throw new Error(`memory("${name}"): no tier enabled — enable \`working\` (default) or pass a \`semantic\` / \`episodic\` / \`procedural\` config; a memory with no tiers can neither store nor recall`);
67
+ const defaultTier = config.defaultTier ?? "working";
68
+ assertTierEnabled(defaultTier, tiers, name);
69
+ return {
70
+ name,
71
+ async remember(items) {
72
+ const list = Array.isArray(items) ? items : [items];
73
+ const writes = [];
74
+ for (const item of list) {
75
+ const tier = item.tier ?? defaultTier;
76
+ assertTierEnabled(tier, tiers, name);
77
+ if (tier === "working") {
78
+ working.remember(item);
79
+ continue;
80
+ }
81
+ if (tier === "semantic") {
82
+ writes.push(semantic.remember(item));
83
+ continue;
84
+ }
85
+ if (tier === "episodic") {
86
+ writes.push(episodic.remember(item));
87
+ continue;
88
+ }
89
+ writes.push(procedural.remember(item));
90
+ }
91
+ await Promise.all(writes);
92
+ },
93
+ async recall(query, options = {}) {
94
+ const k = options.k ?? defaultK;
95
+ const threshold = options.threshold ?? defaultThreshold;
96
+ if (options.tier) assertTierEnabled(options.tier, tiers, name);
97
+ const wants = (tier) => !options.tier || options.tier === tier;
98
+ const [workingHits, semanticHits, episodicHits, proceduralHits] = await Promise.all([
99
+ working && wants("working") ? Promise.resolve(working.recall(k)) : Promise.resolve([]),
100
+ semantic && wants("semantic") ? semantic.recall(query, k, threshold) : Promise.resolve([]),
101
+ episodic && wants("episodic") ? episodic.recall(query, k, threshold) : Promise.resolve([]),
102
+ procedural && wants("procedural") ? procedural.recall(query, k, threshold) : Promise.resolve([])
103
+ ]);
104
+ return [
105
+ ...workingHits,
106
+ ...semanticHits,
107
+ ...episodicHits,
108
+ ...proceduralHits
109
+ ].sort((first, second) => second.score - first.score).slice(0, k);
110
+ },
111
+ async clear(tier) {
112
+ const clears = [];
113
+ if (working && (!tier || tier === "working")) working.clear();
114
+ if (semantic && (!tier || tier === "semantic")) clears.push(semantic.clear());
115
+ if (episodic && (!tier || tier === "episodic")) clears.push(episodic.clear());
116
+ if (procedural && (!tier || tier === "procedural")) clears.push(procedural.clear());
117
+ await Promise.all(clears);
118
+ }
119
+ };
120
+ }
121
+ /**
122
+ * Resolve the semantic tier's store (explicit `store` wins, else the
123
+ * global `ai.config({ defaultStore })`) and build the tier. Throws at
124
+ * construction when neither is available — the same loud-now contract
125
+ * `semanticCache` follows.
126
+ */
127
+ function buildSemanticTier(semanticConfig, name) {
128
+ const store = semanticConfig.store ?? resolveDefaultStore();
129
+ if (!store) throw new Error(`memory("${name}"): semantic tier has no store — pass \`semantic.store\` or call \`ai.config({ defaultStore })\` at app boot before constructing the memory`);
130
+ return new SemanticMemory(semanticConfig.embedder, store, semanticConfig.namespace ?? DEFAULT_SEMANTIC_NAMESPACE);
131
+ }
132
+ /**
133
+ * Resolve the episodic tier's store (explicit `store` wins, else the
134
+ * global default) and build the tier with its recency knobs. Throws at
135
+ * construction when neither store is available — the same loud-now
136
+ * contract the semantic tier follows.
137
+ */
138
+ function buildEpisodicTier(episodicConfig, name) {
139
+ const store = episodicConfig.store ?? resolveDefaultStore();
140
+ if (!store) throw new Error(`memory("${name}"): episodic tier has no store — pass \`episodic.store\` or call \`ai.config({ defaultStore })\` at app boot before constructing the memory`);
141
+ return new EpisodicMemory(episodicConfig.embedder, store, episodicConfig.namespace ?? DEFAULT_EPISODIC_NAMESPACE, episodicConfig.recencyWeight ?? DEFAULT_RECENCY_WEIGHT, episodicConfig.halfLifeMs ?? DEFAULT_HALF_LIFE_MS, episodicConfig.now ?? (() => Date.now()));
142
+ }
143
+ /**
144
+ * Resolve the procedural tier's store and build the tier with its
145
+ * reinforcement knob. Throws at construction when no store is available.
146
+ */
147
+ function buildProceduralTier(proceduralConfig, name) {
148
+ const store = proceduralConfig.store ?? resolveDefaultStore();
149
+ if (!store) throw new Error(`memory("${name}"): procedural tier has no store — pass \`procedural.store\` or call \`ai.config({ defaultStore })\` at app boot before constructing the memory`);
150
+ return new ProceduralMemory(proceduralConfig.embedder, store, proceduralConfig.namespace ?? DEFAULT_PROCEDURAL_NAMESPACE, proceduralConfig.reinforcementWeight ?? DEFAULT_REINFORCEMENT_WEIGHT);
151
+ }
152
+ /**
153
+ * Guard that a tier referenced by config / a call is actually enabled,
154
+ * failing fast with an actionable message instead of a downstream
155
+ * `undefined` dereference.
156
+ */
157
+ function assertTierEnabled(tier, tiers, name) {
158
+ if (tier === "working" && !tiers.working) throw new Error(`memory("${name}"): working tier is disabled — set \`working: true\` (the default) to use it`);
159
+ if (tier === "semantic" && !tiers.semantic) throw new Error(`memory("${name}"): semantic tier is not configured — pass \`semantic\` config to use it`);
160
+ if (tier === "episodic" && !tiers.episodic) throw new Error(`memory("${name}"): episodic tier is not configured — pass \`episodic\` config to use it`);
161
+ if (tier === "procedural" && !tiers.procedural) throw new Error(`memory("${name}"): procedural tier is not configured — pass \`procedural\` config to use it`);
162
+ }
163
+
164
+ //#endregion
165
+ export { memory };
166
+ //# sourceMappingURL=memory.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/memory/memory.ts"],"sourcesContent":["import { resolveDefaultStore } from \"../config\";\nimport type { MemoryConfig } from \"../contracts/memory/memory-config.type\";\nimport type {\n MemoryItem,\n MemoryTier,\n RecalledMemory,\n} from \"../contracts/memory/memory-item.type\";\nimport type { MemoryContract } from \"../contracts/memory/memory.contract\";\nimport type { RecallOptions } from \"../contracts/memory/recall-options.type\";\nimport { EpisodicMemory } from \"./episodic-memory\";\nimport { ProceduralMemory } from \"./procedural-memory\";\nimport { SemanticMemory } from \"./semantic-memory\";\nimport { WorkingMemory } from \"./working-memory\";\n\nconst DEFAULT_NAME = \"memory\";\nconst DEFAULT_SEMANTIC_NAMESPACE = \"ai.memory.semantic\";\nconst DEFAULT_EPISODIC_NAMESPACE = \"ai.memory.episodic\";\nconst DEFAULT_PROCEDURAL_NAMESPACE = \"ai.memory.procedural\";\nconst DEFAULT_K = 5;\nconst DEFAULT_THRESHOLD = 0.7;\nconst DEFAULT_RECENCY_WEIGHT = 0.3;\nconst DEFAULT_HALF_LIFE_MS = 7 * 24 * 60 * 60 * 1000;\nconst DEFAULT_REINFORCEMENT_WEIGHT = 0.3;\n\n/**\n * Create an agent memory store (memory core M2).\n *\n * Wires up to four tiers behind the {@link MemoryContract}: **working**\n * (in-run scratch, recency), **semantic** (durable facts by cosine\n * similarity), **episodic** (durable events, similarity blended with\n * recency), and **procedural** (durable how-tos, similarity blended with\n * reinforcement). The working tier is on by default; the other three each\n * activate only when their config is supplied. The three vector tiers\n * mirror how `semanticCache` delegates similarity to the cache driver's\n * `.similar()`.\n *\n * Resolution happens once here, at construction (loud), rather than per\n * call (silent until first use): a vector-tier config with no `store` and\n * no `ai.config({ defaultStore })` throws now; enabling no tier at all\n * throws now.\n *\n * Decay / forgetting (TTL-based falloff, eviction) remains deferred.\n *\n * @example\n * import { ai } from \"@warlock.js/ai\";\n * import { MemoryCacheDriver } from \"@warlock.js/cache\";\n *\n * const store = new MemoryCacheDriver();\n * store.setOptions({});\n *\n * const mem = ai.memory({\n * semantic: { embedder, store },\n * defaultTier: \"semantic\",\n * });\n *\n * await mem.remember({ text: \"User prefers concise answers.\" });\n * const hits = await mem.recall(\"how should I respond?\", { k: 3 });\n */\nexport function memory(config: MemoryConfig = {}): MemoryContract {\n const name = config.name ?? DEFAULT_NAME;\n const workingEnabled = config.working ?? true;\n const defaultK = config.k ?? DEFAULT_K;\n const defaultThreshold = config.threshold ?? DEFAULT_THRESHOLD;\n\n const working = workingEnabled ? new WorkingMemory() : undefined;\n\n const semantic = config.semantic\n ? buildSemanticTier(config.semantic, name)\n : undefined;\n\n const episodic = config.episodic\n ? buildEpisodicTier(config.episodic, name)\n : undefined;\n\n const procedural = config.procedural\n ? buildProceduralTier(config.procedural, name)\n : undefined;\n\n const tiers: Tiers = { working, semantic, episodic, procedural };\n\n if (!working && !semantic && !episodic && !procedural) {\n throw new Error(\n `memory(\"${name}\"): no tier enabled — enable \\`working\\` (default) or pass a \\`semantic\\` / \\`episodic\\` / \\`procedural\\` config; a memory with no tiers can neither store nor recall`,\n );\n }\n\n const defaultTier: MemoryTier = config.defaultTier ?? \"working\";\n\n assertTierEnabled(defaultTier, tiers, name);\n\n return {\n name,\n async remember(items: MemoryItem | MemoryItem[]): Promise<void> {\n const list = Array.isArray(items) ? items : [items];\n\n const writes: Promise<void>[] = [];\n\n for (const item of list) {\n const tier = item.tier ?? defaultTier;\n\n assertTierEnabled(tier, tiers, name);\n\n if (tier === \"working\") {\n working!.remember(item);\n\n continue;\n }\n\n if (tier === \"semantic\") {\n writes.push(semantic!.remember(item));\n\n continue;\n }\n\n if (tier === \"episodic\") {\n writes.push(episodic!.remember(item));\n\n continue;\n }\n\n writes.push(procedural!.remember(item));\n }\n\n await Promise.all(writes);\n },\n async recall(\n query: string,\n options: RecallOptions = {},\n ): Promise<RecalledMemory[]> {\n const k = options.k ?? defaultK;\n const threshold = options.threshold ?? defaultThreshold;\n\n if (options.tier) {\n assertTierEnabled(options.tier, tiers, name);\n }\n\n const wants = (tier: MemoryTier): boolean =>\n !options.tier || options.tier === tier;\n\n const [workingHits, semanticHits, episodicHits, proceduralHits] =\n await Promise.all([\n working && wants(\"working\")\n ? Promise.resolve(working.recall(k))\n : Promise.resolve([] as RecalledMemory[]),\n semantic && wants(\"semantic\")\n ? semantic.recall(query, k, threshold)\n : Promise.resolve([] as RecalledMemory[]),\n episodic && wants(\"episodic\")\n ? episodic.recall(query, k, threshold)\n : Promise.resolve([] as RecalledMemory[]),\n procedural && wants(\"procedural\")\n ? procedural.recall(query, k, threshold)\n : Promise.resolve([] as RecalledMemory[]),\n ]);\n\n return [\n ...workingHits,\n ...semanticHits,\n ...episodicHits,\n ...proceduralHits,\n ]\n .sort((first, second) => second.score - first.score)\n .slice(0, k);\n },\n async clear(tier?: MemoryTier): Promise<void> {\n const clears: Promise<void>[] = [];\n\n if (working && (!tier || tier === \"working\")) {\n working.clear();\n }\n\n if (semantic && (!tier || tier === \"semantic\")) {\n clears.push(semantic.clear());\n }\n\n if (episodic && (!tier || tier === \"episodic\")) {\n clears.push(episodic.clear());\n }\n\n if (procedural && (!tier || tier === \"procedural\")) {\n clears.push(procedural.clear());\n }\n\n await Promise.all(clears);\n },\n };\n}\n\n/** The four tier instances a `memory()` composes; `undefined` when off. */\ntype Tiers = {\n working: WorkingMemory | undefined;\n semantic: SemanticMemory | undefined;\n episodic: EpisodicMemory | undefined;\n procedural: ProceduralMemory | undefined;\n};\n\n/**\n * Resolve the semantic tier's store (explicit `store` wins, else the\n * global `ai.config({ defaultStore })`) and build the tier. Throws at\n * construction when neither is available — the same loud-now contract\n * `semanticCache` follows.\n */\nfunction buildSemanticTier(\n semanticConfig: NonNullable<MemoryConfig[\"semantic\"]>,\n name: string,\n): SemanticMemory {\n const store = semanticConfig.store ?? resolveDefaultStore();\n\n if (!store) {\n throw new Error(\n `memory(\"${name}\"): semantic tier has no store — pass \\`semantic.store\\` or call \\`ai.config({ defaultStore })\\` at app boot before constructing the memory`,\n );\n }\n\n return new SemanticMemory(\n semanticConfig.embedder,\n store,\n semanticConfig.namespace ?? DEFAULT_SEMANTIC_NAMESPACE,\n );\n}\n\n/**\n * Resolve the episodic tier's store (explicit `store` wins, else the\n * global default) and build the tier with its recency knobs. Throws at\n * construction when neither store is available — the same loud-now\n * contract the semantic tier follows.\n */\nfunction buildEpisodicTier(\n episodicConfig: NonNullable<MemoryConfig[\"episodic\"]>,\n name: string,\n): EpisodicMemory {\n const store = episodicConfig.store ?? resolveDefaultStore();\n\n if (!store) {\n throw new Error(\n `memory(\"${name}\"): episodic tier has no store — pass \\`episodic.store\\` or call \\`ai.config({ defaultStore })\\` at app boot before constructing the memory`,\n );\n }\n\n return new EpisodicMemory(\n episodicConfig.embedder,\n store,\n episodicConfig.namespace ?? DEFAULT_EPISODIC_NAMESPACE,\n episodicConfig.recencyWeight ?? DEFAULT_RECENCY_WEIGHT,\n episodicConfig.halfLifeMs ?? DEFAULT_HALF_LIFE_MS,\n episodicConfig.now ?? (() => Date.now()),\n );\n}\n\n/**\n * Resolve the procedural tier's store and build the tier with its\n * reinforcement knob. Throws at construction when no store is available.\n */\nfunction buildProceduralTier(\n proceduralConfig: NonNullable<MemoryConfig[\"procedural\"]>,\n name: string,\n): ProceduralMemory {\n const store = proceduralConfig.store ?? resolveDefaultStore();\n\n if (!store) {\n throw new Error(\n `memory(\"${name}\"): procedural tier has no store — pass \\`procedural.store\\` or call \\`ai.config({ defaultStore })\\` at app boot before constructing the memory`,\n );\n }\n\n return new ProceduralMemory(\n proceduralConfig.embedder,\n store,\n proceduralConfig.namespace ?? DEFAULT_PROCEDURAL_NAMESPACE,\n proceduralConfig.reinforcementWeight ?? DEFAULT_REINFORCEMENT_WEIGHT,\n );\n}\n\n/**\n * Guard that a tier referenced by config / a call is actually enabled,\n * failing fast with an actionable message instead of a downstream\n * `undefined` dereference.\n */\nfunction assertTierEnabled(tier: MemoryTier, tiers: Tiers, name: string): void {\n if (tier === \"working\" && !tiers.working) {\n throw new Error(\n `memory(\"${name}\"): working tier is disabled — set \\`working: true\\` (the default) to use it`,\n );\n }\n\n if (tier === \"semantic\" && !tiers.semantic) {\n throw new Error(\n `memory(\"${name}\"): semantic tier is not configured — pass \\`semantic\\` config to use it`,\n );\n }\n\n if (tier === \"episodic\" && !tiers.episodic) {\n throw new Error(\n `memory(\"${name}\"): episodic tier is not configured — pass \\`episodic\\` config to use it`,\n );\n }\n\n if (tier === \"procedural\" && !tiers.procedural) {\n throw new Error(\n `memory(\"${name}\"): procedural tier is not configured — pass \\`procedural\\` config to use it`,\n );\n }\n}\n"],"mappings":";;;;;;;AAcA,MAAM,eAAe;AACrB,MAAM,6BAA6B;AACnC,MAAM,6BAA6B;AACnC,MAAM,+BAA+B;AACrC,MAAM,YAAY;AAClB,MAAM,oBAAoB;AAC1B,MAAM,yBAAyB;AAC/B,MAAM,uBAAuB,QAAc,KAAK;AAChD,MAAM,+BAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCrC,SAAgB,OAAO,SAAuB,CAAC,GAAmB;CAChE,MAAM,OAAO,OAAO,QAAQ;CAC5B,MAAM,iBAAiB,OAAO,WAAW;CACzC,MAAM,WAAW,OAAO,KAAK;CAC7B,MAAM,mBAAmB,OAAO,aAAa;CAE7C,MAAM,UAAU,iBAAiB,IAAI,cAAc,IAAI;CAEvD,MAAM,WAAW,OAAO,WACpB,kBAAkB,OAAO,UAAU,IAAI,IACvC;CAEJ,MAAM,WAAW,OAAO,WACpB,kBAAkB,OAAO,UAAU,IAAI,IACvC;CAEJ,MAAM,aAAa,OAAO,aACtB,oBAAoB,OAAO,YAAY,IAAI,IAC3C;CAEJ,MAAM,QAAe;EAAE;EAAS;EAAU;EAAU;CAAW;CAE/D,IAAI,CAAC,WAAW,CAAC,YAAY,CAAC,YAAY,CAAC,YACzC,MAAM,IAAI,MACR,WAAW,KAAK,sKAClB;CAGF,MAAM,cAA0B,OAAO,eAAe;CAEtD,kBAAkB,aAAa,OAAO,IAAI;CAE1C,OAAO;EACL;EACA,MAAM,SAAS,OAAiD;GAC9D,MAAM,OAAO,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;GAElD,MAAM,SAA0B,CAAC;GAEjC,KAAK,MAAM,QAAQ,MAAM;IACvB,MAAM,OAAO,KAAK,QAAQ;IAE1B,kBAAkB,MAAM,OAAO,IAAI;IAEnC,IAAI,SAAS,WAAW;KACtB,QAAS,SAAS,IAAI;KAEtB;IACF;IAEA,IAAI,SAAS,YAAY;KACvB,OAAO,KAAK,SAAU,SAAS,IAAI,CAAC;KAEpC;IACF;IAEA,IAAI,SAAS,YAAY;KACvB,OAAO,KAAK,SAAU,SAAS,IAAI,CAAC;KAEpC;IACF;IAEA,OAAO,KAAK,WAAY,SAAS,IAAI,CAAC;GACxC;GAEA,MAAM,QAAQ,IAAI,MAAM;EAC1B;EACA,MAAM,OACJ,OACA,UAAyB,CAAC,GACC;GAC3B,MAAM,IAAI,QAAQ,KAAK;GACvB,MAAM,YAAY,QAAQ,aAAa;GAEvC,IAAI,QAAQ,MACV,kBAAkB,QAAQ,MAAM,OAAO,IAAI;GAG7C,MAAM,SAAS,SACb,CAAC,QAAQ,QAAQ,QAAQ,SAAS;GAEpC,MAAM,CAAC,aAAa,cAAc,cAAc,kBAC9C,MAAM,QAAQ,IAAI;IAChB,WAAW,MAAM,SAAS,IACtB,QAAQ,QAAQ,QAAQ,OAAO,CAAC,CAAC,IACjC,QAAQ,QAAQ,CAAC,CAAqB;IAC1C,YAAY,MAAM,UAAU,IACxB,SAAS,OAAO,OAAO,GAAG,SAAS,IACnC,QAAQ,QAAQ,CAAC,CAAqB;IAC1C,YAAY,MAAM,UAAU,IACxB,SAAS,OAAO,OAAO,GAAG,SAAS,IACnC,QAAQ,QAAQ,CAAC,CAAqB;IAC1C,cAAc,MAAM,YAAY,IAC5B,WAAW,OAAO,OAAO,GAAG,SAAS,IACrC,QAAQ,QAAQ,CAAC,CAAqB;GAC5C,CAAC;GAEH,OAAO;IACL,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;GACL,CAAC,CACE,MAAM,OAAO,WAAW,OAAO,QAAQ,MAAM,KAAK,CAAC,CACnD,MAAM,GAAG,CAAC;EACf;EACA,MAAM,MAAM,MAAkC;GAC5C,MAAM,SAA0B,CAAC;GAEjC,IAAI,YAAY,CAAC,QAAQ,SAAS,YAChC,QAAQ,MAAM;GAGhB,IAAI,aAAa,CAAC,QAAQ,SAAS,aACjC,OAAO,KAAK,SAAS,MAAM,CAAC;GAG9B,IAAI,aAAa,CAAC,QAAQ,SAAS,aACjC,OAAO,KAAK,SAAS,MAAM,CAAC;GAG9B,IAAI,eAAe,CAAC,QAAQ,SAAS,eACnC,OAAO,KAAK,WAAW,MAAM,CAAC;GAGhC,MAAM,QAAQ,IAAI,MAAM;EAC1B;CACF;AACF;;;;;;;AAgBA,SAAS,kBACP,gBACA,MACgB;CAChB,MAAM,QAAQ,eAAe,SAAS,oBAAoB;CAE1D,IAAI,CAAC,OACH,MAAM,IAAI,MACR,WAAW,KAAK,4IAClB;CAGF,OAAO,IAAI,eACT,eAAe,UACf,OACA,eAAe,aAAa,0BAC9B;AACF;;;;;;;AAQA,SAAS,kBACP,gBACA,MACgB;CAChB,MAAM,QAAQ,eAAe,SAAS,oBAAoB;CAE1D,IAAI,CAAC,OACH,MAAM,IAAI,MACR,WAAW,KAAK,4IAClB;CAGF,OAAO,IAAI,eACT,eAAe,UACf,OACA,eAAe,aAAa,4BAC5B,eAAe,iBAAiB,wBAChC,eAAe,cAAc,sBAC7B,eAAe,cAAc,KAAK,IAAI,EACxC;AACF;;;;;AAMA,SAAS,oBACP,kBACA,MACkB;CAClB,MAAM,QAAQ,iBAAiB,SAAS,oBAAoB;CAE5D,IAAI,CAAC,OACH,MAAM,IAAI,MACR,WAAW,KAAK,gJAClB;CAGF,OAAO,IAAI,iBACT,iBAAiB,UACjB,OACA,iBAAiB,aAAa,8BAC9B,iBAAiB,uBAAuB,4BAC1C;AACF;;;;;;AAOA,SAAS,kBAAkB,MAAkB,OAAc,MAAoB;CAC7E,IAAI,SAAS,aAAa,CAAC,MAAM,SAC/B,MAAM,IAAI,MACR,WAAW,KAAK,6EAClB;CAGF,IAAI,SAAS,cAAc,CAAC,MAAM,UAChC,MAAM,IAAI,MACR,WAAW,KAAK,yEAClB;CAGF,IAAI,SAAS,cAAc,CAAC,MAAM,UAChC,MAAM,IAAI,MACR,WAAW,KAAK,yEAClB;CAGF,IAAI,SAAS,gBAAgB,CAAC,MAAM,YAClC,MAAM,IAAI,MACR,WAAW,KAAK,6EAClB;AAEJ"}
@@ -0,0 +1,103 @@
1
+ import { deriveMemoryId } from "./derive-id.mjs";
2
+
3
+ //#region ../@warlock.js/ai/src/memory/procedural-memory.ts
4
+ /**
5
+ * Extra candidates pulled from `similar()` before re-ranking by the
6
+ * reinforcement-blended score and slicing to `k` — reinforcement can
7
+ * promote a well-worn procedure past a slightly-closer one-off, which the
8
+ * raw top-`k` by similarity would miss.
9
+ */
10
+ const RECALL_OVERSCAN = 5;
11
+ /**
12
+ * Procedural recall tier (memory core M2).
13
+ *
14
+ * Holds durable *how-to* knowledge — learned procedures, policies, and
15
+ * playbooks — and retrieves the ones relevant to a query, **blended with
16
+ * reinforcement** so procedures that have proven themselves (remembered /
17
+ * re-affirmed more often) outrank one-offs at equal similarity. That
18
+ * reinforcement weighting is the difference from the semantic tier (which
19
+ * treats every fact equally): procedural memory gets *stronger with use*.
20
+ *
21
+ * Reinforcement is explicit and side-effect-free on read: re-remembering
22
+ * a procedure (same id, or same text → same derived id) increments its
23
+ * `uses`, so a caller strengthens a procedure by remembering it again
24
+ * after a successful application. Recall never mutates.
25
+ *
26
+ * Like the other vector tiers it delegates similarity to the
27
+ * `@warlock.js/cache` driver's `similar()`. The blended `score` stays in
28
+ * `[0, 1]` so procedural hits merge and sort alongside the other tiers.
29
+ *
30
+ * Internal to the `memory()` factory — never exported on the package
31
+ * surface.
32
+ */
33
+ var ProceduralMemory = class {
34
+ constructor(embedder, store, namespace, reinforcementWeight) {
35
+ this.embedder = embedder;
36
+ this.store = store;
37
+ this.namespace = namespace;
38
+ this.reinforcementWeight = reinforcementWeight;
39
+ }
40
+ /**
41
+ * Embed the procedure text and index it, incrementing its `uses` when
42
+ * it already exists (reinforcement) or seeding it at `1` when new.
43
+ * Metadata on a reinforcing write wins; an omitted metadata keeps the
44
+ * prior value rather than wiping it.
45
+ */
46
+ async remember(item) {
47
+ const id = item.id ?? deriveMemoryId(item.text);
48
+ const { vector } = await this.embedder.embed(item.text);
49
+ const existing = await this.store.get(this.keyFor(id));
50
+ const uses = (existing?.uses ?? 0) + 1;
51
+ const value = {
52
+ id,
53
+ text: item.text,
54
+ uses,
55
+ metadata: item.metadata ?? existing?.metadata
56
+ };
57
+ await this.store.set(this.keyFor(id), value, { vector });
58
+ }
59
+ /**
60
+ * Embed `query`, pull the nearest procedures clearing the similarity
61
+ * `threshold`, then re-rank each by a reinforcement-blended score and
62
+ * return the top `k`. The similarity floor still gates relevance;
63
+ * reinforcement only reorders procedures that already cleared it.
64
+ */
65
+ async recall(query, k, threshold) {
66
+ const { vector } = await this.embedder.embed(query);
67
+ const hits = await this.store.similar(vector, {
68
+ topK: Math.max(k * RECALL_OVERSCAN, k),
69
+ threshold
70
+ });
71
+ const prefix = `${this.namespace}.`;
72
+ return hits.filter((hit) => hit.key.startsWith(prefix)).map((hit) => ({
73
+ id: hit.value.id,
74
+ text: hit.value.text,
75
+ tier: "procedural",
76
+ score: this.blend(hit.score, hit.value.uses),
77
+ metadata: hit.value.metadata
78
+ })).sort((first, second) => second.score - first.score).slice(0, k);
79
+ }
80
+ /** Drop every procedure written under this instance's namespace. */
81
+ async clear() {
82
+ await this.store.removeNamespace(this.namespace);
83
+ }
84
+ /**
85
+ * Combine raw similarity with a saturating reinforcement proxy:
86
+ * `(1 - w)·similarity + w·(uses / (uses + 1))`. A first-time procedure
87
+ * contributes `0.5`; each reinforcement nudges it toward `1` with
88
+ * diminishing returns. With `reinforcementWeight` 0 the score is pure
89
+ * similarity.
90
+ */
91
+ blend(similarity, uses) {
92
+ const reinforcement = uses / (uses + 1);
93
+ return (1 - this.reinforcementWeight) * similarity + this.reinforcementWeight * reinforcement;
94
+ }
95
+ /** Namespaced key for an entry — dot separator, matching `similar()` keys. */
96
+ keyFor(id) {
97
+ return `${this.namespace}.${id}`;
98
+ }
99
+ };
100
+
101
+ //#endregion
102
+ export { ProceduralMemory };
103
+ //# sourceMappingURL=procedural-memory.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"procedural-memory.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/memory/procedural-memory.ts"],"sourcesContent":["import type { CacheDriver, CacheSimilarHit } from \"@warlock.js/cache\";\nimport type { EmbedderContract } from \"../contracts/embedder.contract\";\nimport type {\n MemoryItem,\n RecalledMemory,\n} from \"../contracts/memory/memory-item.type\";\nimport { deriveMemoryId } from \"./derive-id\";\n\n/**\n * Shape persisted per procedure. `uses` is the reinforcement counter —\n * how many times the procedure has been remembered/re-affirmed — and\n * feeds the reinforcement half of the blended recall score. The vector\n * lives in the driver's index, so it is not duplicated here.\n */\ntype StoredProcedure = {\n id: string;\n text: string;\n uses: number;\n metadata?: Record<string, unknown>;\n};\n\n/**\n * Extra candidates pulled from `similar()` before re-ranking by the\n * reinforcement-blended score and slicing to `k` — reinforcement can\n * promote a well-worn procedure past a slightly-closer one-off, which the\n * raw top-`k` by similarity would miss.\n */\nconst RECALL_OVERSCAN = 5;\n\n/**\n * Procedural recall tier (memory core M2).\n *\n * Holds durable *how-to* knowledge — learned procedures, policies, and\n * playbooks — and retrieves the ones relevant to a query, **blended with\n * reinforcement** so procedures that have proven themselves (remembered /\n * re-affirmed more often) outrank one-offs at equal similarity. That\n * reinforcement weighting is the difference from the semantic tier (which\n * treats every fact equally): procedural memory gets *stronger with use*.\n *\n * Reinforcement is explicit and side-effect-free on read: re-remembering\n * a procedure (same id, or same text → same derived id) increments its\n * `uses`, so a caller strengthens a procedure by remembering it again\n * after a successful application. Recall never mutates.\n *\n * Like the other vector tiers it delegates similarity to the\n * `@warlock.js/cache` driver's `similar()`. The blended `score` stays in\n * `[0, 1]` so procedural hits merge and sort alongside the other tiers.\n *\n * Internal to the `memory()` factory — never exported on the package\n * surface.\n */\nexport class ProceduralMemory {\n public constructor(\n private readonly embedder: EmbedderContract,\n private readonly store: CacheDriver<any, any>,\n private readonly namespace: string,\n private readonly reinforcementWeight: number,\n ) {}\n\n /**\n * Embed the procedure text and index it, incrementing its `uses` when\n * it already exists (reinforcement) or seeding it at `1` when new.\n * Metadata on a reinforcing write wins; an omitted metadata keeps the\n * prior value rather than wiping it.\n */\n public async remember(item: MemoryItem): Promise<void> {\n const id = item.id ?? deriveMemoryId(item.text);\n const { vector } = await this.embedder.embed(item.text);\n\n const existing = await this.store.get<StoredProcedure>(this.keyFor(id));\n const uses = (existing?.uses ?? 0) + 1;\n\n const value: StoredProcedure = {\n id,\n text: item.text,\n uses,\n metadata: item.metadata ?? existing?.metadata,\n };\n\n await this.store.set(this.keyFor(id), value, { vector });\n }\n\n /**\n * Embed `query`, pull the nearest procedures clearing the similarity\n * `threshold`, then re-rank each by a reinforcement-blended score and\n * return the top `k`. The similarity floor still gates relevance;\n * reinforcement only reorders procedures that already cleared it.\n */\n public async recall(\n query: string,\n k: number,\n threshold: number,\n ): Promise<RecalledMemory[]> {\n const { vector } = await this.embedder.embed(query);\n\n const hits = await this.store.similar<StoredProcedure>(vector, {\n topK: Math.max(k * RECALL_OVERSCAN, k),\n threshold,\n });\n\n const prefix = `${this.namespace}.`;\n\n return hits\n .filter((hit: CacheSimilarHit<StoredProcedure>) =>\n hit.key.startsWith(prefix),\n )\n .map((hit: CacheSimilarHit<StoredProcedure>) => ({\n id: hit.value.id,\n text: hit.value.text,\n tier: \"procedural\" as const,\n score: this.blend(hit.score, hit.value.uses),\n metadata: hit.value.metadata,\n }))\n .sort((first, second) => second.score - first.score)\n .slice(0, k);\n }\n\n /** Drop every procedure written under this instance's namespace. */\n public async clear(): Promise<void> {\n await this.store.removeNamespace(this.namespace);\n }\n\n /**\n * Combine raw similarity with a saturating reinforcement proxy:\n * `(1 - w)·similarity + w·(uses / (uses + 1))`. A first-time procedure\n * contributes `0.5`; each reinforcement nudges it toward `1` with\n * diminishing returns. With `reinforcementWeight` 0 the score is pure\n * similarity.\n */\n private blend(similarity: number, uses: number): number {\n const reinforcement = uses / (uses + 1);\n\n return (\n (1 - this.reinforcementWeight) * similarity +\n this.reinforcementWeight * reinforcement\n );\n }\n\n /** Namespaced key for an entry — dot separator, matching `similar()` keys. */\n private keyFor(id: string): string {\n return `${this.namespace}.${id}`;\n }\n}\n"],"mappings":";;;;;;;;;AA2BA,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;AAwBxB,IAAa,mBAAb,MAA8B;CAC5B,AAAO,YACL,AAAiB,UACjB,AAAiB,OACjB,AAAiB,WACjB,AAAiB,qBACjB;EAJiB;EACA;EACA;EACA;CAChB;;;;;;;CAQH,MAAa,SAAS,MAAiC;EACrD,MAAM,KAAK,KAAK,MAAM,eAAe,KAAK,IAAI;EAC9C,MAAM,EAAE,WAAW,MAAM,KAAK,SAAS,MAAM,KAAK,IAAI;EAEtD,MAAM,WAAW,MAAM,KAAK,MAAM,IAAqB,KAAK,OAAO,EAAE,CAAC;EACtE,MAAM,QAAQ,UAAU,QAAQ,KAAK;EAErC,MAAM,QAAyB;GAC7B;GACA,MAAM,KAAK;GACX;GACA,UAAU,KAAK,YAAY,UAAU;EACvC;EAEA,MAAM,KAAK,MAAM,IAAI,KAAK,OAAO,EAAE,GAAG,OAAO,EAAE,OAAO,CAAC;CACzD;;;;;;;CAQA,MAAa,OACX,OACA,GACA,WAC2B;EAC3B,MAAM,EAAE,WAAW,MAAM,KAAK,SAAS,MAAM,KAAK;EAElD,MAAM,OAAO,MAAM,KAAK,MAAM,QAAyB,QAAQ;GAC7D,MAAM,KAAK,IAAI,IAAI,iBAAiB,CAAC;GACrC;EACF,CAAC;EAED,MAAM,SAAS,GAAG,KAAK,UAAU;EAEjC,OAAO,KACJ,QAAQ,QACP,IAAI,IAAI,WAAW,MAAM,CAC3B,CAAC,CACA,KAAK,SAA2C;GAC/C,IAAI,IAAI,MAAM;GACd,MAAM,IAAI,MAAM;GAChB,MAAM;GACN,OAAO,KAAK,MAAM,IAAI,OAAO,IAAI,MAAM,IAAI;GAC3C,UAAU,IAAI,MAAM;EACtB,EAAE,CAAC,CACF,MAAM,OAAO,WAAW,OAAO,QAAQ,MAAM,KAAK,CAAC,CACnD,MAAM,GAAG,CAAC;CACf;;CAGA,MAAa,QAAuB;EAClC,MAAM,KAAK,MAAM,gBAAgB,KAAK,SAAS;CACjD;;;;;;;;CASA,AAAQ,MAAM,YAAoB,MAAsB;EACtD,MAAM,gBAAgB,QAAQ,OAAO;EAErC,QACG,IAAI,KAAK,uBAAuB,aACjC,KAAK,sBAAsB;CAE/B;;CAGA,AAAQ,OAAO,IAAoB;EACjC,OAAO,GAAG,KAAK,UAAU,GAAG;CAC9B;AACF"}
@@ -0,0 +1,80 @@
1
+ import { deriveMemoryId } from "./derive-id.mjs";
2
+
3
+ //#region ../@warlock.js/ai/src/memory/semantic-memory.ts
4
+ /**
5
+ * Semantic recall tier (memory core M1).
6
+ *
7
+ * Owns: embedding remembered text, writing it to a `@warlock.js/cache`
8
+ * driver with `set({ vector })`, and retrieving by cosine similarity via
9
+ * the driver's `similar()`. Does NOT own: the similarity algorithm or
10
+ * the ANN index — those belong to the cache driver. This mirrors the
11
+ * delegation model of `middleware/builtins/semantic-cache.ts`: memory is
12
+ * embedding-agnostic and store-agnostic, gluing an {@link EmbedderContract}
13
+ * to a {@link CacheDriver}.
14
+ *
15
+ * The driver may be shared across memory instances, so every key carries
16
+ * the configured `namespace` and recall filters hits to that prefix —
17
+ * foreign entries indexed by another instance never leak into a query.
18
+ *
19
+ * Internal to the `memory()` factory — never exported on the package
20
+ * surface.
21
+ */
22
+ var SemanticMemory = class {
23
+ constructor(embedder, store, namespace) {
24
+ this.embedder = embedder;
25
+ this.store = store;
26
+ this.namespace = namespace;
27
+ }
28
+ /**
29
+ * Embed the item's text and index it under a namespaced, id-derived
30
+ * key. Re-remembering the same id overwrites the prior vector +
31
+ * value (the driver upserts by key).
32
+ */
33
+ async remember(item) {
34
+ const id = item.id ?? deriveMemoryId(item.text);
35
+ const { vector } = await this.embedder.embed(item.text);
36
+ const value = {
37
+ id,
38
+ text: item.text,
39
+ metadata: item.metadata
40
+ };
41
+ await this.store.set(this.keyFor(id), value, { vector });
42
+ }
43
+ /**
44
+ * Embed `query`, ask the driver for the `k` nearest entries clearing
45
+ * `threshold`, and return those within this instance's namespace as
46
+ * scored {@link RecalledMemory}. Hits indexed under a different
47
+ * namespace (a shared driver) are filtered out.
48
+ */
49
+ async recall(query, k, threshold) {
50
+ const { vector } = await this.embedder.embed(query);
51
+ const hits = await this.store.similar(vector, {
52
+ topK: k,
53
+ threshold
54
+ });
55
+ const prefix = `${this.namespace}.`;
56
+ return hits.filter((hit) => hit.key.startsWith(prefix)).map((hit) => ({
57
+ id: hit.value.id,
58
+ text: hit.value.text,
59
+ tier: "semantic",
60
+ score: hit.score,
61
+ metadata: hit.value.metadata
62
+ }));
63
+ }
64
+ /** Drop every semantic entry written under this instance's namespace. */
65
+ async clear() {
66
+ await this.store.removeNamespace(this.namespace);
67
+ }
68
+ /**
69
+ * Namespaced key for an entry. The cache's `parseKey` normalizes `:`
70
+ * to `.`, so a dot separator keeps the prefix used here aligned with
71
+ * the `hit.key` the driver returns from `similar()`.
72
+ */
73
+ keyFor(id) {
74
+ return `${this.namespace}.${id}`;
75
+ }
76
+ };
77
+
78
+ //#endregion
79
+ export { SemanticMemory };
80
+ //# sourceMappingURL=semantic-memory.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"semantic-memory.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/memory/semantic-memory.ts"],"sourcesContent":["import type { CacheDriver, CacheSimilarHit } from \"@warlock.js/cache\";\nimport type { EmbedderContract } from \"../contracts/embedder.contract\";\nimport type {\n MemoryItem,\n RecalledMemory,\n} from \"../contracts/memory/memory-item.type\";\nimport { deriveMemoryId } from \"./derive-id\";\n\n/**\n * Shape persisted per semantic memory in the cache driver. The vector\n * itself is stored by the driver's own index (passed via\n * `set({ vector })`), so it is not duplicated in the value.\n */\ntype StoredMemory = {\n id: string;\n text: string;\n metadata?: Record<string, unknown>;\n};\n\n/**\n * Semantic recall tier (memory core M1).\n *\n * Owns: embedding remembered text, writing it to a `@warlock.js/cache`\n * driver with `set({ vector })`, and retrieving by cosine similarity via\n * the driver's `similar()`. Does NOT own: the similarity algorithm or\n * the ANN index — those belong to the cache driver. This mirrors the\n * delegation model of `middleware/builtins/semantic-cache.ts`: memory is\n * embedding-agnostic and store-agnostic, gluing an {@link EmbedderContract}\n * to a {@link CacheDriver}.\n *\n * The driver may be shared across memory instances, so every key carries\n * the configured `namespace` and recall filters hits to that prefix —\n * foreign entries indexed by another instance never leak into a query.\n *\n * Internal to the `memory()` factory — never exported on the package\n * surface.\n */\nexport class SemanticMemory {\n public constructor(\n private readonly embedder: EmbedderContract,\n private readonly store: CacheDriver<any, any>,\n private readonly namespace: string,\n ) {}\n\n /**\n * Embed the item's text and index it under a namespaced, id-derived\n * key. Re-remembering the same id overwrites the prior vector +\n * value (the driver upserts by key).\n */\n public async remember(item: MemoryItem): Promise<void> {\n const id = item.id ?? deriveMemoryId(item.text);\n const { vector } = await this.embedder.embed(item.text);\n\n const value: StoredMemory = {\n id,\n text: item.text,\n metadata: item.metadata,\n };\n\n await this.store.set(this.keyFor(id), value, { vector });\n }\n\n /**\n * Embed `query`, ask the driver for the `k` nearest entries clearing\n * `threshold`, and return those within this instance's namespace as\n * scored {@link RecalledMemory}. Hits indexed under a different\n * namespace (a shared driver) are filtered out.\n */\n public async recall(\n query: string,\n k: number,\n threshold: number,\n ): Promise<RecalledMemory[]> {\n const { vector } = await this.embedder.embed(query);\n\n const hits = await this.store.similar<StoredMemory>(vector, {\n topK: k,\n threshold,\n });\n\n const prefix = `${this.namespace}.`;\n\n return hits\n .filter((hit: CacheSimilarHit<StoredMemory>) =>\n hit.key.startsWith(prefix),\n )\n .map((hit: CacheSimilarHit<StoredMemory>) => ({\n id: hit.value.id,\n text: hit.value.text,\n tier: \"semantic\" as const,\n score: hit.score,\n metadata: hit.value.metadata,\n }));\n }\n\n /** Drop every semantic entry written under this instance's namespace. */\n public async clear(): Promise<void> {\n await this.store.removeNamespace(this.namespace);\n }\n\n /**\n * Namespaced key for an entry. The cache's `parseKey` normalizes `:`\n * to `.`, so a dot separator keeps the prefix used here aligned with\n * the `hit.key` the driver returns from `similar()`.\n */\n private keyFor(id: string): string {\n return `${this.namespace}.${id}`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqCA,IAAa,iBAAb,MAA4B;CAC1B,AAAO,YACL,AAAiB,UACjB,AAAiB,OACjB,AAAiB,WACjB;EAHiB;EACA;EACA;CAChB;;;;;;CAOH,MAAa,SAAS,MAAiC;EACrD,MAAM,KAAK,KAAK,MAAM,eAAe,KAAK,IAAI;EAC9C,MAAM,EAAE,WAAW,MAAM,KAAK,SAAS,MAAM,KAAK,IAAI;EAEtD,MAAM,QAAsB;GAC1B;GACA,MAAM,KAAK;GACX,UAAU,KAAK;EACjB;EAEA,MAAM,KAAK,MAAM,IAAI,KAAK,OAAO,EAAE,GAAG,OAAO,EAAE,OAAO,CAAC;CACzD;;;;;;;CAQA,MAAa,OACX,OACA,GACA,WAC2B;EAC3B,MAAM,EAAE,WAAW,MAAM,KAAK,SAAS,MAAM,KAAK;EAElD,MAAM,OAAO,MAAM,KAAK,MAAM,QAAsB,QAAQ;GAC1D,MAAM;GACN;EACF,CAAC;EAED,MAAM,SAAS,GAAG,KAAK,UAAU;EAEjC,OAAO,KACJ,QAAQ,QACP,IAAI,IAAI,WAAW,MAAM,CAC3B,CAAC,CACA,KAAK,SAAwC;GAC5C,IAAI,IAAI,MAAM;GACd,MAAM,IAAI,MAAM;GAChB,MAAM;GACN,OAAO,IAAI;GACX,UAAU,IAAI,MAAM;EACtB,EAAE;CACN;;CAGA,MAAa,QAAuB;EAClC,MAAM,KAAK,MAAM,gBAAgB,KAAK,SAAS;CACjD;;;;;;CAOA,AAAQ,OAAO,IAAoB;EACjC,OAAO,GAAG,KAAK,UAAU,GAAG;CAC9B;AACF"}
@@ -0,0 +1,62 @@
1
+ import { deriveMemoryId } from "./derive-id.mjs";
2
+
3
+ //#region ../@warlock.js/ai/src/memory/working-memory.ts
4
+ /**
5
+ * In-run working memory — the volatile scratch tier (memory core M1).
6
+ *
7
+ * Owns: an insertion-ordered buffer of remembered items keyed by id,
8
+ * with overwrite-in-place on a repeated id. Does NOT own: durability,
9
+ * cross-process sharing, embeddings, or similarity — working memory is
10
+ * a plain in-process buffer the orchestrator threads across the turns of
11
+ * a single run.
12
+ *
13
+ * Recall here is not semantic: with no vector index, "relevant" reduces
14
+ * to "recent." `recall()` returns the most-recently-remembered items
15
+ * first, each scored on a `[0, 1]` recency proxy so a caller can merge
16
+ * working hits with semantic hits and sort on one `score` field.
17
+ *
18
+ * Internal to the `memory()` factory — never exported on the package
19
+ * surface.
20
+ */
21
+ var WorkingMemory = class {
22
+ constructor() {
23
+ this.entries = /* @__PURE__ */ new Map();
24
+ }
25
+ /**
26
+ * Append an item to the buffer (or overwrite the entry sharing its
27
+ * id). Re-inserting an existing id keeps its original position; delete
28
+ * + set would move it to the end and lie about recency, so the value
29
+ * is updated in place.
30
+ */
31
+ remember(item) {
32
+ const id = item.id ?? deriveMemoryId(item.text);
33
+ this.entries.set(id, {
34
+ text: item.text,
35
+ metadata: item.metadata
36
+ });
37
+ }
38
+ /**
39
+ * Return up to `k` most-recently-remembered items, newest first. The
40
+ * `score` is a linear recency proxy: the newest item scores `1`, the
41
+ * oldest of the returned slice trends toward `0`. Working memory
42
+ * ignores any similarity threshold — it has no vector to compare.
43
+ */
44
+ recall(k) {
45
+ const slice = [...this.entries.entries()].reverse().slice(0, Math.max(0, k));
46
+ return slice.map(([id, entry], index) => ({
47
+ id,
48
+ text: entry.text,
49
+ tier: "working",
50
+ score: slice.length <= 1 ? 1 : 1 - index / slice.length,
51
+ metadata: entry.metadata
52
+ }));
53
+ }
54
+ /** Drop every working-tier entry. */
55
+ clear() {
56
+ this.entries.clear();
57
+ }
58
+ };
59
+
60
+ //#endregion
61
+ export { WorkingMemory };
62
+ //# sourceMappingURL=working-memory.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"working-memory.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/memory/working-memory.ts"],"sourcesContent":["import type {\n MemoryItem,\n RecalledMemory,\n} from \"../contracts/memory/memory-item.type\";\nimport { deriveMemoryId } from \"./derive-id\";\n\n/**\n * In-run working memory — the volatile scratch tier (memory core M1).\n *\n * Owns: an insertion-ordered buffer of remembered items keyed by id,\n * with overwrite-in-place on a repeated id. Does NOT own: durability,\n * cross-process sharing, embeddings, or similarity — working memory is\n * a plain in-process buffer the orchestrator threads across the turns of\n * a single run.\n *\n * Recall here is not semantic: with no vector index, \"relevant\" reduces\n * to \"recent.\" `recall()` returns the most-recently-remembered items\n * first, each scored on a `[0, 1]` recency proxy so a caller can merge\n * working hits with semantic hits and sort on one `score` field.\n *\n * Internal to the `memory()` factory — never exported on the package\n * surface.\n */\nexport class WorkingMemory {\n /**\n * Id → text/metadata. A `Map` preserves insertion order, so iteration\n * yields oldest-first; recall reverses it for most-recent-first.\n */\n private readonly entries = new Map<\n string,\n { text: string; metadata?: Record<string, unknown> }\n >();\n\n /**\n * Append an item to the buffer (or overwrite the entry sharing its\n * id). Re-inserting an existing id keeps its original position; delete\n * + set would move it to the end and lie about recency, so the value\n * is updated in place.\n */\n public remember(item: MemoryItem): void {\n const id = item.id ?? deriveMemoryId(item.text);\n\n this.entries.set(id, { text: item.text, metadata: item.metadata });\n }\n\n /**\n * Return up to `k` most-recently-remembered items, newest first. The\n * `score` is a linear recency proxy: the newest item scores `1`, the\n * oldest of the returned slice trends toward `0`. Working memory\n * ignores any similarity threshold — it has no vector to compare.\n */\n public recall(k: number): RecalledMemory[] {\n const ordered = [...this.entries.entries()].reverse();\n const slice = ordered.slice(0, Math.max(0, k));\n\n return slice.map(([id, entry], index) => ({\n id,\n text: entry.text,\n tier: \"working\" as const,\n score: slice.length <= 1 ? 1 : 1 - index / slice.length,\n metadata: entry.metadata,\n }));\n }\n\n /** Drop every working-tier entry. */\n public clear(): void {\n this.entries.clear();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,gBAAb,MAA2B;;iCAKE,IAAI,IAG7B;;;;;;;;CAQF,AAAO,SAAS,MAAwB;EACtC,MAAM,KAAK,KAAK,MAAM,eAAe,KAAK,IAAI;EAE9C,KAAK,QAAQ,IAAI,IAAI;GAAE,MAAM,KAAK;GAAM,UAAU,KAAK;EAAS,CAAC;CACnE;;;;;;;CAQA,AAAO,OAAO,GAA6B;EAEzC,MAAM,QADU,CAAC,GAAG,KAAK,QAAQ,QAAQ,CAAC,CAAC,CAAC,QACxB,CAAC,CAAC,MAAM,GAAG,KAAK,IAAI,GAAG,CAAC,CAAC;EAE7C,OAAO,MAAM,KAAK,CAAC,IAAI,QAAQ,WAAW;GACxC;GACA,MAAM,MAAM;GACZ,MAAM;GACN,OAAO,MAAM,UAAU,IAAI,IAAI,IAAI,QAAQ,MAAM;GACjD,UAAU,MAAM;EAClB,EAAE;CACJ;;CAGA,AAAO,QAAc;EACnB,KAAK,QAAQ,MAAM;CACrB;AACF"}