@desplega.ai/agent-swarm 2.7.10 → 2.8.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 (281) hide show
  1. package/dist/acp-adapter-t949vbbp.js +15 -0
  2. package/dist/{actions-b8aqhrsg.js → actions-7e9czc7s.js} +18 -19
  3. package/dist/{amp-adapter-4c165vgn.js → amp-adapter-gv6cbb7d.js} +2 -3
  4. package/dist/{app-m9khefrh.js → app-b9fbkp9v.js} +3 -3
  5. package/dist/{assistant-rh4v3ntz.js → assistant-wjb7v4c7.js} +20 -21
  6. package/dist/{boot-args-schema-hwkc8bzv.js → boot-args-schema-2t37e0fe.js} +1 -1
  7. package/dist/{boot-reembed-5y6yw9sj.js → boot-reembed-a35nkyr1.js} +1 -1
  8. package/dist/{boot-reembed-fdyk55h4.js → boot-reembed-gka3zas7.js} +1 -1
  9. package/dist/{boot-scrub-sweep-r5r8kqsn.js → boot-scrub-sweep-65sdnp6c.js} +3 -3
  10. package/dist/{boot-seeds-8f9zt5cm.js → boot-seeds-x42tzytw.js} +4 -5
  11. package/dist/{claude-adapter-s5df247c.js → claude-adapter-v221b2fd.js} +7 -8
  12. package/dist/{claude-managed-adapter-h74d06yz.js → claude-managed-adapter-29eq09wd.js} +2 -2
  13. package/dist/{claude-managed-setup-9gsmwzyx.js → claude-managed-setup-9m6450zk.js} +2 -2
  14. package/dist/{claude-sdk-session-dq1j4nz9.js → claude-sdk-session-0q0ptaba.js} +9066 -8818
  15. package/dist/{cli-n5yexkdg.js → cli-0b4zam62.js} +1 -0
  16. package/dist/{cli-5wfz00be.js → cli-0jzra9ad.js} +2 -2
  17. package/dist/{cli-eqtfgfr6.js → cli-2gxeg5gr.js} +1 -1
  18. package/dist/{cli-eqk5p56g.js → cli-2wnq8jkz.js} +9 -9
  19. package/dist/{cli-hfkwwy1h.js → cli-2zp0et3v.js} +21 -2
  20. package/dist/{cli-rt0ag4x1.js → cli-334z18y3.js} +4 -4
  21. package/dist/{cli-6m6b4bep.js → cli-3rkdne1h.js} +2 -2
  22. package/dist/{cli-3xddv0rk.js → cli-4txa0ter.js} +5 -7
  23. package/dist/{cli-jc1g9ndz.js → cli-5j88qqa8.js} +10 -5
  24. package/dist/{cli-xfjrc279.js → cli-5mrq3ake.js} +48 -14
  25. package/dist/{cli-n07eecjs.js → cli-6t09sdhy.js} +3 -3
  26. package/dist/{cli-38yww4e9.js → cli-6wxjceza.js} +8 -8
  27. package/dist/{cli-5xcb8gxq.js → cli-7b8sbmag.js} +8 -8
  28. package/dist/{cli-3xj33nrx.js → cli-7cp6aa1q.js} +10 -3
  29. package/dist/{cli-mp9aa8g5.js → cli-7p1kvkck.js} +6 -6
  30. package/dist/{cli-w3bk0dgv.js → cli-8aes17e4.js} +2 -2
  31. package/dist/{cli-n9abj89w.js → cli-8fknbnhw.js} +8 -8
  32. package/dist/{cli-xd5ebp64.js → cli-8kzasymh.js} +3 -3
  33. package/dist/{cli-2tsfpc70.js → cli-a7wvp2km.js} +1 -1
  34. package/dist/{cli-kx4c8j05.js → cli-abejgen1.js} +63 -19
  35. package/dist/{cli-36wdfzgn.js → cli-bsywb58a.js} +8 -8
  36. package/dist/{cli-yz7v0sh4.js → cli-c55z5chy.js} +4 -6
  37. package/dist/{cli-18qt3few.js → cli-deefvewm.js} +1 -1
  38. package/dist/{cli-jg24scat.js → cli-ee0b971j.js} +3 -3
  39. package/dist/cli-f3vq58d2.js +242 -0
  40. package/dist/{cli-3xcwp3z8.js → cli-ffhtssbp.js} +2 -2
  41. package/dist/{cli-rjyghzg4.js → cli-g70vxtjh.js} +2 -2
  42. package/dist/{cli-g1px1g2e.js → cli-gxkx0zzp.js} +1 -1
  43. package/dist/{cli-j7d73g1y.js → cli-h38x262p.js} +3035 -354
  44. package/dist/{cli-zjphdj1a.js → cli-j790gp2w.js} +40 -18
  45. package/dist/{cli-f2zenhja.js → cli-kc7v1nfv.js} +1 -1
  46. package/dist/{cli-td33w98c.js → cli-m23zjcy2.js} +10 -10
  47. package/dist/{cli-8ewkreqd.js → cli-m28atx8q.js} +7 -9
  48. package/dist/{cli-x9exydey.js → cli-m4dqmnbp.js} +1 -1
  49. package/dist/{cli-ybjdc978.js → cli-mrt48bx7.js} +7 -4
  50. package/dist/{cli-mr97t7cc.js → cli-p1bq50aa.js} +263 -14
  51. package/dist/{cli-ttbqe3q4.js → cli-p1w18yhx.js} +1 -1
  52. package/dist/{cli-nj3x45rw.js → cli-p2gfst4m.js} +52 -43
  53. package/dist/{cli-z9cs5m0w.js → cli-pasjcnmj.js} +12 -12
  54. package/dist/{cli-an1knn2k.js → cli-qa4wdgsy.js} +5 -5
  55. package/dist/{cli-xncjscpm.js → cli-qfedvmcr.js} +50 -24
  56. package/dist/{cli-tmft5dz2.js → cli-qmqk2yc2.js} +1 -1
  57. package/dist/{cli-bxz823sz.js → cli-qsnnd04k.js} +1 -1
  58. package/dist/{cli-cr14kftt.js → cli-qwca7s44.js} +3 -3
  59. package/dist/{cli-7wz05bx3.js → cli-rfywm85n.js} +460 -737
  60. package/dist/{cli-v2fwbnsk.js → cli-rmmpt0wm.js} +6 -6
  61. package/dist/{cli-xbtq4d6s.js → cli-rzsy6nc6.js} +12 -8
  62. package/dist/{cli-0m7rtm11.js → cli-s7t6p9my.js} +1 -1
  63. package/dist/{cli-16phend6.js → cli-sdtt3men.js} +1 -1
  64. package/dist/{cli-pyrxt9gw.js → cli-tk7cjj8h.js} +1 -1
  65. package/dist/{cli-xvymtmv4.js → cli-tqegb8eq.js} +3 -3
  66. package/dist/{cli-kf3pxxdg.js → cli-v1dv1r37.js} +1 -1
  67. package/dist/{cli-h49ejvmc.js → cli-wcg8x116.js} +1 -1
  68. package/dist/{cli-q581b386.js → cli-wk18cm92.js} +5 -5
  69. package/dist/{cli-4vwxp550.js → cli-x1wa213s.js} +1 -1
  70. package/dist/{cli-jrp1dt73.js → cli-xzm9vcfg.js} +1 -1
  71. package/dist/{cli-eb2azq8n.js → cli-y97qxcfx.js} +9 -9
  72. package/dist/{cli-55bkx8hh.js → cli-yq3zak69.js} +1 -1
  73. package/dist/cli.js +17 -17
  74. package/dist/{codex-adapter-yr60sme6.js → codex-adapter-30j9bpzd.js} +5 -6
  75. package/dist/{codex-hook-fac6175r.js → codex-hook-h3vk6xzr.js} +1 -1
  76. package/dist/{codex-session-runner-pch8x584.js → codex-session-runner-8vp57v8w.js} +5 -6
  77. package/dist/{commands-phjfbkv0.js → commands-bngnz9g7.js} +3 -3
  78. package/dist/{controller-jkx994pz.js → controller-hxx8wwy1.js} +2 -2
  79. package/dist/{controllers-connect-c4448kwa.js → controllers-connect-e2b4gyxc.js} +19 -20
  80. package/dist/{cursor-adapter-ndebqnm8.js → cursor-adapter-n5nc3mfe.js} +1 -2
  81. package/dist/{db-ez6egt6v.js → db-bgm7vkc0.js} +3 -3
  82. package/dist/{db-ef32tbfc.js → db-c6np41ca.js} +10 -2
  83. package/dist/{devin-adapter-z46ep5ph.js → devin-adapter-xedz98zv.js} +1 -1
  84. package/dist/{dispatcher-g3tt9hs9.js → dispatcher-jnybck15.js} +17 -18
  85. package/dist/{dsh-adapter-tcyn3099.js → dsh-adapter-nrhbrjz8.js} +1 -2
  86. package/dist/{easter-egg-3d-e36hk5td.js → easter-egg-3d-533knw22.js} +1 -1
  87. package/dist/{embedding-space-4kyh5qqj.js → embedding-space-crsm2zp0.js} +6 -6
  88. package/dist/{embeddings-6a8v4a6t.js → embeddings-e7z3f27f.js} +1 -1
  89. package/dist/{execute-3cbg0twf.js → execute-b3mrb1mv.js} +1 -1
  90. package/dist/{external-channel-se646snz.js → external-channel-m77wf5z3.js} +2 -2
  91. package/dist/{fx-adapter-yw795hqq.js → fx-adapter-b6w0kf56.js} +7 -8
  92. package/dist/{grok-adapter-ttmcss2j.js → grok-adapter-4sqtebdk.js} +7 -8
  93. package/dist/handlers-kdjcyzdj.js +32 -0
  94. package/dist/heartbeat-xgb036sx.js +43 -0
  95. package/dist/{hook-g3nhexsy.js → hook-5h02c9ga.js} +6 -6
  96. package/dist/{hook-hq93y5ej.js → hook-xsk1jbha.js} +5 -5
  97. package/dist/{http-5a9p4h6y.js → http-txe7qhvn.js} +282 -140
  98. package/dist/{index-6haqt3v5.js → index-4a0670yh.js} +8917 -8476
  99. package/dist/index-835xdgnm.js +33 -0
  100. package/dist/index-d469300x.js +37 -0
  101. package/dist/index-rzqwp11g.js +32 -0
  102. package/dist/{index-s72rqgsx.js → index-tvfafeyy.js} +1 -1
  103. package/dist/{index-hgn3c961.js → index-vk63emp7.js} +978 -35
  104. package/dist/{index-3c5pxbge.js → index-ysvbhg5m.js} +1 -1
  105. package/dist/{keepalive-1j4n4dmk.js → keepalive-4zsrce78.js} +3 -3
  106. package/dist/lead-yqt47dkr.js +70 -0
  107. package/dist/{maintenance-dmghacy5.js → maintenance-86jvartk.js} +1 -1
  108. package/dist/{oauth-refresh-sweep-yy06c03c.js → oauth-refresh-sweep-j52kg9pr.js} +2 -2
  109. package/dist/{onboard-52f9t5dm.js → onboard-c2aj5p8q.js} +3 -3
  110. package/dist/{opencode-adapter-krnh9jkn.js → opencode-adapter-dsagkhtw.js} +5 -6
  111. package/dist/{otel-impl-xjqz6wjj.js → otel-impl-yyy203z8.js} +1 -1
  112. package/dist/{pi-mono-adapter-dbxyp0qv.js → pi-mono-adapter-546cd1cc.js} +9 -9
  113. package/dist/{pricing-refresh-ctdr74pd.js → pricing-refresh-1rgzqyzz.js} +2 -3
  114. package/dist/{rbac-roles-q0gr8eyj.js → rbac-roles-e70xfeyj.js} +4 -6
  115. package/dist/{rbac-roles-ehv8s10n.js → rbac-roles-q89qe8er.js} +3 -3
  116. package/dist/{registry-hpjfmcfz.js → registry-32b1mft6.js} +1 -1
  117. package/dist/{render-v2-5b6chvcq.js → render-v2-k6tt107q.js} +3 -3
  118. package/dist/{resume-5a5d2845.js → resume-cnnrjfxa.js} +6 -6
  119. package/dist/{runtime-khxszyfp.js → runtime-1hv06jsn.js} +1 -1
  120. package/dist/{session-access-gj0bjhqg.js → session-access-xkxkjw3n.js} +4 -4
  121. package/dist/{session-source-backfill-2sy0krfk.js → session-source-backfill-1d5pdwww.js} +2 -2
  122. package/dist/{setup-7ssfakk1.js → setup-se8q7gkc.js} +1 -1
  123. package/dist/{virtual-modules-pjj0knwf.js → virtual-modules-gazyapte.js} +3 -3
  124. package/dist/{work-objects-bf3syvhq.js → work-objects-1kxnbzy5.js} +20 -21
  125. package/dist/{worker-follow-up-38xevga6.js → worker-follow-up-zqm8apt4.js} +17 -18
  126. package/dist/worker-j6xxtq7p.js +70 -0
  127. package/openapi.json +334 -7
  128. package/package.json +4 -4
  129. package/src/apps/definition.ts +11 -0
  130. package/src/apps/store.ts +28 -8
  131. package/src/be/db/model-profiles.ts +147 -38
  132. package/src/be/db/tasks/read.ts +5 -1
  133. package/src/be/db/workflow-run-definitions.ts +117 -0
  134. package/src/be/db.ts +24 -3
  135. package/src/be/memory/constants.ts +14 -1
  136. package/src/be/memory/key-paths.ts +8 -0
  137. package/src/be/memory/providers/sqlite-store.ts +160 -10
  138. package/src/be/memory/task-learning.ts +79 -14
  139. package/src/be/memory/types.ts +24 -1
  140. package/src/be/migrations/279_backfill_learning_expiry.sql +15 -0
  141. package/src/be/migrations/281_model_profiles_pr2.sql +28 -0
  142. package/src/be/migrations/283_workflow_run_definitions.sql +14 -0
  143. package/src/be/model-profile-check.ts +284 -0
  144. package/src/be/model-tier-resolution.ts +112 -12
  145. package/src/be/multi-runtime.ts +27 -0
  146. package/src/be/runtime-pools/routing.ts +52 -4
  147. package/src/be/scripts/typecheck.ts +1 -0
  148. package/src/be/seed-scripts/catalog/dreaming-learnings.ts +552 -0
  149. package/src/be/seed-scripts/catalog/dreaming-memtax-create.ts +389 -14
  150. package/src/be/seed-scripts/catalog/dreaming-memtax.ts +6 -3
  151. package/src/be/seed-scripts/index.ts +9 -0
  152. package/src/be/steering.ts +8 -2
  153. package/src/commands/onboard/agent-fs-version.ts +1 -1
  154. package/src/commands/runner.ts +32 -1
  155. package/src/fs/provider.ts +17 -3
  156. package/src/heartbeat/heartbeat.ts +12 -1
  157. package/src/heartbeat/index.ts +1 -0
  158. package/src/http/agents.ts +56 -4
  159. package/src/http/apps.ts +3 -1
  160. package/src/http/config.ts +2 -6
  161. package/src/http/index.ts +2 -3
  162. package/src/http/model-profiles.ts +58 -10
  163. package/src/http/poll.ts +36 -3
  164. package/src/http/schedules.ts +42 -3
  165. package/src/http/tasks.ts +37 -12
  166. package/src/http/workflows.ts +15 -2
  167. package/src/prompts/session-templates.ts +1 -1
  168. package/src/providers/acp-targets.ts +11 -6
  169. package/src/providers/amp-adapter.ts +1 -1
  170. package/src/providers/claude-sdk-session.ts +132 -23
  171. package/src/providers/codex-skill-resolver.ts +10 -4
  172. package/src/providers/cursor-adapter.ts +1 -1
  173. package/src/providers/devin-skill-resolver.ts +5 -5
  174. package/src/providers/dsh-adapter.ts +1 -1
  175. package/src/scheduler/schedule-task.ts +1 -0
  176. package/src/scripts-runtime/sdk-allowlist.ts +1 -0
  177. package/src/scripts-runtime/swarm-sdk.ts +18 -1
  178. package/src/scripts-runtime/types/stdlib.d.ts +1 -0
  179. package/src/scripts-runtime/types/swarm-sdk.d.ts +1 -0
  180. package/src/server.ts +2 -0
  181. package/src/slack/app.ts +93 -0
  182. package/src/slack/inbound-dispatch.ts +18 -1
  183. package/src/slack/workspace-guard.ts +345 -0
  184. package/src/tasks/task-terminal-effects.ts +4 -0
  185. package/src/tasks/worker-follow-up.ts +102 -2
  186. package/src/tests/acp-adapter.test.ts +82 -0
  187. package/src/tests/apps-icon.test.ts +120 -0
  188. package/src/tests/chained-task-follow-up.test.ts +248 -0
  189. package/src/tests/check-pr-body.test.ts +40 -0
  190. package/src/tests/claude-sdk-lifecycle.test.ts +216 -1
  191. package/src/tests/claude-sdk-process.fixture.ts +57 -0
  192. package/src/tests/codex-skill-resolver.test.ts +31 -0
  193. package/src/tests/credentials-allowlist.test.ts +470 -0
  194. package/src/tests/db-task-read-contract.test.ts +5 -0
  195. package/src/tests/db-task-write-contract.test.ts +5 -0
  196. package/src/tests/deferred-wake-follow-up.test.ts +47 -0
  197. package/src/tests/docs-index-footprint.test.js +3 -3
  198. package/src/tests/dreaming-learnings.test.ts +1395 -0
  199. package/src/tests/dsh-adapter.test.ts +1 -1
  200. package/src/tests/explicit-model-validation.test.ts +2 -0
  201. package/src/tests/fs-provider.test.ts +42 -0
  202. package/src/tests/heartbeat.test.ts +28 -1
  203. package/src/tests/human-free-reclassify.test.ts +5 -1
  204. package/src/tests/list-endpoint-slimming.test.ts +17 -0
  205. package/src/tests/migration-283-workflow-run-definitions.test.ts +69 -0
  206. package/src/tests/model-profile-check.test.ts +387 -0
  207. package/src/tests/model-profiles-api.test.ts +528 -1
  208. package/src/tests/profile-claim.test.ts +415 -3
  209. package/src/tests/profile-tier-alias.test.ts +382 -0
  210. package/src/tests/schedule-profile.test.ts +359 -0
  211. package/src/tests/script-connections.test.ts +6 -0
  212. package/src/tests/script-per-script-executor.test.ts +1 -0
  213. package/src/tests/scripts-sdk-bridge-tool-failure.test.ts +141 -0
  214. package/src/tests/seed-scripts.test.ts +2 -2
  215. package/src/tests/slack-inbound-receipts.test.ts +22 -2
  216. package/src/tests/slack-socket-ack.test.ts +16 -1
  217. package/src/tests/slack-workspace-guard.test.ts +905 -0
  218. package/src/tests/steering-core.test.ts +40 -0
  219. package/src/tests/store-progress-learning.test.ts +605 -20
  220. package/src/tests/tool-annotations.test.ts +1 -1
  221. package/src/tests/workflow-convergence.test.ts +46 -40
  222. package/src/tests/workflow-definition-pinning-recovery.test.ts +552 -0
  223. package/src/tests/workflow-definition-pinning.test.ts +645 -0
  224. package/src/tests/workflow-executors.test.ts +16 -7
  225. package/src/tests/workflow-foreach.test.ts +43 -20
  226. package/src/tests/workflow-notify-slack-ready.test.ts +161 -0
  227. package/src/tests/workflow-profile.test.ts +328 -0
  228. package/src/tools/app-upsert.ts +1 -1
  229. package/src/tools/memory-edit.ts +2 -1
  230. package/src/tools/model-profiles/check-model-profile.ts +63 -0
  231. package/src/tools/schedules/create-schedule.ts +45 -4
  232. package/src/tools/schedules/patch-schedule.ts +50 -4
  233. package/src/tools/schedules/update-schedule.ts +50 -4
  234. package/src/tools/send-task.ts +17 -2
  235. package/src/tools/store-progress.ts +15 -3
  236. package/src/tools/task-action.ts +9 -1
  237. package/src/tools/templates.ts +13 -0
  238. package/src/tools/tool-config.ts +2 -1
  239. package/src/tools/utils.ts +61 -4
  240. package/src/tools/workflows/create-workflow.ts +1 -1
  241. package/src/tools/workflows/retry-workflow-run.ts +1 -1
  242. package/src/tools/workflows/update-workflow.ts +10 -1
  243. package/src/types.ts +56 -1
  244. package/src/utils/credentials.ts +89 -12
  245. package/src/workflows/engine.ts +10 -1
  246. package/src/workflows/executors/agent-task.ts +21 -2
  247. package/src/workflows/executors/foreach.ts +4 -1
  248. package/src/workflows/executors/notify.ts +62 -6
  249. package/src/workflows/executors/sub-workflow.ts +1 -1
  250. package/src/workflows/executors/swarm-script.ts +4 -1
  251. package/src/workflows/foreach-driver.ts +8 -5
  252. package/src/workflows/limits.ts +2 -1
  253. package/src/workflows/model-validation.ts +27 -2
  254. package/src/workflows/patch-definition.ts +3 -1
  255. package/src/workflows/recovery.ts +6 -6
  256. package/src/workflows/resume.ts +9 -9
  257. package/src/workflows/retry-poller.ts +2 -2
  258. package/templates/skills/apps/SKILL.md +2 -0
  259. package/templates/skills/apps/content.md +2 -0
  260. package/templates/skills/code-quality/content.md +12 -0
  261. package/templates/skills/memory/content.md +8 -0
  262. package/templates/skills/scheduling/config.json +1 -1
  263. package/templates/skills/scheduling/content.md +2 -2
  264. package/templates/skills/swarm-docs/content.md +4 -0
  265. package/templates/skills/swarm-extensions/content.md +1 -1
  266. package/templates/skills/swarm-scripts/SKILL.md +1 -1
  267. package/templates/skills/swarm-scripts/content.md +1 -1
  268. package/templates/skills/work-on-task/SKILL.md +2 -0
  269. package/templates/skills/work-on-task/content.md +2 -0
  270. package/templates/workflows/dreaming/content.md +174 -7
  271. package/dist/acp-adapter-srfhs1s9.js +0 -16
  272. package/dist/cli-bzvs88tv.js +0 -339
  273. package/dist/cli-cyn9v8zr.js +0 -748
  274. package/dist/cli-ed6yqpf1.js +0 -779
  275. package/dist/handlers-17wha3ze.js +0 -33
  276. package/dist/heartbeat-gwewgdms.js +0 -42
  277. package/dist/index-8arwq8mw.js +0 -34
  278. package/dist/index-tpw054az.js +0 -38
  279. package/dist/index-waq75j2j.js +0 -31
  280. package/dist/lead-re73kdgc.js +0 -72
  281. package/dist/worker-r8mz7a65.js +0 -72
package/src/apps/store.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { defaultAssetKey } from "../assets/key";
2
2
  import { getDbClient, literalPrefixPattern } from "../be/db";
3
+ import type { AppIcon } from "../types";
4
+ import { AppIconSchema } from "../types";
3
5
  import type { AppDefinition, AppValidationIssue } from "./definition";
4
6
  import { AppDefinitionSchema, appDefinitionIssues } from "./definition";
5
7
  import {
@@ -132,11 +134,25 @@ export async function getApp(id: string): Promise<AppRecord | null> {
132
134
  return row ? decodeApp(row) : null;
133
135
  }
134
136
 
137
+ /** Best-effort `definition.icon` extraction: a malformed or absent value just means no custom icon. */
138
+ function extractIcon(rawDefinitionJson: string): AppIcon | undefined {
139
+ try {
140
+ const parsed: unknown = JSON.parse(rawDefinitionJson);
141
+ const candidate =
142
+ typeof parsed === "object" && parsed !== null
143
+ ? (parsed as Record<string, unknown>).icon
144
+ : undefined;
145
+ return AppIconSchema.safeParse(candidate).data;
146
+ } catch {
147
+ return undefined;
148
+ }
149
+ }
150
+
135
151
  export async function listApps(filters?: {
136
152
  /** Matches the name or description anywhere, case-insensitive. */
137
153
  q?: string;
138
154
  limit?: number;
139
- }): Promise<Array<Omit<AppRecord, "definition">>> {
155
+ }): Promise<Array<Omit<AppRecord, "definition"> & { icon?: AppIcon }>> {
140
156
  const params: (string | number)[] = [];
141
157
  let where = "";
142
158
  if (filters?.q) {
@@ -154,13 +170,17 @@ export async function listApps(filters?: {
154
170
  FROM apps${where} ORDER BY created_at DESC, id${limit}`,
155
171
  params,
156
172
  );
157
- return rows.map((row) => ({
158
- id: row.id,
159
- name: row.name,
160
- ...(row.description === null ? {} : { description: row.description }),
161
- createdAt: row.created_at,
162
- updatedAt: row.updated_at,
163
- }));
173
+ return rows.map((row) => {
174
+ const icon = extractIcon(row.definition);
175
+ return {
176
+ id: row.id,
177
+ name: row.name,
178
+ ...(row.description === null ? {} : { description: row.description }),
179
+ ...(icon ? { icon } : {}),
180
+ createdAt: row.created_at,
181
+ updatedAt: row.updated_at,
182
+ };
183
+ });
164
184
  }
165
185
 
166
186
  export async function listAppRecords(): Promise<AppRecord[]> {
@@ -6,12 +6,18 @@
6
6
  */
7
7
  import {
8
8
  type ModelProfile,
9
+ type ModelProfileCredentials,
10
+ ModelProfileCredentialsSchema,
9
11
  type ProviderName,
10
12
  ProviderNameSchema,
11
13
  type ReasoningEffort,
12
14
  ReasoningEffortSchema,
13
15
  } from "../../types";
14
- import { vcsRepoName, vcsRepoUrlMatches } from "../../utils/vcs-repo-match";
16
+ import {
17
+ checkProfileForAgent,
18
+ formatProfileCheckFailures,
19
+ vcsRepoId,
20
+ } from "../model-profile-check";
15
21
  import { getDbClient } from "./runtime";
16
22
  import { SUPERSEDED_RESUME_REPAIR_WINDOW_MS } from "./tasks/read";
17
23
 
@@ -27,12 +33,50 @@ type ModelProfileRow = {
27
33
  allowCustomModel: number;
28
34
  description: string | null;
29
35
  seededFrom: string | null;
36
+ credentialAllowlist: string | null;
30
37
  createdAt: string;
31
38
  lastUpdatedAt: string;
32
39
  };
33
40
 
41
+ /**
42
+ * Profiles whose stored allowlist is set but unreadable (bad JSON or schema).
43
+ * They read back with `credentials: null`, so list and get endpoints still
44
+ * render them, but null means the whole pool: every dispatch path must check
45
+ * `hasUnreadableCredentialAllowlist` and refuse the profile instead.
46
+ */
47
+ const unreadableAllowlists = new WeakSet<ModelProfile>();
48
+
49
+ /** Whether `profile`'s stored credential allowlist is set but unreadable. */
50
+ export function hasUnreadableCredentialAllowlist(profile: ModelProfile): boolean {
51
+ return unreadableAllowlists.has(profile);
52
+ }
53
+
54
+ /** The stored allowlist JSON as a map; `unreadable` when set but not a valid allowlist. */
55
+ function parseCredentialAllowlist(value: string | null): {
56
+ credentials: ModelProfileCredentials | null;
57
+ unreadable: boolean;
58
+ } {
59
+ // Only NULL means "no allowlist". An empty string is malformed: the writer
60
+ // never stores one, so it fails closed like any other unreadable value.
61
+ if (value === null) return { credentials: null, unreadable: false };
62
+ try {
63
+ const parsed = ModelProfileCredentialsSchema.safeParse(JSON.parse(value));
64
+ if (parsed.success) return { credentials: parsed.data, unreadable: false };
65
+ } catch {
66
+ // Falls through to unreadable.
67
+ }
68
+ return { credentials: null, unreadable: true };
69
+ }
70
+
71
+ function serializeCredentialAllowlist(
72
+ value: ModelProfileCredentials | null | undefined,
73
+ ): string | null {
74
+ return value && Object.keys(value).length > 0 ? JSON.stringify(value) : null;
75
+ }
76
+
34
77
  function rowToModelProfile(row: ModelProfileRow): ModelProfile {
35
- return {
78
+ const allowlist = parseCredentialAllowlist(row.credentialAllowlist);
79
+ const profile: ModelProfile = {
36
80
  id: row.id,
37
81
  name: row.name,
38
82
  harness: ProviderNameSchema.parse(row.harness),
@@ -43,9 +87,12 @@ function rowToModelProfile(row: ModelProfileRow): ModelProfile {
43
87
  allowCustomModel: row.allowCustomModel === 1,
44
88
  description: row.description,
45
89
  seededFrom: row.seededFrom,
90
+ credentials: allowlist.credentials,
46
91
  createdAt: row.createdAt,
47
92
  lastUpdatedAt: row.lastUpdatedAt,
48
93
  };
94
+ if (allowlist.unreadable) unreadableAllowlists.add(profile);
95
+ return profile;
49
96
  }
50
97
 
51
98
  export async function listModelProfiles(
@@ -78,6 +125,8 @@ export interface ModelProfileInput {
78
125
  allowCustomModel?: boolean;
79
126
  description?: string | null;
80
127
  seededFrom?: string | null;
128
+ /** Pooled-key allowlist, stored as `credentialAllowlist`; null uses the whole pool. */
129
+ credentials?: ModelProfileCredentials | null;
81
130
  }
82
131
 
83
132
  /** Insert a profile. Returns null when the name is taken. */
@@ -88,8 +137,8 @@ export async function createModelProfile(
88
137
  const now = new Date().toISOString();
89
138
  const row = await getDbClient().get<ModelProfileRow>(
90
139
  `INSERT INTO model_profiles
91
- (id, name, harness, model, effort, allowCustomModel, description, seededFrom, createdAt, lastUpdatedAt, created_by, updated_by)
92
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
140
+ (id, name, harness, model, effort, allowCustomModel, description, seededFrom, credentialAllowlist, createdAt, lastUpdatedAt, created_by, updated_by)
141
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
93
142
  ON CONFLICT(name) DO NOTHING
94
143
  RETURNING *`,
95
144
  [
@@ -101,6 +150,7 @@ export async function createModelProfile(
101
150
  input.allowCustomModel ? 1 : 0,
102
151
  input.description ?? null,
103
152
  input.seededFrom ?? null,
153
+ serializeCredentialAllowlist(input.credentials),
104
154
  now,
105
155
  now,
106
156
  audit.userId ?? null,
@@ -111,10 +161,13 @@ export async function createModelProfile(
111
161
  }
112
162
 
113
163
  export type ModelProfilePatch = Partial<
114
- Pick<ModelProfileInput, "model" | "effort" | "allowCustomModel" | "description">
164
+ Pick<ModelProfileInput, "model" | "effort" | "allowCustomModel" | "description" | "credentials">
115
165
  >;
116
166
 
117
- /** Update a profile's model, effort or description. The name and harness are fixed. */
167
+ /**
168
+ * Update a profile's model, effort, description or credential allowlist
169
+ * (`credentials: null` clears it). The name and harness are fixed.
170
+ */
118
171
  export async function updateModelProfile(
119
172
  name: string,
120
173
  patch: ModelProfilePatch,
@@ -138,6 +191,10 @@ export async function updateModelProfile(
138
191
  sets.push("description = ?");
139
192
  params.push(patch.description);
140
193
  }
194
+ if (patch.credentials !== undefined) {
195
+ sets.push("credentialAllowlist = ?");
196
+ params.push(serializeCredentialAllowlist(patch.credentials));
197
+ }
141
198
  sets.push("lastUpdatedAt = ?", "updated_by = ?");
142
199
  params.push(new Date().toISOString(), audit.userId ?? null);
143
200
  const row = await getDbClient().get<ModelProfileRow>(
@@ -167,24 +224,36 @@ function repairWindowStart(): string {
167
224
  return new Date(Date.now() - SUPERSEDED_RESUME_REPAIR_WINDOW_MS).toISOString();
168
225
  }
169
226
 
170
- /** Who still points at a profile: agents with it as default, and tasks that still hold it. */
227
+ /**
228
+ * Who still points at a profile: agents with it as default, tasks that still
229
+ * hold it, and schedules that fire tasks with it.
230
+ */
171
231
  export async function modelProfileReferences(
172
232
  name: string,
173
- ): Promise<{ agentIds: string[]; openTaskCount: number }> {
233
+ ): Promise<{ agentIds: string[]; openTaskCount: number; scheduleIds: string[] }> {
174
234
  const agents = await getDbClient().query<{ scopeId: string }>(
175
235
  "SELECT scopeId FROM swarm_config WHERE scope = 'agent' AND key = ? AND value = ?",
176
236
  [MODEL_PROFILE_CONFIG_KEY, name],
177
237
  );
178
238
  const tasks = await getDbClient().get<{ n: number }>(
179
- `SELECT COUNT(*) AS n FROM agent_tasks t WHERE t.profile = ? AND ${TASK_HOLDS_PROFILE_SQL}`,
180
- [name, repairWindowStart()],
239
+ `SELECT COUNT(*) AS n FROM agent_tasks t
240
+ WHERE (t.profile = ? OR t.resolvedProfile = ?) AND ${TASK_HOLDS_PROFILE_SQL}`,
241
+ [name, name, repairWindowStart()],
181
242
  );
182
- return { agentIds: agents.map((a) => a.scopeId), openTaskCount: tasks?.n ?? 0 };
243
+ const schedules = await getDbClient().query<{ id: string }>(
244
+ "SELECT id FROM scheduled_tasks WHERE profile = ? ORDER BY id",
245
+ [name],
246
+ );
247
+ return {
248
+ agentIds: agents.map((a) => a.scopeId),
249
+ openTaskCount: tasks?.n ?? 0,
250
+ scheduleIds: schedules.map((s) => s.id),
251
+ };
183
252
  }
184
253
 
185
254
  /**
186
- * Which migration-220 reference trigger refused a write: `missing` when a task
187
- * or an agent default names a profile that does not exist.
255
+ * Which reference trigger (migrations 220, 240) refused a write: `missing` when
256
+ * a task, a schedule or an agent default names a profile that does not exist.
188
257
  */
189
258
  export function modelProfileRefError(error: unknown): "missing" | null {
190
259
  const message = error instanceof Error ? error.message : "";
@@ -192,11 +261,13 @@ export function modelProfileRefError(error: unknown): "missing" | null {
192
261
  }
193
262
 
194
263
  /**
195
- * Delete a profile unless a task still holds it (`TASK_HOLDS_PROFILE_SQL`) or
196
- * an agent default names it. The check is part of the DELETE statement, so a
197
- * reference written after the caller's own count still makes it `in-use`; the
198
- * triggers in migration 220 refuse the opposite order (a reference written
199
- * after this delete).
264
+ * Delete a profile unless a task still holds it (`TASK_HOLDS_PROFILE_SQL`) as
265
+ * its ask or as the profile claim applied (`resolvedProfile`, which a paused
266
+ * task's resume re-reads for its credential allowlist), an
267
+ * agent default names it, or a schedule names it. The check is part of the
268
+ * DELETE statement, so a reference written after the caller's own count still
269
+ * makes it `in-use`; the triggers in migrations 220 and 240 refuse the
270
+ * opposite order (a reference written after this delete).
200
271
  */
201
272
  export async function deleteModelProfile(name: string): Promise<"deleted" | "missing" | "in-use"> {
202
273
  const row = await getDbClient().get<{ id: string }>(
@@ -204,10 +275,13 @@ export async function deleteModelProfile(name: string): Promise<"deleted" | "mis
204
275
  WHERE name = ?
205
276
  AND NOT EXISTS (
206
277
  SELECT 1 FROM agent_tasks t
207
- WHERE t.profile = model_profiles.name AND ${TASK_HOLDS_PROFILE_SQL})
278
+ WHERE (t.profile = model_profiles.name OR t.resolvedProfile = model_profiles.name)
279
+ AND ${TASK_HOLDS_PROFILE_SQL})
208
280
  AND NOT EXISTS (
209
281
  SELECT 1 FROM swarm_config
210
282
  WHERE scope = 'agent' AND key = ? AND trim(value) = model_profiles.name)
283
+ AND NOT EXISTS (
284
+ SELECT 1 FROM scheduled_tasks s WHERE s.profile = model_profiles.name)
211
285
  RETURNING id`,
212
286
  [name, repairWindowStart(), MODEL_PROFILE_CONFIG_KEY],
213
287
  );
@@ -237,33 +311,31 @@ export async function repoModelOverrideKeys(
237
311
  vcsRepo: string | null | undefined,
238
312
  { includeSecrets = true }: { includeSecrets?: boolean } = {},
239
313
  ): Promise<Set<string>> {
240
- if (!vcsRepo?.trim()) return new Set();
241
- const repos = await getDbClient().query<{ id: string; url: string }>(
242
- "SELECT id, url FROM swarm_repos WHERE name = ? ORDER BY name ASC",
243
- [vcsRepoName(vcsRepo)],
244
- );
245
- const repo = repos.find((r) => vcsRepoUrlMatches(r.url, vcsRepo));
246
- if (!repo) return new Set();
314
+ const repoId = await vcsRepoId(vcsRepo);
315
+ if (!repoId) return new Set();
247
316
  const rows = await getDbClient().query<{ key: string }>(
248
317
  `SELECT key FROM swarm_config
249
318
  WHERE scope = 'repo' AND scopeId = ? AND key IN ('MODEL_OVERRIDE', 'REASONING_EFFORT_OVERRIDE')
250
319
  ${includeSecrets ? "" : "AND isSecret = 0"}`,
251
- [repo.id],
320
+ [repoId],
252
321
  );
253
322
  return new Set(rows.map((row) => row.key));
254
323
  }
255
324
 
256
325
  /**
257
- * Why a task cannot ask for `profile`, or null when it can. PR 1 validity is
258
- * the harness only: the profile must exist and, when the target agent is known
259
- * and has a harness, run on that harness. `profile` is exclusive with `model`
260
- * and `modelTier`, which pick the model another way.
326
+ * Why a task cannot ask for `profile`, or null when it can. The profile must
327
+ * exist and, when the target agent is known, pass `checkProfileForAgent`
328
+ * (harness, model, credentials, allowlist). A pooled task (no agent) is judged
329
+ * per agent at claim instead. `profile` is exclusive with `model` and
330
+ * `modelTier`, which pick the model another way.
261
331
  */
262
332
  export async function taskProfileError(check: {
263
333
  profile?: string | null;
264
334
  model?: string | null;
265
335
  modelTier?: string | null;
266
336
  agentId?: string | null;
337
+ /** The task's repo; its scoped credentials count, as on the worker. */
338
+ vcsRepo?: string | null;
267
339
  }): Promise<string | null> {
268
340
  const name = check.profile?.trim();
269
341
  if (!name) return null;
@@ -275,14 +347,51 @@ export async function taskProfileError(check: {
275
347
  return `Unknown model profile "${name}". List profiles with list-model-profiles.`;
276
348
  }
277
349
  if (!check.agentId) return null;
278
- const agent = await getDbClient().get<{ harness: string | null }>(
279
- "SELECT COALESCE(harness_provider, provider) AS harness FROM agents WHERE id = ?",
280
- [check.agentId],
281
- );
282
- if (agent?.harness && agent.harness !== profile.harness) {
283
- return `Model profile "${name}" runs on the ${profile.harness} harness; the target agent runs ${agent.harness}.`;
350
+ const result = await checkProfileForAgent(check.agentId, name, { vcsRepo: check.vcsRepo });
351
+ if (!result || result.ok) return null;
352
+ return formatProfileCheckFailures(result);
353
+ }
354
+
355
+ /**
356
+ * The profile half of a schedule update. `profile` and `model`/`modelTier`
357
+ * pick the model two ways, so setting one clears the other, and sending both
358
+ * is an error. A new profile, or a move of a profiled schedule to another
359
+ * agent, is judged by `taskProfileError`. Returns the columns to write.
360
+ */
361
+ export async function scheduleProfileUpdate(
362
+ existing: { profile?: string | null; targetAgentId?: string | null },
363
+ patch: {
364
+ profile?: string | null;
365
+ model?: string | null;
366
+ modelTier?: string | null;
367
+ targetAgentId?: string | null;
368
+ },
369
+ ): Promise<
370
+ | { error: string }
371
+ | { error?: undefined; fields: { profile?: string | null; model?: null; modelTier?: null } }
372
+ > {
373
+ const profile = patch.profile === undefined ? undefined : patch.profile?.trim() || null;
374
+ const agentId = patch.targetAgentId !== undefined ? patch.targetAgentId : existing.targetAgentId;
375
+ if (profile) {
376
+ const error = await taskProfileError({
377
+ profile,
378
+ model: patch.model,
379
+ modelTier: patch.modelTier,
380
+ agentId,
381
+ });
382
+ if (error) return { error };
383
+ return { fields: { profile, model: null, modelTier: null } };
384
+ }
385
+ if (patch.model?.trim() || patch.modelTier?.trim() || profile === null) {
386
+ return { fields: { profile: null } };
387
+ }
388
+ const agentChanged =
389
+ patch.targetAgentId !== undefined && patch.targetAgentId !== existing.targetAgentId;
390
+ if (agentChanged && existing.profile) {
391
+ const error = await taskProfileError({ profile: existing.profile, agentId });
392
+ if (error) return { error };
284
393
  }
285
- return null;
394
+ return { fields: {} };
286
395
  }
287
396
 
288
397
  type OverrideRowState = { value: string; exportToEnv?: number } | null;
@@ -163,6 +163,8 @@ type AgentTaskSummaryRow = Pick<
163
163
  | "modelAlias"
164
164
  | "effort"
165
165
  | "resolvedEffort"
166
+ | "profile"
167
+ | "resolvedProfile"
166
168
  | "provider"
167
169
  | "requestedByUserId"
168
170
  | "progress"
@@ -243,7 +245,7 @@ const LIST_COLUMNS = {
243
245
  agent_tasks.offeredTo, agent_tasks.acceptedAt, agent_tasks.parentTaskId,
244
246
  agent_tasks.scheduleId, agent_tasks.model, agent_tasks.modelTier,
245
247
  agent_tasks.resolvedModel, agent_tasks.modelSource, agent_tasks.modelAlias, agent_tasks.effort,
246
- agent_tasks.resolvedEffort,
248
+ agent_tasks.resolvedEffort, agent_tasks.profile, agent_tasks.resolvedProfile,
247
249
  agent_tasks.provider, agent_tasks.requestedByUserId, agent_tasks.progress,
248
250
  agent_tasks.createdAt, agent_tasks.lastUpdatedAt, agent_tasks.finishedAt,
249
251
  agent_tasks.peakContextPercent`,
@@ -432,6 +434,8 @@ export function rowToAgentTaskSummary(row: AgentTaskSummaryRow): AgentTaskSummar
432
434
  resolvedEffort: ReasoningEffortSchema.safeParse(row.resolvedEffort).success
433
435
  ? (row.resolvedEffort as ReasoningEffort)
434
436
  : undefined,
437
+ profile: row.profile ?? undefined,
438
+ resolvedProfile: row.resolvedProfile ?? undefined,
435
439
  provider: (row.provider as ProviderName | null) ?? undefined,
436
440
  requestedByUserId: row.requestedByUserId ?? undefined,
437
441
  progress: row.progress ?? undefined,
@@ -0,0 +1,117 @@
1
+ import type { Workflow, WorkflowSnapshot } from "../../types";
2
+ import { getWorkflow } from "../db";
3
+ import { computeContentHash } from "./context-versions";
4
+ import { getDbClient } from "./runtime";
5
+
6
+ // A run is pinned to the definition it started with (migration 283). The
7
+ // snapshot lives once per distinct content in `workflow_run_definitions`, keyed
8
+ // by its hash; `workflow_runs.definitionHash` points at it. Rows are immutable,
9
+ // so a lookup never races an edit.
10
+
11
+ /**
12
+ * The definition fields a run keeps from its start. `enabled` stays live: it
13
+ * does not stop in-flight runs today, and toggling it must not mint a new row.
14
+ * Row identity and the security principal (`id`, `key`, `createdByAgentId`)
15
+ * are not part of the snapshot and always come from the live row.
16
+ */
17
+ export type PinnedWorkflowDefinition = Omit<WorkflowSnapshot, "enabled">;
18
+
19
+ export const PINNED_WORKFLOW_KEYS = [
20
+ "name",
21
+ "description",
22
+ "definition",
23
+ "triggers",
24
+ "cooldown",
25
+ "input",
26
+ "triggerSchema",
27
+ "params",
28
+ "requiredParams",
29
+ "requires",
30
+ "dir",
31
+ "vcsRepo",
32
+ ] as const satisfies readonly (keyof PinnedWorkflowDefinition)[];
33
+
34
+ export function toPinnedDefinition(workflow: PinnedWorkflowDefinition): PinnedWorkflowDefinition {
35
+ const pinned: Record<string, unknown> = {};
36
+ for (const key of PINNED_WORKFLOW_KEYS) pinned[key] = workflow[key];
37
+ return pinned as PinnedWorkflowDefinition;
38
+ }
39
+
40
+ /**
41
+ * The stored snapshot and its hash. Nested key order is kept exactly as the
42
+ * definition wrote it: executors iterate config objects (script `args`, System
43
+ * One `questions` and `choices`) in insertion order, so a resumed run must see
44
+ * the order it started with, and two definitions that differ only in order get
45
+ * two rows. Only the top level is normalized (`PINNED_WORKFLOW_KEYS` order);
46
+ * absent and `undefined` fields serialize the same.
47
+ */
48
+ export function hashPinnedDefinition(pinned: PinnedWorkflowDefinition): {
49
+ hash: string;
50
+ snapshot: string;
51
+ } {
52
+ const snapshot = JSON.stringify(toPinnedDefinition(pinned));
53
+ return { hash: computeContentHash(snapshot), snapshot };
54
+ }
55
+
56
+ /** Store the workflow's pinned definition (once per content) and return its hash. */
57
+ export async function pinWorkflowDefinition(workflow: Workflow): Promise<string> {
58
+ const { hash, snapshot } = hashPinnedDefinition(toPinnedDefinition(workflow));
59
+ await getDbClient().run(
60
+ "INSERT OR IGNORE INTO workflow_run_definitions (hash, snapshot, createdAt) VALUES (?, ?, ?)",
61
+ [hash, snapshot, new Date().toISOString()],
62
+ );
63
+ return hash;
64
+ }
65
+
66
+ /** The pinned definition of a run, or null when the run has none (pre-283 or preflight-failed). */
67
+ export async function getPinnedRunDefinition(
68
+ runId: string,
69
+ ): Promise<PinnedWorkflowDefinition | null> {
70
+ const row = await getDbClient().get<{ snapshot: string }>(
71
+ `SELECT d.snapshot FROM workflow_runs r
72
+ JOIN workflow_run_definitions d ON d.hash = r.definitionHash
73
+ WHERE r.id = ?`,
74
+ [runId],
75
+ );
76
+ // Not schema-validated, like `rowToWorkflow`: a later tightening of the
77
+ // definition schema must not break runs pinned under the old one.
78
+ return row ? (JSON.parse(row.snapshot) as PinnedWorkflowDefinition) : null;
79
+ }
80
+
81
+ /**
82
+ * The live row with every pinned field taken from the snapshot. Each key is
83
+ * assigned explicitly, `undefined` included, so a field the edit added (a `dir`
84
+ * the run started without) cannot leak into the run.
85
+ */
86
+ export function mergePinnedDefinition(live: Workflow, pinned: PinnedWorkflowDefinition): Workflow {
87
+ const merged: Record<string, unknown> = { ...live };
88
+ for (const key of PINNED_WORKFLOW_KEYS) merged[key] = pinned[key];
89
+ return merged as Workflow;
90
+ }
91
+
92
+ /**
93
+ * The workflow a run executes: the definition it started with (migration 283)
94
+ * on top of the live row. Live fields (`enabled`, `key`, `createdByAgentId`,
95
+ * row metadata) come from the row. A run with no pin (created before 283, or
96
+ * a preflight failure) gets the live row unchanged. Null when the workflow is
97
+ * gone. Use this, not `getWorkflow`, for every read made on behalf of a run.
98
+ */
99
+ export async function getRunWorkflow(run: {
100
+ id: string;
101
+ workflowId: string;
102
+ }): Promise<Workflow | null> {
103
+ const live = await getWorkflow(run.workflowId);
104
+ if (!live) return null;
105
+ const pinned = await getPinnedRunDefinition(run.id);
106
+ return pinned ? mergePinnedDefinition(live, pinned) : live;
107
+ }
108
+
109
+ /** Remove snapshots no run references any more. Call after deleting runs. */
110
+ export async function deleteOrphanedRunDefinitions(): Promise<void> {
111
+ await getDbClient().run(
112
+ `DELETE FROM workflow_run_definitions
113
+ WHERE NOT EXISTS (
114
+ SELECT 1 FROM workflow_runs r WHERE r.definitionHash = workflow_run_definitions.hash
115
+ )`,
116
+ );
117
+ }
package/src/be/db.ts CHANGED
@@ -232,6 +232,7 @@ import {
232
232
  } from "./db/tasks/read";
233
233
  import { configureTaskWriteDependencies, failTask } from "./db/tasks/write";
234
234
  import { tombstoneWorkflowIdempotencyKeys } from "./db/workflow-idempotency";
235
+ import { deleteOrphanedRunDefinitions } from "./db/workflow-run-definitions";
235
236
  import {
236
237
  emitChildRunFinished,
237
238
  emitRunFinished,
@@ -327,6 +328,13 @@ export {
327
328
  assertAssetKeyMovesAllowed,
328
329
  moveTaskChainKeyInTx,
329
330
  } from "./db/session-moves";
331
+ export {
332
+ getRunWorkflow,
333
+ PINNED_WORKFLOW_KEYS,
334
+ type PinnedWorkflowDefinition,
335
+ pinWorkflowDefinition,
336
+ toPinnedDefinition,
337
+ } from "./db/workflow-run-definitions";
330
338
 
331
339
  configureAgentDependencies({
332
340
  createLogEntry: (entry) => createLogEntry(entry),
@@ -6026,6 +6034,7 @@ type ScheduledTaskRow = {
6026
6034
  lastErrorMessage: string | null;
6027
6035
  model: string | null;
6028
6036
  modelTier: string | null;
6037
+ profile: string | null;
6029
6038
  scheduleType: string;
6030
6039
  targetType: string;
6031
6040
  workflowId: string | null;
@@ -6078,6 +6087,7 @@ function rowToScheduledTask(row: ScheduledTaskRow): ScheduledTask {
6078
6087
  lastErrorMessage: row.lastErrorMessage ?? undefined,
6079
6088
  model: row.model ?? undefined,
6080
6089
  modelTier: parseModelTier(row.modelTier) ?? undefined,
6090
+ profile: row.profile ?? undefined,
6081
6091
  scheduleType: row.scheduleType as "recurring" | "one_time",
6082
6092
  targetType: row.targetType as "agent-task" | "workflow" | "script",
6083
6093
  workflowId: row.workflowId ?? undefined,
@@ -6239,6 +6249,7 @@ export interface CreateScheduledTaskData {
6239
6249
  timezone?: string;
6240
6250
  model?: string;
6241
6251
  modelTier?: ModelTier;
6252
+ profile?: string;
6242
6253
  scheduleType?: "recurring" | "one_time";
6243
6254
  targetType?: "agent-task" | "workflow" | "script";
6244
6255
  workflowId?: string;
@@ -6259,11 +6270,11 @@ export async function createScheduledTask(data: CreateScheduledTaskData): Promis
6259
6270
  id, "key", name, description, cronExpression, intervalMs, taskTemplate,
6260
6271
  taskType, tags, priority, targetAgentId, enabled, nextRunAt,
6261
6272
  createdByAgentId, parentTaskId, requestedDelayMs, requestedRunAt,
6262
- timezone, model, modelTier, scheduleType,
6273
+ timezone, model, modelTier, profile, scheduleType,
6263
6274
  targetType, workflowId, scriptName, scriptArgs, params, requiredParams, requires,
6264
6275
  createdAt, lastUpdatedAt,
6265
6276
  created_by, updated_by
6266
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`,
6277
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`,
6267
6278
  [
6268
6279
  id,
6269
6280
  normalizeAssetKey(data.key ?? defaultAssetKey("schedule", id)),
@@ -6285,6 +6296,7 @@ export async function createScheduledTask(data: CreateScheduledTaskData): Promis
6285
6296
  data.timezone ?? "UTC",
6286
6297
  data.model ?? null,
6287
6298
  data.modelTier ?? null,
6299
+ data.profile ?? null,
6288
6300
  data.scheduleType ?? "recurring",
6289
6301
  data.targetType ?? "agent-task",
6290
6302
  data.workflowId ?? null,
@@ -6324,6 +6336,7 @@ export interface UpdateScheduledTaskData {
6324
6336
  lastErrorMessage?: string | null;
6325
6337
  model?: string | null;
6326
6338
  modelTier?: ModelTier | null;
6339
+ profile?: string | null;
6327
6340
  scheduleType?: "recurring" | "one_time";
6328
6341
  targetType?: "agent-task" | "workflow" | "script";
6329
6342
  workflowId?: string | null;
@@ -6420,6 +6433,10 @@ export async function updateScheduledTask(
6420
6433
  updates.push("modelTier = ?");
6421
6434
  params.push(data.modelTier);
6422
6435
  }
6436
+ if (data.profile !== undefined) {
6437
+ updates.push("profile = ?");
6438
+ params.push(data.profile);
6439
+ }
6423
6440
  if (data.scheduleType !== undefined) {
6424
6441
  updates.push("scheduleType = ?");
6425
6442
  params.push(data.scheduleType);
@@ -7947,6 +7964,7 @@ async function deleteWorkflowRows(id: string, source?: "api" | "mcp"): Promise<b
7947
7964
  );
7948
7965
  // 3. Delete runs (they reference workflow)
7949
7966
  await client.run("DELETE FROM workflow_runs WHERE workflowId = ?", [id]);
7967
+ await deleteOrphanedRunDefinitions();
7950
7968
  await reclassifyTaskHumanFree(linkedTaskIds);
7951
7969
  // 4. Delete every user's favorite of it (no FK to the workflow)
7952
7970
  await client.run("DELETE FROM user_favorites WHERE itemType = 'workflow' AND itemId = ?", [id]);
@@ -7999,10 +8017,12 @@ export async function createWorkflowRun(data: {
7999
8017
  parentStepAttempt?: number;
8000
8018
  /** Server-stamped agent that started the run (migration 247). Never from trigger data. */
8001
8019
  triggeredByAgentId?: string;
8020
+ /** The `workflow_run_definitions` row the run is pinned to (migration 283). */
8021
+ definitionHash?: string;
8002
8022
  }): Promise<WorkflowRun> {
8003
8023
  const now = new Date().toISOString();
8004
8024
  const row = await getDbClient().get<WorkflowRunRow>(
8005
- `INSERT INTO workflow_runs (id, workflowId, triggerType, startedAt, triggerData, created_by, parentStepId, parentStepAttempt, triggeredByAgentId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`,
8025
+ `INSERT INTO workflow_runs (id, workflowId, triggerType, startedAt, triggerData, created_by, parentStepId, parentStepAttempt, triggeredByAgentId, definitionHash) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`,
8006
8026
  [
8007
8027
  data.id,
8008
8028
  data.workflowId,
@@ -8013,6 +8033,7 @@ export async function createWorkflowRun(data: {
8013
8033
  data.parentStepId ?? null,
8014
8034
  data.parentStepAttempt ?? 0,
8015
8035
  data.triggeredByAgentId ?? null,
8036
+ data.definitionHash ?? null,
8016
8037
  ],
8017
8038
  );
8018
8039
  if (!row) throw new Error("Failed to create workflow run");
@@ -15,6 +15,11 @@ export const TTL_DEFAULTS: Record<AgentMemorySource, number | null> = {
15
15
  manual: null,
16
16
  };
17
17
 
18
+ // TTL (in days) of a `/learnings/*` memory, whatever its source. A learning is
19
+ // raw material: one worth keeping is distilled into `/longterm` (a move there
20
+ // clears the expiry); the rest age out.
21
+ export const LEARNING_TTL_DAYS = 30;
22
+
18
23
  // Per-source recency decay half-life (in days).
19
24
  // manual = Infinity (no decay — curated knowledge stays relevant forever).
20
25
  // A global MEMORY_RECENCY_HALF_LIFE_DAYS override forces ALL sources to the
@@ -78,6 +83,13 @@ export function minSimilarity(): number {
78
83
  // pair 0.705.
79
84
  export const LEARNING_DUPLICATE_MIN_SIMILARITY = 0.8;
80
85
 
86
+ // Most eligible rows an exhaustive search scores per call, newest `updatedAt`
87
+ // first. The learning dedup runs it on every store-progress learning (once per
88
+ // prefix), so its cost must not grow with the corpus. Below the cap the scan is
89
+ // exact; past it, older rows are not scored and the search logs `capped=true`.
90
+ // Production holds about 1,260 `/learnings` + `/longterm` rows.
91
+ export const EXHAUSTIVE_SEARCH_MAX_ROWS = 10_000;
92
+
81
93
  // Reranking parameters
82
94
  export function accessBoostMaxMultiplier(): number {
83
95
  return numEnv("MEMORY_ACCESS_BOOST_MAX", 1.5);
@@ -104,5 +116,6 @@ export const EMBEDDING_DIMENSIONS = numEnv("EMBEDDING_DIMENSIONS", 512);
104
116
  export const DEFAULT_EMBEDDING_DIMENSIONS = EMBEDDING_DIMENSIONS;
105
117
  export const DEFAULT_EMBEDDING_MODEL = "openai/text-embedding-3-small";
106
118
 
107
- // Manual memories must NEVER be deleted by automated processes (curator, GC, etc.)
119
+ // Manual memories must NEVER be deleted by automated processes (curator, GC, etc.).
120
+ // The one exception is the expiry purge of `/learnings/*` rows (LEARNING_TTL_DAYS).
108
121
  export const PROTECTED_SOURCES: ReadonlySet<AgentMemorySource> = new Set(["manual"]);