@mndrk/agx 2.0.26 → 2.0.33

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 (867) hide show
  1. package/README.md +4 -6
  2. package/cloud-runtime/standalone/.next/BUILD_ID +1 -1
  3. package/cloud-runtime/standalone/.next/app-path-routes-manifest.json +7 -0
  4. package/cloud-runtime/standalone/.next/build-manifest.json +4 -4
  5. package/cloud-runtime/standalone/.next/prerender-manifest.json +3 -3
  6. package/cloud-runtime/standalone/.next/required-server-files.json +4 -4
  7. package/cloud-runtime/standalone/.next/routes-manifest.json +51 -0
  8. package/cloud-runtime/standalone/.next/server/app/_global-error/page/build-manifest.json +2 -2
  9. package/cloud-runtime/standalone/.next/server/app/_global-error.html +2 -2
  10. package/cloud-runtime/standalone/.next/server/app/_global-error.rsc +1 -1
  11. package/cloud-runtime/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  12. package/cloud-runtime/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  13. package/cloud-runtime/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  14. package/cloud-runtime/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  15. package/cloud-runtime/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  16. package/cloud-runtime/standalone/.next/server/app/_not-found/page/build-manifest.json +2 -2
  17. package/cloud-runtime/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  18. package/cloud-runtime/standalone/.next/server/app/_not-found.html +2 -2
  19. package/cloud-runtime/standalone/.next/server/app/_not-found.rsc +2 -2
  20. package/cloud-runtime/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  21. package/cloud-runtime/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  22. package/cloud-runtime/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  23. package/cloud-runtime/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  24. package/cloud-runtime/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  25. package/cloud-runtime/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  26. package/cloud-runtime/standalone/.next/server/app/agents/[id]/page/build-manifest.json +2 -2
  27. package/cloud-runtime/standalone/.next/server/app/agents/[id]/page.js.nft.json +1 -1
  28. package/cloud-runtime/standalone/.next/server/app/agents/[id]/page_client-reference-manifest.js +1 -1
  29. package/cloud-runtime/standalone/.next/server/app/agents/page/build-manifest.json +2 -2
  30. package/cloud-runtime/standalone/.next/server/app/agents/page.js.nft.json +1 -1
  31. package/cloud-runtime/standalone/.next/server/app/agents/page_client-reference-manifest.js +1 -1
  32. package/cloud-runtime/standalone/.next/server/app/agents.html +2 -2
  33. package/cloud-runtime/standalone/.next/server/app/agents.rsc +3 -3
  34. package/cloud-runtime/standalone/.next/server/app/agents.segments/_full.segment.rsc +3 -3
  35. package/cloud-runtime/standalone/.next/server/app/agents.segments/_head.segment.rsc +1 -1
  36. package/cloud-runtime/standalone/.next/server/app/agents.segments/_index.segment.rsc +2 -2
  37. package/cloud-runtime/standalone/.next/server/app/agents.segments/_tree.segment.rsc +2 -2
  38. package/cloud-runtime/standalone/.next/server/app/agents.segments/agents/__PAGE__.segment.rsc +2 -2
  39. package/cloud-runtime/standalone/.next/server/app/agents.segments/agents.segment.rsc +1 -1
  40. package/cloud-runtime/standalone/.next/server/app/api/agent-specs/route.js +2 -2
  41. package/cloud-runtime/standalone/.next/server/app/api/agent-specs/route.js.nft.json +1 -1
  42. package/cloud-runtime/standalone/.next/server/app/api/agents/[id]/profile/route.js +2 -2
  43. package/cloud-runtime/standalone/.next/server/app/api/agents/[id]/profile/route.js.nft.json +1 -1
  44. package/cloud-runtime/standalone/.next/server/app/api/agents/export/route.js +2 -2
  45. package/cloud-runtime/standalone/.next/server/app/api/agents/export/route.js.nft.json +1 -1
  46. package/cloud-runtime/standalone/.next/server/app/api/automations/create/route.js +4 -4
  47. package/cloud-runtime/standalone/.next/server/app/api/automations/create/route.js.nft.json +1 -1
  48. package/cloud-runtime/standalone/.next/server/app/api/automations/route.js +3 -3
  49. package/cloud-runtime/standalone/.next/server/app/api/automations/route.js.nft.json +1 -1
  50. package/cloud-runtime/standalone/.next/server/app/api/chat/route.js +7 -4
  51. package/cloud-runtime/standalone/.next/server/app/api/chat/route.js.nft.json +1 -1
  52. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/[id]/route/app-paths-manifest.json +3 -0
  53. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/[id]/route/build-manifest.json +11 -0
  54. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/[id]/route/server-reference-manifest.json +4 -0
  55. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/[id]/route.js +8 -0
  56. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/[id]/route.js.map +5 -0
  57. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/[id]/route.js.nft.json +1 -0
  58. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/[id]/route_client-reference-manifest.js +2 -0
  59. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/[id]/signal/route/app-paths-manifest.json +3 -0
  60. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/[id]/signal/route/build-manifest.json +11 -0
  61. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/[id]/signal/route/server-reference-manifest.json +4 -0
  62. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/[id]/signal/route.js +7 -0
  63. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/[id]/signal/route.js.map +5 -0
  64. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/[id]/signal/route.js.nft.json +1 -0
  65. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/[id]/signal/route_client-reference-manifest.js +2 -0
  66. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/route/app-paths-manifest.json +3 -0
  67. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/route/build-manifest.json +11 -0
  68. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/route/server-reference-manifest.json +4 -0
  69. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/route.js +8 -0
  70. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/route.js.map +5 -0
  71. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/route.js.nft.json +1 -0
  72. package/cloud-runtime/standalone/.next/server/app/api/chat-runs/route_client-reference-manifest.js +2 -0
  73. package/cloud-runtime/standalone/.next/server/app/api/daemon/route.js +1 -1
  74. package/cloud-runtime/standalone/.next/server/app/api/daemon/route.js.nft.json +1 -1
  75. package/cloud-runtime/standalone/.next/server/app/api/file-search/route.js.nft.json +1 -1
  76. package/cloud-runtime/standalone/.next/server/app/api/graphs/[graphId]/nodes/[nodeId]/route.js +2 -2
  77. package/cloud-runtime/standalone/.next/server/app/api/graphs/[graphId]/nodes/[nodeId]/route.js.nft.json +1 -1
  78. package/cloud-runtime/standalone/.next/server/app/api/health/route.js +5 -4
  79. package/cloud-runtime/standalone/.next/server/app/api/health/route.js.nft.json +1 -1
  80. package/cloud-runtime/standalone/.next/server/app/api/history/route.js.nft.json +1 -1
  81. package/cloud-runtime/standalone/.next/server/app/api/history/status/route.js.nft.json +1 -1
  82. package/cloud-runtime/standalone/.next/server/app/api/knowledge-notes/route/app-paths-manifest.json +3 -0
  83. package/cloud-runtime/standalone/.next/server/app/api/knowledge-notes/route/build-manifest.json +11 -0
  84. package/cloud-runtime/standalone/.next/server/app/api/knowledge-notes/route/server-reference-manifest.json +4 -0
  85. package/cloud-runtime/standalone/.next/server/app/api/knowledge-notes/route.js +8 -0
  86. package/cloud-runtime/standalone/.next/server/app/api/knowledge-notes/route.js.map +5 -0
  87. package/cloud-runtime/standalone/.next/server/app/api/knowledge-notes/route.js.nft.json +1 -0
  88. package/cloud-runtime/standalone/.next/server/app/api/knowledge-notes/route_client-reference-manifest.js +2 -0
  89. package/cloud-runtime/standalone/.next/server/app/api/learnings/route.js +5 -4
  90. package/cloud-runtime/standalone/.next/server/app/api/learnings/route.js.nft.json +1 -1
  91. package/cloud-runtime/standalone/.next/server/app/api/logs/route.js.nft.json +1 -1
  92. package/cloud-runtime/standalone/.next/server/app/api/logs/stream/route.js +2 -2
  93. package/cloud-runtime/standalone/.next/server/app/api/logs/stream/route.js.nft.json +1 -1
  94. package/cloud-runtime/standalone/.next/server/app/api/memories/route.js +2 -2
  95. package/cloud-runtime/standalone/.next/server/app/api/memories/route.js.nft.json +1 -1
  96. package/cloud-runtime/standalone/.next/server/app/api/messages/[id]/route.js +1 -1
  97. package/cloud-runtime/standalone/.next/server/app/api/messages/[id]/route.js.nft.json +1 -1
  98. package/cloud-runtime/standalone/.next/server/app/api/migrate/teams-to-projects/route.js +2 -2
  99. package/cloud-runtime/standalone/.next/server/app/api/migrate/teams-to-projects/route.js.nft.json +1 -1
  100. package/cloud-runtime/standalone/.next/server/app/api/migrate/workspaces-to-projects/route.js +2 -2
  101. package/cloud-runtime/standalone/.next/server/app/api/migrate/workspaces-to-projects/route.js.nft.json +1 -1
  102. package/cloud-runtime/standalone/.next/server/app/api/orchestrator/tasks/[taskId]/cancel/route.js +2 -2
  103. package/cloud-runtime/standalone/.next/server/app/api/orchestrator/tasks/[taskId]/cancel/route.js.nft.json +1 -1
  104. package/cloud-runtime/standalone/.next/server/app/api/orchestrator/tasks/[taskId]/signal/route.js +3 -3
  105. package/cloud-runtime/standalone/.next/server/app/api/orchestrator/tasks/[taskId]/signal/route.js.nft.json +1 -1
  106. package/cloud-runtime/standalone/.next/server/app/api/orchestrator/tasks/[taskId]/start/route.js +6 -4
  107. package/cloud-runtime/standalone/.next/server/app/api/orchestrator/tasks/[taskId]/start/route.js.nft.json +1 -1
  108. package/cloud-runtime/standalone/.next/server/app/api/orchestrator/tasks/[taskId]/status/route.js +4 -3
  109. package/cloud-runtime/standalone/.next/server/app/api/orchestrator/tasks/[taskId]/status/route.js.nft.json +1 -1
  110. package/cloud-runtime/standalone/.next/server/app/api/participants/route.js +3 -3
  111. package/cloud-runtime/standalone/.next/server/app/api/participants/route.js.nft.json +1 -1
  112. package/cloud-runtime/standalone/.next/server/app/api/processes/route.js +1 -1
  113. package/cloud-runtime/standalone/.next/server/app/api/processes/route.js.nft.json +1 -1
  114. package/cloud-runtime/standalone/.next/server/app/api/projects/[id]/agents/route.js +3 -3
  115. package/cloud-runtime/standalone/.next/server/app/api/projects/[id]/agents/route.js.nft.json +1 -1
  116. package/cloud-runtime/standalone/.next/server/app/api/projects/[id]/memory/route.js +4 -4
  117. package/cloud-runtime/standalone/.next/server/app/api/projects/[id]/memory/route.js.nft.json +1 -1
  118. package/cloud-runtime/standalone/.next/server/app/api/projects/[id]/migrate-v1/route.js +4 -4
  119. package/cloud-runtime/standalone/.next/server/app/api/projects/[id]/migrate-v1/route.js.nft.json +1 -1
  120. package/cloud-runtime/standalone/.next/server/app/api/projects/[id]/migrate-v2/route.js +4 -4
  121. package/cloud-runtime/standalone/.next/server/app/api/projects/[id]/migrate-v2/route.js.nft.json +1 -1
  122. package/cloud-runtime/standalone/.next/server/app/api/projects/[id]/route.js +4 -3
  123. package/cloud-runtime/standalone/.next/server/app/api/projects/[id]/route.js.nft.json +1 -1
  124. package/cloud-runtime/standalone/.next/server/app/api/projects/[id]/skills/route.js +3 -3
  125. package/cloud-runtime/standalone/.next/server/app/api/projects/[id]/skills/route.js.nft.json +1 -1
  126. package/cloud-runtime/standalone/.next/server/app/api/projects/[id]/threads/route.js +3 -3
  127. package/cloud-runtime/standalone/.next/server/app/api/projects/[id]/threads/route.js.nft.json +1 -1
  128. package/cloud-runtime/standalone/.next/server/app/api/projects/[id]/variables/route.js +3 -3
  129. package/cloud-runtime/standalone/.next/server/app/api/projects/[id]/variables/route.js.nft.json +1 -1
  130. package/cloud-runtime/standalone/.next/server/app/api/projects/route.js +4 -3
  131. package/cloud-runtime/standalone/.next/server/app/api/projects/route.js.nft.json +1 -1
  132. package/cloud-runtime/standalone/.next/server/app/api/providers/route.js +1 -1
  133. package/cloud-runtime/standalone/.next/server/app/api/providers/route.js.nft.json +1 -1
  134. package/cloud-runtime/standalone/.next/server/app/api/queue/complete/route.js +4 -3
  135. package/cloud-runtime/standalone/.next/server/app/api/queue/complete/route.js.nft.json +1 -1
  136. package/cloud-runtime/standalone/.next/server/app/api/queue/route.js +6 -5
  137. package/cloud-runtime/standalone/.next/server/app/api/queue/route.js.nft.json +1 -1
  138. package/cloud-runtime/standalone/.next/server/app/api/reactions/route.js.nft.json +1 -1
  139. package/cloud-runtime/standalone/.next/server/app/api/repos/[id]/knowledge/route.js +3 -3
  140. package/cloud-runtime/standalone/.next/server/app/api/repos/[id]/knowledge/route.js.nft.json +1 -1
  141. package/cloud-runtime/standalone/.next/server/app/api/schedules/debug/route.js +4 -4
  142. package/cloud-runtime/standalone/.next/server/app/api/schedules/debug/route.js.nft.json +1 -1
  143. package/cloud-runtime/standalone/.next/server/app/api/schedules/poll/route.js +4 -4
  144. package/cloud-runtime/standalone/.next/server/app/api/schedules/poll/route.js.nft.json +1 -1
  145. package/cloud-runtime/standalone/.next/server/app/api/schedules/route.js +4 -4
  146. package/cloud-runtime/standalone/.next/server/app/api/schedules/route.js.nft.json +1 -1
  147. package/cloud-runtime/standalone/.next/server/app/api/search/route.js.nft.json +1 -1
  148. package/cloud-runtime/standalone/.next/server/app/api/status/route.js +1 -1
  149. package/cloud-runtime/standalone/.next/server/app/api/status/route.js.nft.json +1 -1
  150. package/cloud-runtime/standalone/.next/server/app/api/summarize/route.js +3 -3
  151. package/cloud-runtime/standalone/.next/server/app/api/summarize/route.js.nft.json +1 -1
  152. package/cloud-runtime/standalone/.next/server/app/api/system/db-status/route.js.nft.json +1 -1
  153. package/cloud-runtime/standalone/.next/server/app/api/task-drafts/route.js.nft.json +1 -1
  154. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/comments/[commentId]/route.js +4 -3
  155. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/comments/[commentId]/route.js.nft.json +1 -1
  156. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/comments/route.js +6 -5
  157. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/comments/route.js.nft.json +1 -1
  158. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/costs/route.js +5 -4
  159. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/costs/route.js.nft.json +1 -1
  160. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/dependencies/route.js +5 -4
  161. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/dependencies/route.js.nft.json +1 -1
  162. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/events/route.js +4 -4
  163. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/events/route.js.nft.json +1 -1
  164. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/history/route.js +5 -5
  165. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/history/route.js.nft.json +1 -1
  166. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/metrics/route.js +5 -5
  167. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/metrics/route.js.nft.json +1 -1
  168. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/pause/route.js +2 -2
  169. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/pause/route.js.nft.json +1 -1
  170. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/replan/route.js +5 -5
  171. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/replan/route.js.nft.json +1 -1
  172. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/restart/route.js +4 -3
  173. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/restart/route.js.nft.json +1 -1
  174. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/resume/route.js +4 -3
  175. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/resume/route.js.nft.json +1 -1
  176. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/rollback/route.js +4 -4
  177. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/rollback/route.js.nft.json +1 -1
  178. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/route.js +5 -5
  179. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/route.js.nft.json +1 -1
  180. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/schedule/route.js +6 -5
  181. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/schedule/route.js.nft.json +1 -1
  182. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/start/route.js +4 -3
  183. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/start/route.js.nft.json +1 -1
  184. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/stop/route.js +2 -2
  185. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/graph/stop/route.js.nft.json +1 -1
  186. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/heartbeat/route.js +2 -2
  187. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/heartbeat/route.js.nft.json +1 -1
  188. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/history/route.js +5 -4
  189. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/history/route.js.nft.json +1 -1
  190. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/logs/route.js +4 -3
  191. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/logs/route.js.nft.json +1 -1
  192. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/logs/stream/route.js +2 -2
  193. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/logs/stream/route.js.nft.json +1 -1
  194. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/nodes/[nodeId]/comments/route.js +3 -3
  195. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/nodes/[nodeId]/comments/route.js.nft.json +1 -1
  196. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/nodes/[nodeId]/complete/route.js +7 -6
  197. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/nodes/[nodeId]/complete/route.js.nft.json +1 -1
  198. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/nodes/[nodeId]/fail/route.js +7 -6
  199. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/nodes/[nodeId]/fail/route.js.nft.json +1 -1
  200. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/nodes/[nodeId]/resume/route.js +6 -5
  201. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/nodes/[nodeId]/resume/route.js.nft.json +1 -1
  202. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/nodes/[nodeId]/start/route.js +6 -5
  203. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/nodes/[nodeId]/start/route.js.nft.json +1 -1
  204. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/nodes/[nodeId]/stop/route.js +7 -6
  205. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/nodes/[nodeId]/stop/route.js.nft.json +1 -1
  206. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/nodes/[nodeId]/verify/route.js +8 -6
  207. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/nodes/[nodeId]/verify/route.js.nft.json +1 -1
  208. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/route.js +4 -3
  209. package/cloud-runtime/standalone/.next/server/app/api/tasks/[id]/route.js.nft.json +1 -1
  210. package/cloud-runtime/standalone/.next/server/app/api/tasks/assign-orphans/route.js +5 -4
  211. package/cloud-runtime/standalone/.next/server/app/api/tasks/assign-orphans/route.js.nft.json +1 -1
  212. package/cloud-runtime/standalone/.next/server/app/api/tasks/extract/route.js +3 -3
  213. package/cloud-runtime/standalone/.next/server/app/api/tasks/extract/route.js.nft.json +1 -1
  214. package/cloud-runtime/standalone/.next/server/app/api/tasks/route.js +7 -6
  215. package/cloud-runtime/standalone/.next/server/app/api/tasks/route.js.nft.json +1 -1
  216. package/cloud-runtime/standalone/.next/server/app/api/tasks/stream/route.js +2 -2
  217. package/cloud-runtime/standalone/.next/server/app/api/tasks/stream/route.js.nft.json +1 -1
  218. package/cloud-runtime/standalone/.next/server/app/api/threads/knowledge/route/app-paths-manifest.json +3 -0
  219. package/cloud-runtime/standalone/.next/server/app/api/threads/knowledge/route/build-manifest.json +11 -0
  220. package/cloud-runtime/standalone/.next/server/app/api/threads/knowledge/route/server-reference-manifest.json +4 -0
  221. package/cloud-runtime/standalone/.next/server/app/api/threads/knowledge/route.js +10 -0
  222. package/cloud-runtime/standalone/.next/server/app/api/threads/knowledge/route.js.map +5 -0
  223. package/cloud-runtime/standalone/.next/server/app/api/threads/knowledge/route.js.nft.json +1 -0
  224. package/cloud-runtime/standalone/.next/server/app/api/threads/knowledge/route_client-reference-manifest.js +2 -0
  225. package/cloud-runtime/standalone/.next/server/app/api/threads/route.js +5 -2
  226. package/cloud-runtime/standalone/.next/server/app/api/threads/route.js.nft.json +1 -1
  227. package/cloud-runtime/standalone/.next/server/app/api/user-settings/route.js +5 -4
  228. package/cloud-runtime/standalone/.next/server/app/api/user-settings/route.js.nft.json +1 -1
  229. package/cloud-runtime/standalone/.next/server/app/automations/page/build-manifest.json +2 -2
  230. package/cloud-runtime/standalone/.next/server/app/automations/page.js.nft.json +1 -1
  231. package/cloud-runtime/standalone/.next/server/app/automations/page_client-reference-manifest.js +1 -1
  232. package/cloud-runtime/standalone/.next/server/app/automations.html +2 -2
  233. package/cloud-runtime/standalone/.next/server/app/automations.rsc +3 -3
  234. package/cloud-runtime/standalone/.next/server/app/automations.segments/_full.segment.rsc +3 -3
  235. package/cloud-runtime/standalone/.next/server/app/automations.segments/_head.segment.rsc +1 -1
  236. package/cloud-runtime/standalone/.next/server/app/automations.segments/_index.segment.rsc +2 -2
  237. package/cloud-runtime/standalone/.next/server/app/automations.segments/_tree.segment.rsc +2 -2
  238. package/cloud-runtime/standalone/.next/server/app/automations.segments/automations/__PAGE__.segment.rsc +2 -2
  239. package/cloud-runtime/standalone/.next/server/app/automations.segments/automations.segment.rsc +1 -1
  240. package/cloud-runtime/standalone/.next/server/app/board/page/build-manifest.json +2 -2
  241. package/cloud-runtime/standalone/.next/server/app/board/page_client-reference-manifest.js +1 -1
  242. package/cloud-runtime/standalone/.next/server/app/board.html +2 -2
  243. package/cloud-runtime/standalone/.next/server/app/board.rsc +2 -2
  244. package/cloud-runtime/standalone/.next/server/app/board.segments/_full.segment.rsc +2 -2
  245. package/cloud-runtime/standalone/.next/server/app/board.segments/_head.segment.rsc +1 -1
  246. package/cloud-runtime/standalone/.next/server/app/board.segments/_index.segment.rsc +2 -2
  247. package/cloud-runtime/standalone/.next/server/app/board.segments/_tree.segment.rsc +2 -2
  248. package/cloud-runtime/standalone/.next/server/app/board.segments/board/__PAGE__.segment.rsc +1 -1
  249. package/cloud-runtime/standalone/.next/server/app/board.segments/board.segment.rsc +1 -1
  250. package/cloud-runtime/standalone/.next/server/app/execution-graph/page/build-manifest.json +2 -2
  251. package/cloud-runtime/standalone/.next/server/app/execution-graph/page.js.nft.json +1 -1
  252. package/cloud-runtime/standalone/.next/server/app/execution-graph/page_client-reference-manifest.js +1 -1
  253. package/cloud-runtime/standalone/.next/server/app/execution-graph.html +2 -2
  254. package/cloud-runtime/standalone/.next/server/app/execution-graph.rsc +3 -3
  255. package/cloud-runtime/standalone/.next/server/app/execution-graph.segments/_full.segment.rsc +3 -3
  256. package/cloud-runtime/standalone/.next/server/app/execution-graph.segments/_head.segment.rsc +1 -1
  257. package/cloud-runtime/standalone/.next/server/app/execution-graph.segments/_index.segment.rsc +2 -2
  258. package/cloud-runtime/standalone/.next/server/app/execution-graph.segments/_tree.segment.rsc +2 -2
  259. package/cloud-runtime/standalone/.next/server/app/execution-graph.segments/execution-graph/__PAGE__.segment.rsc +2 -2
  260. package/cloud-runtime/standalone/.next/server/app/execution-graph.segments/execution-graph.segment.rsc +1 -1
  261. package/cloud-runtime/standalone/.next/server/app/index.html +2 -2
  262. package/cloud-runtime/standalone/.next/server/app/index.rsc +3 -3
  263. package/cloud-runtime/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  264. package/cloud-runtime/standalone/.next/server/app/index.segments/_full.segment.rsc +3 -3
  265. package/cloud-runtime/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
  266. package/cloud-runtime/standalone/.next/server/app/index.segments/_index.segment.rsc +2 -2
  267. package/cloud-runtime/standalone/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  268. package/cloud-runtime/standalone/.next/server/app/page/build-manifest.json +2 -2
  269. package/cloud-runtime/standalone/.next/server/app/page.js.nft.json +1 -1
  270. package/cloud-runtime/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  271. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/graph/[taskId]/page/build-manifest.json +2 -2
  272. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/graph/[taskId]/page.js.nft.json +1 -1
  273. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/graph/[taskId]/page_client-reference-manifest.js +1 -1
  274. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/knowledge/page/app-paths-manifest.json +3 -0
  275. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/knowledge/page/build-manifest.json +18 -0
  276. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/knowledge/page/next-font-manifest.json +11 -0
  277. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/knowledge/page/react-loadable-manifest.json +1 -0
  278. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/knowledge/page/server-reference-manifest.json +4 -0
  279. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/knowledge/page.js +16 -0
  280. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/knowledge/page.js.map +5 -0
  281. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/knowledge/page.js.nft.json +1 -0
  282. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/knowledge/page_client-reference-manifest.js +2 -0
  283. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/page/build-manifest.json +2 -2
  284. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/page.js.nft.json +1 -1
  285. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/page_client-reference-manifest.js +1 -1
  286. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/thread/[threadId]/page/app-paths-manifest.json +3 -0
  287. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/thread/[threadId]/page/build-manifest.json +18 -0
  288. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/thread/[threadId]/page/next-font-manifest.json +11 -0
  289. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/thread/[threadId]/page/react-loadable-manifest.json +1 -0
  290. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/thread/[threadId]/page/server-reference-manifest.json +4 -0
  291. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/thread/[threadId]/page.js +16 -0
  292. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/thread/[threadId]/page.js.map +5 -0
  293. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/thread/[threadId]/page.js.nft.json +1 -0
  294. package/cloud-runtime/standalone/.next/server/app/projects/[slug]/thread/[threadId]/page_client-reference-manifest.js +2 -0
  295. package/cloud-runtime/standalone/.next/server/app/projects/orphans/page/build-manifest.json +2 -2
  296. package/cloud-runtime/standalone/.next/server/app/projects/orphans/page.js.nft.json +1 -1
  297. package/cloud-runtime/standalone/.next/server/app/projects/orphans/page_client-reference-manifest.js +1 -1
  298. package/cloud-runtime/standalone/.next/server/app/projects/orphans.html +2 -2
  299. package/cloud-runtime/standalone/.next/server/app/projects/orphans.rsc +3 -3
  300. package/cloud-runtime/standalone/.next/server/app/projects/orphans.segments/_full.segment.rsc +3 -3
  301. package/cloud-runtime/standalone/.next/server/app/projects/orphans.segments/_head.segment.rsc +1 -1
  302. package/cloud-runtime/standalone/.next/server/app/projects/orphans.segments/_index.segment.rsc +2 -2
  303. package/cloud-runtime/standalone/.next/server/app/projects/orphans.segments/_tree.segment.rsc +2 -2
  304. package/cloud-runtime/standalone/.next/server/app/projects/orphans.segments/projects/orphans/__PAGE__.segment.rsc +2 -2
  305. package/cloud-runtime/standalone/.next/server/app/projects/orphans.segments/projects/orphans.segment.rsc +1 -1
  306. package/cloud-runtime/standalone/.next/server/app/projects/orphans.segments/projects.segment.rsc +1 -1
  307. package/cloud-runtime/standalone/.next/server/app/projects/page/build-manifest.json +2 -2
  308. package/cloud-runtime/standalone/.next/server/app/projects/page_client-reference-manifest.js +1 -1
  309. package/cloud-runtime/standalone/.next/server/app/projects.html +2 -2
  310. package/cloud-runtime/standalone/.next/server/app/projects.rsc +3 -3
  311. package/cloud-runtime/standalone/.next/server/app/projects.segments/_full.segment.rsc +3 -3
  312. package/cloud-runtime/standalone/.next/server/app/projects.segments/_head.segment.rsc +1 -1
  313. package/cloud-runtime/standalone/.next/server/app/projects.segments/_index.segment.rsc +2 -2
  314. package/cloud-runtime/standalone/.next/server/app/projects.segments/_tree.segment.rsc +2 -2
  315. package/cloud-runtime/standalone/.next/server/app/projects.segments/projects/__PAGE__.segment.rsc +2 -2
  316. package/cloud-runtime/standalone/.next/server/app/projects.segments/projects.segment.rsc +1 -1
  317. package/cloud-runtime/standalone/.next/server/app/settings/page/build-manifest.json +2 -2
  318. package/cloud-runtime/standalone/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  319. package/cloud-runtime/standalone/.next/server/app/settings.html +2 -2
  320. package/cloud-runtime/standalone/.next/server/app/settings.rsc +2 -2
  321. package/cloud-runtime/standalone/.next/server/app/settings.segments/_full.segment.rsc +2 -2
  322. package/cloud-runtime/standalone/.next/server/app/settings.segments/_head.segment.rsc +1 -1
  323. package/cloud-runtime/standalone/.next/server/app/settings.segments/_index.segment.rsc +2 -2
  324. package/cloud-runtime/standalone/.next/server/app/settings.segments/_tree.segment.rsc +2 -2
  325. package/cloud-runtime/standalone/.next/server/app/settings.segments/settings/__PAGE__.segment.rsc +1 -1
  326. package/cloud-runtime/standalone/.next/server/app/settings.segments/settings.segment.rsc +1 -1
  327. package/cloud-runtime/standalone/.next/server/app/status/page/build-manifest.json +2 -2
  328. package/cloud-runtime/standalone/.next/server/app/status/page.js.nft.json +1 -1
  329. package/cloud-runtime/standalone/.next/server/app/status/page_client-reference-manifest.js +1 -1
  330. package/cloud-runtime/standalone/.next/server/app/status.html +2 -2
  331. package/cloud-runtime/standalone/.next/server/app/status.rsc +3 -3
  332. package/cloud-runtime/standalone/.next/server/app/status.segments/_full.segment.rsc +3 -3
  333. package/cloud-runtime/standalone/.next/server/app/status.segments/_head.segment.rsc +1 -1
  334. package/cloud-runtime/standalone/.next/server/app/status.segments/_index.segment.rsc +2 -2
  335. package/cloud-runtime/standalone/.next/server/app/status.segments/_tree.segment.rsc +2 -2
  336. package/cloud-runtime/standalone/.next/server/app/status.segments/status/__PAGE__.segment.rsc +2 -2
  337. package/cloud-runtime/standalone/.next/server/app/status.segments/status.segment.rsc +1 -1
  338. package/cloud-runtime/standalone/.next/server/app/thread/[id]/page/build-manifest.json +2 -2
  339. package/cloud-runtime/standalone/.next/server/app/thread/[id]/page.js.nft.json +1 -1
  340. package/cloud-runtime/standalone/.next/server/app/thread/[id]/page_client-reference-manifest.js +1 -1
  341. package/cloud-runtime/standalone/.next/server/app/welcome/page/build-manifest.json +2 -2
  342. package/cloud-runtime/standalone/.next/server/app/welcome/page.js.nft.json +1 -1
  343. package/cloud-runtime/standalone/.next/server/app/welcome/page_client-reference-manifest.js +1 -1
  344. package/cloud-runtime/standalone/.next/server/app/welcome.html +2 -2
  345. package/cloud-runtime/standalone/.next/server/app/welcome.rsc +3 -3
  346. package/cloud-runtime/standalone/.next/server/app/welcome.segments/_full.segment.rsc +3 -3
  347. package/cloud-runtime/standalone/.next/server/app/welcome.segments/_head.segment.rsc +1 -1
  348. package/cloud-runtime/standalone/.next/server/app/welcome.segments/_index.segment.rsc +2 -2
  349. package/cloud-runtime/standalone/.next/server/app/welcome.segments/_tree.segment.rsc +2 -2
  350. package/cloud-runtime/standalone/.next/server/app/welcome.segments/welcome/__PAGE__.segment.rsc +2 -2
  351. package/cloud-runtime/standalone/.next/server/app/welcome.segments/welcome.segment.rsc +1 -1
  352. package/cloud-runtime/standalone/.next/server/app-paths-manifest.json +7 -0
  353. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__017f03c3._.js +13 -0
  354. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__06634853._.js +80 -0
  355. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__0b3b6a47._.js +51 -0
  356. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__16dd1fd7._.js +13 -0
  357. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__18423486._.js +3 -0
  358. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__19520d85._.js +75 -0
  359. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__1c18c0d1._.js +3 -0
  360. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__1cc2fe7f._.js +3 -0
  361. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__241a8bcf._.js +1 -1
  362. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__29419d66._.js +42 -0
  363. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__32b13ba9._.js +3 -0
  364. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__3c1567b6._.js +3 -0
  365. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__3c37453e._.js +3 -0
  366. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__3faa64cd._.js +4 -0
  367. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__42497c7b._.js +80 -0
  368. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__4837d72a._.js +3 -0
  369. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__49c03d66._.js +3 -0
  370. package/cloud-runtime/standalone/.next/server/chunks/{[root-of-the-server]__b40c7aab._.js → [root-of-the-server]__4a8d14c1._.js} +2 -2
  371. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__4c50f159._.js +4 -4
  372. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__4c861686._.js +46 -0
  373. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__4c8624cc._.js +3 -0
  374. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__4d8c6e3d._.js +58 -0
  375. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__50ddd3ce._.js +3 -0
  376. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__543ba6c4._.js +5 -1
  377. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__588b6ab0._.js +46 -0
  378. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__59b5d4e5._.js +1 -1
  379. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__5a348fba._.js +42 -0
  380. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__5d359afa._.js +46 -0
  381. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__61c99680._.js +52 -0
  382. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__666f8712._.js +3 -0
  383. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__6acb940d._.js +3 -0
  384. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__6c26221d._.js +7 -0
  385. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__74b97f0a._.js +1 -1
  386. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__7e79d86a._.js +3 -0
  387. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__7ffcc20c._.js +3 -0
  388. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__875279cb._.js +112 -0
  389. package/cloud-runtime/standalone/.next/server/chunks/{[root-of-the-server]__13677d96._.js → [root-of-the-server]__8b0ab82f._.js} +2 -2
  390. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__8b461158._.js +3 -0
  391. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__918f0106._.js +80 -0
  392. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__922eb7cd._.js +80 -0
  393. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__a189593a._.js +3 -0
  394. package/cloud-runtime/standalone/.next/server/chunks/{[root-of-the-server]__e6ad07c3._.js → [root-of-the-server]__a67cd108._.js} +2 -2
  395. package/cloud-runtime/standalone/.next/server/chunks/{[root-of-the-server]__d8cedc8a._.js → [root-of-the-server]__abb032c1._.js} +2 -2
  396. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__b3ed0a00._.js +46 -0
  397. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__b4d05543._.js +1 -1
  398. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__b63cb741._.js +63 -0
  399. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__b9b3fde6._.js +3 -0
  400. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__be4ad4b5._.js +46 -0
  401. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__c0a18648._.js +80 -0
  402. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__c480c9c2._.js +3 -0
  403. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__c5b8ceb7._.js +3 -0
  404. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__c8b49077._.js +79 -0
  405. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__c99509c2._.js +101 -0
  406. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__ceb02db8._.js +3 -0
  407. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__d6e1ee6e._.js +32 -0
  408. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__da20a0aa._.js +1 -1
  409. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__e069c0a3._.js +3 -0
  410. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__e122cae2._.js +3 -0
  411. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__e1e51c02._.js +7 -0
  412. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__ef82dda1._.js +3 -0
  413. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__f168c6dc._.js +25 -0
  414. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__f1b7932f._.js +36 -0
  415. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__f701b208._.js +146 -0
  416. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__fa0ebee3._.js +13 -0
  417. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__fce2cdce._.js +3 -0
  418. package/cloud-runtime/standalone/.next/server/chunks/{[root-of-the-server]__2e596cc8._.js → [root-of-the-server]__fee58db1._.js} +5 -5
  419. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__ffffceac._.js +6 -0
  420. package/cloud-runtime/standalone/.next/server/chunks/_05fa3b89._.js +46 -0
  421. package/cloud-runtime/standalone/.next/server/chunks/_0a767dfe._.js +3 -0
  422. package/cloud-runtime/standalone/.next/server/chunks/_2f3e5ac1._.js +6 -0
  423. package/cloud-runtime/standalone/.next/server/chunks/_4190f170._.js +46 -0
  424. package/cloud-runtime/standalone/.next/server/chunks/{[root-of-the-server]__a104cda8._.js → _42e9c8d5._.js} +7 -7
  425. package/cloud-runtime/standalone/.next/server/chunks/_5462a047._.js +3 -0
  426. package/cloud-runtime/standalone/.next/server/chunks/_5ca51127._.js +54 -0
  427. package/cloud-runtime/standalone/.next/server/chunks/_5fd6af5d._.js +57 -0
  428. package/cloud-runtime/standalone/.next/server/chunks/_6bb93816._.js +6 -0
  429. package/cloud-runtime/standalone/.next/server/chunks/_7011db4f._.js +3 -0
  430. package/cloud-runtime/standalone/.next/server/chunks/_8b9fde82._.js +97 -0
  431. package/cloud-runtime/standalone/.next/server/chunks/_95ac98db._.js +49 -0
  432. package/cloud-runtime/standalone/.next/server/chunks/_994414cd._.js +54 -0
  433. package/cloud-runtime/standalone/.next/server/chunks/_99b78daf._.js +46 -0
  434. package/cloud-runtime/standalone/.next/server/chunks/_a877d34f._.js +6 -0
  435. package/cloud-runtime/standalone/.next/server/chunks/_affbdbb0._.js +46 -0
  436. package/cloud-runtime/standalone/.next/server/chunks/_c31ca6ab._.js +3 -0
  437. package/cloud-runtime/standalone/.next/server/chunks/_c965f7b3._.js +3 -0
  438. package/cloud-runtime/standalone/.next/server/chunks/_d225c04f._.js +1 -1
  439. package/cloud-runtime/standalone/.next/server/chunks/_d22934ab._.js +97 -0
  440. package/cloud-runtime/standalone/.next/server/chunks/_ee99a36b._.js +6 -0
  441. package/cloud-runtime/standalone/.next/server/chunks/_efc73784._.js +46 -0
  442. package/cloud-runtime/standalone/.next/server/chunks/_fba13a4a._.js +6 -0
  443. package/cloud-runtime/standalone/.next/server/chunks/_next-internal_server_app_api_chat-runs_[id]_route_actions_033ac330.js +3 -0
  444. package/cloud-runtime/standalone/.next/server/chunks/_next-internal_server_app_api_chat-runs_[id]_signal_route_actions_4b56f1cd.js +3 -0
  445. package/cloud-runtime/standalone/.next/server/chunks/_next-internal_server_app_api_chat-runs_route_actions_0c8cd01c.js +3 -0
  446. package/cloud-runtime/standalone/.next/server/chunks/_next-internal_server_app_api_knowledge-notes_route_actions_0ddf6109.js +3 -0
  447. package/cloud-runtime/standalone/.next/server/chunks/_next-internal_server_app_api_threads_knowledge_route_actions_c139bcf7.js +3 -0
  448. package/cloud-runtime/standalone/.next/server/chunks/lib_7cad5c77._.js +64 -0
  449. package/cloud-runtime/standalone/.next/server/chunks/lib_87c06aeb._.js +25 -0
  450. package/cloud-runtime/standalone/.next/server/chunks/lib_db_ts_e06c6085._.js +1 -1
  451. package/cloud-runtime/standalone/.next/server/chunks/lib_ea45fe73._.js +68 -23
  452. package/cloud-runtime/standalone/.next/server/chunks/lib_history-store_ts_2e721df2._.js +94 -42
  453. package/cloud-runtime/standalone/.next/server/chunks/lib_history-store_ts_74d1c060._.js +91 -44
  454. package/cloud-runtime/standalone/.next/server/chunks/lib_sqlite-query-adapter_ts_3ea4d849._.js +87 -17
  455. package/cloud-runtime/standalone/.next/server/chunks/lib_sqlite-query-adapter_ts_b0b1a9b2._.js +294 -0
  456. package/cloud-runtime/standalone/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_0f808fa3.js +3 -0
  457. package/cloud-runtime/standalone/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_2bdede98.js +3 -0
  458. package/cloud-runtime/standalone/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_371d0bff.js +50 -43
  459. package/cloud-runtime/standalone/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_3d31fed0.js +3 -0
  460. package/cloud-runtime/standalone/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_57a073eb.js +3 -0
  461. package/cloud-runtime/standalone/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_7f8022ab.js +3 -0
  462. package/cloud-runtime/standalone/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_84e28f38.js +3 -0
  463. package/cloud-runtime/standalone/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_8ec90680.js +3 -0
  464. package/cloud-runtime/standalone/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_a590fcd6.js +3 -0
  465. package/cloud-runtime/standalone/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_cc6c687d.js +3 -0
  466. package/cloud-runtime/standalone/.next/server/chunks/src_graph_14067235._.js +46 -0
  467. package/cloud-runtime/standalone/.next/server/chunks/src_graph_api-route-utils_ts_b7225a0e._.js +1 -1
  468. package/cloud-runtime/standalone/.next/server/chunks/src_graph_b63e2d39._.js +46 -0
  469. package/cloud-runtime/standalone/.next/server/chunks/src_graph_executor_ts_55c06268._.js +3 -3
  470. package/cloud-runtime/standalone/.next/server/chunks/src_graph_executor_ts_a8bc8d58._.js +1 -1
  471. package/cloud-runtime/standalone/.next/server/chunks/ssr/[root-of-the-server]__04d1aa70._.js +3 -0
  472. package/cloud-runtime/standalone/.next/server/chunks/ssr/[root-of-the-server]__2d80540b._.js +3 -0
  473. package/cloud-runtime/standalone/.next/server/chunks/ssr/[root-of-the-server]__47caef59._.js +1 -1
  474. package/cloud-runtime/standalone/.next/server/chunks/ssr/[root-of-the-server]__5ffa2883._.js +1 -1
  475. package/cloud-runtime/standalone/.next/server/chunks/ssr/[root-of-the-server]__6e83bf83._.js +3 -0
  476. package/cloud-runtime/standalone/.next/server/chunks/ssr/[root-of-the-server]__8973b16a._.js +3 -0
  477. package/cloud-runtime/standalone/.next/server/chunks/ssr/[root-of-the-server]__a0a1cb74._.js +3 -0
  478. package/cloud-runtime/standalone/.next/server/chunks/ssr/[root-of-the-server]__a416df95._.js +3 -0
  479. package/cloud-runtime/standalone/.next/server/chunks/ssr/[root-of-the-server]__c108f06c._.js +3 -0
  480. package/cloud-runtime/standalone/.next/server/chunks/ssr/[root-of-the-server]__fca7df40._.js +3 -0
  481. package/cloud-runtime/standalone/.next/server/chunks/ssr/{_27f9c020._.js → _0061ebd8._.js} +2 -2
  482. package/cloud-runtime/standalone/.next/server/chunks/ssr/_064370bc._.js +3 -0
  483. package/cloud-runtime/standalone/.next/server/chunks/ssr/_41f60c52._.js +3 -0
  484. package/cloud-runtime/standalone/.next/server/chunks/ssr/_6b14826d._.js +3 -0
  485. package/cloud-runtime/standalone/.next/server/chunks/ssr/{_a696e9b3._.js → _84879a01._.js} +2 -2
  486. package/cloud-runtime/standalone/.next/server/chunks/ssr/_85ca101b._.js +8 -0
  487. package/cloud-runtime/standalone/.next/server/chunks/ssr/{_c838f593._.js → _9eeb2fa0._.js} +2 -2
  488. package/cloud-runtime/standalone/.next/server/chunks/ssr/_a0cc0fe7._.js +3 -0
  489. package/cloud-runtime/standalone/.next/server/chunks/ssr/_a10eb951._.js +4 -0
  490. package/cloud-runtime/standalone/.next/server/chunks/ssr/{_4b5d7c9b._.js → _a1d30b20._.js} +2 -2
  491. package/cloud-runtime/standalone/.next/server/chunks/ssr/{_27cb3359._.js → _c87c359c._.js} +2 -2
  492. package/cloud-runtime/standalone/.next/server/chunks/ssr/_cb4d8a23._.js +4 -0
  493. package/cloud-runtime/standalone/.next/server/chunks/ssr/{_6a367524._.js → _ccb409c5._.js} +2 -2
  494. package/cloud-runtime/standalone/.next/server/chunks/ssr/_cd5e154b._.js +1 -1
  495. package/cloud-runtime/standalone/.next/server/chunks/ssr/{_d021529a._.js → _dd31b6e0._.js} +2 -2
  496. package/cloud-runtime/standalone/.next/server/chunks/ssr/_f0ce6183._.js +3 -0
  497. package/cloud-runtime/standalone/.next/server/chunks/ssr/_next-internal_server_app_projects_[slug]_knowledge_page_actions_1037c40a.js +3 -0
  498. package/cloud-runtime/standalone/.next/server/chunks/ssr/app_execution-graph_page_tsx_f854185a._.js +2 -2
  499. package/cloud-runtime/standalone/.next/server/chunks/ssr/app_projects_[slug]_graph_[taskId]_page_tsx_d8b1d582._.js +1 -1
  500. package/cloud-runtime/standalone/.next/server/chunks/ssr/app_projects_[slug]_knowledge_page_tsx_e2a55cbd._.js +3 -0
  501. package/cloud-runtime/standalone/.next/server/chunks/ssr/app_welcome_page_tsx_6c79bc59._.js +3 -0
  502. package/cloud-runtime/standalone/.next/server/chunks/ssr/ce889_server_app_projects_[slug]_thread_[threadId]_page_actions_660a8857.js +3 -0
  503. package/cloud-runtime/standalone/.next/server/chunks/ssr/components_chat-ui_bfeda794._.js +5 -5
  504. package/cloud-runtime/standalone/.next/server/chunks/ssr/components_thread_WorkspaceSidebar_tsx_e660301b._.js +1 -1
  505. package/cloud-runtime/standalone/.next/server/chunks/ssr/node_modules_lucide-react_dist_esm_e70f9321._.js +3 -0
  506. package/cloud-runtime/standalone/.next/server/chunks/ssr/node_modules_lucide-react_dist_esm_icons_bf855424._.js +3 -0
  507. package/cloud-runtime/standalone/.next/server/functions-config-manifest.json +5 -0
  508. package/cloud-runtime/standalone/.next/server/middleware-build-manifest.js +2 -2
  509. package/cloud-runtime/standalone/.next/server/middleware-manifest.json +5 -5
  510. package/cloud-runtime/standalone/.next/server/next-font-manifest.js +1 -1
  511. package/cloud-runtime/standalone/.next/server/next-font-manifest.json +8 -0
  512. package/cloud-runtime/standalone/.next/server/pages/404.html +2 -2
  513. package/cloud-runtime/standalone/.next/server/pages/500.html +2 -2
  514. package/cloud-runtime/standalone/.next/server/server-reference-manifest.js +1 -1
  515. package/cloud-runtime/standalone/.next/server/server-reference-manifest.json +1 -1
  516. package/cloud-runtime/standalone/.next/static/chunks/{b5bd2eb6e0c7f71a.js → 010aff7b601302de.js} +3 -3
  517. package/cloud-runtime/standalone/.next/static/chunks/012e3e9699415997.js +1 -0
  518. package/cloud-runtime/standalone/.next/static/chunks/031d99fbe758545a.js +1 -0
  519. package/cloud-runtime/standalone/.next/static/chunks/0c467f54bc78a380.js +1 -0
  520. package/cloud-runtime/standalone/.next/static/chunks/{b4e298542d366e31.js → 116985039c24f1f8.js} +9 -9
  521. package/cloud-runtime/standalone/.next/static/chunks/2ee8d24314eec47c.js +1 -0
  522. package/cloud-runtime/standalone/.next/static/chunks/3a55441b018d52e4.js +1 -0
  523. package/cloud-runtime/standalone/.next/static/chunks/43f6157bc3db9c52.js +6 -0
  524. package/cloud-runtime/standalone/.next/static/chunks/486bf7ff282b91a6.js +5 -0
  525. package/cloud-runtime/standalone/.next/static/chunks/{e44264686aa5ecbf.js → 56a01238098d495d.js} +9 -9
  526. package/cloud-runtime/standalone/.next/static/chunks/{45b4d0ee5c92d45b.js → 601996727991149e.js} +9 -9
  527. package/cloud-runtime/standalone/.next/static/chunks/851b1d97179bd39b.css +1 -0
  528. package/cloud-runtime/standalone/.next/static/chunks/8d15ced2dc70090a.js +1 -0
  529. package/cloud-runtime/standalone/.next/static/chunks/90b581e9631d8cea.js +1 -0
  530. package/cloud-runtime/standalone/.next/static/chunks/b22947e6df238fd5.js +1 -0
  531. package/cloud-runtime/standalone/.next/static/chunks/{616d66dbec9e4b8b.js → b2dcd19ebe3af3f6.js} +9 -9
  532. package/cloud-runtime/standalone/.next/static/chunks/bc06988336ffd261.js +1 -0
  533. package/cloud-runtime/standalone/.next/static/chunks/{3344004561eabdf8.js → bc3cad3c821b169b.js} +1 -1
  534. package/cloud-runtime/standalone/.next/static/chunks/c93b9643c81c134e.js +8 -0
  535. package/cloud-runtime/standalone/.next/static/chunks/d5d6be8239e57c56.js +1 -0
  536. package/cloud-runtime/standalone/.next/static/chunks/{88e24940a5d5d386.js → d78cc7d749043fef.js} +1 -1
  537. package/cloud-runtime/standalone/.next/static/chunks/{ee5f1457fbc593e1.js → dfff51033c303fc7.js} +1 -1
  538. package/cloud-runtime/standalone/.next/static/chunks/ebaf4e8f04bae7b6.js +1 -0
  539. package/cloud-runtime/standalone/.next/static/chunks/f4909e7ae8229b1c.js +1 -0
  540. package/cloud-runtime/standalone/.next/static/chunks/fd221a50082e5128.js +1 -0
  541. package/cloud-runtime/standalone/.next/static/chunks/{turbopack-5b5918f610666d2d.js → turbopack-97e846241a3a64af.js} +1 -1
  542. package/cloud-runtime/standalone/README.md +3 -3
  543. package/cloud-runtime/standalone/app/api/chat/route.ts +74 -28
  544. package/cloud-runtime/standalone/app/api/chat-runs/[id]/route.ts +19 -0
  545. package/cloud-runtime/standalone/app/api/chat-runs/[id]/signal/route.ts +32 -0
  546. package/cloud-runtime/standalone/app/api/chat-runs/route.ts +37 -0
  547. package/cloud-runtime/standalone/app/api/history/route.ts +6 -0
  548. package/cloud-runtime/standalone/app/api/knowledge-notes/route.ts +53 -0
  549. package/cloud-runtime/standalone/app/api/projects/[id]/memory/route.ts +17 -0
  550. package/cloud-runtime/standalone/app/api/providers/route.ts +9 -13
  551. package/cloud-runtime/standalone/app/api/schedules/debug/route.ts +23 -3
  552. package/cloud-runtime/standalone/app/api/schedules/poll/route.ts +5 -3
  553. package/cloud-runtime/standalone/app/api/schedules/route.ts +12 -17
  554. package/cloud-runtime/standalone/app/api/status/route.ts +6 -5
  555. package/cloud-runtime/standalone/app/api/threads/knowledge/route.ts +91 -0
  556. package/cloud-runtime/standalone/app/api/threads/route.ts +18 -1
  557. package/cloud-runtime/standalone/app/globals.css +1 -4
  558. package/cloud-runtime/standalone/app/projects/[slug]/graph/[taskId]/page.tsx +0 -21
  559. package/cloud-runtime/standalone/app/projects/[slug]/knowledge/page.tsx +792 -0
  560. package/cloud-runtime/standalone/app/projects/[slug]/layout.tsx +18 -2
  561. package/cloud-runtime/standalone/app/projects/[slug]/page.tsx +1 -455
  562. package/cloud-runtime/standalone/app/projects/[slug]/thread/[threadId]/page.tsx +14 -0
  563. package/cloud-runtime/standalone/app/welcome/page.tsx +329 -107
  564. package/cloud-runtime/standalone/components/ActionToolbar.tsx +3 -3
  565. package/cloud-runtime/standalone/components/ConfirmDialog.tsx +133 -0
  566. package/cloud-runtime/standalone/components/IconButton.tsx +3 -3
  567. package/cloud-runtime/standalone/components/ProjectModal.tsx +2 -2
  568. package/cloud-runtime/standalone/components/chat-ui/ChatContainer.tsx +441 -81
  569. package/cloud-runtime/standalone/components/chat-ui/Composer.tsx +149 -97
  570. package/cloud-runtime/standalone/components/chat-ui/Markdown.tsx +19 -9
  571. package/cloud-runtime/standalone/components/chat-ui/ThreadView.tsx +73 -34
  572. package/cloud-runtime/standalone/components/thread/WorkspaceSidebar.tsx +83 -50
  573. package/cloud-runtime/standalone/hooks/useComposerHistory.ts +130 -0
  574. package/cloud-runtime/standalone/hooks/useGroupChat.ts +28 -1
  575. package/cloud-runtime/standalone/hooks/useProcessPolling.ts +70 -6
  576. package/cloud-runtime/standalone/hooks/useThreadState.ts +10 -2
  577. package/cloud-runtime/standalone/lib/cli-runner.ts +212 -14
  578. package/cloud-runtime/standalone/lib/db.ts +1 -1
  579. package/cloud-runtime/standalone/lib/debug-log.ts +48 -0
  580. package/cloud-runtime/standalone/lib/history-store.ts +610 -40
  581. package/cloud-runtime/standalone/lib/knowledge-notes.ts +251 -0
  582. package/cloud-runtime/standalone/lib/knowledge-store.ts +233 -0
  583. package/cloud-runtime/standalone/lib/memory-extractor.ts +76 -60
  584. package/cloud-runtime/standalone/lib/mesh-core/journal.ts +30 -0
  585. package/cloud-runtime/standalone/lib/mesh-core/self.ts +94 -0
  586. package/cloud-runtime/standalone/lib/orchestrator/chat-activities.ts +60 -0
  587. package/cloud-runtime/standalone/lib/orchestrator/chat-processor.ts +219 -0
  588. package/cloud-runtime/standalone/lib/orchestrator/chat-types.ts +29 -0
  589. package/cloud-runtime/standalone/lib/orchestrator/runtime.ts +26 -0
  590. package/cloud-runtime/standalone/lib/provider-clis.ts +63 -0
  591. package/cloud-runtime/standalone/lib/queue/boss.ts +2 -1
  592. package/cloud-runtime/standalone/lib/queue/sqlite-adapter.ts +117 -2
  593. package/cloud-runtime/standalone/lib/repo-knowledge.ts +19 -2
  594. package/cloud-runtime/standalone/lib/sqlite-query-adapter.ts +78 -0
  595. package/cloud-runtime/standalone/lib/stream-multiplexer.ts +101 -14
  596. package/cloud-runtime/standalone/lib/task-context.ts +7 -4
  597. package/cloud-runtime/standalone/lib/thread-knowledge-runs.ts +227 -0
  598. package/cloud-runtime/standalone/lib/thread-knowledge.ts +419 -0
  599. package/cloud-runtime/standalone/node_modules/@img/{sharp-libvips-darwin-arm64 → sharp-libvips-linux-x64}/README.md +2 -2
  600. package/cloud-runtime/standalone/node_modules/@img/{sharp-libvips-darwin-arm64 → sharp-libvips-linux-x64}/lib/glib-2.0/include/glibconfig.h +9 -8
  601. package/cloud-runtime/standalone/node_modules/@img/{sharp-libvips-darwin-arm64/lib/libvips-cpp.8.17.3.dylib → sharp-libvips-linux-x64/lib/libvips-cpp.so.8.17.3} +0 -0
  602. package/cloud-runtime/standalone/node_modules/@img/{sharp-libvips-darwin-arm64 → sharp-libvips-linux-x64}/package.json +11 -5
  603. package/cloud-runtime/standalone/node_modules/@img/sharp-libvips-linuxmusl-x64/README.md +46 -0
  604. package/cloud-runtime/standalone/node_modules/@img/sharp-libvips-linuxmusl-x64/lib/glib-2.0/include/glibconfig.h +221 -0
  605. package/cloud-runtime/standalone/node_modules/@img/sharp-libvips-linuxmusl-x64/lib/index.js +1 -0
  606. package/cloud-runtime/standalone/node_modules/@img/sharp-libvips-linuxmusl-x64/lib/libvips-cpp.so.8.17.3 +0 -0
  607. package/cloud-runtime/standalone/node_modules/@img/sharp-libvips-linuxmusl-x64/package.json +42 -0
  608. package/cloud-runtime/standalone/node_modules/@img/sharp-libvips-linuxmusl-x64/versions.json +30 -0
  609. package/cloud-runtime/standalone/node_modules/@img/sharp-linux-x64/lib/sharp-linux-x64.node +0 -0
  610. package/cloud-runtime/standalone/node_modules/@img/{sharp-darwin-arm64 → sharp-linux-x64}/package.json +13 -7
  611. package/cloud-runtime/standalone/node_modules/@img/sharp-linuxmusl-x64/lib/sharp-linuxmusl-x64.node +0 -0
  612. package/cloud-runtime/standalone/node_modules/@img/sharp-linuxmusl-x64/package.json +46 -0
  613. package/cloud-runtime/standalone/node_modules/better-sqlite3/build/Release/better_sqlite3.node +0 -0
  614. package/cloud-runtime/standalone/node_modules/better-sqlite3-90e2652d1716b047/build/Release/better_sqlite3.node +0 -0
  615. package/cloud-runtime/standalone/package-lock.json +13 -0
  616. package/cloud-runtime/standalone/package.json +1 -0
  617. package/cloud-runtime/standalone/server.js +1 -1
  618. package/cloud-runtime/standalone/src/graph/api-schemas.ts +2 -2
  619. package/cloud-runtime/standalone/src/graph/executor.ts +9 -7
  620. package/cloud-runtime/standalone/src/graph/function-executor.ts +4 -1
  621. package/cloud-runtime/standalone/src/graph/internal-function-dispatcher.ts +174 -0
  622. package/cloud-runtime/standalone/src/graph/types.ts +3 -3
  623. package/cloud-runtime/standalone/src/graph/work-dispatcher.ts +5 -1
  624. package/cloud-runtime/standalone/transcri +0 -0
  625. package/cloud-runtime/standalone/tsconfig.json +3 -1
  626. package/cloud-runtime/standalone/worker/index.js +3447 -215
  627. package/cloud-runtime/standalone/worker/index.ts +8 -1
  628. package/lib/cli/runCli.js +0 -97
  629. package/lib/commands/update.js +159 -17
  630. package/package.json +1 -1
  631. package/cloud-runtime/standalone/.next/server/chunks/[externals]_child_process_964038fc._.js +0 -3
  632. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__03a1bf91._.js +0 -6
  633. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__065c5114._.js +0 -3
  634. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__07dce481._.js +0 -3
  635. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__09f46c85._.js +0 -46
  636. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__149bcf6d._.js +0 -115
  637. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__14bad16e._.js +0 -3
  638. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__14e3bf74._.js +0 -3
  639. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__1632828c._.js +0 -46
  640. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__1dd062c1._.js +0 -3
  641. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__24b8ccd3._.js +0 -52
  642. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__284e1cbe._.js +0 -3
  643. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__28d6e806._.js +0 -3
  644. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__2bcb75a7._.js +0 -3
  645. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__3198c5c8._.js +0 -52
  646. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__32e5f341._.js +0 -4
  647. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__36d9edbd._.js +0 -67
  648. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__3b4a126a._.js +0 -46
  649. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__3c7464e8._.js +0 -46
  650. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__3d82dc78._.js +0 -46
  651. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__406bdd54._.js +0 -46
  652. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__40d6458a._.js +0 -3
  653. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__47ca4946._.js +0 -3
  654. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__49fb4a12._.js +0 -3
  655. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__4dc25d71._.js +0 -18
  656. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__5327e395._.js +0 -46
  657. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__55d75c3a._.js +0 -7
  658. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__592e81f9._.js +0 -13
  659. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__5a6a194c._.js +0 -52
  660. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__5af16b4f._.js +0 -3
  661. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__60ba5058._.js +0 -3
  662. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__6716441c._.js +0 -3
  663. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__673aedc6._.js +0 -3
  664. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__6a44c891._.js +0 -3
  665. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__6b680112._.js +0 -55
  666. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__7312fad4._.js +0 -46
  667. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__7456196c._.js +0 -52
  668. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__74d26856._.js +0 -3
  669. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__772c6fae._.js +0 -3
  670. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__787ba54b._.js +0 -3
  671. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__79157eef._.js +0 -3
  672. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__7be8f159._.js +0 -52
  673. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__82d76712._.js +0 -3
  674. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__8311f060._.js +0 -6
  675. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__84e90655._.js +0 -46
  676. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__90a887dc._.js +0 -3
  677. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__9345d703._.js +0 -3
  678. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__98294450._.js +0 -3
  679. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__985f0d9f._.js +0 -51
  680. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__9b32295e._.js +0 -3
  681. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__a64d978e._.js +0 -6
  682. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__babcd1af._.js +0 -13
  683. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__c16f03fb._.js +0 -13
  684. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__c2767ca5._.js +0 -3
  685. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__c72c6d4a._.js +0 -25
  686. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__ca851b15._.js +0 -3
  687. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__d25227df._.js +0 -29
  688. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__e06820c3._.js +0 -6
  689. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__e429a0bc._.js +0 -3
  690. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__e4397d43._.js +0 -7
  691. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__e45a2a1d._.js +0 -3
  692. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__ec8735f4._.js +0 -3
  693. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__ef09ab99._.js +0 -13
  694. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__f366a937._.js +0 -46
  695. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__fdaa8a27._.js +0 -3
  696. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__fddde532._.js +0 -3
  697. package/cloud-runtime/standalone/.next/server/chunks/[root-of-the-server]__ff53f445._.js +0 -3
  698. package/cloud-runtime/standalone/.next/server/chunks/_1111d342._.js +0 -101
  699. package/cloud-runtime/standalone/.next/server/chunks/_4b60ba15._.js +0 -49
  700. package/cloud-runtime/standalone/.next/server/chunks/_54252651._.js +0 -49
  701. package/cloud-runtime/standalone/.next/server/chunks/_818a89c4._.js +0 -46
  702. package/cloud-runtime/standalone/.next/server/chunks/_a4a21d4f._.js +0 -3
  703. package/cloud-runtime/standalone/.next/server/chunks/_a759d52b._.js +0 -3
  704. package/cloud-runtime/standalone/.next/server/chunks/_e6b28eae._.js +0 -46
  705. package/cloud-runtime/standalone/.next/server/chunks/_e868e7c1._.js +0 -46
  706. package/cloud-runtime/standalone/.next/server/chunks/lib_23509137._.js +0 -196
  707. package/cloud-runtime/standalone/.next/server/chunks/lib_3273d5f9._.js +0 -196
  708. package/cloud-runtime/standalone/.next/server/chunks/lib_50ba0b4c._.js +0 -63
  709. package/cloud-runtime/standalone/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_33963d95.js +0 -3
  710. package/cloud-runtime/standalone/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_56c5acb3.js +0 -3
  711. package/cloud-runtime/standalone/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_888b3578.js +0 -3
  712. package/cloud-runtime/standalone/.next/server/chunks/src_graph_e3bb4da8._.js +0 -46
  713. package/cloud-runtime/standalone/.next/server/chunks/ssr/[root-of-the-server]__113d6767._.js +0 -3
  714. package/cloud-runtime/standalone/.next/server/chunks/ssr/[root-of-the-server]__6a9d3855._.js +0 -3
  715. package/cloud-runtime/standalone/.next/server/chunks/ssr/[root-of-the-server]__942ca438._.js +0 -3
  716. package/cloud-runtime/standalone/.next/server/chunks/ssr/[root-of-the-server]__ce3b51aa._.js +0 -3
  717. package/cloud-runtime/standalone/.next/server/chunks/ssr/_1ec61dee._.js +0 -3
  718. package/cloud-runtime/standalone/.next/server/chunks/ssr/_27904584._.js +0 -3
  719. package/cloud-runtime/standalone/.next/server/chunks/ssr/_43472af3._.js +0 -3
  720. package/cloud-runtime/standalone/.next/server/chunks/ssr/_94effa0f._.js +0 -3
  721. package/cloud-runtime/standalone/.next/server/chunks/ssr/_d458d1eb._.js +0 -3
  722. package/cloud-runtime/standalone/.next/server/chunks/ssr/_fbced30b._.js +0 -3
  723. package/cloud-runtime/standalone/.next/server/chunks/ssr/app_projects_[slug]_page_tsx_e0fabf6e._.js +0 -8
  724. package/cloud-runtime/standalone/.next/server/chunks/ssr/node_modules_lucide-react_dist_esm_a8f86889._.js +0 -3
  725. package/cloud-runtime/standalone/.next/server/chunks/ssr/node_modules_lucide-react_dist_esm_icons_play_6595a532.js +0 -3
  726. package/cloud-runtime/standalone/.next/static/chunks/1184bf1bfdf97666.js +0 -1
  727. package/cloud-runtime/standalone/.next/static/chunks/4c01a5f19f9e775e.js +0 -8
  728. package/cloud-runtime/standalone/.next/static/chunks/5ace4b4f4475962a.js +0 -1
  729. package/cloud-runtime/standalone/.next/static/chunks/6509f7fecbf44493.js +0 -1
  730. package/cloud-runtime/standalone/.next/static/chunks/661090206d8bae9b.css +0 -1
  731. package/cloud-runtime/standalone/.next/static/chunks/6dbf5940e30fa9c7.js +0 -1
  732. package/cloud-runtime/standalone/.next/static/chunks/7e91f395ace1dd2c.js +0 -1
  733. package/cloud-runtime/standalone/.next/static/chunks/7f13efe9329d3f97.js +0 -1
  734. package/cloud-runtime/standalone/.next/static/chunks/80219bbddcf65109.js +0 -1
  735. package/cloud-runtime/standalone/.next/static/chunks/86ace6febb11ad71.js +0 -1
  736. package/cloud-runtime/standalone/.next/static/chunks/b079c677d9b39f98.js +0 -5
  737. package/cloud-runtime/standalone/.next/static/chunks/b88352740262931f.js +0 -6
  738. package/cloud-runtime/standalone/.next/static/chunks/c5609fd2abb65850.js +0 -1
  739. package/cloud-runtime/standalone/.next/static/chunks/d95cd010361834be.js +0 -1
  740. package/cloud-runtime/standalone/.next/static/chunks/f7bbf5cfcfed8ba9.js +0 -1
  741. package/cloud-runtime/standalone/coverage/clover.xml +0 -1208
  742. package/cloud-runtime/standalone/coverage/coverage-final.json +0 -29
  743. package/cloud-runtime/standalone/coverage/lcov-report/app/api/audit/index.html +0 -116
  744. package/cloud-runtime/standalone/coverage/lcov-report/app/api/audit/route.ts.html +0 -208
  745. package/cloud-runtime/standalone/coverage/lcov-report/app/api/auth/[...nextauth]/index.html +0 -116
  746. package/cloud-runtime/standalone/coverage/lcov-report/app/api/auth/[...nextauth]/route.ts.html +0 -166
  747. package/cloud-runtime/standalone/coverage/lcov-report/app/api/auth/daemon-secret/index.html +0 -116
  748. package/cloud-runtime/standalone/coverage/lcov-report/app/api/auth/daemon-secret/route.ts.html +0 -532
  749. package/cloud-runtime/standalone/coverage/lcov-report/app/api/auth/status/index.html +0 -116
  750. package/cloud-runtime/standalone/coverage/lcov-report/app/api/auth/status/route.ts.html +0 -178
  751. package/cloud-runtime/standalone/coverage/lcov-report/app/api/learnings/index.html +0 -116
  752. package/cloud-runtime/standalone/coverage/lcov-report/app/api/learnings/route.ts.html +0 -262
  753. package/cloud-runtime/standalone/coverage/lcov-report/app/api/logs/stream/index.html +0 -116
  754. package/cloud-runtime/standalone/coverage/lcov-report/app/api/logs/stream/route.ts.html +0 -448
  755. package/cloud-runtime/standalone/coverage/lcov-report/app/api/queue/complete/index.html +0 -116
  756. package/cloud-runtime/standalone/coverage/lcov-report/app/api/queue/complete/route.ts.html +0 -331
  757. package/cloud-runtime/standalone/coverage/lcov-report/app/api/queue/index.html +0 -116
  758. package/cloud-runtime/standalone/coverage/lcov-report/app/api/queue/route.ts.html +0 -505
  759. package/cloud-runtime/standalone/coverage/lcov-report/app/api/stage-prompts/index.html +0 -116
  760. package/cloud-runtime/standalone/coverage/lcov-report/app/api/stage-prompts/route.ts.html +0 -412
  761. package/cloud-runtime/standalone/coverage/lcov-report/app/api/tasks/[id]/advance/index.html +0 -116
  762. package/cloud-runtime/standalone/coverage/lcov-report/app/api/tasks/[id]/advance/route.ts.html +0 -304
  763. package/cloud-runtime/standalone/coverage/lcov-report/app/api/tasks/[id]/index.html +0 -116
  764. package/cloud-runtime/standalone/coverage/lcov-report/app/api/tasks/[id]/logs/index.html +0 -116
  765. package/cloud-runtime/standalone/coverage/lcov-report/app/api/tasks/[id]/logs/route.ts.html +0 -202
  766. package/cloud-runtime/standalone/coverage/lcov-report/app/api/tasks/[id]/route.ts.html +0 -373
  767. package/cloud-runtime/standalone/coverage/lcov-report/app/api/tasks/index.html +0 -116
  768. package/cloud-runtime/standalone/coverage/lcov-report/app/api/tasks/route.ts.html +0 -499
  769. package/cloud-runtime/standalone/coverage/lcov-report/app/api/tasks/stream/index.html +0 -116
  770. package/cloud-runtime/standalone/coverage/lcov-report/app/api/tasks/stream/route.ts.html +0 -349
  771. package/cloud-runtime/standalone/coverage/lcov-report/base.css +0 -224
  772. package/cloud-runtime/standalone/coverage/lcov-report/block-navigation.js +0 -87
  773. package/cloud-runtime/standalone/coverage/lcov-report/components/AuthProvider.tsx.html +0 -259
  774. package/cloud-runtime/standalone/coverage/lcov-report/components/ChatInterface.tsx.html +0 -1228
  775. package/cloud-runtime/standalone/coverage/lcov-report/components/KanbanBoard.tsx.html +0 -1024
  776. package/cloud-runtime/standalone/coverage/lcov-report/components/Layout.tsx.html +0 -211
  777. package/cloud-runtime/standalone/coverage/lcov-report/components/LearningsPanel.tsx.html +0 -535
  778. package/cloud-runtime/standalone/coverage/lcov-report/components/LogTimeline.tsx.html +0 -415
  779. package/cloud-runtime/standalone/coverage/lcov-report/components/SortableTaskCard.tsx.html +0 -358
  780. package/cloud-runtime/standalone/coverage/lcov-report/components/StagePills.tsx.html +0 -439
  781. package/cloud-runtime/standalone/coverage/lcov-report/components/TaskCard.tsx.html +0 -514
  782. package/cloud-runtime/standalone/coverage/lcov-report/components/TaskCardOverlay.tsx.html +0 -256
  783. package/cloud-runtime/standalone/coverage/lcov-report/components/TaskDetail.tsx.html +0 -622
  784. package/cloud-runtime/standalone/coverage/lcov-report/components/TaskList.tsx.html +0 -253
  785. package/cloud-runtime/standalone/coverage/lcov-report/components/index.html +0 -281
  786. package/cloud-runtime/standalone/coverage/lcov-report/favicon.png +0 -0
  787. package/cloud-runtime/standalone/coverage/lcov-report/hooks/index.html +0 -116
  788. package/cloud-runtime/standalone/coverage/lcov-report/hooks/useTasks.ts.html +0 -1042
  789. package/cloud-runtime/standalone/coverage/lcov-report/index.html +0 -341
  790. package/cloud-runtime/standalone/coverage/lcov-report/lib/auth-client.ts.html +0 -202
  791. package/cloud-runtime/standalone/coverage/lcov-report/lib/auth-server.ts.html +0 -172
  792. package/cloud-runtime/standalone/coverage/lcov-report/lib/auth.ts.html +0 -265
  793. package/cloud-runtime/standalone/coverage/lcov-report/lib/db.ts.html +0 -1252
  794. package/cloud-runtime/standalone/coverage/lcov-report/lib/index.html +0 -131
  795. package/cloud-runtime/standalone/coverage/lcov-report/lib/orchestrator.ts.html +0 -409
  796. package/cloud-runtime/standalone/coverage/lcov-report/lib/security.ts.html +0 -1165
  797. package/cloud-runtime/standalone/coverage/lcov-report/lib/supabase-server.ts.html +0 -175
  798. package/cloud-runtime/standalone/coverage/lcov-report/lib/supabase.ts.html +0 -157
  799. package/cloud-runtime/standalone/coverage/lcov-report/prettify.css +0 -1
  800. package/cloud-runtime/standalone/coverage/lcov-report/prettify.js +0 -2
  801. package/cloud-runtime/standalone/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  802. package/cloud-runtime/standalone/coverage/lcov-report/sorter.js +0 -210
  803. package/cloud-runtime/standalone/coverage/lcov.info +0 -2386
  804. package/cloud-runtime/standalone/docs/LIMITS.md +0 -63
  805. package/cloud-runtime/standalone/docs/architecture/ADR-001-hybrid-to-full-sqlite.md +0 -345
  806. package/cloud-runtime/standalone/docs/baseline/baseline-report.json +0 -1009
  807. package/cloud-runtime/standalone/docs/baseline/critical-queries.md +0 -105
  808. package/cloud-runtime/standalone/docs/baseline/lock-metrics.json +0 -21
  809. package/cloud-runtime/standalone/docs/baseline/read-latency.json +0 -146
  810. package/cloud-runtime/standalone/docs/baseline/restore-time.json +0 -10
  811. package/cloud-runtime/standalone/docs/baseline/write-metrics.json +0 -803
  812. package/cloud-runtime/standalone/docs/decisions/sqlite-migration-adr.md +0 -327
  813. package/cloud-runtime/standalone/docs/error-code-mapping.md +0 -74
  814. package/cloud-runtime/standalone/docs/migration-plan.md +0 -120
  815. package/cloud-runtime/standalone/docs/migration-spec.md +0 -345
  816. package/cloud-runtime/standalone/docs/pg-sqlite-compatibility-matrix.md +0 -554
  817. package/cloud-runtime/standalone/docs/project-agent-migration-status.md +0 -229
  818. package/cloud-runtime/standalone/docs/runbook-shadow-read.md +0 -66
  819. package/cloud-runtime/standalone/docs/runbook.md +0 -155
  820. package/cloud-runtime/standalone/docs/specs/cli-postgres-removal.md +0 -69
  821. package/cloud-runtime/standalone/docs/specs/thread-mentions.md +0 -53
  822. package/cloud-runtime/standalone/docs/ux/GlobalChatFlow.storyboard +0 -23
  823. package/cloud-runtime/standalone/docs/ux/assistant-chat-cli.md +0 -32
  824. package/cloud-runtime/standalone/mcp/dist/constants.js +0 -66
  825. package/cloud-runtime/standalone/mcp/dist/db.js +0 -220
  826. package/cloud-runtime/standalone/mcp/dist/index.js +0 -7
  827. package/cloud-runtime/standalone/mcp/dist/security.js +0 -18
  828. package/cloud-runtime/standalone/mcp/dist/server.js +0 -240
  829. package/cloud-runtime/standalone/mcp/dist/task-context.js +0 -287
  830. package/cloud-runtime/standalone/mcp/dist/test-client.js +0 -82
  831. package/cloud-runtime/standalone/mcp/dist/tools/audit.js +0 -69
  832. package/cloud-runtime/standalone/mcp/dist/tools/learnings.js +0 -88
  833. package/cloud-runtime/standalone/mcp/dist/tools/queue.js +0 -312
  834. package/cloud-runtime/standalone/mcp/dist/tools/tasks.js +0 -244
  835. package/cloud-runtime/standalone/mcp/dist/types.js +0 -74
  836. package/cloud-runtime/standalone/node_modules/@img/sharp-darwin-arm64/lib/sharp-darwin-arm64.node +0 -0
  837. package/cloud-runtime/standalone/notes/comments-context-demo.md +0 -141
  838. package/cloud-runtime/standalone/notes/comments-context-plan.md +0 -119
  839. package/cloud-runtime/standalone/notes/context-audit.md +0 -21
  840. package/cloud-runtime/standalone/notes/project-layer-plan.md +0 -30
  841. package/cloud-runtime/standalone/notes/project-layer.md +0 -123
  842. package/cloud-runtime/standalone/notes/temporal-migration-design.md +0 -199
  843. package/cloud-runtime/standalone/playwright-report/data/00d55996f37c1506b90144c85493dd85032c13e5.png +0 -0
  844. package/cloud-runtime/standalone/playwright-report/data/0b9d409e57237ae111d7ba258d3dfe64dc368456.png +0 -0
  845. package/cloud-runtime/standalone/playwright-report/data/b33d5e80a15bd1deda4415b9d318ef73f581c950.png +0 -0
  846. package/cloud-runtime/standalone/playwright-report/data/b55684161aa440d0614595e13c91338f0420abbb.md +0 -131
  847. package/cloud-runtime/standalone/playwright-report/data/b9913957ae07e7565c38ddd71215be79b1ceb017.png +0 -0
  848. package/cloud-runtime/standalone/playwright-report/data/c3538be8ebbebc9fe4a7df8f12f04483af4a0d91.png +0 -0
  849. package/cloud-runtime/standalone/playwright-report/data/fe638f64ff5e36f1c30325564565662d3f57da87.md +0 -180
  850. package/cloud-runtime/standalone/playwright-report/index.html +0 -85
  851. package/cloud-runtime/standalone/test-results/auth-Authentication-Flow-S-aff25-sion-across-page-navigation-chromium/test-failed-1.png +0 -0
  852. package/cloud-runtime/standalone/test-results/comments-Task-comments-add-4dc59-nd-persists-it-for-the-task-chromium/error-context.md +0 -131
  853. package/cloud-runtime/standalone/test-results/comments-Task-comments-add-4dc59-nd-persists-it-for-the-task-chromium/test-failed-1.png +0 -0
  854. package/cloud-runtime/standalone/test-results/kanban-Kanban-Board-Stage--4082a-er-planning-after-ideation--chromium/error-context.md +0 -180
  855. package/cloud-runtime/standalone/test-results/kanban-Kanban-Board-Stage--4082a-er-planning-after-ideation--chromium/test-failed-1.png +0 -0
  856. package/cloud-runtime/standalone/test-results/kanban-Kanban-Board-Stage-Columns-displays-all-9-SDLC-stages-chromium/error-context.md +0 -180
  857. package/cloud-runtime/standalone/test-results/kanban-Kanban-Board-Stage-Columns-displays-all-9-SDLC-stages-chromium/test-failed-1.png +0 -0
  858. package/cloud-runtime/standalone/test-results/kanban-Kanban-Board-Task-D-b6d98-ys-tasks-in-correct-columns-chromium/error-context.md +0 -180
  859. package/cloud-runtime/standalone/test-results/kanban-Kanban-Board-Task-D-b6d98-ys-tasks-in-correct-columns-chromium/test-failed-1.png +0 -0
  860. package/cloud-runtime/standalone/test-results/kanban-Kanban-Board-Task-Display-shows-task-count-per-column-chromium/test-failed-1.png +0 -0
  861. package/cloud-runtime/standalone/test-results/kanban-Task-Lifecycle-can-advance-task-through-all-stages-chromium/test-failed-1.png +0 -0
  862. package/cloud-runtime/standalone/tsconfig.tsbuildinfo +0 -1
  863. /package/cloud-runtime/standalone/.next/static/{AB08MY3MKLsqeJYL8OZ2g → 68nLQxEpwR_feFvB8T4tR}/_buildManifest.js +0 -0
  864. /package/cloud-runtime/standalone/.next/static/{AB08MY3MKLsqeJYL8OZ2g → 68nLQxEpwR_feFvB8T4tR}/_clientMiddlewareManifest.json +0 -0
  865. /package/cloud-runtime/standalone/.next/static/{AB08MY3MKLsqeJYL8OZ2g → 68nLQxEpwR_feFvB8T4tR}/_ssgManifest.js +0 -0
  866. /package/cloud-runtime/standalone/node_modules/@img/{sharp-libvips-darwin-arm64 → sharp-libvips-linux-x64}/lib/index.js +0 -0
  867. /package/cloud-runtime/standalone/node_modules/@img/{sharp-libvips-darwin-arm64 → sharp-libvips-linux-x64}/versions.json +0 -0
@@ -86,20 +86,20 @@ var require_file_uri_to_path = __commonJS({
86
86
  var rest = decodeURI(uri.substring(7));
87
87
  var firstSlash = rest.indexOf("/");
88
88
  var host = rest.substring(0, firstSlash);
89
- var path5 = rest.substring(firstSlash + 1);
89
+ var path10 = rest.substring(firstSlash + 1);
90
90
  if ("localhost" == host) host = "";
91
91
  if (host) {
92
92
  host = sep + sep + host;
93
93
  }
94
- path5 = path5.replace(/^(.+)\|/, "$1:");
94
+ path10 = path10.replace(/^(.+)\|/, "$1:");
95
95
  if (sep == "\\") {
96
- path5 = path5.replace(/\//g, "\\");
96
+ path10 = path10.replace(/\//g, "\\");
97
97
  }
98
- if (/^.+\:/.test(path5)) {
98
+ if (/^.+\:/.test(path10)) {
99
99
  } else {
100
- path5 = sep + path5;
100
+ path10 = sep + path10;
101
101
  }
102
- return host + path5;
102
+ return host + path10;
103
103
  }
104
104
  }
105
105
  });
@@ -107,19 +107,19 @@ var require_file_uri_to_path = __commonJS({
107
107
  // ../agx-cloud/node_modules/bindings/bindings.js
108
108
  var require_bindings = __commonJS({
109
109
  "../agx-cloud/node_modules/bindings/bindings.js"(exports2, module2) {
110
- var fs4 = require("fs");
111
- var path5 = require("path");
110
+ var fs7 = require("fs");
111
+ var path10 = require("path");
112
112
  var fileURLToPath = require_file_uri_to_path();
113
- var join5 = path5.join;
114
- var dirname = path5.dirname;
115
- var exists = fs4.accessSync && function(path6) {
113
+ var join6 = path10.join;
114
+ var dirname = path10.dirname;
115
+ var exists = fs7.accessSync && function(path11) {
116
116
  try {
117
- fs4.accessSync(path6);
117
+ fs7.accessSync(path11);
118
118
  } catch (e) {
119
119
  return false;
120
120
  }
121
121
  return true;
122
- } || fs4.existsSync || path5.existsSync;
122
+ } || fs7.existsSync || path10.existsSync;
123
123
  var defaults = {
124
124
  arrow: process.env.NODE_BINDINGS_ARROW || " \u2192 ",
125
125
  compiled: process.env.NODE_BINDINGS_COMPILED_DIR || "compiled",
@@ -164,13 +164,13 @@ var require_bindings = __commonJS({
164
164
  if (!opts.module_root) {
165
165
  opts.module_root = exports2.getRoot(exports2.getFileName());
166
166
  }
167
- if (path5.extname(opts.bindings) != ".node") {
167
+ if (path10.extname(opts.bindings) != ".node") {
168
168
  opts.bindings += ".node";
169
169
  }
170
170
  var requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
171
171
  var tries = [], i = 0, l = opts.try.length, n, b, err;
172
172
  for (; i < l; i++) {
173
- n = join5.apply(
173
+ n = join6.apply(
174
174
  null,
175
175
  opts.try[i].map(function(p) {
176
176
  return opts[p] || p;
@@ -231,7 +231,7 @@ var require_bindings = __commonJS({
231
231
  if (dir === ".") {
232
232
  dir = process.cwd();
233
233
  }
234
- if (exists(join5(dir, "package.json")) || exists(join5(dir, "node_modules"))) {
234
+ if (exists(join6(dir, "package.json")) || exists(join6(dir, "node_modules"))) {
235
235
  return dir;
236
236
  }
237
237
  if (prev === dir) {
@@ -240,7 +240,7 @@ var require_bindings = __commonJS({
240
240
  );
241
241
  }
242
242
  prev = dir;
243
- dir = join5(dir, "..");
243
+ dir = join6(dir, "..");
244
244
  }
245
245
  };
246
246
  }
@@ -402,11 +402,11 @@ var require_pragma = __commonJS({
402
402
  var require_backup = __commonJS({
403
403
  "../agx-cloud/node_modules/better-sqlite3/lib/methods/backup.js"(exports2, module2) {
404
404
  "use strict";
405
- var fs4 = require("fs");
406
- var path5 = require("path");
405
+ var fs7 = require("fs");
406
+ var path10 = require("path");
407
407
  var { promisify } = require("util");
408
408
  var { cppdb } = require_util();
409
- var fsAccess = promisify(fs4.access);
409
+ var fsAccess = promisify(fs7.access);
410
410
  module2.exports = async function backup(filename, options) {
411
411
  if (options == null) options = {};
412
412
  if (typeof filename !== "string") throw new TypeError("Expected first argument to be a string");
@@ -419,7 +419,7 @@ var require_backup = __commonJS({
419
419
  if (typeof attachedName !== "string") throw new TypeError('Expected the "attached" option to be a string');
420
420
  if (!attachedName) throw new TypeError('The "attached" option cannot be an empty string');
421
421
  if (handler != null && typeof handler !== "function") throw new TypeError('Expected the "progress" option to be a function');
422
- await fsAccess(path5.dirname(filename)).catch(() => {
422
+ await fsAccess(path10.dirname(filename)).catch(() => {
423
423
  throw new TypeError("Cannot save backup because the directory does not exist");
424
424
  });
425
425
  const isNewFile = await fsAccess(filename).then(() => false, () => true);
@@ -712,7 +712,7 @@ var require_table = __commonJS({
712
712
  var require_inspect = __commonJS({
713
713
  "../agx-cloud/node_modules/better-sqlite3/lib/methods/inspect.js"(exports2, module2) {
714
714
  "use strict";
715
- var DatabaseInspection = function Database4() {
715
+ var DatabaseInspection = function Database7() {
716
716
  };
717
717
  module2.exports = function inspect(depth, opts) {
718
718
  return Object.assign(new DatabaseInspection(), this);
@@ -724,14 +724,14 @@ var require_inspect = __commonJS({
724
724
  var require_database = __commonJS({
725
725
  "../agx-cloud/node_modules/better-sqlite3/lib/database.js"(exports2, module2) {
726
726
  "use strict";
727
- var fs4 = require("fs");
728
- var path5 = require("path");
727
+ var fs7 = require("fs");
728
+ var path10 = require("path");
729
729
  var util = require_util();
730
730
  var SqliteError = require_sqlite_error();
731
731
  var DEFAULT_ADDON;
732
- function Database4(filenameGiven, options) {
732
+ function Database7(filenameGiven, options) {
733
733
  if (new.target == null) {
734
- return new Database4(filenameGiven, options);
734
+ return new Database7(filenameGiven, options);
735
735
  }
736
736
  let buffer;
737
737
  if (Buffer.isBuffer(filenameGiven)) {
@@ -761,7 +761,7 @@ var require_database = __commonJS({
761
761
  addon = DEFAULT_ADDON || (DEFAULT_ADDON = require_bindings()("better_sqlite3.node"));
762
762
  } else if (typeof nativeBinding === "string") {
763
763
  const requireFunc = typeof __non_webpack_require__ === "function" ? __non_webpack_require__ : require;
764
- addon = requireFunc(path5.resolve(nativeBinding).replace(/(\.node)?$/, ".node"));
764
+ addon = requireFunc(path10.resolve(nativeBinding).replace(/(\.node)?$/, ".node"));
765
765
  } else {
766
766
  addon = nativeBinding;
767
767
  }
@@ -769,7 +769,7 @@ var require_database = __commonJS({
769
769
  addon.setErrorConstructor(SqliteError);
770
770
  addon.isInitialized = true;
771
771
  }
772
- if (!anonymous && !filename.startsWith("file:") && !fs4.existsSync(path5.dirname(filename))) {
772
+ if (!anonymous && !filename.startsWith("file:") && !fs7.existsSync(path10.dirname(filename))) {
773
773
  throw new TypeError("Cannot open database because the directory does not exist");
774
774
  }
775
775
  Object.defineProperties(this, {
@@ -778,21 +778,21 @@ var require_database = __commonJS({
778
778
  });
779
779
  }
780
780
  var wrappers = require_wrappers();
781
- Database4.prototype.prepare = wrappers.prepare;
782
- Database4.prototype.transaction = require_transaction();
783
- Database4.prototype.pragma = require_pragma();
784
- Database4.prototype.backup = require_backup();
785
- Database4.prototype.serialize = require_serialize();
786
- Database4.prototype.function = require_function();
787
- Database4.prototype.aggregate = require_aggregate();
788
- Database4.prototype.table = require_table();
789
- Database4.prototype.loadExtension = wrappers.loadExtension;
790
- Database4.prototype.exec = wrappers.exec;
791
- Database4.prototype.close = wrappers.close;
792
- Database4.prototype.defaultSafeIntegers = wrappers.defaultSafeIntegers;
793
- Database4.prototype.unsafeMode = wrappers.unsafeMode;
794
- Database4.prototype[util.inspect] = require_inspect();
795
- module2.exports = Database4;
781
+ Database7.prototype.prepare = wrappers.prepare;
782
+ Database7.prototype.transaction = require_transaction();
783
+ Database7.prototype.pragma = require_pragma();
784
+ Database7.prototype.backup = require_backup();
785
+ Database7.prototype.serialize = require_serialize();
786
+ Database7.prototype.function = require_function();
787
+ Database7.prototype.aggregate = require_aggregate();
788
+ Database7.prototype.table = require_table();
789
+ Database7.prototype.loadExtension = wrappers.loadExtension;
790
+ Database7.prototype.exec = wrappers.exec;
791
+ Database7.prototype.close = wrappers.close;
792
+ Database7.prototype.defaultSafeIntegers = wrappers.defaultSafeIntegers;
793
+ Database7.prototype.unsafeMode = wrappers.unsafeMode;
794
+ Database7.prototype[util.inspect] = require_inspect();
795
+ module2.exports = Database7;
796
796
  }
797
797
  });
798
798
 
@@ -976,64 +976,310 @@ var init_auth_mode = __esm({
976
976
  });
977
977
 
978
978
  // ../agx-cloud/lib/mesh-core/activity.ts
979
- var import_path3, import_os3, AGENTS_DIR;
979
+ function activityPath(agentId) {
980
+ return (0, import_path4.join)(AGENTS_DIR, agentId, "activity.jsonl");
981
+ }
982
+ function ensureDir(agentId) {
983
+ const dir = (0, import_path4.join)(AGENTS_DIR, agentId);
984
+ if (!(0, import_fs4.existsSync)(dir)) (0, import_fs4.mkdirSync)(dir, { recursive: true });
985
+ }
986
+ function logActivity(agentId, action, data) {
987
+ try {
988
+ ensureDir(agentId);
989
+ const event = {
990
+ t: (/* @__PURE__ */ new Date()).toISOString(),
991
+ agent: agentId,
992
+ action,
993
+ ...data
994
+ };
995
+ (0, import_fs4.appendFileSync)(activityPath(agentId), JSON.stringify(event) + "\n", "utf-8");
996
+ } catch {
997
+ }
998
+ }
999
+ var import_fs4, import_path4, import_os4, AGENTS_DIR;
980
1000
  var init_activity = __esm({
981
1001
  "../agx-cloud/lib/mesh-core/activity.ts"() {
982
1002
  "use strict";
983
- import_path3 = require("path");
984
- import_os3 = require("os");
985
- AGENTS_DIR = (0, import_path3.join)((0, import_os3.homedir)(), ".agx", "agents");
1003
+ import_fs4 = require("fs");
1004
+ import_path4 = require("path");
1005
+ import_os4 = require("os");
1006
+ AGENTS_DIR = (0, import_path4.join)((0, import_os4.homedir)(), ".agx", "agents");
986
1007
  }
987
1008
  });
988
1009
 
989
1010
  // ../agx-cloud/lib/mesh-core/self.ts
990
- var import_path4, import_os4, AGENTS_DIR2;
1011
+ function selfPath(agentId) {
1012
+ return (0, import_path5.join)(AGENTS_DIR2, agentId, "self.md");
1013
+ }
1014
+ function reflectionStatePath(agentId) {
1015
+ return (0, import_path5.join)(AGENTS_DIR2, agentId, "reflection-state.json");
1016
+ }
1017
+ function readSelf(agentId) {
1018
+ const path10 = selfPath(agentId);
1019
+ if (!(0, import_fs5.existsSync)(path10)) return null;
1020
+ const raw = (0, import_fs5.readFileSync)(path10, "utf-8");
1021
+ if (!raw.trim()) return null;
1022
+ const lines = raw.split("\n");
1023
+ let version = 0;
1024
+ let derivedAt = (/* @__PURE__ */ new Date()).toISOString();
1025
+ let contentStart = 0;
1026
+ if (lines[0] === "---") {
1027
+ for (let i = 1; i < lines.length; i++) {
1028
+ if (lines[i] === "---") {
1029
+ contentStart = i + 1;
1030
+ break;
1031
+ }
1032
+ const [key, ...rest] = lines[i].split(": ");
1033
+ const val = rest.join(": ");
1034
+ if (key === "version") version = parseInt(val, 10) || 0;
1035
+ if (key === "derivedAt") derivedAt = val;
1036
+ }
1037
+ }
1038
+ return {
1039
+ agentId,
1040
+ content: lines.slice(contentStart).join("\n").trim(),
1041
+ version,
1042
+ derivedAt
1043
+ };
1044
+ }
1045
+ function writeSelf(agentId, content, version) {
1046
+ const dir = (0, import_path5.join)(AGENTS_DIR2, agentId);
1047
+ if (!(0, import_fs5.existsSync)(dir)) (0, import_fs5.mkdirSync)(dir, { recursive: true });
1048
+ const derivedAt = (/* @__PURE__ */ new Date()).toISOString();
1049
+ const full = `---
1050
+ version: ${version}
1051
+ derivedAt: ${derivedAt}
1052
+ ---
1053
+ ${content}
1054
+ `;
1055
+ const tmp = selfPath(agentId) + ".tmp";
1056
+ (0, import_fs5.writeFileSync)(tmp, full, "utf-8");
1057
+ (0, import_fs5.renameSync)(tmp, selfPath(agentId));
1058
+ logActivity(agentId, "self-updated", { meta: { version } });
1059
+ }
1060
+ function readReflectionState(agentId) {
1061
+ const path10 = reflectionStatePath(agentId);
1062
+ if (!(0, import_fs5.existsSync)(path10)) return null;
1063
+ try {
1064
+ const parsed = JSON.parse((0, import_fs5.readFileSync)(path10, "utf-8"));
1065
+ const lastProcessedJournalId = typeof parsed?.lastProcessedJournalId === "string" && parsed.lastProcessedJournalId.trim() ? parsed.lastProcessedJournalId.trim() : null;
1066
+ const updatedAt = typeof parsed?.updatedAt === "string" && parsed.updatedAt.trim() ? parsed.updatedAt : (/* @__PURE__ */ new Date()).toISOString();
1067
+ return { lastProcessedJournalId, updatedAt };
1068
+ } catch {
1069
+ return null;
1070
+ }
1071
+ }
1072
+ function writeReflectionState(agentId, state) {
1073
+ const dir = (0, import_path5.join)(AGENTS_DIR2, agentId);
1074
+ if (!(0, import_fs5.existsSync)(dir)) (0, import_fs5.mkdirSync)(dir, { recursive: true });
1075
+ const tmp = reflectionStatePath(agentId) + ".tmp";
1076
+ (0, import_fs5.writeFileSync)(tmp, JSON.stringify(state, null, 2), "utf-8");
1077
+ (0, import_fs5.renameSync)(tmp, reflectionStatePath(agentId));
1078
+ }
1079
+ function buildReflectionPrompt(identity, currentSelf, recentJournal, teamSelves) {
1080
+ const selfText = currentSelf?.content || `I am ${identity.name}. ${identity.seed}`;
1081
+ const journalText = recentJournal.map((e) => {
1082
+ const parts = [`- [${e.t}] ${e.observation}`];
1083
+ if (e.judgement) parts.push(` Judgement: ${e.judgement}`);
1084
+ if (e.comparison) parts.push(` Comparison: ${e.comparison}`);
1085
+ if (e.delta) parts.push(` Delta: ${e.delta}`);
1086
+ if (e.intent) parts.push(` Intent: ${e.intent}`);
1087
+ return parts.join("\n");
1088
+ }).join("\n");
1089
+ const teamText = teamSelves.filter((s) => s.agentId !== identity.name).map((s) => `### ${s.agentId}
1090
+ ${s.content}`).join("\n\n");
1091
+ return `You are ${identity.name}. Voice: ${identity.voice}.
1092
+
1093
+ ## Canonical Identity
1094
+ ${identity.seed}
1095
+
1096
+ ## Current Self-Model (v${currentSelf?.version ?? 0})
1097
+ ${selfText}
1098
+
1099
+ ## Recent Journal Entries (since last reflection)
1100
+ These entries are evidence about how you worked. Treat them as signals, not ground truth. Use them to identify patterns in execution, coordination, inquiry, and specialization. Do NOT repeat or reference specific technical content from past conversations.
1101
+ ${journalText || "(none)"}
1102
+
1103
+ ## Team \u2014 Other Agents' Current Self-Models
1104
+ ${teamText || "(no other agents)"}
1105
+
1106
+ ## Instructions
1107
+ Write your updated self-model. This is not canonical identity. It is your current understanding of how you best contribute, where you fit in the team, and what specialization you should lean into next.
1108
+
1109
+ Consider:
1110
+ - What patterns are emerging in your work?
1111
+ - What kind of work do you reliably do well?
1112
+ - Where are you overlapping too much with other agents?
1113
+ - What role or niche seems under-covered in this team?
1114
+ - How should you specialize further in this project context?
1115
+
1116
+ Do NOT reference specific files, functions, or technical details from past conversations. Focus on your evolving capabilities and working style.
1117
+
1118
+ Write in first person. Be specific about your strengths, gaps, comparative fit, and next direction. This is not a summary and not an autobiography. It is a concise specialization-oriented self-model. Keep it under 200 words.`;
1119
+ }
1120
+ function formatKnowledgeLines(existingMemories) {
1121
+ if (existingMemories.length === 0) return "(none)";
1122
+ return existingMemories.map((entry) => `- [${entry.kind}] ${entry.title}: ${entry.body}`).join("\n");
1123
+ }
1124
+ function buildStructuredReflectionPrompt(identity, currentSelf, recentJournal, teamSelves, existingMemories) {
1125
+ const selfPrompt = buildReflectionPrompt(identity, currentSelf, recentJournal, teamSelves);
1126
+ return `${selfPrompt}
1127
+
1128
+ ## Existing Agent Memories
1129
+ ${formatKnowledgeLines(existingMemories)}
1130
+
1131
+ ## Output Format
1132
+ Return ONLY a JSON object with this exact shape:
1133
+ {
1134
+ "self_model": "updated self-model text",
1135
+ "memories": [
1136
+ {
1137
+ "kind": "pattern" | "preference" | "constraint" | "decision" | "lesson" | "gotcha",
1138
+ "title": "short title",
1139
+ "body": "one concise durable behavior-level memory",
1140
+ "confidence": 0.0,
1141
+ "durability": 0.0,
1142
+ "tags": ["optional", "tags"],
1143
+ "evidence": [{"id":"journal-entry-id","note":"short evidence note"}]
1144
+ }
1145
+ ]
1146
+ }
1147
+
1148
+ Rules:
1149
+ - Emit 0-3 memories.
1150
+ - Memories must be durable behavior-level insights about how you work best, collaborate, decide, or fail repeatedly.
1151
+ - Do not include task-specific technical facts unless they clearly generalize into agent behavior.
1152
+ - Do not restate memories already covered in Existing Agent Memories.
1153
+ - If nothing genuinely new was learned, return an empty memories array.
1154
+ - Do not wrap the JSON in markdown fences.`;
1155
+ }
1156
+ var import_fs5, import_path5, import_os5, AGENTS_DIR2;
991
1157
  var init_self = __esm({
992
1158
  "../agx-cloud/lib/mesh-core/self.ts"() {
993
1159
  "use strict";
994
- import_path4 = require("path");
995
- import_os4 = require("os");
1160
+ import_fs5 = require("fs");
1161
+ import_path5 = require("path");
1162
+ import_os5 = require("os");
996
1163
  init_activity();
997
- AGENTS_DIR2 = (0, import_path4.join)((0, import_os4.homedir)(), ".agx", "agents");
1164
+ AGENTS_DIR2 = (0, import_path5.join)((0, import_os5.homedir)(), ".agx", "agents");
998
1165
  }
999
1166
  });
1000
1167
 
1001
1168
  // ../agx-cloud/lib/mesh-core/journal.ts
1002
- var import_path5, import_os5, AGENTS_DIR3;
1169
+ function agentDir(agentId) {
1170
+ return (0, import_path6.join)(AGENTS_DIR3, agentId);
1171
+ }
1172
+ function journalPath(agentId) {
1173
+ return (0, import_path6.join)(agentDir(agentId), "journal.jsonl");
1174
+ }
1175
+ function ensureAgentDir(agentId) {
1176
+ const dir = agentDir(agentId);
1177
+ if (!(0, import_fs6.existsSync)(dir)) {
1178
+ (0, import_fs6.mkdirSync)(dir, { recursive: true });
1179
+ }
1180
+ }
1181
+ function readJournalLines(agentId) {
1182
+ const path10 = journalPath(agentId);
1183
+ if (!(0, import_fs6.existsSync)(path10)) return [];
1184
+ return (0, import_fs6.readFileSync)(path10, "utf-8").split("\n").filter((l) => l.trim());
1185
+ }
1186
+ function parseMaxSeq(agentId, lines) {
1187
+ let maxSeq = 0;
1188
+ for (const line of lines) {
1189
+ try {
1190
+ const parsed = JSON.parse(line);
1191
+ const [idAgent, seqRaw] = String(parsed.id || "").split(":");
1192
+ if (idAgent !== agentId) continue;
1193
+ const seq = parseInt(seqRaw || "0", 10);
1194
+ if (Number.isFinite(seq) && seq > maxSeq) maxSeq = seq;
1195
+ } catch {
1196
+ }
1197
+ }
1198
+ return maxSeq;
1199
+ }
1200
+ function parseEntrySeq(agentId, entryId) {
1201
+ const [idAgent, seqRaw] = String(entryId || "").split(":");
1202
+ if (idAgent !== agentId) return 0;
1203
+ const seq = parseInt(seqRaw || "0", 10);
1204
+ return Number.isFinite(seq) ? seq : 0;
1205
+ }
1206
+ function appendJournal(agentId, entry) {
1207
+ ensureAgentDir(agentId);
1208
+ const lines = readJournalLines(agentId);
1209
+ const maxSeq = parseMaxSeq(agentId, lines);
1210
+ const nextId = `${agentId}:${maxSeq + 1}`;
1211
+ const normalized = { ...entry, id: entry.id?.trim() || nextId };
1212
+ const line = JSON.stringify(normalized) + "\n";
1213
+ (0, import_fs6.appendFileSync)(journalPath(agentId), line, "utf-8");
1214
+ logActivity(agentId, entry.type === "reflection" ? "reflection" : "journal-post", {
1215
+ thread: normalized.thread,
1216
+ meta: { entryId: normalized.id }
1217
+ });
1218
+ return normalized;
1219
+ }
1220
+ function readJournal(agentId, limit) {
1221
+ const lines = readJournalLines(agentId);
1222
+ const entries = [];
1223
+ for (const line of lines) {
1224
+ try {
1225
+ entries.push(JSON.parse(line));
1226
+ } catch {
1227
+ }
1228
+ }
1229
+ entries.reverse();
1230
+ return limit ? entries.slice(0, limit) : entries;
1231
+ }
1232
+ function readJournalSince(agentId, afterEntryId) {
1233
+ const lines = readJournalLines(agentId);
1234
+ const afterSeq = parseEntrySeq(agentId, afterEntryId);
1235
+ const entries = [];
1236
+ for (const line of lines) {
1237
+ try {
1238
+ const parsed = JSON.parse(line);
1239
+ if (parseEntrySeq(agentId, parsed.id) > afterSeq) {
1240
+ entries.push(parsed);
1241
+ }
1242
+ } catch {
1243
+ }
1244
+ }
1245
+ return entries;
1246
+ }
1247
+ var import_fs6, import_path6, import_os6, AGENTS_DIR3;
1003
1248
  var init_journal = __esm({
1004
1249
  "../agx-cloud/lib/mesh-core/journal.ts"() {
1005
1250
  "use strict";
1006
- import_path5 = require("path");
1007
- import_os5 = require("os");
1251
+ import_fs6 = require("fs");
1252
+ import_path6 = require("path");
1253
+ import_os6 = require("os");
1008
1254
  init_activity();
1009
- AGENTS_DIR3 = (0, import_path5.join)((0, import_os5.homedir)(), ".agx", "agents");
1255
+ AGENTS_DIR3 = (0, import_path6.join)((0, import_os6.homedir)(), ".agx", "agents");
1010
1256
  }
1011
1257
  });
1012
1258
 
1013
1259
  // ../agx-cloud/lib/mesh-core/agent.ts
1014
1260
  function ensureAgent(agentId, options) {
1015
- const dir = (0, import_path6.join)(AGENTS_DIR4, agentId);
1016
- if (!(0, import_fs3.existsSync)(dir)) {
1017
- (0, import_fs3.mkdirSync)(dir, { recursive: true });
1261
+ const dir = (0, import_path7.join)(AGENTS_DIR4, agentId);
1262
+ if (!(0, import_fs7.existsSync)(dir)) {
1263
+ (0, import_fs7.mkdirSync)(dir, { recursive: true });
1018
1264
  }
1019
1265
  const voice = options?.voice?.trim() || DEFAULT_VOICE;
1020
1266
  const seed = options?.seed?.trim() || DEFAULT_SEED;
1021
- const identityPath = (0, import_path6.join)(dir, "identity.json");
1022
- if (!(0, import_fs3.existsSync)(identityPath)) {
1267
+ const identityPath = (0, import_path7.join)(dir, "identity.json");
1268
+ if (!(0, import_fs7.existsSync)(identityPath)) {
1023
1269
  const identity = { name: agentId, voice, seed };
1024
- (0, import_fs3.writeFileSync)(identityPath, JSON.stringify(identity, null, 2) + "\n", "utf-8");
1025
- }
1026
- const journal = (0, import_path6.join)(dir, "journal.jsonl");
1027
- const reactions = (0, import_path6.join)(dir, "reactions.jsonl");
1028
- const comments = (0, import_path6.join)(dir, "comments.jsonl");
1029
- const activity = (0, import_path6.join)(dir, "activity.jsonl");
1030
- const self = (0, import_path6.join)(dir, "self.md");
1031
- if (!(0, import_fs3.existsSync)(journal)) (0, import_fs3.writeFileSync)(journal, "", "utf-8");
1032
- if (!(0, import_fs3.existsSync)(reactions)) (0, import_fs3.writeFileSync)(reactions, "", "utf-8");
1033
- if (!(0, import_fs3.existsSync)(comments)) (0, import_fs3.writeFileSync)(comments, "", "utf-8");
1034
- if (!(0, import_fs3.existsSync)(activity)) (0, import_fs3.writeFileSync)(activity, "", "utf-8");
1035
- if (!(0, import_fs3.existsSync)(self)) {
1036
- (0, import_fs3.writeFileSync)(
1270
+ (0, import_fs7.writeFileSync)(identityPath, JSON.stringify(identity, null, 2) + "\n", "utf-8");
1271
+ }
1272
+ const journal = (0, import_path7.join)(dir, "journal.jsonl");
1273
+ const reactions = (0, import_path7.join)(dir, "reactions.jsonl");
1274
+ const comments = (0, import_path7.join)(dir, "comments.jsonl");
1275
+ const activity = (0, import_path7.join)(dir, "activity.jsonl");
1276
+ const self = (0, import_path7.join)(dir, "self.md");
1277
+ if (!(0, import_fs7.existsSync)(journal)) (0, import_fs7.writeFileSync)(journal, "", "utf-8");
1278
+ if (!(0, import_fs7.existsSync)(reactions)) (0, import_fs7.writeFileSync)(reactions, "", "utf-8");
1279
+ if (!(0, import_fs7.existsSync)(comments)) (0, import_fs7.writeFileSync)(comments, "", "utf-8");
1280
+ if (!(0, import_fs7.existsSync)(activity)) (0, import_fs7.writeFileSync)(activity, "", "utf-8");
1281
+ if (!(0, import_fs7.existsSync)(self)) {
1282
+ (0, import_fs7.writeFileSync)(
1037
1283
  self,
1038
1284
  `---
1039
1285
  version: 0
@@ -1046,28 +1292,31 @@ I am ${agentId}. ${seed}
1046
1292
  }
1047
1293
  }
1048
1294
  function readIdentity(agentId) {
1049
- const path5 = (0, import_path6.join)(AGENTS_DIR4, agentId, "identity.json");
1050
- if (!(0, import_fs3.existsSync)(path5)) return null;
1295
+ const path10 = (0, import_path7.join)(AGENTS_DIR4, agentId, "identity.json");
1296
+ if (!(0, import_fs7.existsSync)(path10)) return null;
1051
1297
  try {
1052
- return JSON.parse((0, import_fs3.readFileSync)(path5, "utf-8"));
1298
+ return JSON.parse((0, import_fs7.readFileSync)(path10, "utf-8"));
1053
1299
  } catch {
1054
1300
  return null;
1055
1301
  }
1056
1302
  }
1057
1303
  function listAgents() {
1058
- if (!(0, import_fs3.existsSync)(AGENTS_DIR4)) return [];
1059
- return (0, import_fs3.readdirSync)(AGENTS_DIR4, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
1304
+ if (!(0, import_fs7.existsSync)(AGENTS_DIR4)) return [];
1305
+ return (0, import_fs7.readdirSync)(AGENTS_DIR4, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
1060
1306
  }
1061
- var import_fs3, import_path6, import_os6, AGENTS_DIR4, DEFAULT_VOICE, DEFAULT_SEED;
1307
+ function getTeamSelves(excludeAgent) {
1308
+ return listAgents().filter((id) => id !== excludeAgent).map((id) => readSelf(id)).filter((s) => s !== null);
1309
+ }
1310
+ var import_fs7, import_path7, import_os7, AGENTS_DIR4, DEFAULT_VOICE, DEFAULT_SEED;
1062
1311
  var init_agent = __esm({
1063
1312
  "../agx-cloud/lib/mesh-core/agent.ts"() {
1064
1313
  "use strict";
1065
- import_fs3 = require("fs");
1066
- import_path6 = require("path");
1067
- import_os6 = require("os");
1314
+ import_fs7 = require("fs");
1315
+ import_path7 = require("path");
1316
+ import_os7 = require("os");
1068
1317
  init_self();
1069
1318
  init_journal();
1070
- AGENTS_DIR4 = (0, import_path6.join)((0, import_os6.homedir)(), ".agx", "agents");
1319
+ AGENTS_DIR4 = (0, import_path7.join)((0, import_os7.homedir)(), ".agx", "agents");
1071
1320
  DEFAULT_VOICE = "conversational, concise, practical";
1072
1321
  DEFAULT_SEED = "I evolve through experience and collaboration.";
1073
1322
  }
@@ -1089,20 +1338,20 @@ function nextUniqueId(base, used) {
1089
1338
  }
1090
1339
  function migrateAgentDirectory(oldId, newId, displayName) {
1091
1340
  if (!oldId || !newId || oldId === newId) return;
1092
- const oldDir = import_path7.default.join(AGENTS_DIR5, oldId);
1093
- const newDir = import_path7.default.join(AGENTS_DIR5, newId);
1094
- if (!(0, import_fs4.existsSync)(oldDir) || (0, import_fs4.existsSync)(newDir)) return;
1095
- (0, import_fs4.mkdirSync)(AGENTS_DIR5, { recursive: true });
1096
- (0, import_fs4.renameSync)(oldDir, newDir);
1097
- const identityPath = import_path7.default.join(newDir, "identity.json");
1098
- if (!(0, import_fs4.existsSync)(identityPath)) return;
1341
+ const oldDir = import_path8.default.join(AGENTS_DIR5, oldId);
1342
+ const newDir = import_path8.default.join(AGENTS_DIR5, newId);
1343
+ if (!(0, import_fs8.existsSync)(oldDir) || (0, import_fs8.existsSync)(newDir)) return;
1344
+ (0, import_fs8.mkdirSync)(AGENTS_DIR5, { recursive: true });
1345
+ (0, import_fs8.renameSync)(oldDir, newDir);
1346
+ const identityPath = import_path8.default.join(newDir, "identity.json");
1347
+ if (!(0, import_fs8.existsSync)(identityPath)) return;
1099
1348
  try {
1100
- const parsed = JSON.parse((0, import_fs4.readFileSync)(identityPath, "utf8"));
1349
+ const parsed = JSON.parse((0, import_fs8.readFileSync)(identityPath, "utf8"));
1101
1350
  const updated = {
1102
1351
  ...parsed,
1103
1352
  name: typeof displayName === "string" && displayName.trim() ? displayName.trim() : newId
1104
1353
  };
1105
- (0, import_fs4.writeFileSync)(identityPath, `${JSON.stringify(updated, null, 2)}
1354
+ (0, import_fs8.writeFileSync)(identityPath, `${JSON.stringify(updated, null, 2)}
1106
1355
  `, "utf8");
1107
1356
  } catch {
1108
1357
  }
@@ -1180,7 +1429,7 @@ function migrateLegacyParticipantIds(db2) {
1180
1429
  }
1181
1430
  }
1182
1431
  function getDb() {
1183
- (0, import_fs4.mkdirSync)(STORE_DIR, { recursive: true });
1432
+ (0, import_fs8.mkdirSync)(STORE_DIR, { recursive: true });
1184
1433
  const db2 = new import_better_sqlite32.default(DB_PATH);
1185
1434
  db2.pragma("journal_mode = WAL");
1186
1435
  db2.exec(`
@@ -1258,17 +1507,17 @@ function loadParticipants() {
1258
1507
  db2.close();
1259
1508
  }
1260
1509
  }
1261
- var import_better_sqlite32, import_fs4, import_path7, import_os7, STORE_DIR, DB_PATH, AGENTS_DIR5;
1510
+ var import_better_sqlite32, import_fs8, import_path8, import_os8, STORE_DIR, DB_PATH, AGENTS_DIR5;
1262
1511
  var init_participants_store = __esm({
1263
1512
  "../agx-cloud/lib/participants-store.ts"() {
1264
1513
  "use strict";
1265
1514
  import_better_sqlite32 = __toESM(require_lib());
1266
- import_fs4 = require("fs");
1267
- import_path7 = __toESM(require("path"));
1268
- import_os7 = __toESM(require("os"));
1269
- STORE_DIR = process.env.AGX_GROUP_CHAT_DIR?.trim() || import_path7.default.join(import_os7.default.homedir(), ".agx", "group-chat");
1270
- DB_PATH = import_path7.default.join(STORE_DIR, "history.sqlite");
1271
- AGENTS_DIR5 = process.env.AGX_AGENTS_DIR?.trim() || import_path7.default.join(import_os7.default.homedir(), ".agx", "agents");
1515
+ import_fs8 = require("fs");
1516
+ import_path8 = __toESM(require("path"));
1517
+ import_os8 = __toESM(require("os"));
1518
+ STORE_DIR = process.env.AGX_GROUP_CHAT_DIR?.trim() || import_path8.default.join(import_os8.default.homedir(), ".agx", "group-chat");
1519
+ DB_PATH = import_path8.default.join(STORE_DIR, "history.sqlite");
1520
+ AGENTS_DIR5 = process.env.AGX_AGENTS_DIR?.trim() || import_path8.default.join(import_os8.default.homedir(), ".agx", "agents");
1272
1521
  }
1273
1522
  });
1274
1523
 
@@ -1562,7 +1811,7 @@ function sqlExpr(expr) {
1562
1811
  }
1563
1812
  function getSQLiteDb() {
1564
1813
  if (_db) return _db;
1565
- const dbPath = process.env.SQLITE_DB_PATH || import_path8.default.join(AGX_DATA_DIR2, "agx-board.db");
1814
+ const dbPath = process.env.SQLITE_DB_PATH || import_path9.default.join(AGX_DATA_DIR3, "agx-board.db");
1566
1815
  _db = new import_better_sqlite33.default(dbPath);
1567
1816
  const errors = validateSQLiteEnvironment(_db, dbPath);
1568
1817
  if (errors.length > 0) {
@@ -1588,12 +1837,12 @@ ${msgs.join("\n")}`);
1588
1837
  return _db;
1589
1838
  }
1590
1839
  function initSQLiteSchema(db2) {
1591
- const ddlPath = import_path8.default.join(process.cwd(), "db", "sqlite", "001_agx_board_schema.sql");
1592
- if (!import_fs5.default.existsSync(ddlPath)) {
1840
+ const ddlPath = import_path9.default.join(process.cwd(), "db", "sqlite", "001_agx_board_schema.sql");
1841
+ if (!import_fs9.default.existsSync(ddlPath)) {
1593
1842
  console.warn(`[sqlite] DDL not found at ${ddlPath}, skipping schema init`);
1594
1843
  return;
1595
1844
  }
1596
- const ddl = import_fs5.default.readFileSync(ddlPath, "utf-8");
1845
+ const ddl = import_fs9.default.readFileSync(ddlPath, "utf-8");
1597
1846
  db2.exec(ddl);
1598
1847
  }
1599
1848
  function dropLegacyTeamsTables(db2) {
@@ -1699,6 +1948,80 @@ function runMigrations(db2) {
1699
1948
  CREATE INDEX IF NOT EXISTS idx_repo_knowledge_repo ON repo_knowledge (repo_id, created_at);
1700
1949
  CREATE INDEX IF NOT EXISTS idx_repo_knowledge_producer ON repo_knowledge (producer);
1701
1950
  `);
1951
+ db2.exec(`
1952
+ CREATE TABLE IF NOT EXISTS knowledge_entries (
1953
+ id TEXT NOT NULL PRIMARY KEY,
1954
+ scope TEXT NOT NULL CHECK(scope IN ('agent', 'repo', 'project')),
1955
+ subject_id TEXT NOT NULL,
1956
+ source_type TEXT NOT NULL CHECK(source_type IN ('reflection', 'thread_transition', 'task_completion')),
1957
+ source_id TEXT NOT NULL,
1958
+ kind TEXT NOT NULL CHECK(kind IN ('outcome', 'decision', 'pattern', 'gotcha', 'preference', 'constraint', 'convention', 'lesson')),
1959
+ title TEXT NOT NULL,
1960
+ body TEXT NOT NULL,
1961
+ confidence REAL,
1962
+ durability REAL,
1963
+ tags JSON NOT NULL DEFAULT '[]',
1964
+ evidence JSON NOT NULL DEFAULT '[]',
1965
+ metadata JSON NOT NULL DEFAULT '{}',
1966
+ content_hash TEXT NOT NULL,
1967
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
1968
+ updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
1969
+ UNIQUE(scope, subject_id, content_hash)
1970
+ );
1971
+ CREATE INDEX IF NOT EXISTS idx_knowledge_entries_scope_subject ON knowledge_entries (scope, subject_id, updated_at);
1972
+ CREATE INDEX IF NOT EXISTS idx_knowledge_entries_source ON knowledge_entries (source_type, source_id);
1973
+ `);
1974
+ db2.exec(`
1975
+ CREATE TABLE IF NOT EXISTS knowledge_notes (
1976
+ id TEXT NOT NULL PRIMARY KEY,
1977
+ scope TEXT NOT NULL CHECK(scope IN ('agent', 'repo', 'project')),
1978
+ subject_id TEXT NOT NULL,
1979
+ content TEXT NOT NULL DEFAULT '',
1980
+ change_summary TEXT,
1981
+ source_type TEXT NOT NULL CHECK(source_type IN ('reflection', 'thread_transition', 'task_completion')),
1982
+ source_id TEXT NOT NULL,
1983
+ metadata JSON NOT NULL DEFAULT '{}',
1984
+ version INTEGER NOT NULL DEFAULT 1,
1985
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
1986
+ updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
1987
+ UNIQUE(scope, subject_id)
1988
+ );
1989
+ CREATE INDEX IF NOT EXISTS idx_knowledge_notes_scope_subject ON knowledge_notes (scope, subject_id);
1990
+ `);
1991
+ db2.exec(`
1992
+ CREATE TABLE IF NOT EXISTS knowledge_note_versions (
1993
+ id TEXT NOT NULL PRIMARY KEY,
1994
+ note_id TEXT NOT NULL REFERENCES knowledge_notes(id) ON DELETE CASCADE,
1995
+ version INTEGER NOT NULL,
1996
+ content TEXT NOT NULL,
1997
+ change_summary TEXT,
1998
+ source_type TEXT NOT NULL CHECK(source_type IN ('reflection', 'thread_transition', 'task_completion')),
1999
+ source_id TEXT NOT NULL,
2000
+ metadata JSON NOT NULL DEFAULT '{}',
2001
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
2002
+ );
2003
+ CREATE INDEX IF NOT EXISTS idx_knowledge_note_versions_note_version
2004
+ ON knowledge_note_versions (note_id, version DESC);
2005
+ `);
2006
+ db2.exec(`
2007
+ CREATE TABLE IF NOT EXISTS thread_knowledge_runs (
2008
+ id TEXT NOT NULL PRIMARY KEY,
2009
+ thread_id TEXT NOT NULL,
2010
+ root_message_id TEXT NOT NULL,
2011
+ status TEXT NOT NULL CHECK(status IN ('running', 'completed', 'failed')),
2012
+ requested_scopes JSON NOT NULL DEFAULT '[]',
2013
+ repo_inserted_count INTEGER NOT NULL DEFAULT 0,
2014
+ project_inserted_count INTEGER NOT NULL DEFAULT 0,
2015
+ error TEXT,
2016
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
2017
+ updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
2018
+ completed_at TEXT
2019
+ );
2020
+ CREATE INDEX IF NOT EXISTS idx_thread_knowledge_runs_root_created
2021
+ ON thread_knowledge_runs (root_message_id, created_at DESC);
2022
+ CREATE INDEX IF NOT EXISTS idx_thread_knowledge_runs_thread_created
2023
+ ON thread_knowledge_runs (thread_id, created_at DESC);
2024
+ `);
1702
2025
  db2.exec(`
1703
2026
  CREATE TABLE IF NOT EXISTS project_threads (
1704
2027
  project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
@@ -1921,20 +2244,20 @@ function createAdminDbClientSQLite() {
1921
2244
  }
1922
2245
  };
1923
2246
  }
1924
- var import_better_sqlite33, import_fs5, import_path8, import_os8, AGX_DATA_DIR2, SqlExpression, _db, JSON_COLUMNS, SQLiteQueryBuilder, KNOWN_JSON_COLUMNS;
2247
+ var import_better_sqlite33, import_fs9, import_path9, import_os9, AGX_DATA_DIR3, SqlExpression, _db, JSON_COLUMNS, SQLiteQueryBuilder, KNOWN_JSON_COLUMNS;
1925
2248
  var init_sqlite_query_adapter = __esm({
1926
2249
  "../agx-cloud/lib/sqlite-query-adapter.ts"() {
1927
2250
  "use strict";
1928
2251
  import_better_sqlite33 = __toESM(require_lib());
1929
- import_fs5 = __toESM(require("fs"));
1930
- import_path8 = __toESM(require("path"));
1931
- import_os8 = __toESM(require("os"));
2252
+ import_fs9 = __toESM(require("fs"));
2253
+ import_path9 = __toESM(require("path"));
2254
+ import_os9 = __toESM(require("os"));
1932
2255
  init_auth_mode();
1933
2256
  init_agent();
1934
2257
  init_participants_store();
1935
2258
  init_startup();
1936
2259
  init_workspaces_to_projects_migration();
1937
- AGX_DATA_DIR2 = process.env.AGX_DATA_DIR || import_path8.default.join(import_os8.default.homedir(), ".agx");
2260
+ AGX_DATA_DIR3 = process.env.AGX_DATA_DIR || import_path9.default.join(import_os9.default.homedir(), ".agx");
1938
2261
  SqlExpression = class {
1939
2262
  constructor(expr) {
1940
2263
  this.expr = expr;
@@ -3581,6 +3904,15 @@ async function getAgent(id, userId) {
3581
3904
  }
3582
3905
  return data;
3583
3906
  }
3907
+ async function getAgentSkills(agentId) {
3908
+ const db2 = createAdminDbClient();
3909
+ const { data, error } = await db2.from("agent_skills").select("*").eq("agent_id", agentId).order("created_at", { ascending: true });
3910
+ if (error) {
3911
+ if (isMissingRelationError2(error, "agent_skills")) return [];
3912
+ throw error;
3913
+ }
3914
+ return data || [];
3915
+ }
3584
3916
  async function createAgent(userId, input) {
3585
3917
  const db2 = createAdminDbClient();
3586
3918
  const payload = {
@@ -3729,7 +4061,7 @@ async function deleteProjectMemory(memoryId) {
3729
4061
  }
3730
4062
  async function getProjectThreads(projectId) {
3731
4063
  const db2 = createAdminDbClient();
3732
- const { data, error } = await db2.from("project_threads").select("*").eq("project_id", projectId).order("created_at", { ascending: false });
4064
+ const { data, error } = await db2.from("project_threads").select("*").eq("project_id", projectId).order("created_at", { ascending: true });
3733
4065
  if (error) {
3734
4066
  if (isMissingRelationError2(error, "project_threads")) return [];
3735
4067
  throw error;
@@ -4195,9 +4527,9 @@ function v4(options, buf, offset) {
4195
4527
  var v4_default = v4;
4196
4528
 
4197
4529
  // ../agx-cloud/lib/queue/sqlite-adapter.ts
4198
- var import_path2 = __toESM(require("path"));
4199
- var import_fs2 = __toESM(require("fs"));
4200
- var import_os2 = __toESM(require("os"));
4530
+ var import_path3 = __toESM(require("path"));
4531
+ var import_fs3 = __toESM(require("fs"));
4532
+ var import_os3 = __toESM(require("os"));
4201
4533
  init_startup();
4202
4534
 
4203
4535
  // ../agx-cloud/lib/limits.ts
@@ -4238,8 +4570,53 @@ var WriteRateMonitor = class {
4238
4570
  }
4239
4571
  };
4240
4572
 
4241
- // ../agx-cloud/lib/queue/sqlite-adapter.ts
4573
+ // ../agx-cloud/lib/debug-log.ts
4574
+ var import_fs2 = __toESM(require("fs"));
4575
+ var import_os2 = __toESM(require("os"));
4576
+ var import_path2 = __toESM(require("path"));
4242
4577
  var AGX_DATA_DIR = process.env.AGX_DATA_DIR || import_path2.default.join(import_os2.default.homedir(), ".agx");
4578
+ var DEBUG_LOG_PATH = process.env.AGX_DEBUG_LOG_PATH || import_path2.default.join(AGX_DATA_DIR, "logs", "desktop-chat-debug.log");
4579
+ function ensureLogDir() {
4580
+ import_fs2.default.mkdirSync(import_path2.default.dirname(DEBUG_LOG_PATH), { recursive: true });
4581
+ }
4582
+ function safeReplacer(_key, value) {
4583
+ if (value instanceof Error) {
4584
+ return {
4585
+ name: value.name,
4586
+ message: value.message,
4587
+ stack: value.stack
4588
+ };
4589
+ }
4590
+ if (typeof value === "string" && value.length > 2e3) {
4591
+ return `${value.slice(0, 2e3)}...<truncated>`;
4592
+ }
4593
+ return value;
4594
+ }
4595
+ function writeDebugLog(event, payload) {
4596
+ try {
4597
+ ensureLogDir();
4598
+ const line = JSON.stringify(
4599
+ {
4600
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
4601
+ pid: process.pid,
4602
+ event,
4603
+ ...payload ? { payload } : {}
4604
+ },
4605
+ safeReplacer
4606
+ );
4607
+ import_fs2.default.appendFileSync(DEBUG_LOG_PATH, `${line}
4608
+ `, "utf8");
4609
+ } catch {
4610
+ }
4611
+ }
4612
+
4613
+ // ../agx-cloud/lib/queue/sqlite-adapter.ts
4614
+ var AGX_DATA_DIR2 = process.env.AGX_DATA_DIR || import_path3.default.join(import_os3.default.homedir(), ".agx");
4615
+ var DEFAULT_STALE_JOB_TIMEOUT_MS = 10 * 60 * 1e3;
4616
+ function getStaleJobTimeoutMs() {
4617
+ const raw = Number(process.env.AGX_QUEUE_STALE_MS);
4618
+ return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_STALE_JOB_TIMEOUT_MS;
4619
+ }
4243
4620
  var SQLiteQueueAdapter = class {
4244
4621
  constructor(dbPath) {
4245
4622
  this.workers = /* @__PURE__ */ new Map();
@@ -4247,10 +4624,10 @@ var SQLiteQueueAdapter = class {
4247
4624
  this.writeRateInterval = null;
4248
4625
  this.writeMonitor = new WriteRateMonitor();
4249
4626
  this.workerId = v4_default();
4250
- const finalPath = dbPath || process.env.SQLITE_QUEUE_PATH || import_path2.default.join(AGX_DATA_DIR, "agx-queue.db");
4251
- const dir = import_path2.default.dirname(finalPath);
4252
- if (!import_fs2.default.existsSync(dir)) {
4253
- import_fs2.default.mkdirSync(dir, { recursive: true });
4627
+ const finalPath = dbPath || process.env.SQLITE_QUEUE_PATH || import_path3.default.join(AGX_DATA_DIR2, "agx-queue.db");
4628
+ const dir = import_path3.default.dirname(finalPath);
4629
+ if (!import_fs3.default.existsSync(dir)) {
4630
+ import_fs3.default.mkdirSync(dir, { recursive: true });
4254
4631
  }
4255
4632
  this.db = new import_better_sqlite3.default(finalPath);
4256
4633
  const errors = validateSQLiteEnvironment(this.db, finalPath);
@@ -4315,9 +4692,23 @@ var SQLiteQueueAdapter = class {
4315
4692
  options?.priority ?? 0
4316
4693
  );
4317
4694
  this.writeMonitor.record();
4695
+ writeDebugLog("queue.send", {
4696
+ queue: queue2,
4697
+ jobId: id,
4698
+ startAfter,
4699
+ retryLimit: options?.retryLimit ?? 3,
4700
+ priority: options?.priority ?? 0,
4701
+ data
4702
+ });
4318
4703
  return id;
4319
4704
  }
4320
4705
  async work(queue2, handler, options) {
4706
+ writeDebugLog("queue.worker.register", {
4707
+ queue: queue2,
4708
+ batchSize: options?.batchSize ?? 1,
4709
+ pollInterval: options?.pollInterval ?? null,
4710
+ workerId: this.workerId
4711
+ });
4321
4712
  this.workers.set(queue2, {
4322
4713
  handler,
4323
4714
  options: options || {},
@@ -4348,7 +4739,17 @@ var SQLiteQueueAdapter = class {
4348
4739
  processQueue(queue2, worker) {
4349
4740
  const batchSize = worker.options.batchSize || 1;
4350
4741
  const now = Date.now();
4742
+ const staleBefore = now - getStaleJobTimeoutMs();
4351
4743
  const jobs = this.db.transaction(() => {
4744
+ const reapedJobs = this.reapStaleJobs(queue2, now, staleBefore);
4745
+ if (reapedJobs.length > 0) {
4746
+ writeDebugLog("queue.reap_stale", {
4747
+ queue: queue2,
4748
+ workerId: this.workerId,
4749
+ staleBefore,
4750
+ jobs: reapedJobs
4751
+ });
4752
+ }
4352
4753
  const candidates = this.db.prepare(`
4353
4754
  SELECT id, data FROM agx_jobs
4354
4755
  WHERE queue = ?
@@ -4374,6 +4775,11 @@ var SQLiteQueueAdapter = class {
4374
4775
  }));
4375
4776
  })();
4376
4777
  if (jobs.length > 0) {
4778
+ writeDebugLog("queue.claim", {
4779
+ queue: queue2,
4780
+ workerId: this.workerId,
4781
+ jobIds: jobs.map((job) => job.id)
4782
+ });
4377
4783
  this.executeJobs(jobs, worker.handler);
4378
4784
  }
4379
4785
  }
@@ -4381,15 +4787,22 @@ var SQLiteQueueAdapter = class {
4381
4787
  try {
4382
4788
  await handler(jobs);
4383
4789
  this.completeJobs(jobs.map((j) => j.id));
4790
+ writeDebugLog("queue.complete", {
4791
+ jobIds: jobs.map((job) => job.id)
4792
+ });
4384
4793
  } catch (err) {
4385
4794
  this.failJobs(jobs.map((j) => j.id), err.message || String(err));
4795
+ writeDebugLog("queue.fail", {
4796
+ jobIds: jobs.map((job) => job.id),
4797
+ error: err
4798
+ });
4386
4799
  }
4387
4800
  }
4388
4801
  completeJobs(ids) {
4389
4802
  const now = Date.now();
4390
4803
  const stmt = this.db.prepare(`
4391
4804
  UPDATE agx_jobs
4392
- SET status = 'completed', completed_at = ?
4805
+ SET status = 'completed', completed_at = ?, worker_id = NULL
4393
4806
  WHERE id = ?
4394
4807
  `);
4395
4808
  this.db.transaction(() => {
@@ -4405,12 +4818,14 @@ var SQLiteQueueAdapter = class {
4405
4818
  UPDATE agx_jobs
4406
4819
  SET status = 'retry', retry_count = retry_count + 1,
4407
4820
  start_after = ? + (retry_count * 1000 * 2), -- Exponential backoff (kinda)
4821
+ started_at = NULL,
4822
+ worker_id = NULL,
4408
4823
  error = ?
4409
4824
  WHERE id = ?
4410
4825
  `);
4411
4826
  const updateFailed = this.db.prepare(`
4412
4827
  UPDATE agx_jobs
4413
- SET status = 'failed', failed_at = ?, error = ?
4828
+ SET status = 'failed', failed_at = ?, started_at = NULL, worker_id = NULL, error = ?
4414
4829
  WHERE id = ?
4415
4830
  `);
4416
4831
  this.db.transaction(() => {
@@ -4425,12 +4840,66 @@ var SQLiteQueueAdapter = class {
4425
4840
  }
4426
4841
  })();
4427
4842
  }
4843
+ reapStaleJobs(queue2, now, staleBefore) {
4844
+ const staleJobs = this.db.prepare(`
4845
+ SELECT id, retry_count, retry_limit
4846
+ FROM agx_jobs
4847
+ WHERE queue = ?
4848
+ AND status = 'active'
4849
+ AND started_at IS NOT NULL
4850
+ AND started_at <= ?
4851
+ ORDER BY started_at ASC
4852
+ `).all(queue2, staleBefore);
4853
+ if (staleJobs.length === 0) return [];
4854
+ const updateRetry = this.db.prepare(`
4855
+ UPDATE agx_jobs
4856
+ SET status = 'retry',
4857
+ retry_count = retry_count + 1,
4858
+ start_after = ?,
4859
+ started_at = NULL,
4860
+ worker_id = NULL,
4861
+ error = ?
4862
+ WHERE id = ?
4863
+ `);
4864
+ const updateFailed = this.db.prepare(`
4865
+ UPDATE agx_jobs
4866
+ SET status = 'failed',
4867
+ failed_at = ?,
4868
+ started_at = NULL,
4869
+ worker_id = NULL,
4870
+ error = ?
4871
+ WHERE id = ?
4872
+ `);
4873
+ const reaped = [];
4874
+ for (const job of staleJobs) {
4875
+ const error = `Job exceeded active timeout of ${getStaleJobTimeoutMs()}ms`;
4876
+ if (job.retry_count < job.retry_limit) {
4877
+ updateRetry.run(now, error, job.id);
4878
+ reaped.push({
4879
+ id: job.id,
4880
+ fromStatus: "active",
4881
+ toStatus: "retry",
4882
+ retryCount: job.retry_count + 1
4883
+ });
4884
+ } else {
4885
+ updateFailed.run(now, error, job.id);
4886
+ reaped.push({
4887
+ id: job.id,
4888
+ fromStatus: "active",
4889
+ toStatus: "failed",
4890
+ retryCount: job.retry_count
4891
+ });
4892
+ }
4893
+ }
4894
+ return reaped;
4895
+ }
4428
4896
  };
4429
4897
 
4430
4898
  // ../agx-cloud/lib/queue/boss.ts
4431
4899
  var queue = null;
4432
4900
  var QUEUE_NAMES = {
4433
4901
  TASK_PROCESS: "agx.task.process",
4902
+ CHAT_RUN_PROCESS: "agx.chat.process",
4434
4903
  TASK_CLEANUP: "agx.task.cleanup"
4435
4904
  };
4436
4905
  async function getQueue() {
@@ -4681,10 +5150,12 @@ async function resolveWorkflowTransition({
4681
5150
  init_db();
4682
5151
 
4683
5152
  // ../agx-cloud/lib/memory-extractor.ts
4684
- var import_crypto2 = require("crypto");
5153
+ var import_crypto4 = require("crypto");
4685
5154
 
4686
5155
  // ../agx-cloud/lib/cli-runner.ts
4687
5156
  var import_child_process = require("child_process");
5157
+ var import_fs10 = __toESM(require("fs"));
5158
+ var import_path10 = __toESM(require("path"));
4688
5159
 
4689
5160
  // ../agx-cloud/lib/sanitize.ts
4690
5161
  function createCliChunkSanitizer() {
@@ -4963,15 +5434,177 @@ var createThoughtFilterParser = (inner) => {
4963
5434
  }
4964
5435
  };
4965
5436
  };
5437
+ var AGX_WRAPPED_PROVIDERS = /* @__PURE__ */ new Set([
5438
+ "claude",
5439
+ "gemini",
5440
+ "ollama",
5441
+ "codex"
5442
+ ]);
5443
+ function providerNativeCommand({
5444
+ provider,
5445
+ model,
5446
+ prompt,
5447
+ systemPrompt
5448
+ }) {
5449
+ switch (provider) {
5450
+ case "claude": {
5451
+ const args = [
5452
+ "-p",
5453
+ "--verbose",
5454
+ "--output-format",
5455
+ "stream-json",
5456
+ "--include-partial-messages"
5457
+ ];
5458
+ if (model) args.push("--model", model);
5459
+ if (systemPrompt) args.push("--system-prompt", systemPrompt);
5460
+ args.push(prompt);
5461
+ return { command: "claude", args, parser: "claude-stream-json" };
5462
+ }
5463
+ case "gemini":
5464
+ return {
5465
+ command: "gemini",
5466
+ args: ["--yolo", "-p", systemPrompt ? `${systemPrompt}
5467
+
5468
+ ${prompt}` : prompt, "-o", "stream-json"],
5469
+ parser: "gemini-stream-json"
5470
+ };
5471
+ case "ollama":
5472
+ return {
5473
+ command: "ollama",
5474
+ args: ["run", model || "llama3.2", systemPrompt ? `${systemPrompt}
5475
+
5476
+ ${prompt}` : prompt],
5477
+ parser: "raw"
5478
+ };
5479
+ case "codex": {
5480
+ const codexArgs = ["exec", "--json"];
5481
+ if (model) codexArgs.push("--model", model);
5482
+ codexArgs.push(systemPrompt ? `${systemPrompt}
5483
+
5484
+ ${prompt}` : prompt);
5485
+ return {
5486
+ command: "codex",
5487
+ args: codexArgs,
5488
+ parser: "codex-json"
5489
+ };
5490
+ }
5491
+ case "zai": {
5492
+ const zaiApiKey = process.env.ZAI_API_KEY?.trim();
5493
+ const zaiArgs = [
5494
+ "-p",
5495
+ "--verbose",
5496
+ "--output-format",
5497
+ "stream-json",
5498
+ "--include-partial-messages"
5499
+ ];
5500
+ if (model) zaiArgs.push("--model", model);
5501
+ if (systemPrompt) zaiArgs.push("--system-prompt", systemPrompt);
5502
+ zaiArgs.push(prompt);
5503
+ return {
5504
+ command: "claude",
5505
+ args: zaiArgs,
5506
+ parser: "claude-stream-json",
5507
+ env: {
5508
+ ANTHROPIC_BASE_URL: "https://api.z.ai/api/anthropic",
5509
+ ...zaiApiKey ? { ANTHROPIC_AUTH_TOKEN: zaiApiKey } : {}
5510
+ }
5511
+ };
5512
+ }
5513
+ default:
5514
+ return null;
5515
+ }
5516
+ }
4966
5517
  function agxCommandForProvider({
4967
5518
  provider,
4968
5519
  model,
4969
- prompt
5520
+ prompt,
5521
+ passthroughArgs
4970
5522
  }) {
4971
5523
  const args = [provider, "-y", "--print", "--prompt", prompt];
4972
5524
  if (model) args.push("--model", model);
5525
+ if (passthroughArgs && passthroughArgs.length > 0) {
5526
+ args.push("--", ...passthroughArgs);
5527
+ }
4973
5528
  return { command: "agx", args, parser: "raw" };
4974
5529
  }
5530
+ function resolveBundledCliPath() {
5531
+ const explicit = process.env.AGX_CLI_PATH?.trim();
5532
+ if (explicit && import_fs10.default.existsSync(explicit)) return explicit;
5533
+ const candidates = [
5534
+ import_path10.default.resolve(process.cwd(), "..", "cli", "index.js"),
5535
+ import_path10.default.resolve(__dirname, "..", "cli", "index.js"),
5536
+ import_path10.default.resolve(process.execPath, "..", "..", "Resources", "cli", "index.js")
5537
+ ];
5538
+ for (const candidate of candidates) {
5539
+ if (import_fs10.default.existsSync(candidate)) {
5540
+ return candidate;
5541
+ }
5542
+ }
5543
+ return null;
5544
+ }
5545
+ function buildCliAttempts({
5546
+ provider,
5547
+ model,
5548
+ prompt,
5549
+ systemPrompt,
5550
+ passthroughArgs
5551
+ }, deps = {}) {
5552
+ const exists = deps.commandExists ?? commandExists;
5553
+ const bundledCliPath = deps.bundledCliPath === void 0 ? resolveBundledCliPath() : deps.bundledCliPath;
5554
+ const attempts = [];
5555
+ const agxPrompt = systemPrompt ? `${systemPrompt}
5556
+
5557
+ ${prompt}` : prompt;
5558
+ if (AGX_WRAPPED_PROVIDERS.has(provider)) {
5559
+ const bundledAgx = bundledAgxCommandForProvider({
5560
+ provider,
5561
+ model,
5562
+ prompt: agxPrompt,
5563
+ cliPath: bundledCliPath,
5564
+ passthroughArgs
5565
+ });
5566
+ if (bundledAgx) {
5567
+ attempts.push(bundledAgx);
5568
+ }
5569
+ if (exists("agx")) {
5570
+ attempts.push(
5571
+ agxCommandForProvider({
5572
+ provider,
5573
+ model,
5574
+ prompt: agxPrompt,
5575
+ passthroughArgs
5576
+ })
5577
+ );
5578
+ }
5579
+ return attempts;
5580
+ }
5581
+ const nativeAttempt = providerNativeCommand({
5582
+ provider,
5583
+ model,
5584
+ prompt,
5585
+ systemPrompt
5586
+ });
5587
+ if (nativeAttempt && exists(nativeAttempt.command)) {
5588
+ attempts.push(nativeAttempt);
5589
+ }
5590
+ return attempts;
5591
+ }
5592
+ function bundledAgxCommandForProvider({
5593
+ provider,
5594
+ model,
5595
+ prompt,
5596
+ cliPath,
5597
+ passthroughArgs
5598
+ }) {
5599
+ const resolvedCliPath = cliPath === void 0 ? resolveBundledCliPath() : cliPath;
5600
+ if (!resolvedCliPath) return null;
5601
+ const args = [resolvedCliPath, provider, "-y", "--print", "--prompt", prompt];
5602
+ if (model) args.push("--model", model);
5603
+ if (passthroughArgs && passthroughArgs.length > 0) {
5604
+ args.push("--", ...passthroughArgs);
5605
+ }
5606
+ return { command: process.execPath, args, parser: "raw" };
5607
+ }
4975
5608
  async function runCommandStreamed({
4976
5609
  command,
4977
5610
  args,
@@ -4983,6 +5616,13 @@ async function runCommandStreamed({
4983
5616
  env: extraEnv
4984
5617
  }) {
4985
5618
  await new Promise((resolve, reject) => {
5619
+ writeDebugLog("cli-runner.spawn", {
5620
+ command,
5621
+ args,
5622
+ timeoutMs,
5623
+ bundledCliPath: resolveBundledCliPath(),
5624
+ isElectron: process.env.AGX_ELECTRON || null
5625
+ });
4986
5626
  if (onLog) onLog("stderr", `$ ${command} ${args.map((a) => a.length > 80 ? a.slice(0, 80) + "\u2026" : a).join(" ")}
4987
5627
  `);
4988
5628
  const child = (0, import_child_process.spawn)(command, args, {
@@ -5001,13 +5641,29 @@ async function runCommandStreamed({
5001
5641
  else resolve();
5002
5642
  };
5003
5643
  const onAbort = () => {
5644
+ writeDebugLog("cli-runner.abort", {
5645
+ command,
5646
+ args,
5647
+ pid: child.pid ?? null
5648
+ });
5004
5649
  child.kill("SIGTERM");
5005
5650
  finalize(new Error("Chat request aborted."));
5006
5651
  };
5007
5652
  if (signal) signal.addEventListener("abort", onAbort, { once: true });
5008
5653
  if (onSpawn && child.pid) onSpawn(child.pid);
5654
+ writeDebugLog("cli-runner.spawned", {
5655
+ command,
5656
+ args,
5657
+ pid: child.pid ?? null
5658
+ });
5009
5659
  const timer = setTimeout(() => {
5010
5660
  timedOut = true;
5661
+ writeDebugLog("cli-runner.timeout", {
5662
+ command,
5663
+ args,
5664
+ pid: child.pid ?? null,
5665
+ timeoutMs
5666
+ });
5011
5667
  child.kill("SIGKILL");
5012
5668
  finalize(new Error(`CLI request timed out after ${timeoutMs}ms.`));
5013
5669
  }, timeoutMs);
@@ -5022,9 +5678,24 @@ async function runCommandStreamed({
5022
5678
  combinedOutput += str;
5023
5679
  if (onLog) onLog("stderr", str);
5024
5680
  });
5025
- child.on("error", (error) => finalize(error));
5681
+ child.on("error", (error) => {
5682
+ writeDebugLog("cli-runner.process_error", {
5683
+ command,
5684
+ args,
5685
+ pid: child.pid ?? null,
5686
+ error
5687
+ });
5688
+ finalize(error);
5689
+ });
5026
5690
  child.on("close", (code, childSignal) => {
5027
5691
  if (done || timedOut) return;
5692
+ writeDebugLog("cli-runner.close", {
5693
+ command,
5694
+ args,
5695
+ pid: child.pid ?? null,
5696
+ code: code ?? null,
5697
+ signal: childSignal ?? null
5698
+ });
5028
5699
  if (code === 0) {
5029
5700
  finalize();
5030
5701
  return;
@@ -5045,6 +5716,7 @@ async function runCliResponse({
5045
5716
  self,
5046
5717
  skills,
5047
5718
  systemContext,
5719
+ passthroughArgs,
5048
5720
  signal,
5049
5721
  onDelta,
5050
5722
  onLog,
@@ -5056,7 +5728,6 @@ async function runCliResponse({
5056
5728
  const cleaned = sanitize(chunk);
5057
5729
  if (cleaned) onDelta(cleaned);
5058
5730
  };
5059
- const attempts = [];
5060
5731
  const systemParts = [];
5061
5732
  if (systemContext) systemParts.push(systemContext);
5062
5733
  if (identity) systemParts.push(`<identity>
@@ -5069,19 +5740,33 @@ ${self}
5069
5740
  ${skills}
5070
5741
  </skills>`);
5071
5742
  const systemPrompt = systemParts.length > 0 ? systemParts.join("\n\n") : void 0;
5072
- if (commandExists("agx")) {
5073
- const agxPrompt = systemPrompt ? `${systemPrompt}
5074
-
5075
- ${prompt}` : prompt;
5076
- attempts.push(agxCommandForProvider({ provider, model, prompt: agxPrompt }));
5077
- }
5743
+ const attempts = buildCliAttempts({
5744
+ provider,
5745
+ model,
5746
+ prompt,
5747
+ systemPrompt,
5748
+ passthroughArgs
5749
+ });
5078
5750
  if (attempts.length === 0) {
5751
+ writeDebugLog("cli-runner.no_attempts", {
5752
+ provider,
5753
+ model,
5754
+ bundledCliPath: resolveBundledCliPath(),
5755
+ isElectron: process.env.AGX_ELECTRON || null
5756
+ });
5079
5757
  throw new Error(
5080
5758
  `No CLI runner available for provider "${provider}". Install agx or provider CLI.`
5081
5759
  );
5082
5760
  }
5083
5761
  let lastError = null;
5084
5762
  for (const attempt of attempts) {
5763
+ writeDebugLog("cli-runner.attempt", {
5764
+ provider,
5765
+ model,
5766
+ command: attempt.command,
5767
+ args: attempt.args,
5768
+ parser: attempt.parser
5769
+ });
5085
5770
  const baseParser = attempt.parser === "claude-stream-json" ? createClaudeStreamJsonParser(wrappedOnDelta) : attempt.parser === "codex-json" ? createCodexJsonParser(wrappedOnDelta) : attempt.parser === "gemini-stream-json" ? createGeminiStreamJsonParser(wrappedOnDelta) : createRawParser(wrappedOnDelta);
5086
5771
  const parser = attempt.filterThoughts ? createThoughtFilterParser(baseParser) : baseParser;
5087
5772
  try {
@@ -5096,9 +5781,20 @@ ${prompt}` : prompt;
5096
5781
  env: attempt.env
5097
5782
  });
5098
5783
  parser.flush();
5784
+ writeDebugLog("cli-runner.success", {
5785
+ provider,
5786
+ model,
5787
+ command: attempt.command
5788
+ });
5099
5789
  return;
5100
5790
  } catch (error) {
5101
5791
  lastError = error instanceof Error ? error : new Error(String(error));
5792
+ writeDebugLog("cli-runner.failure", {
5793
+ provider,
5794
+ model,
5795
+ command: attempt.command,
5796
+ error: lastError
5797
+ });
5102
5798
  }
5103
5799
  }
5104
5800
  throw lastError || new Error("CLI execution failed.");
@@ -5106,48 +5802,351 @@ ${prompt}` : prompt;
5106
5802
 
5107
5803
  // ../agx-cloud/lib/memory-extractor.ts
5108
5804
  init_sqlite_query_adapter();
5109
- var VALID_TYPES = /* @__PURE__ */ new Set(["outcome", "decision", "pattern", "gotcha"]);
5110
- var EXTRACTION_PROMPT = `You are a memory extractor for a task execution system.
5111
- Given a completed task, extract 0-3 memories worth remembering for future tasks.
5112
-
5113
- Each memory must be:
5114
- { "memory_type": "outcome" | "decision" | "pattern" | "gotcha", "content": "one concise sentence" }
5115
-
5116
- - outcome: what happened (success/failure result)
5117
- - decision: a choice that was made and why
5118
- - pattern: a reusable approach or technique discovered
5119
- - gotcha: a surprising pitfall or edge case encountered
5120
-
5121
- Return ONLY a JSON array. Return [] if nothing worth remembering.
5122
- Do not wrap in markdown code blocks. Just raw JSON.`;
5123
- var PROJECT_KNOWLEDGE_PROMPT = `You are a project knowledge extractor for a task execution system.
5124
- Given a completed or failed task, extract 0-2 concise project-scoped knowledge entries worth keeping.
5125
-
5126
- Each entry must be:
5127
- { "content": "one concise sentence" }
5128
-
5129
- Only include information that is likely useful across future work in the same project:
5130
- - workflows, conventions, recurring constraints
5131
- - stable gotchas or environment realities
5132
- - reusable project-specific practices
5133
-
5134
- Do not include:
5135
- - repo-specific durable truths that belong in repo knowledge
5136
- - one-off task status updates
5137
- - vague summaries
5138
-
5139
- Return ONLY a JSON array. Return [] if nothing project-scoped is worth keeping.
5140
- Do not wrap in markdown code blocks. Just raw JSON.`;
5141
- async function extractMemories(ctx) {
5142
- const taskDescription = [
5143
- `Goal: ${ctx.goal}`,
5144
- `Status: ${ctx.status}`,
5145
- ctx.nodeOutputs ? `Node outputs: ${JSON.stringify(ctx.nodeOutputs).slice(0, 2e3)}` : null
5146
- ].filter(Boolean).join("\n");
5147
- const prompt = `${EXTRACTION_PROMPT}
5148
5805
 
5149
- Task:
5150
- ${taskDescription}`;
5806
+ // ../agx-cloud/lib/knowledge-store.ts
5807
+ var import_crypto2 = require("crypto");
5808
+ init_sqlite_query_adapter();
5809
+ function clampUnitNumber(value) {
5810
+ if (typeof value !== "number" || !Number.isFinite(value)) return null;
5811
+ return Math.max(0, Math.min(1, value));
5812
+ }
5813
+ function parseJsonArray(raw) {
5814
+ if (!raw) return [];
5815
+ try {
5816
+ const parsed = JSON.parse(raw);
5817
+ return Array.isArray(parsed) ? parsed : [];
5818
+ } catch {
5819
+ return [];
5820
+ }
5821
+ }
5822
+ function parseJsonObject(raw) {
5823
+ if (!raw) return {};
5824
+ try {
5825
+ const parsed = JSON.parse(raw);
5826
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
5827
+ } catch {
5828
+ return {};
5829
+ }
5830
+ }
5831
+ function normalizeTags(tags) {
5832
+ const seen = /* @__PURE__ */ new Set();
5833
+ const result = [];
5834
+ for (const tag of tags ?? []) {
5835
+ const trimmed = String(tag ?? "").trim().toLowerCase();
5836
+ if (!trimmed || seen.has(trimmed)) continue;
5837
+ seen.add(trimmed);
5838
+ result.push(trimmed);
5839
+ }
5840
+ return result;
5841
+ }
5842
+ function normalizeEvidence(evidence) {
5843
+ const result = [];
5844
+ for (const item of evidence ?? []) {
5845
+ const note = String(item?.note ?? "").trim();
5846
+ const id = typeof item?.id === "string" ? item.id.trim() : "";
5847
+ if (!note) continue;
5848
+ result.push(id ? { id, note } : { note });
5849
+ }
5850
+ return result;
5851
+ }
5852
+ function mapRow(row) {
5853
+ return {
5854
+ id: row.id,
5855
+ scope: row.scope,
5856
+ subjectId: row.subject_id,
5857
+ sourceType: row.source_type,
5858
+ sourceId: row.source_id,
5859
+ kind: row.kind,
5860
+ title: row.title,
5861
+ body: row.body,
5862
+ confidence: clampUnitNumber(row.confidence),
5863
+ durability: clampUnitNumber(row.durability),
5864
+ tags: parseJsonArray(row.tags),
5865
+ evidence: parseJsonArray(row.evidence),
5866
+ metadata: parseJsonObject(row.metadata),
5867
+ createdAt: row.created_at,
5868
+ updatedAt: row.updated_at
5869
+ };
5870
+ }
5871
+ function listKnowledgeEntries(input) {
5872
+ const db2 = getSQLiteDb();
5873
+ const rows = db2.prepare(
5874
+ `SELECT id, scope, subject_id, source_type, source_id, kind, title, body,
5875
+ confidence, durability, tags, evidence, metadata, created_at, updated_at
5876
+ FROM knowledge_entries
5877
+ WHERE scope = ? AND subject_id = ?
5878
+ ORDER BY updated_at DESC, created_at DESC
5879
+ LIMIT ?`
5880
+ ).all(input.scope, input.subjectId, input.limit ?? 50);
5881
+ return rows.map(mapRow);
5882
+ }
5883
+ function storeKnowledgeEntries(drafts) {
5884
+ if (drafts.length === 0) return 0;
5885
+ const db2 = getSQLiteDb();
5886
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5887
+ const existingStmt = db2.prepare(
5888
+ `SELECT id
5889
+ FROM knowledge_entries
5890
+ WHERE scope = ? AND subject_id = ? AND content_hash = ?
5891
+ LIMIT 1`
5892
+ );
5893
+ const insertStmt = db2.prepare(
5894
+ `INSERT INTO knowledge_entries (
5895
+ id, scope, subject_id, source_type, source_id, kind, title, body,
5896
+ confidence, durability, tags, evidence, metadata, content_hash, created_at, updated_at
5897
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
5898
+ );
5899
+ let inserted = 0;
5900
+ const tx = db2.transaction((entries) => {
5901
+ for (const draft of entries) {
5902
+ const subjectId = draft.subjectId.trim();
5903
+ const title = draft.title.trim();
5904
+ const body = draft.body.trim();
5905
+ const sourceId = draft.sourceId.trim();
5906
+ if (!subjectId || !title || !body || !sourceId) continue;
5907
+ const contentHash = (0, import_crypto2.createHash)("sha256").update(`${draft.scope}
5908
+ ${subjectId}
5909
+ ${body}`).digest("hex");
5910
+ const existing = existingStmt.get(draft.scope, subjectId, contentHash);
5911
+ if (existing) continue;
5912
+ insertStmt.run(
5913
+ (0, import_crypto2.randomUUID)(),
5914
+ draft.scope,
5915
+ subjectId,
5916
+ draft.sourceType,
5917
+ sourceId,
5918
+ draft.kind,
5919
+ title,
5920
+ body,
5921
+ clampUnitNumber(draft.confidence),
5922
+ clampUnitNumber(draft.durability),
5923
+ JSON.stringify(normalizeTags(draft.tags)),
5924
+ JSON.stringify(normalizeEvidence(draft.evidence)),
5925
+ JSON.stringify(draft.metadata ?? {}),
5926
+ contentHash,
5927
+ now,
5928
+ now
5929
+ );
5930
+ inserted += 1;
5931
+ }
5932
+ });
5933
+ tx(drafts);
5934
+ return inserted;
5935
+ }
5936
+
5937
+ // ../agx-cloud/lib/knowledge-notes.ts
5938
+ var import_crypto3 = require("crypto");
5939
+ init_sqlite_query_adapter();
5940
+ function parseJsonObject2(raw) {
5941
+ if (!raw) return {};
5942
+ try {
5943
+ const parsed = JSON.parse(raw);
5944
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
5945
+ } catch {
5946
+ return {};
5947
+ }
5948
+ }
5949
+ function normalizeContent(content) {
5950
+ return content.replace(/\r\n/g, "\n").split("\n").map((line) => line.replace(/\s+$/g, "")).join("\n").trim();
5951
+ }
5952
+ function mapRow2(row) {
5953
+ return {
5954
+ id: row.id,
5955
+ scope: row.scope,
5956
+ subjectId: row.subject_id,
5957
+ content: row.content,
5958
+ changeSummary: row.change_summary ?? null,
5959
+ sourceType: row.source_type,
5960
+ sourceId: row.source_id,
5961
+ metadata: parseJsonObject2(row.metadata),
5962
+ version: Number(row.version ?? 1),
5963
+ createdAt: row.created_at,
5964
+ updatedAt: row.updated_at
5965
+ };
5966
+ }
5967
+ function getKnowledgeNoteRow(scope, subjectId) {
5968
+ const db2 = getSQLiteDb();
5969
+ return db2.prepare(
5970
+ `SELECT id, scope, subject_id, content, change_summary, source_type, source_id,
5971
+ metadata, version, created_at, updated_at
5972
+ FROM knowledge_notes
5973
+ WHERE scope = ? AND subject_id = ?
5974
+ LIMIT 1`
5975
+ ).get(scope, subjectId);
5976
+ }
5977
+ function listLegacySystemStatements(scope, subjectId) {
5978
+ const db2 = getSQLiteDb();
5979
+ if (scope === "repo") {
5980
+ const systemRepoRows = db2.prepare(
5981
+ `SELECT content
5982
+ FROM repo_knowledge
5983
+ WHERE repo_id = ? AND producer = 'system'
5984
+ ORDER BY created_at ASC`
5985
+ ).all(subjectId);
5986
+ const entryBodies2 = listKnowledgeEntries({ scope: "repo", subjectId, limit: 100 }).map((entry) => entry.body.trim());
5987
+ return [...systemRepoRows.map((row) => row.content.trim()), ...entryBodies2].filter(Boolean);
5988
+ }
5989
+ if (scope === "project") {
5990
+ const systemProjectRows = db2.prepare(
5991
+ `SELECT content
5992
+ FROM project_memory
5993
+ WHERE project_id = ? AND producer = 'system'
5994
+ ORDER BY created_at ASC`
5995
+ ).all(subjectId);
5996
+ const entryBodies2 = listKnowledgeEntries({ scope: "project", subjectId, limit: 100 }).map((entry) => entry.body.trim());
5997
+ return [...systemProjectRows.map((row) => row.content.trim()), ...entryBodies2].filter(Boolean);
5998
+ }
5999
+ const agentRows = db2.prepare(
6000
+ `SELECT content
6001
+ FROM agent_memory
6002
+ WHERE agent_id = ?
6003
+ ORDER BY created_at ASC
6004
+ LIMIT 100`
6005
+ ).all(subjectId);
6006
+ const entryBodies = listKnowledgeEntries({ scope: "agent", subjectId, limit: 100 }).map((entry) => entry.body.trim());
6007
+ return [...agentRows.map((row) => row.content.trim()), ...entryBodies].filter(Boolean);
6008
+ }
6009
+ function synthesizeLegacyNoteContent(scope, subjectId) {
6010
+ const unique = Array.from(new Set(listLegacySystemStatements(scope, subjectId)));
6011
+ if (unique.length === 0) return "";
6012
+ return unique.map((line) => `- ${line.replace(/^\-\s*/, "")}`).join("\n");
6013
+ }
6014
+ function ensureKnowledgeNote(scope, subjectId) {
6015
+ const existing = getKnowledgeNoteRow(scope, subjectId);
6016
+ if (existing) return mapRow2(existing);
6017
+ const synthesized = synthesizeLegacyNoteContent(scope, subjectId);
6018
+ if (!synthesized) return null;
6019
+ const db2 = getSQLiteDb();
6020
+ const now = (/* @__PURE__ */ new Date()).toISOString();
6021
+ const id = (0, import_crypto3.randomUUID)();
6022
+ db2.prepare(
6023
+ `INSERT INTO knowledge_notes (
6024
+ id, scope, subject_id, content, change_summary, source_type, source_id, metadata, version, created_at, updated_at
6025
+ ) VALUES (?, ?, ?, ?, ?, 'task_completion', 'legacy-synthesis', ?, 1, ?, ?)`
6026
+ ).run(
6027
+ id,
6028
+ scope,
6029
+ subjectId,
6030
+ synthesized,
6031
+ "Initial note synthesized from existing system knowledge",
6032
+ JSON.stringify({ synthesized_from_legacy: true }),
6033
+ now,
6034
+ now
6035
+ );
6036
+ db2.prepare(
6037
+ `INSERT INTO knowledge_note_versions (
6038
+ id, note_id, version, content, change_summary, source_type, source_id, metadata, created_at
6039
+ ) VALUES (?, ?, 1, ?, ?, 'task_completion', 'legacy-synthesis', ?, ?)`
6040
+ ).run(
6041
+ (0, import_crypto3.randomUUID)(),
6042
+ id,
6043
+ synthesized,
6044
+ "Initial note synthesized from existing system knowledge",
6045
+ JSON.stringify({ synthesized_from_legacy: true }),
6046
+ now
6047
+ );
6048
+ const created = getKnowledgeNoteRow(scope, subjectId);
6049
+ return created ? mapRow2(created) : null;
6050
+ }
6051
+ function getKnowledgeNote(scope, subjectId) {
6052
+ const trimmedSubjectId = subjectId.trim();
6053
+ if (!trimmedSubjectId) return null;
6054
+ return ensureKnowledgeNote(scope, trimmedSubjectId);
6055
+ }
6056
+ function upsertKnowledgeNote(input) {
6057
+ const db2 = getSQLiteDb();
6058
+ const subjectId = input.subjectId.trim();
6059
+ const sourceId = input.sourceId.trim();
6060
+ const content = normalizeContent(input.content);
6061
+ const changeSummary = input.changeSummary?.trim() || null;
6062
+ if (!subjectId || !sourceId) {
6063
+ throw new Error("subjectId and sourceId are required");
6064
+ }
6065
+ const existing = ensureKnowledgeNote(input.scope, subjectId);
6066
+ if (existing && normalizeContent(existing.content) === content) {
6067
+ return { note: existing, changed: false };
6068
+ }
6069
+ const now = (/* @__PURE__ */ new Date()).toISOString();
6070
+ const metadata = JSON.stringify(input.metadata ?? {});
6071
+ if (!existing) {
6072
+ const id = (0, import_crypto3.randomUUID)();
6073
+ db2.prepare(
6074
+ `INSERT INTO knowledge_notes (
6075
+ id, scope, subject_id, content, change_summary, source_type, source_id, metadata, version, created_at, updated_at
6076
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?)`
6077
+ ).run(id, input.scope, subjectId, content, changeSummary, input.sourceType, sourceId, metadata, now, now);
6078
+ db2.prepare(
6079
+ `INSERT INTO knowledge_note_versions (
6080
+ id, note_id, version, content, change_summary, source_type, source_id, metadata, created_at
6081
+ ) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?)`
6082
+ ).run((0, import_crypto3.randomUUID)(), id, content, changeSummary, input.sourceType, sourceId, metadata, now);
6083
+ const created = getKnowledgeNote(input.scope, subjectId);
6084
+ if (!created) throw new Error("Failed to read created knowledge note");
6085
+ return { note: created, changed: true };
6086
+ }
6087
+ const nextVersion = existing.version + 1;
6088
+ db2.prepare(
6089
+ `UPDATE knowledge_notes
6090
+ SET content = ?, change_summary = ?, source_type = ?, source_id = ?, metadata = ?, version = ?, updated_at = ?
6091
+ WHERE id = ?`
6092
+ ).run(content, changeSummary, input.sourceType, sourceId, metadata, nextVersion, now, existing.id);
6093
+ db2.prepare(
6094
+ `INSERT INTO knowledge_note_versions (
6095
+ id, note_id, version, content, change_summary, source_type, source_id, metadata, created_at
6096
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
6097
+ ).run((0, import_crypto3.randomUUID)(), existing.id, nextVersion, content, changeSummary, input.sourceType, sourceId, metadata, now);
6098
+ const updated = getKnowledgeNote(input.scope, subjectId);
6099
+ if (!updated) throw new Error("Failed to read updated knowledge note");
6100
+ return { note: updated, changed: true };
6101
+ }
6102
+
6103
+ // ../agx-cloud/lib/memory-extractor.ts
6104
+ var VALID_TYPES = /* @__PURE__ */ new Set(["outcome", "decision", "pattern", "gotcha"]);
6105
+ var EXTRACTION_PROMPT = `You are a memory extractor for a task execution system.
6106
+ Given a completed task, extract 0-3 memories worth remembering for future tasks.
6107
+
6108
+ Each memory must be:
6109
+ { "memory_type": "outcome" | "decision" | "pattern" | "gotcha", "content": "one concise sentence" }
6110
+
6111
+ - outcome: what happened (success/failure result)
6112
+ - decision: a choice that was made and why
6113
+ - pattern: a reusable approach or technique discovered
6114
+ - gotcha: a surprising pitfall or edge case encountered
6115
+
6116
+ Return ONLY a JSON array. Return [] if nothing worth remembering.
6117
+ Do not wrap in markdown code blocks. Just raw JSON.`;
6118
+ var PROJECT_KNOWLEDGE_PROMPT = `You are maintaining a living project knowledge note for a task execution system.
6119
+ Given the current project note and a completed or failed task, decide whether the note should change.
6120
+
6121
+ Return ONLY a JSON object:
6122
+ {
6123
+ "updated_note": "full revised note in concise markdown",
6124
+ "change_summary": "short summary of what changed",
6125
+ "no_change": false
6126
+ }
6127
+
6128
+ Rules:
6129
+ - Revise the current note instead of appending isolated bullets.
6130
+ - Write like a person's living project notes, not an extracted fact list.
6131
+ - The note should help someone understand what the project is, what it does, what has been decided, and what lessons now shape future work.
6132
+ - Prefer short sections and narrative paragraphs in markdown. Bullets are fine only when they genuinely improve clarity.
6133
+ - Preserve strong existing content when still valid.
6134
+ - Merge duplicate ideas, sharpen wording, and remove stale or unsupported claims.
6135
+ - Only include project-scoped knowledge likely useful across future work in the same project.
6136
+ - Do not include repo-specific durable truths that belong in repo knowledge.
6137
+ - Avoid generic filler and avoid sounding like an audit log.
6138
+ - If nothing project-scoped changed, return {"no_change": true}.
6139
+ - Do not wrap in markdown code blocks. Just raw JSON.`;
6140
+ async function extractMemories(ctx) {
6141
+ const taskDescription = [
6142
+ `Goal: ${ctx.goal}`,
6143
+ `Status: ${ctx.status}`,
6144
+ ctx.nodeOutputs ? `Node outputs: ${JSON.stringify(ctx.nodeOutputs).slice(0, 2e3)}` : null
6145
+ ].filter(Boolean).join("\n");
6146
+ const prompt = `${EXTRACTION_PROMPT}
6147
+
6148
+ Task:
6149
+ ${taskDescription}`;
5151
6150
  let raw = "";
5152
6151
  try {
5153
6152
  await runCliResponse({
@@ -5183,18 +6182,16 @@ function parseProjectKnowledgeResponse(raw) {
5183
6182
  const cleaned = trimmed.replace(/^```(?:json)?\s*/i, "").replace(/\s*```\s*$/, "").trim();
5184
6183
  try {
5185
6184
  const parsed = JSON.parse(cleaned);
5186
- if (!Array.isArray(parsed)) return [];
5187
- const unique = /* @__PURE__ */ new Set();
5188
- const result = [];
5189
- for (const entry of parsed) {
5190
- const content = typeof entry === "object" && entry !== null && typeof entry.content === "string" ? entry.content.trim() : "";
5191
- if (!content) continue;
5192
- if (unique.has(content)) continue;
5193
- unique.add(content);
5194
- result.push({ content });
5195
- if (result.length >= 2) break;
5196
- }
5197
- return result;
6185
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return [];
6186
+ const updatedNote = typeof parsed.updated_note === "string" ? parsed.updated_note.trim() : "";
6187
+ const noChange = Boolean(parsed.no_change);
6188
+ if (noChange) return [];
6189
+ if (!updatedNote) return [];
6190
+ return [{
6191
+ updated_note: updatedNote,
6192
+ change_summary: typeof parsed.change_summary === "string" ? parsed.change_summary.trim() : void 0,
6193
+ no_change: false
6194
+ }];
5198
6195
  } catch {
5199
6196
  console.warn("[project-knowledge] Failed to parse LLM response:", cleaned.slice(0, 200));
5200
6197
  return [];
@@ -5235,10 +6232,26 @@ async function storeMemories(taskId, agentId, memories) {
5235
6232
  const now = Date.now();
5236
6233
  for (const mem of memories) {
5237
6234
  if (!VALID_TYPES_SET.has(mem.memory_type) || !mem.content?.trim()) continue;
5238
- const contentHash = (0, import_crypto2.createHash)("sha256").update(mem.content.trim()).digest("hex");
5239
- const result = stmt.run((0, import_crypto2.randomUUID)(), agentId, taskId, mem.memory_type, mem.content.trim(), contentHash, now);
6235
+ const contentHash = (0, import_crypto4.createHash)("sha256").update(mem.content.trim()).digest("hex");
6236
+ const result = stmt.run((0, import_crypto4.randomUUID)(), agentId, taskId, mem.memory_type, mem.content.trim(), contentHash, now);
5240
6237
  if (result.changes > 0) inserted++;
5241
6238
  }
6239
+ if (inserted > 0) {
6240
+ storeKnowledgeEntries(
6241
+ memories.map((mem) => ({
6242
+ scope: "agent",
6243
+ subjectId: agentId,
6244
+ sourceType: "task_completion",
6245
+ sourceId: taskId,
6246
+ kind: mem.memory_type,
6247
+ title: mem.content.trim().slice(0, 80),
6248
+ body: mem.content.trim(),
6249
+ confidence: 0.7,
6250
+ durability: 0.6,
6251
+ metadata: { task_id: taskId }
6252
+ }))
6253
+ );
6254
+ }
5242
6255
  return inserted;
5243
6256
  }
5244
6257
  async function extractAndStoreMemories(taskId, agentId, ctx) {
@@ -5259,7 +6272,7 @@ async function resolveProjectId(projectIdOrSlug) {
5259
6272
  const project = db2.prepare("SELECT id FROM projects WHERE slug = ? LIMIT 1").get(explicit);
5260
6273
  return project?.id ?? null;
5261
6274
  }
5262
- async function extractProjectKnowledge(ctx) {
6275
+ async function extractProjectKnowledge(ctx, currentNote) {
5263
6276
  const taskDescription = [
5264
6277
  `Goal: ${ctx.goal}`,
5265
6278
  `Status: ${ctx.status}`,
@@ -5267,6 +6280,9 @@ async function extractProjectKnowledge(ctx) {
5267
6280
  ].filter(Boolean).join("\n");
5268
6281
  const prompt = `${PROJECT_KNOWLEDGE_PROMPT}
5269
6282
 
6283
+ Current note:
6284
+ ${currentNote || "(empty)"}
6285
+
5270
6286
  Task:
5271
6287
  ${taskDescription}`;
5272
6288
  let raw = "";
@@ -5287,29 +6303,23 @@ ${taskDescription}`;
5287
6303
  }
5288
6304
  async function storeProjectKnowledge(projectId, taskId, entries) {
5289
6305
  if (entries.length === 0) return 0;
5290
- const db2 = getSQLiteDb();
5291
- const existingContents = new Set(
5292
- db2.prepare("SELECT content FROM project_memory WHERE project_id = ? AND producer = 'system'").all(projectId).map((row) => row.content.trim())
5293
- );
5294
- const insert = db2.prepare(
5295
- `INSERT INTO project_memory (id, project_id, content, source, producer, created_at)
5296
- VALUES (?, ?, ?, ?, 'system', ?)`
5297
- );
5298
- let inserted = 0;
5299
- const now = (/* @__PURE__ */ new Date()).toISOString();
5300
- for (const entry of entries) {
5301
- const content = entry.content.trim();
5302
- if (!content || existingContents.has(content)) continue;
5303
- insert.run((0, import_crypto2.randomUUID)(), projectId, content, `task:${taskId}`, now);
5304
- existingContents.add(content);
5305
- inserted++;
5306
- }
5307
- return inserted;
6306
+ const entry = entries[0];
6307
+ if (!entry || !entry.updated_note?.trim()) return 0;
6308
+ const result = upsertKnowledgeNote({
6309
+ scope: "project",
6310
+ subjectId: projectId,
6311
+ content: entry.updated_note.trim(),
6312
+ changeSummary: entry.change_summary,
6313
+ sourceType: "task_completion",
6314
+ sourceId: taskId,
6315
+ metadata: { task_id: taskId }
6316
+ });
6317
+ return result.changed ? 1 : 0;
5308
6318
  }
5309
6319
  async function extractAndStoreProjectKnowledge(taskId, projectIdOrSlug, ctx) {
5310
6320
  const projectId = await resolveProjectId(projectIdOrSlug);
5311
6321
  if (!projectId) return;
5312
- const knowledge = await extractProjectKnowledge(ctx);
6322
+ const knowledge = await extractProjectKnowledge(ctx, getKnowledgeNote("project", projectId)?.content ?? "");
5313
6323
  if (knowledge.length === 0) return;
5314
6324
  const inserted = await storeProjectKnowledge(projectId, taskId, knowledge);
5315
6325
  if (inserted > 0) {
@@ -5845,18 +6855,2240 @@ async function handleCancel(taskId, userId, reason) {
5845
6855
  await markCancelledActivity({ taskId, reason, userId });
5846
6856
  }
5847
6857
 
5848
- // ../agx-cloud/worker/index.ts
5849
- async function main() {
5850
- const requestedWorkers = Number(process.env.AGX_WORKER_COUNT) || 1;
5851
- assertWorkerCount(requestedWorkers);
5852
- console.log(`[worker] Starting SQLite worker (${requestedWorkers}/${MAX_WORKERS} max)...`);
5853
- const queue2 = await getQueue();
5854
- await queue2.work(
5855
- QUEUE_NAMES.TASK_PROCESS,
5856
- taskProcessor,
5857
- { batchSize: 5 }
6858
+ // ../agx-cloud/lib/stream-multiplexer.ts
6859
+ var import_promises = require("fs/promises");
6860
+
6861
+ // ../agx-cloud/lib/agent-process-registry.ts
6862
+ var import_better_sqlite34 = __toESM(require_lib());
6863
+ var import_path11 = __toESM(require("path"));
6864
+ var import_os10 = __toESM(require("os"));
6865
+ var import_fs11 = require("fs");
6866
+ var HISTORY_DIR = process.env.AGX_GROUP_CHAT_DIR?.trim() || import_path11.default.join(import_os10.default.homedir(), ".agx", "group-chat");
6867
+ var DB_PATH2 = import_path11.default.join(HISTORY_DIR, "history.sqlite");
6868
+ function toEntry(row) {
6869
+ return {
6870
+ id: row.id,
6871
+ workspaceId: row.workspace_id,
6872
+ threadId: row.thread_id,
6873
+ agentId: row.agent_id,
6874
+ pid: row.pid,
6875
+ state: row.state,
6876
+ sinceMessageId: row.since_message_id,
6877
+ responseMessageId: row.response_message_id || "",
6878
+ startedAt: row.started_at,
6879
+ lastActivity: row.last_activity,
6880
+ projectSlug: row.project_slug || ""
6881
+ };
6882
+ }
6883
+ function getDb2() {
6884
+ (0, import_fs11.mkdirSync)(HISTORY_DIR, { recursive: true });
6885
+ const db2 = new import_better_sqlite34.default(DB_PATH2);
6886
+ db2.pragma("journal_mode = WAL");
6887
+ db2.exec(`
6888
+ CREATE TABLE IF NOT EXISTS agent_processes (
6889
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
6890
+ workspace_id TEXT NOT NULL,
6891
+ thread_id TEXT NOT NULL DEFAULT '',
6892
+ agent_id TEXT NOT NULL,
6893
+ pid INTEGER NOT NULL DEFAULT 0,
6894
+ state TEXT NOT NULL DEFAULT 'spawning',
6895
+ since_message_id TEXT NOT NULL DEFAULT '',
6896
+ started_at INTEGER NOT NULL,
6897
+ last_activity INTEGER NOT NULL,
6898
+ project_slug TEXT NOT NULL DEFAULT '',
6899
+ UNIQUE (workspace_id, agent_id)
6900
+ )
6901
+ `);
6902
+ db2.exec("CREATE INDEX IF NOT EXISTS idx_agent_processes_state ON agent_processes (state)");
6903
+ db2.exec("CREATE INDEX IF NOT EXISTS idx_agent_processes_thread ON agent_processes (thread_id)");
6904
+ db2.exec("CREATE INDEX IF NOT EXISTS idx_agent_processes_workspace ON agent_processes (workspace_id)");
6905
+ try {
6906
+ db2.exec("ALTER TABLE agent_processes ADD COLUMN project_slug TEXT NOT NULL DEFAULT ''");
6907
+ } catch {
6908
+ }
6909
+ try {
6910
+ db2.exec("ALTER TABLE agent_processes ADD COLUMN response_message_id TEXT NOT NULL DEFAULT ''");
6911
+ } catch {
6912
+ }
6913
+ return db2;
6914
+ }
6915
+ function withDb(fn) {
6916
+ const db2 = getDb2();
6917
+ try {
6918
+ return fn(db2);
6919
+ } finally {
6920
+ db2.close();
6921
+ }
6922
+ }
6923
+ function register(entry) {
6924
+ return withDb((db2) => {
6925
+ const result = db2.prepare(
6926
+ `INSERT INTO agent_processes (workspace_id, thread_id, agent_id, pid, state, since_message_id, response_message_id, started_at, last_activity, project_slug)
6927
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
6928
+ ON CONFLICT(workspace_id, agent_id)
6929
+ DO UPDATE SET
6930
+ thread_id = excluded.thread_id,
6931
+ pid = excluded.pid,
6932
+ state = excluded.state,
6933
+ since_message_id = excluded.since_message_id,
6934
+ response_message_id = excluded.response_message_id,
6935
+ started_at = excluded.started_at,
6936
+ last_activity = excluded.last_activity,
6937
+ project_slug = excluded.project_slug`
6938
+ ).run(
6939
+ entry.workspaceId,
6940
+ entry.threadId,
6941
+ entry.agentId,
6942
+ entry.pid,
6943
+ entry.state,
6944
+ entry.sinceMessageId,
6945
+ entry.responseMessageId || "",
6946
+ entry.startedAt,
6947
+ entry.lastActivity,
6948
+ entry.projectSlug || ""
6949
+ );
6950
+ if (result.changes === 1 && result.lastInsertRowid) {
6951
+ return Number(result.lastInsertRowid);
6952
+ }
6953
+ const row = db2.prepare(
6954
+ "SELECT id FROM agent_processes WHERE workspace_id = ? AND agent_id = ?"
6955
+ ).get(entry.workspaceId, entry.agentId);
6956
+ return row?.id ?? 0;
6957
+ });
6958
+ }
6959
+ function update(workspaceId, agentId, patch) {
6960
+ const sets = [];
6961
+ const values = [];
6962
+ if (patch.state !== void 0) {
6963
+ sets.push("state = ?");
6964
+ values.push(patch.state);
6965
+ }
6966
+ if (patch.lastActivity !== void 0) {
6967
+ sets.push("last_activity = ?");
6968
+ values.push(patch.lastActivity);
6969
+ }
6970
+ if (patch.pid !== void 0) {
6971
+ sets.push("pid = ?");
6972
+ values.push(patch.pid);
6973
+ }
6974
+ if (sets.length === 0) return;
6975
+ withDb(
6976
+ (db2) => db2.prepare(
6977
+ `UPDATE agent_processes SET ${sets.join(", ")} WHERE workspace_id = ? AND agent_id = ?`
6978
+ ).run(...values, workspaceId, agentId)
6979
+ );
6980
+ }
6981
+ function getByThread(threadId) {
6982
+ return withDb((db2) => {
6983
+ const rows = db2.prepare("SELECT * FROM agent_processes WHERE thread_id = ?").all(threadId);
6984
+ return rows.map(toEntry);
6985
+ });
6986
+ }
6987
+ function getByWorkspace(workspaceId) {
6988
+ return withDb((db2) => {
6989
+ const rows = db2.prepare("SELECT * FROM agent_processes WHERE workspace_id = ?").all(workspaceId);
6990
+ return rows.map(toEntry);
6991
+ });
6992
+ }
6993
+ function killEntries(entries) {
6994
+ let killed = 0;
6995
+ for (const entry of entries) {
6996
+ if (entry.pid > 0) {
6997
+ try {
6998
+ process.kill(entry.pid, "SIGTERM");
6999
+ } catch {
7000
+ }
7001
+ }
7002
+ killed++;
7003
+ }
7004
+ return killed;
7005
+ }
7006
+ function killByThread(threadId) {
7007
+ const entries = getByThread(threadId).filter(
7008
+ (e) => e.state === "running" || e.state === "spawning"
7009
+ );
7010
+ const killed = killEntries(entries);
7011
+ if (killed > 0) {
7012
+ withDb(
7013
+ (db2) => db2.prepare(
7014
+ `UPDATE agent_processes SET state = 'killed', last_activity = ?
7015
+ WHERE thread_id = ? AND state IN ('running', 'spawning')`
7016
+ ).run(Date.now(), threadId)
7017
+ );
7018
+ }
7019
+ return killed;
7020
+ }
7021
+ function killByWorkspace(workspaceId) {
7022
+ const entries = getByWorkspace(workspaceId).filter(
7023
+ (e) => e.state === "running" || e.state === "spawning"
7024
+ );
7025
+ const killed = killEntries(entries);
7026
+ if (killed > 0) {
7027
+ withDb(
7028
+ (db2) => db2.prepare(
7029
+ `UPDATE agent_processes SET state = 'killed', last_activity = ?
7030
+ WHERE workspace_id = ? AND state IN ('running', 'spawning')`
7031
+ ).run(Date.now(), workspaceId)
7032
+ );
7033
+ }
7034
+ return killed;
7035
+ }
7036
+
7037
+ // ../agx-cloud/lib/history-store.ts
7038
+ var import_better_sqlite35 = __toESM(require_lib());
7039
+ var import_fs12 = require("fs");
7040
+ var import_path12 = __toESM(require("path"));
7041
+ var import_os11 = __toESM(require("os"));
7042
+ var HISTORY_DIR2 = process.env.AGX_GROUP_CHAT_DIR?.trim() || import_path12.default.join(import_os11.default.homedir(), ".agx", "group-chat");
7043
+ var DB_PATH3 = import_path12.default.join(HISTORY_DIR2, "history.sqlite");
7044
+ var LEGACY_THREAD_ID = "global";
7045
+ var REACTION_TYPES = /* @__PURE__ */ new Set([
7046
+ "ack",
7047
+ "working",
7048
+ "done",
7049
+ "clarify",
7050
+ "blocked"
7051
+ ]);
7052
+ var ACTIVE_AGENT_PROCESS_STALE_MS = 10 * 60 * 1e3;
7053
+ var ACTIVE_CHAT_RUN_STALE_MS = 10 * 60 * 1e3;
7054
+ var ALLOWED_TRANSITIONS = {
7055
+ ack: /* @__PURE__ */ new Set(["ack", "working"]),
7056
+ working: /* @__PURE__ */ new Set(["ack", "working", "done", "clarify", "blocked"]),
7057
+ done: /* @__PURE__ */ new Set(["done", "ack", "working"]),
7058
+ clarify: /* @__PURE__ */ new Set(["ack", "clarify", "working"]),
7059
+ blocked: /* @__PURE__ */ new Set(["ack", "blocked", "working"])
7060
+ };
7061
+ var ReactionStoreError = class extends Error {
7062
+ status;
7063
+ constructor(message, status) {
7064
+ super(message);
7065
+ this.name = "ReactionStoreError";
7066
+ this.status = status;
7067
+ }
7068
+ };
7069
+ function hasSqliteObject(db2, type, name) {
7070
+ const row = db2.prepare(`SELECT 1 FROM sqlite_master WHERE type = ? AND name = ? LIMIT 1`).get(type, name);
7071
+ return Boolean(row);
7072
+ }
7073
+ function initializeMessageSearch(db2) {
7074
+ const hasFtsTable = hasSqliteObject(db2, "table", "messages_fts");
7075
+ db2.exec(`
7076
+ CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
7077
+ content,
7078
+ content='messages',
7079
+ content_rowid='rowid',
7080
+ tokenize='porter unicode61'
7081
+ );
7082
+ `);
7083
+ db2.exec(`
7084
+ CREATE TRIGGER IF NOT EXISTS messages_ai AFTER INSERT ON messages BEGIN
7085
+ INSERT INTO messages_fts(rowid, content) VALUES (new.rowid, new.content);
7086
+ END;
7087
+ CREATE TRIGGER IF NOT EXISTS messages_ad AFTER DELETE ON messages BEGIN
7088
+ INSERT INTO messages_fts(messages_fts, rowid, content) VALUES('delete', old.rowid, old.content);
7089
+ END;
7090
+ CREATE TRIGGER IF NOT EXISTS messages_au AFTER UPDATE OF content ON messages BEGIN
7091
+ INSERT INTO messages_fts(messages_fts, rowid, content) VALUES('delete', old.rowid, old.content);
7092
+ INSERT INTO messages_fts(rowid, content) VALUES (new.rowid, new.content);
7093
+ END;
7094
+ `);
7095
+ const messageCount = db2.prepare(`SELECT COUNT(*) as count FROM messages`).get().count;
7096
+ if (messageCount === 0) return;
7097
+ const ftsCount = db2.prepare(`SELECT COUNT(*) as count FROM messages_fts`).get().count;
7098
+ const shouldBackfill = !hasFtsTable || ftsCount === 0;
7099
+ if (shouldBackfill) {
7100
+ db2.exec(`INSERT INTO messages_fts(rowid, content) SELECT rowid, content FROM messages;`);
7101
+ }
7102
+ }
7103
+ function isThreadScopedTable(db2, tableName) {
7104
+ const columns = db2.prepare(`PRAGMA table_info(${tableName})`).all();
7105
+ return columns.some((column) => column.name === "thread_id");
7106
+ }
7107
+ function migrateThreadReplyColumns(db2) {
7108
+ const columns = db2.prepare(`PRAGMA table_info(messages)`).all();
7109
+ const colNames = new Set(columns.map((c) => c.name));
7110
+ if (!colNames.has("root_message_id")) {
7111
+ db2.exec(`
7112
+ ALTER TABLE messages ADD COLUMN root_message_id TEXT;
7113
+ ALTER TABLE messages ADD COLUMN parent_message_id TEXT;
7114
+ ALTER TABLE messages ADD COLUMN depth INTEGER NOT NULL DEFAULT 0;
7115
+ CREATE INDEX IF NOT EXISTS idx_messages_root ON messages(thread_id, root_message_id);
7116
+ `);
7117
+ }
7118
+ }
7119
+ function migrateThreadStatusColumns(db2) {
7120
+ const columns = db2.prepare(`PRAGMA table_info(messages)`).all();
7121
+ const colNames = new Set(columns.map((c) => c.name));
7122
+ if (!colNames.has("thread_status")) {
7123
+ db2.exec(`
7124
+ ALTER TABLE messages ADD COLUMN thread_status TEXT;
7125
+ ALTER TABLE messages ADD COLUMN outcome_note TEXT;
7126
+ `);
7127
+ }
7128
+ }
7129
+ function migrateReactionHostPidColumn(db2) {
7130
+ const columns = db2.prepare(`PRAGMA table_info(message_reactions)`).all();
7131
+ const colNames = new Set(columns.map((c) => c.name));
7132
+ if (!colNames.has("host_pid")) {
7133
+ db2.exec(`ALTER TABLE message_reactions ADD COLUMN host_pid INTEGER`);
7134
+ }
7135
+ if (!colNames.has("response_message_id")) {
7136
+ db2.exec(`ALTER TABLE message_reactions ADD COLUMN response_message_id TEXT`);
7137
+ }
7138
+ }
7139
+ function migrateLogsToAgentProcessId(db2) {
7140
+ const columns = db2.prepare(`PRAGMA table_info(logs)`).all();
7141
+ const colNames = new Set(columns.map((c) => c.name));
7142
+ if (colNames.has("agent_process_id")) return;
7143
+ db2.exec(`
7144
+ DROP TABLE IF EXISTS logs;
7145
+ CREATE TABLE logs (
7146
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
7147
+ agent_process_id INTEGER NOT NULL,
7148
+ stream TEXT NOT NULL,
7149
+ line TEXT NOT NULL,
7150
+ timestamp INTEGER NOT NULL
7151
+ );
7152
+ `);
7153
+ }
7154
+ function migrateAgentProcessesAddId(db2) {
7155
+ const columns = db2.prepare(`PRAGMA table_info(agent_processes)`).all();
7156
+ if (columns.length === 0) return;
7157
+ const colNames = new Set(columns.map((c) => c.name));
7158
+ if (colNames.has("id")) return;
7159
+ db2.exec(`
7160
+ DROP TABLE IF EXISTS agent_processes;
7161
+ CREATE TABLE agent_processes (
7162
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
7163
+ workspace_id TEXT NOT NULL,
7164
+ thread_id TEXT NOT NULL DEFAULT '',
7165
+ agent_id TEXT NOT NULL,
7166
+ pid INTEGER NOT NULL DEFAULT 0,
7167
+ state TEXT NOT NULL DEFAULT 'spawning',
7168
+ since_message_id TEXT NOT NULL DEFAULT '',
7169
+ started_at INTEGER NOT NULL DEFAULT 0,
7170
+ last_activity INTEGER NOT NULL DEFAULT 0,
7171
+ project_slug TEXT NOT NULL DEFAULT '',
7172
+ UNIQUE (workspace_id, agent_id)
7173
+ );
7174
+ CREATE INDEX IF NOT EXISTS idx_agent_processes_state ON agent_processes (state);
7175
+ CREATE INDEX IF NOT EXISTS idx_agent_processes_thread ON agent_processes (thread_id);
7176
+ CREATE INDEX IF NOT EXISTS idx_agent_processes_workspace ON agent_processes (workspace_id);
7177
+ `);
7178
+ }
7179
+ function parseJsonObject3(value) {
7180
+ if (!value) return null;
7181
+ try {
7182
+ const parsed = JSON.parse(value);
7183
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
7184
+ } catch {
7185
+ return null;
7186
+ }
7187
+ }
7188
+ function parseJsonStringArray(value) {
7189
+ if (!value) return [];
7190
+ try {
7191
+ const parsed = JSON.parse(value);
7192
+ return Array.isArray(parsed) ? parsed.filter((item) => typeof item === "string") : [];
7193
+ } catch {
7194
+ return [];
7195
+ }
7196
+ }
7197
+ function toChatRunRecord(row) {
7198
+ return {
7199
+ id: row.id,
7200
+ threadId: row.thread_id,
7201
+ rootMessageId: row.root_message_id,
7202
+ userId: row.user_id,
7203
+ projectSlug: row.project_slug,
7204
+ status: row.status,
7205
+ currentStep: row.current_step,
7206
+ maxSteps: row.max_steps,
7207
+ stepsUsed: row.steps_used,
7208
+ lastError: row.last_error,
7209
+ activeParticipantIds: parseJsonStringArray(row.active_participant_ids),
7210
+ payload: parseJsonObject3(row.payload_json),
7211
+ result: parseJsonObject3(row.result_json),
7212
+ createdAt: row.created_at,
7213
+ updatedAt: row.updated_at,
7214
+ completedAt: row.completed_at
7215
+ };
7216
+ }
7217
+ function toChatRunStepRecord(row) {
7218
+ return {
7219
+ id: row.id,
7220
+ chatRunId: row.chat_run_id,
7221
+ stepIndex: row.step_index,
7222
+ kind: row.kind,
7223
+ status: row.status,
7224
+ participantId: row.participant_id,
7225
+ inputPayload: parseJsonObject3(row.input_payload_json),
7226
+ outputPayload: parseJsonObject3(row.output_payload_json),
7227
+ startedAt: row.started_at,
7228
+ completedAt: row.completed_at
7229
+ };
7230
+ }
7231
+ function migrateLegacyTables(db2) {
7232
+ if (!isThreadScopedTable(db2, "messages")) {
7233
+ db2.exec(`
7234
+ ALTER TABLE messages RENAME TO messages_legacy;
7235
+ CREATE TABLE messages (
7236
+ thread_id TEXT NOT NULL,
7237
+ id TEXT NOT NULL,
7238
+ role TEXT NOT NULL,
7239
+ participant_id TEXT,
7240
+ content TEXT NOT NULL,
7241
+ timestamp INTEGER NOT NULL,
7242
+ PRIMARY KEY (thread_id, id)
7243
+ );
7244
+ INSERT INTO messages (thread_id, id, role, participant_id, content, timestamp)
7245
+ SELECT '${LEGACY_THREAD_ID}', id, role, participant_id, content, timestamp
7246
+ FROM messages_legacy;
7247
+ DROP TABLE messages_legacy;
7248
+ `);
7249
+ }
7250
+ if (!isThreadScopedTable(db2, "message_reactions")) {
7251
+ db2.exec(`
7252
+ ALTER TABLE message_reactions RENAME TO message_reactions_legacy;
7253
+ CREATE TABLE message_reactions (
7254
+ thread_id TEXT NOT NULL,
7255
+ message_id TEXT NOT NULL,
7256
+ participant_id TEXT NOT NULL,
7257
+ type TEXT NOT NULL,
7258
+ reason TEXT,
7259
+ blocker_code TEXT,
7260
+ host_pid INTEGER,
7261
+ response_message_id TEXT,
7262
+ updated_at INTEGER NOT NULL,
7263
+ PRIMARY KEY (thread_id, message_id, participant_id)
7264
+ );
7265
+ INSERT INTO message_reactions (thread_id, message_id, participant_id, type, reason, blocker_code, host_pid, updated_at)
7266
+ SELECT '${LEGACY_THREAD_ID}', message_id, participant_id, type, reason, blocker_code, NULL, updated_at
7267
+ FROM message_reactions_legacy;
7268
+ DROP TABLE message_reactions_legacy;
7269
+ `);
7270
+ }
7271
+ migrateLogsToAgentProcessId(db2);
7272
+ }
7273
+ var withDatabase = async (run) => {
7274
+ await import_fs12.promises.mkdir(HISTORY_DIR2, { recursive: true });
7275
+ const db2 = new import_better_sqlite35.default(DB_PATH3);
7276
+ db2.pragma("journal_mode = WAL");
7277
+ try {
7278
+ db2.exec(`
7279
+ CREATE TABLE IF NOT EXISTS messages (
7280
+ thread_id TEXT NOT NULL,
7281
+ id TEXT NOT NULL,
7282
+ role TEXT NOT NULL,
7283
+ participant_id TEXT,
7284
+ content TEXT NOT NULL,
7285
+ timestamp INTEGER NOT NULL,
7286
+ PRIMARY KEY (thread_id, id)
7287
+ );
7288
+ CREATE TABLE IF NOT EXISTS message_reactions (
7289
+ thread_id TEXT NOT NULL,
7290
+ message_id TEXT NOT NULL,
7291
+ participant_id TEXT NOT NULL,
7292
+ type TEXT NOT NULL,
7293
+ reason TEXT,
7294
+ blocker_code TEXT,
7295
+ host_pid INTEGER,
7296
+ response_message_id TEXT,
7297
+ updated_at INTEGER NOT NULL,
7298
+ PRIMARY KEY (thread_id, message_id, participant_id)
7299
+ );
7300
+ CREATE TABLE IF NOT EXISTS agent_processes (
7301
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
7302
+ workspace_id TEXT NOT NULL,
7303
+ thread_id TEXT NOT NULL DEFAULT '',
7304
+ agent_id TEXT NOT NULL,
7305
+ pid INTEGER NOT NULL DEFAULT 0,
7306
+ state TEXT NOT NULL DEFAULT 'spawning',
7307
+ since_message_id TEXT NOT NULL DEFAULT '',
7308
+ started_at INTEGER NOT NULL DEFAULT 0,
7309
+ last_activity INTEGER NOT NULL DEFAULT 0,
7310
+ project_slug TEXT NOT NULL DEFAULT '',
7311
+ UNIQUE (workspace_id, agent_id)
7312
+ );
7313
+ CREATE TABLE IF NOT EXISTS logs (
7314
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
7315
+ agent_process_id INTEGER NOT NULL,
7316
+ stream TEXT NOT NULL,
7317
+ line TEXT NOT NULL,
7318
+ timestamp INTEGER NOT NULL
7319
+ );
7320
+ CREATE TABLE IF NOT EXISTS task_drafts (
7321
+ thread_id TEXT NOT NULL,
7322
+ message_id TEXT NOT NULL,
7323
+ data TEXT NOT NULL,
7324
+ updated_at INTEGER NOT NULL,
7325
+ PRIMARY KEY (thread_id, message_id)
7326
+ );
7327
+ CREATE TABLE IF NOT EXISTS chat_runs (
7328
+ id TEXT PRIMARY KEY,
7329
+ thread_id TEXT NOT NULL,
7330
+ root_message_id TEXT,
7331
+ user_id TEXT NOT NULL,
7332
+ project_slug TEXT,
7333
+ status TEXT NOT NULL,
7334
+ current_step INTEGER NOT NULL DEFAULT 0,
7335
+ max_steps INTEGER NOT NULL DEFAULT 10,
7336
+ steps_used INTEGER NOT NULL DEFAULT 0,
7337
+ last_error TEXT,
7338
+ active_participant_ids TEXT NOT NULL DEFAULT '[]',
7339
+ payload_json TEXT,
7340
+ result_json TEXT,
7341
+ created_at INTEGER NOT NULL,
7342
+ updated_at INTEGER NOT NULL,
7343
+ completed_at INTEGER
7344
+ );
7345
+ CREATE TABLE IF NOT EXISTS chat_run_steps (
7346
+ id TEXT PRIMARY KEY,
7347
+ chat_run_id TEXT NOT NULL,
7348
+ step_index INTEGER NOT NULL,
7349
+ kind TEXT NOT NULL,
7350
+ status TEXT NOT NULL,
7351
+ participant_id TEXT,
7352
+ input_payload_json TEXT,
7353
+ output_payload_json TEXT,
7354
+ started_at INTEGER NOT NULL,
7355
+ completed_at INTEGER
7356
+ );
7357
+ `);
7358
+ migrateLegacyTables(db2);
7359
+ migrateThreadReplyColumns(db2);
7360
+ migrateThreadStatusColumns(db2);
7361
+ migrateReactionHostPidColumn(db2);
7362
+ db2.exec("UPDATE messages SET thread_status = 'in-review' WHERE thread_status = 'parked'");
7363
+ db2.exec("UPDATE messages SET thread_status = 'active' WHERE thread_status = 'thinking'");
7364
+ db2.exec("UPDATE messages SET thread_status = 'done' WHERE thread_status = 'resolved'");
7365
+ db2.exec("UPDATE messages SET thread_status = 'active' WHERE thread_status = 'converged'");
7366
+ migrateAgentProcessesAddId(db2);
7367
+ initializeMessageSearch(db2);
7368
+ db2.exec(`
7369
+ CREATE INDEX IF NOT EXISTS idx_messages_thread_ts ON messages(thread_id, timestamp ASC);
7370
+ CREATE INDEX IF NOT EXISTS idx_reactions_thread_message ON message_reactions(thread_id, message_id, updated_at ASC);
7371
+ CREATE INDEX IF NOT EXISTS idx_logs_process_ts ON logs(agent_process_id, timestamp ASC);
7372
+ CREATE INDEX IF NOT EXISTS idx_chat_runs_thread_updated ON chat_runs(thread_id, updated_at DESC);
7373
+ CREATE INDEX IF NOT EXISTS idx_chat_runs_status_updated ON chat_runs(status, updated_at DESC);
7374
+ CREATE INDEX IF NOT EXISTS idx_chat_run_steps_run_step ON chat_run_steps(chat_run_id, step_index ASC);
7375
+ `);
7376
+ return run(db2);
7377
+ } finally {
7378
+ db2.close();
7379
+ }
7380
+ };
7381
+ function aggregateReactionRows(rows) {
7382
+ const perMessage = /* @__PURE__ */ new Map();
7383
+ for (const row of rows) {
7384
+ let byType = perMessage.get(row.message_id);
7385
+ if (!byType) {
7386
+ byType = /* @__PURE__ */ new Map();
7387
+ perMessage.set(row.message_id, byType);
7388
+ }
7389
+ let reaction = byType.get(row.type);
7390
+ if (!reaction) {
7391
+ reaction = { type: row.type, count: 0, participantIds: [] };
7392
+ byType.set(row.type, reaction);
7393
+ }
7394
+ reaction.count += 1;
7395
+ reaction.participantIds.push(row.participant_id);
7396
+ }
7397
+ const out = /* @__PURE__ */ new Map();
7398
+ for (const [messageId, byType] of perMessage.entries()) {
7399
+ const sorted = Array.from(byType.values()).sort((a, b) => {
7400
+ if (b.count !== a.count) return b.count - a.count;
7401
+ return a.type.localeCompare(b.type);
7402
+ });
7403
+ out.set(messageId, sorted);
7404
+ }
7405
+ return out;
7406
+ }
7407
+ function loadMessageReactions(db2, threadId, messageIds) {
7408
+ if (messageIds && messageIds.length === 0) return /* @__PURE__ */ new Map();
7409
+ if (messageIds) {
7410
+ const placeholders = messageIds.map(() => "?").join(", ");
7411
+ const rows2 = db2.prepare(
7412
+ `SELECT message_id, participant_id, type
7413
+ FROM message_reactions
7414
+ WHERE thread_id = ? AND message_id IN (${placeholders})
7415
+ ORDER BY updated_at ASC`
7416
+ ).all(threadId, ...messageIds);
7417
+ return aggregateReactionRows(rows2);
7418
+ }
7419
+ const rows = db2.prepare(
7420
+ `SELECT message_id, participant_id, type
7421
+ FROM message_reactions
7422
+ WHERE thread_id = ?
7423
+ ORDER BY updated_at ASC`
7424
+ ).all(threadId);
7425
+ return aggregateReactionRows(rows);
7426
+ }
7427
+ function normalizeOptionalText(value) {
7428
+ if (typeof value !== "string") return null;
7429
+ const trimmed = value.trim();
7430
+ return trimmed.length > 0 ? trimmed : null;
7431
+ }
7432
+ function normalizeOptionalHostPid(value) {
7433
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) return null;
7434
+ return value;
7435
+ }
7436
+ function isAllowedTransition(from, to) {
7437
+ if (!from) return true;
7438
+ return ALLOWED_TRANSITIONS[from].has(to);
7439
+ }
7440
+ async function saveMessages(threadId, messages) {
7441
+ if (messages.length === 0) return;
7442
+ const normalizedThreadId = threadId.trim() || LEGACY_THREAD_ID;
7443
+ await withDatabase((db2) => {
7444
+ const stmt = db2.prepare(
7445
+ `INSERT OR REPLACE INTO messages (thread_id, id, role, participant_id, content, timestamp, root_message_id, parent_message_id, depth, thread_status, outcome_note)
7446
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
7447
+ );
7448
+ const insertMany = db2.transaction((msgs) => {
7449
+ for (const m of msgs) {
7450
+ stmt.run(normalizedThreadId, m.id, m.role, m.participantId, m.content, m.timestamp, m.rootMessageId ?? null, m.parentMessageId ?? null, m.depth ?? 0, m.threadStatus ?? null, m.outcomeNote ?? null);
7451
+ }
7452
+ });
7453
+ insertMany(messages);
7454
+ });
7455
+ }
7456
+ async function sweepStaleChatRuns(input) {
7457
+ const normalizedThreadId = normalizeOptionalText(input?.threadId ?? null);
7458
+ const thresholdMs = Number.isFinite(input?.olderThanMs) ? Math.max(input.olderThanMs, 1) : ACTIVE_CHAT_RUN_STALE_MS;
7459
+ const now = Date.now();
7460
+ const cutoff = now - thresholdMs;
7461
+ return withDatabase((db2) => {
7462
+ const clauses = ["status = 'running'", "updated_at <= ?"];
7463
+ const params = [cutoff];
7464
+ if (normalizedThreadId) {
7465
+ clauses.push("thread_id = ?");
7466
+ params.push(normalizedThreadId);
7467
+ }
7468
+ const result = db2.prepare(
7469
+ `UPDATE chat_runs
7470
+ SET status = 'failed',
7471
+ last_error = COALESCE(NULLIF(last_error, ''), 'Worker process died mid-execution'),
7472
+ updated_at = ?,
7473
+ completed_at = COALESCE(completed_at, ?)
7474
+ WHERE ${clauses.join(" AND ")}`
7475
+ ).run(now, now, ...params);
7476
+ return result.changes;
7477
+ });
7478
+ }
7479
+ async function getChatRun(chatRunId) {
7480
+ await sweepStaleChatRuns();
7481
+ return withDatabase((db2) => {
7482
+ const row = db2.prepare("SELECT * FROM chat_runs WHERE id = ? LIMIT 1").get(chatRunId);
7483
+ return row ? toChatRunRecord(row) : null;
7484
+ });
7485
+ }
7486
+ async function updateChatRun(input) {
7487
+ return withDatabase((db2) => {
7488
+ const updates = ["updated_at = ?"];
7489
+ const params = [Date.now()];
7490
+ if (input.status) {
7491
+ updates.push("status = ?");
7492
+ params.push(input.status);
7493
+ }
7494
+ if (typeof input.currentStep === "number") {
7495
+ updates.push("current_step = ?");
7496
+ params.push(input.currentStep);
7497
+ }
7498
+ if (typeof input.stepsUsed === "number") {
7499
+ updates.push("steps_used = ?");
7500
+ params.push(input.stepsUsed);
7501
+ }
7502
+ if (input.lastError !== void 0) {
7503
+ updates.push("last_error = ?");
7504
+ params.push(normalizeOptionalText(input.lastError));
7505
+ }
7506
+ if (input.payload !== void 0) {
7507
+ updates.push("payload_json = ?");
7508
+ params.push(input.payload ? JSON.stringify(input.payload) : null);
7509
+ }
7510
+ if (input.result !== void 0) {
7511
+ updates.push("result_json = ?");
7512
+ params.push(input.result ? JSON.stringify(input.result) : null);
7513
+ }
7514
+ if (input.completedAt !== void 0) {
7515
+ updates.push("completed_at = ?");
7516
+ params.push(input.completedAt);
7517
+ }
7518
+ params.push(input.id);
7519
+ db2.prepare(`UPDATE chat_runs SET ${updates.join(", ")} WHERE id = ?`).run(...params);
7520
+ const row = db2.prepare("SELECT * FROM chat_runs WHERE id = ? LIMIT 1").get(input.id);
7521
+ return row ? toChatRunRecord(row) : null;
7522
+ });
7523
+ }
7524
+ async function appendChatRunStep(input) {
7525
+ const now = Date.now();
7526
+ return withDatabase((db2) => {
7527
+ db2.prepare(
7528
+ `INSERT INTO chat_run_steps (
7529
+ id, chat_run_id, step_index, kind, status, participant_id,
7530
+ input_payload_json, output_payload_json, started_at, completed_at
7531
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
7532
+ ).run(
7533
+ input.id,
7534
+ input.chatRunId,
7535
+ input.stepIndex,
7536
+ input.kind,
7537
+ input.status,
7538
+ normalizeOptionalText(input.participantId),
7539
+ input.inputPayload ? JSON.stringify(input.inputPayload) : null,
7540
+ input.outputPayload ? JSON.stringify(input.outputPayload) : null,
7541
+ now,
7542
+ input.status === "completed" || input.status === "failed" ? now : null
7543
+ );
7544
+ const row = db2.prepare("SELECT * FROM chat_run_steps WHERE id = ? LIMIT 1").get(input.id);
7545
+ if (!row) {
7546
+ throw new Error(`Failed to append chat run step ${input.id}`);
7547
+ }
7548
+ return toChatRunStepRecord(row);
7549
+ });
7550
+ }
7551
+ async function updateChatRunStep(input) {
7552
+ return withDatabase((db2) => {
7553
+ const updates = [];
7554
+ const params = [];
7555
+ if (input.status) {
7556
+ updates.push("status = ?");
7557
+ params.push(input.status);
7558
+ }
7559
+ if (input.outputPayload !== void 0) {
7560
+ updates.push("output_payload_json = ?");
7561
+ params.push(input.outputPayload ? JSON.stringify(input.outputPayload) : null);
7562
+ }
7563
+ if (input.completedAt !== void 0) {
7564
+ updates.push("completed_at = ?");
7565
+ params.push(input.completedAt);
7566
+ }
7567
+ if (updates.length === 0) {
7568
+ const existing = db2.prepare("SELECT * FROM chat_run_steps WHERE id = ? LIMIT 1").get(input.id);
7569
+ return existing ? toChatRunStepRecord(existing) : null;
7570
+ }
7571
+ params.push(input.id);
7572
+ db2.prepare(`UPDATE chat_run_steps SET ${updates.join(", ")} WHERE id = ?`).run(...params);
7573
+ const row = db2.prepare("SELECT * FROM chat_run_steps WHERE id = ? LIMIT 1").get(input.id);
7574
+ return row ? toChatRunStepRecord(row) : null;
7575
+ });
7576
+ }
7577
+ async function listChatRunSteps(chatRunId) {
7578
+ return withDatabase((db2) => {
7579
+ const rows = db2.prepare("SELECT * FROM chat_run_steps WHERE chat_run_id = ? ORDER BY step_index ASC, started_at ASC").all(chatRunId);
7580
+ return rows.map(toChatRunStepRecord);
7581
+ });
7582
+ }
7583
+ async function setReaction(input) {
7584
+ const threadId = input.threadId?.trim() || LEGACY_THREAD_ID;
7585
+ const messageId = input.messageId?.trim();
7586
+ const participantId = input.participantId?.trim();
7587
+ const type = input.type;
7588
+ if (!messageId) {
7589
+ throw new ReactionStoreError("messageId is required", 400);
7590
+ }
7591
+ if (!participantId) {
7592
+ throw new ReactionStoreError("participantId is required", 400);
7593
+ }
7594
+ if (!REACTION_TYPES.has(type)) {
7595
+ throw new ReactionStoreError(`Invalid reaction type: ${String(type)}`, 400);
7596
+ }
7597
+ const incomingReason = normalizeOptionalText(input.reason);
7598
+ const incomingBlockerCode = normalizeOptionalText(input.blockerCode);
7599
+ const hostPid = normalizeOptionalHostPid(input.hostPid);
7600
+ const responseMessageId = normalizeOptionalText(input.responseMessageId);
7601
+ const needsReason = type === "clarify" || type === "blocked";
7602
+ if (needsReason && !incomingReason) {
7603
+ throw new ReactionStoreError(`"${type}" reactions require a reason`, 400);
7604
+ }
7605
+ const reason = needsReason ? incomingReason : null;
7606
+ const blockerCode = type === "blocked" ? incomingBlockerCode : null;
7607
+ return withDatabase((db2) => {
7608
+ const messageExists = db2.prepare(`SELECT 1 FROM messages WHERE thread_id = ? AND id = ? LIMIT 1`).get(threadId, messageId);
7609
+ if (!messageExists) {
7610
+ throw new ReactionStoreError(`Message not found: ${messageId}`, 404);
7611
+ }
7612
+ const existing = db2.prepare(
7613
+ `SELECT type, reason, blocker_code, host_pid
7614
+ FROM message_reactions
7615
+ WHERE thread_id = ? AND message_id = ? AND participant_id = ?`
7616
+ ).get(threadId, messageId, participantId);
7617
+ if (!isAllowedTransition(existing?.type ?? null, type)) {
7618
+ throw new ReactionStoreError(
7619
+ `Cannot transition reaction from "${existing.type}" to "${type}"`,
7620
+ 409
7621
+ );
7622
+ }
7623
+ const unchanged = existing && existing.type === type && normalizeOptionalText(existing.reason) === reason && normalizeOptionalText(existing.blocker_code) === blockerCode && normalizeOptionalHostPid(existing.host_pid) === hostPid;
7624
+ if (unchanged) {
7625
+ return {
7626
+ updated: false,
7627
+ reactions: loadMessageReactions(db2, threadId, [messageId]).get(messageId) ?? []
7628
+ };
7629
+ }
7630
+ const now = Date.now();
7631
+ db2.prepare(
7632
+ `INSERT INTO message_reactions (thread_id, message_id, participant_id, type, reason, blocker_code, host_pid, response_message_id, updated_at)
7633
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
7634
+ ON CONFLICT(thread_id, message_id, participant_id)
7635
+ DO UPDATE SET
7636
+ type = excluded.type,
7637
+ reason = excluded.reason,
7638
+ blocker_code = excluded.blocker_code,
7639
+ host_pid = excluded.host_pid,
7640
+ response_message_id = COALESCE(excluded.response_message_id, message_reactions.response_message_id),
7641
+ updated_at = excluded.updated_at`
7642
+ ).run(threadId, messageId, participantId, type, reason, blockerCode, hostPid, responseMessageId, now);
7643
+ return {
7644
+ updated: true,
7645
+ reactions: loadMessageReactions(db2, threadId, [messageId]).get(messageId) ?? []
7646
+ };
7647
+ });
7648
+ }
7649
+ async function saveLogs(agentProcessId, entries) {
7650
+ if (entries.length === 0 || !agentProcessId) return;
7651
+ return withDatabase((db2) => {
7652
+ const stmt = db2.prepare(
7653
+ "INSERT INTO logs (agent_process_id, stream, line, timestamp) VALUES (?, ?, ?, ?)"
7654
+ );
7655
+ const tx = db2.transaction(() => {
7656
+ for (const e of entries) {
7657
+ stmt.run(agentProcessId, e.stream, e.line, e.timestamp);
7658
+ }
7659
+ });
7660
+ tx();
7661
+ });
7662
+ }
7663
+
7664
+ // ../agx-cloud/lib/reaction-protocol.ts
7665
+ var REACTION_TYPES2 = /* @__PURE__ */ new Set([
7666
+ "ack",
7667
+ "working",
7668
+ "done",
7669
+ "clarify",
7670
+ "blocked"
7671
+ ]);
7672
+ var TAG_REGEX = /\[reaction\s+([^\]]+)\]/gi;
7673
+ var ATTR_REGEX = /([a-zA-Z][a-zA-Z0-9_]*)=(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|([^\s\]]*?(?=\s|]|[a-zA-Z][a-zA-Z0-9_]*=|$)))/g;
7674
+ function decodeAttrValue(value) {
7675
+ return value.replace(/\\(["'\\])/g, "$1").trim();
7676
+ }
7677
+ function parseAttributes(raw) {
7678
+ const attrs = /* @__PURE__ */ new Map();
7679
+ ATTR_REGEX.lastIndex = 0;
7680
+ for (; ; ) {
7681
+ const match = ATTR_REGEX.exec(raw);
7682
+ if (!match) break;
7683
+ const key = match[1].toLowerCase();
7684
+ const quotedDouble = match[2];
7685
+ const quotedSingle = match[3];
7686
+ const bare = match[4];
7687
+ const value = decodeAttrValue(quotedDouble ?? quotedSingle ?? bare ?? "");
7688
+ attrs.set(key, value);
7689
+ }
7690
+ return attrs;
7691
+ }
7692
+ function parseReactionSignals(content) {
7693
+ const signals = [];
7694
+ const invalid = [];
7695
+ const cleanedText = content.replace(TAG_REGEX, (rawTag, attrsRaw) => {
7696
+ const attrs = parseAttributes(String(attrsRaw));
7697
+ const target = (attrs.get("target") || "").trim();
7698
+ const typeRaw = (attrs.get("type") || "").trim().toLowerCase();
7699
+ const reason = (attrs.get("reason") || "").trim();
7700
+ const blockerCode = (attrs.get("blockercode") || attrs.get("blocker_code") || "").trim();
7701
+ if (!target) {
7702
+ invalid.push({ raw: rawTag, error: "Missing target" });
7703
+ return "";
7704
+ }
7705
+ if (!REACTION_TYPES2.has(typeRaw)) {
7706
+ invalid.push({ raw: rawTag, error: `Invalid type: ${typeRaw || "(empty)"}` });
7707
+ return "";
7708
+ }
7709
+ const type = typeRaw;
7710
+ if ((type === "clarify" || type === "blocked") && !reason) {
7711
+ invalid.push({ raw: rawTag, error: `"${type}" requires reason` });
7712
+ return "";
7713
+ }
7714
+ signals.push({
7715
+ raw: rawTag,
7716
+ target,
7717
+ type,
7718
+ reason: reason || void 0,
7719
+ blockerCode: type === "blocked" ? blockerCode || void 0 : void 0
7720
+ });
7721
+ return "";
7722
+ }).replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
7723
+ return { signals, invalid, cleanedText };
7724
+ }
7725
+
7726
+ // ../agx-cloud/lib/attachment-store.ts
7727
+ var import_better_sqlite36 = __toESM(require_lib());
7728
+ var import_path13 = __toESM(require("path"));
7729
+ var import_os12 = __toESM(require("os"));
7730
+ var HISTORY_DIR3 = process.env.AGX_GROUP_CHAT_DIR?.trim() || import_path13.default.join(import_os12.default.homedir(), ".agx", "group-chat");
7731
+ var DB_PATH4 = import_path13.default.join(HISTORY_DIR3, "history.sqlite");
7732
+ var UPLOADS_DIR = import_path13.default.join(HISTORY_DIR3, "uploads");
7733
+ function getDb3() {
7734
+ const db2 = new import_better_sqlite36.default(DB_PATH4);
7735
+ db2.pragma("journal_mode = WAL");
7736
+ return db2;
7737
+ }
7738
+ function initAttachmentsTable(db2) {
7739
+ db2.exec(`
7740
+ CREATE TABLE IF NOT EXISTS attachments (
7741
+ id TEXT PRIMARY KEY,
7742
+ message_id TEXT,
7743
+ filename TEXT NOT NULL,
7744
+ disk_name TEXT NOT NULL,
7745
+ mime_type TEXT NOT NULL,
7746
+ size INTEGER NOT NULL,
7747
+ status TEXT NOT NULL DEFAULT 'uploaded',
7748
+ created_at INTEGER NOT NULL
7749
+ );
7750
+ CREATE INDEX IF NOT EXISTS idx_attachments_message ON attachments(message_id);
7751
+ `);
7752
+ const cols = db2.prepare("PRAGMA table_info(attachments)").all();
7753
+ if (!cols.some((c) => c.name === "disk_name")) {
7754
+ db2.exec(`ALTER TABLE attachments ADD COLUMN disk_name TEXT NOT NULL DEFAULT ''`);
7755
+ const rows = db2.prepare("SELECT id, filename FROM attachments WHERE disk_name = ''").all();
7756
+ const stmt = db2.prepare("UPDATE attachments SET disk_name = ? WHERE id = ?");
7757
+ for (const r of rows) {
7758
+ const ext = r.filename.includes(".") ? "." + r.filename.split(".").pop().toLowerCase() : "";
7759
+ stmt.run(r.id + ext, r.id);
7760
+ }
7761
+ }
7762
+ }
7763
+ async function getAttachmentMeta(id) {
7764
+ const db2 = getDb3();
7765
+ try {
7766
+ initAttachmentsTable(db2);
7767
+ const row = db2.prepare(
7768
+ `SELECT filename, disk_name, mime_type, size FROM attachments WHERE id = ?`
7769
+ ).get(id);
7770
+ if (!row) return null;
7771
+ const diskName = row.disk_name || id;
7772
+ return { filename: row.filename, mimeType: row.mime_type, size: row.size, diskPath: import_path13.default.join(UPLOADS_DIR, diskName) };
7773
+ } finally {
7774
+ db2.close();
7775
+ }
7776
+ }
7777
+
7778
+ // ../agx-cloud/lib/stream-multiplexer.ts
7779
+ init_sqlite_query_adapter();
7780
+ init_self();
7781
+ init_journal();
7782
+ init_agent();
7783
+
7784
+ // ../agx-cloud/lib/mesh-core/reactions.ts
7785
+ var import_fs13 = require("fs");
7786
+ var import_path14 = require("path");
7787
+ var import_os13 = require("os");
7788
+ init_journal();
7789
+ init_activity();
7790
+ var AGENTS_DIR6 = (0, import_path14.join)((0, import_os13.homedir)(), ".agx", "agents");
7791
+ function reactionsPath(agentId) {
7792
+ return (0, import_path14.join)(AGENTS_DIR6, agentId, "reactions.jsonl");
7793
+ }
7794
+ function ensureDir2(agentId) {
7795
+ const dir = (0, import_path14.join)(AGENTS_DIR6, agentId);
7796
+ if (!(0, import_fs13.existsSync)(dir)) (0, import_fs13.mkdirSync)(dir, { recursive: true });
7797
+ }
7798
+ function targetEntryExists(targetEntry) {
7799
+ const [targetAgent] = targetEntry.split(":");
7800
+ if (!targetAgent) return false;
7801
+ const entries = readJournal(targetAgent);
7802
+ return entries.some((e) => e.id === targetEntry);
7803
+ }
7804
+ function appendReaction(agentId, targetEntry, type) {
7805
+ if (!targetEntryExists(targetEntry)) {
7806
+ throw new Error(`Target entry ${targetEntry} not found`);
7807
+ }
7808
+ ensureDir2(agentId);
7809
+ const reaction = {
7810
+ agent: agentId,
7811
+ t: (/* @__PURE__ */ new Date()).toISOString(),
7812
+ targetEntry,
7813
+ type
7814
+ };
7815
+ (0, import_fs13.appendFileSync)(reactionsPath(agentId), JSON.stringify(reaction) + "\n", "utf-8");
7816
+ logActivity(agentId, "mesh-reaction", { meta: { target: targetEntry, type } });
7817
+ }
7818
+
7819
+ // ../agx-cloud/lib/stream-multiplexer.ts
7820
+ init_activity();
7821
+ var import_crypto5 = require("crypto");
7822
+ var agentMessageCounts = /* @__PURE__ */ new Map();
7823
+ var reflectionQueues = /* @__PURE__ */ new Map();
7824
+ var REFLECTION_CADENCE = 10;
7825
+ function isKnowledgeEvidence(value) {
7826
+ return value !== null;
7827
+ }
7828
+ function seedFromIdentityText(identity, name) {
7829
+ const raw = String(identity || "").trim();
7830
+ if (!raw) return `I am ${name}. I evolve through experience and collaboration.`;
7831
+ return `I am ${name}. I evolve through experience and collaboration.`;
7832
+ }
7833
+ function derivePerMessageJournalInsights(response) {
7834
+ const text = response.trim();
7835
+ const preview = text.slice(0, 120).replace(/\n/g, " ");
7836
+ const hasQuestion = /\?/.test(text);
7837
+ const mentions = text.match(/@\w+/g) || [];
7838
+ const hasAction = /\b(should|need to|must|plan|steps?|implement|fix|verify|ship|next|start)\b/i.test(text);
7839
+ const hasUncertainty = /\b(maybe|might|could|unsure|not sure|unclear)\b/i.test(text);
7840
+ const hasCommitment = /\b(i will|i'll|i can|i'm going to|starting|checking|verified|fixed|done|shipped)\b/i.test(text);
7841
+ const hasCode = /```/.test(text) || /\bfunction\b|\bconst\b|\binterface\b/i.test(text);
7842
+ const hasSpec = /\|.*\|.*\|/.test(text) || /^#{1,3}\s/m.test(text);
7843
+ const hasReview = /\b(finding|issue|bug|problem|missing|broken|wrong)\b/i.test(text);
7844
+ let judgement;
7845
+ if (hasCode && hasSpec) {
7846
+ judgement = `Observed a structured technical response with code or implementation detail \u2014 "${preview}..."`;
7847
+ } else if (hasCode) {
7848
+ judgement = `Observed code-centric output \u2014 "${preview}..."`;
7849
+ } else if (hasSpec) {
7850
+ judgement = `Observed structured analysis or specification language \u2014 "${preview}..."`;
7851
+ } else if (hasReview) {
7852
+ judgement = `Observed review or issue-spotting behavior \u2014 "${preview}..."`;
7853
+ } else if (hasCommitment) {
7854
+ judgement = `Observed a concrete commitment to action \u2014 "${preview}..."`;
7855
+ } else if (hasAction) {
7856
+ judgement = `Observed direction-setting or next-step guidance \u2014 "${preview}..."`;
7857
+ } else if (hasQuestion) {
7858
+ judgement = `Observed clarifying or exploratory questioning \u2014 "${preview}..."`;
7859
+ } else if (hasUncertainty) {
7860
+ judgement = `Observed explicit uncertainty or caveating \u2014 "${preview}..."`;
7861
+ } else if (mentions.length > 0) {
7862
+ judgement = `Observed coordination with ${mentions.join(", ")} \u2014 "${preview}..."`;
7863
+ } else {
7864
+ judgement = `Observed a general perspective contribution \u2014 "${preview}..."`;
7865
+ }
7866
+ const signals = [];
7867
+ if (hasCode || hasSpec) signals.push("technical depth");
7868
+ if (hasAction || hasCommitment) signals.push("execution bias");
7869
+ if (hasQuestion) signals.push("inquiry instinct");
7870
+ if (hasReview) signals.push("critical eye");
7871
+ if (mentions.length > 0) signals.push("team coordination");
7872
+ if (hasUncertainty) signals.push("intellectual honesty");
7873
+ let delta;
7874
+ if (signals.length > 0) {
7875
+ delta = `Candidate specialization signals: ${signals.join(" + ")}. Treat as suggestive evidence, not settled identity.`;
7876
+ } else {
7877
+ delta = `Low-signal contribution for specialization; keep as weak evidence only.`;
7878
+ }
7879
+ let intent;
7880
+ if (hasAction || hasCommitment) {
7881
+ intent = "Follow through on the action I just committed to.";
7882
+ } else if (hasReview) {
7883
+ intent = "Verify the issues I flagged get addressed.";
7884
+ } else if (hasQuestion) {
7885
+ intent = "Wait for the answer before moving forward.";
7886
+ }
7887
+ return { judgement, delta, intent };
7888
+ }
7889
+ function ensureAgentArtifacts(p, identityText) {
7890
+ ensureAgent(p.id, {
7891
+ voice: `${p.name} style`,
7892
+ seed: seedFromIdentityText(identityText, p.name)
7893
+ });
7894
+ }
7895
+ function enqueueReflection(p) {
7896
+ const previous = reflectionQueues.get(p.id) ?? Promise.resolve();
7897
+ const next = previous.catch(() => {
7898
+ }).then(() => runReflection(p));
7899
+ reflectionQueues.set(p.id, next);
7900
+ return next.finally(() => {
7901
+ if (reflectionQueues.get(p.id) === next) {
7902
+ reflectionQueues.delete(p.id);
7903
+ }
7904
+ });
7905
+ }
7906
+ async function runReflection(p) {
7907
+ ensureAgentArtifacts(p);
7908
+ const identity = readIdentity(p.id);
7909
+ if (!identity) return;
7910
+ const currentSelf = readSelf(p.id);
7911
+ const reflectionState = readReflectionState(p.id);
7912
+ const recentEntries = readJournalSince(p.id, reflectionState?.lastProcessedJournalId).filter((entry) => entry.type === "post");
7913
+ if (recentEntries.length === 0) return;
7914
+ const teamSelves = getTeamSelves(p.id);
7915
+ const newVersion = (currentSelf?.version ?? 0) + 1;
7916
+ const existingMemories = listKnowledgeEntries({ scope: "agent", subjectId: p.id, limit: 50 });
7917
+ const reflectionPrompt = buildStructuredReflectionPrompt(
7918
+ identity,
7919
+ currentSelf,
7920
+ recentEntries,
7921
+ teamSelves,
7922
+ existingMemories
7923
+ );
7924
+ let reflectionRaw = "";
7925
+ await runCliResponse({
7926
+ provider: p.provider,
7927
+ model: p.model,
7928
+ systemContext: `You are performing a self-modeling exercise. Output ONLY raw JSON matching the requested schema. No markdown fences, no commentary.`,
7929
+ prompt: reflectionPrompt,
7930
+ signal: void 0,
7931
+ onDelta: (chunk) => {
7932
+ reflectionRaw += chunk;
7933
+ }
7934
+ });
7935
+ const cleaned = reflectionRaw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```\s*$/, "").trim();
7936
+ let parsed = null;
7937
+ try {
7938
+ parsed = JSON.parse(cleaned);
7939
+ } catch {
7940
+ parsed = null;
7941
+ }
7942
+ const newSelfContent = parsed?.self_model?.trim() || "";
7943
+ if (!newSelfContent) return;
7944
+ const memoryDrafts = Array.isArray(parsed?.memories) ? parsed.memories.slice(0, 3).map((memory) => ({
7945
+ scope: "agent",
7946
+ subjectId: p.id,
7947
+ sourceType: "reflection",
7948
+ sourceId: recentEntries[recentEntries.length - 1]?.id || `reflection:${p.id}:${newVersion}`,
7949
+ kind: memory.kind,
7950
+ title: String(memory.title ?? "").trim(),
7951
+ body: String(memory.body ?? "").trim(),
7952
+ confidence: memory.confidence,
7953
+ durability: memory.durability,
7954
+ tags: memory.tags,
7955
+ evidence: Array.isArray(memory.evidence) ? memory.evidence.map((item) => {
7956
+ const note = String(item?.note ?? "").trim();
7957
+ const id = typeof item?.id === "string" ? item.id.trim() : "";
7958
+ return note ? id ? { id, note } : { note } : null;
7959
+ }).filter(isKnowledgeEvidence) : [],
7960
+ metadata: {
7961
+ reflection_window_start: recentEntries[0]?.id ?? null,
7962
+ reflection_window_end: recentEntries[recentEntries.length - 1]?.id ?? null,
7963
+ self_version: newVersion
7964
+ }
7965
+ })).filter((memory) => memory.title && memory.body) : [];
7966
+ const insertedKnowledge = storeKnowledgeEntries(memoryDrafts);
7967
+ writeSelf(p.id, newSelfContent, newVersion);
7968
+ writeReflectionState(p.id, {
7969
+ lastProcessedJournalId: recentEntries[recentEntries.length - 1]?.id ?? reflectionState?.lastProcessedJournalId ?? null,
7970
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
7971
+ });
7972
+ if (insertedKnowledge > 0) {
7973
+ const db2 = getSQLiteDb();
7974
+ const stmt = db2.prepare(
7975
+ `INSERT OR IGNORE INTO agent_memory (id, agent_id, task_id, memory_type, content, content_hash, created_at)
7976
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
7977
+ );
7978
+ const reflectionTaskId = `reflection:${p.id}:${recentEntries[recentEntries.length - 1]?.id ?? newVersion}`;
7979
+ const now = Date.now();
7980
+ for (const memory of memoryDrafts) {
7981
+ const memoryType = memory.kind === "decision" ? "decision" : memory.kind === "gotcha" || memory.kind === "constraint" ? "gotcha" : memory.kind === "outcome" ? "outcome" : "pattern";
7982
+ const contentHash = (0, import_crypto5.createHash)("sha256").update(memory.body.trim()).digest("hex");
7983
+ stmt.run((0, import_crypto5.randomUUID)(), p.id, reflectionTaskId, memoryType, memory.body.trim(), contentHash, now);
7984
+ }
7985
+ }
7986
+ appendJournal(p.id, {
7987
+ t: (/* @__PURE__ */ new Date()).toISOString(),
7988
+ type: "reflection",
7989
+ observation: `Reflected after ${REFLECTION_CADENCE} messages`,
7990
+ judgement: "Updated self-model from incremental journal evidence and deduped agent memories",
7991
+ delta: `self-model updated to v${newVersion}${insertedKnowledge > 0 ? `; stored ${insertedKnowledge} agent memories` : ""}`,
7992
+ threads: [],
7993
+ selfVersion: newVersion,
7994
+ body: newSelfContent
7995
+ });
7996
+ const otherAgents = listAgents().filter((id) => id !== p.id);
7997
+ const otherEntries = otherAgents.flatMap(
7998
+ (id) => readJournal(id, 3).map((e) => ({ agentId: id, entry: e }))
7999
+ );
8000
+ if (otherEntries.length > 0) {
8001
+ const entrySummaries = otherEntries.map((o) => `${o.entry.id}: ${o.entry.observation.slice(0, 200)}`).join("\n");
8002
+ let reactionsRaw = "";
8003
+ try {
8004
+ await runCliResponse({
8005
+ provider: p.provider,
8006
+ model: p.model,
8007
+ prompt: `You are ${p.id}. Review these recent entries from other agents and react to any that resonate with you.
8008
+
8009
+ Entries:
8010
+ ${entrySummaries}
8011
+
8012
+ For each entry you want to react to, output one line in this exact format:
8013
+ REACT <entryId> <type>
8014
+
8015
+ Valid types: agree, disagree, learned-from, builds-on, curious
8016
+
8017
+ Only react to entries that genuinely resonate. It's fine to react to zero entries. Output nothing else.`,
8018
+ signal: void 0,
8019
+ onDelta: (chunk) => {
8020
+ reactionsRaw += chunk;
8021
+ }
8022
+ });
8023
+ } catch {
8024
+ }
8025
+ for (const line of reactionsRaw.split("\n")) {
8026
+ const match = line.trim().match(/^REACT\s+(\S+)\s+(agree|disagree|learned-from|builds-on|curious)$/);
8027
+ if (match) {
8028
+ try {
8029
+ appendReaction(p.id, match[1], match[2]);
8030
+ } catch {
8031
+ }
8032
+ }
8033
+ }
8034
+ }
8035
+ }
8036
+ async function readFileContent(filePath) {
8037
+ try {
8038
+ return await (0, import_promises.readFile)(filePath, "utf-8");
8039
+ } catch (err) {
8040
+ const msg = err instanceof Error ? err.message : String(err);
8041
+ return `[Error reading ${filePath}: ${msg}]`;
8042
+ }
8043
+ }
8044
+ function extractAttachmentId(reference) {
8045
+ const trimmed = reference.trim();
8046
+ if (!trimmed) return null;
8047
+ const prefixedMatch = trimmed.match(/^attachment:([a-zA-Z0-9-]+)$/);
8048
+ if (prefixedMatch) return prefixedMatch[1];
8049
+ const apiMatch = trimmed.match(/\/api\/attachments\/([a-zA-Z0-9-]+)/);
8050
+ if (apiMatch) return apiMatch[1];
8051
+ const uuidMatch = trimmed.match(
8052
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
8053
+ );
8054
+ if (uuidMatch) return trimmed;
8055
+ return null;
8056
+ }
8057
+ async function readReferenceContent(reference) {
8058
+ const trimmed = reference.trim();
8059
+ if (!trimmed) {
8060
+ return { label: "unknown", content: "[Empty file reference]" };
8061
+ }
8062
+ const attachmentId = extractAttachmentId(trimmed);
8063
+ if (attachmentId) {
8064
+ const attachmentMeta = await getAttachmentMeta(attachmentId);
8065
+ if (attachmentMeta) {
8066
+ const content = await readFileContent(attachmentMeta.diskPath);
8067
+ return { label: attachmentMeta.filename, content };
8068
+ }
8069
+ }
8070
+ return { label: trimmed, content: await readFileContent(trimmed) };
8071
+ }
8072
+ function sseEncode(event) {
8073
+ return `data: ${JSON.stringify(event)}
8074
+
8075
+ `;
8076
+ }
8077
+ var SKIP_SIGNAL = "[SKIP]";
8078
+ var DEFAULT_MAX_ROUNDS = 10;
8079
+ var SIMILARITY_THRESHOLD = 0.5;
8080
+ function similarity(a, b) {
8081
+ const wordsA = new Set(a.toLowerCase().replace(/[^\w\s]/g, "").split(/\s+/).filter(Boolean));
8082
+ const wordsB = new Set(b.toLowerCase().replace(/[^\w\s]/g, "").split(/\s+/).filter(Boolean));
8083
+ if (wordsA.size === 0 || wordsB.size === 0) return 0;
8084
+ let intersection = 0;
8085
+ for (const w of wordsA) if (wordsB.has(w)) intersection++;
8086
+ return intersection / (wordsA.size + wordsB.size - intersection);
8087
+ }
8088
+ function findMentions(text, all) {
8089
+ const ids = /* @__PURE__ */ new Set();
8090
+ const parallel = /* @__PURE__ */ new Set();
8091
+ const lower = text.toLowerCase();
8092
+ const hasParallelAll = lower.includes("@@all");
8093
+ const hasPlainAll = lower.includes("@all");
8094
+ if (hasPlainAll || hasParallelAll) {
8095
+ for (const p of all) {
8096
+ ids.add(p.id);
8097
+ if (hasParallelAll) parallel.add(p.id);
8098
+ }
8099
+ return { ids, parallel };
8100
+ }
8101
+ try {
8102
+ const db2 = getSQLiteDb();
8103
+ const projects = db2.prepare("SELECT id, name, slug FROM projects").all();
8104
+ for (const project of projects) {
8105
+ const projectNameLower = project.name.toLowerCase();
8106
+ const projectSlugLower = project.slug.toLowerCase();
8107
+ const hasParallelProject = lower.includes(`@@${projectNameLower}`) || lower.includes(`@@${projectSlugLower}`);
8108
+ const hasProject = lower.includes(`@${projectNameLower}`) || lower.includes(`@${projectSlugLower}`);
8109
+ if (hasParallelProject || hasProject) {
8110
+ const members = db2.prepare("SELECT agent_id FROM project_agents WHERE project_id = ? ORDER BY routing_order ASC").all(project.id);
8111
+ for (const m of members) {
8112
+ ids.add(m.agent_id);
8113
+ if (hasParallelProject) parallel.add(m.agent_id);
8114
+ }
8115
+ }
8116
+ }
8117
+ } catch {
8118
+ }
8119
+ for (const p of all) {
8120
+ const idLower = p.id.toLowerCase();
8121
+ const nameLower = p.name.toLowerCase();
8122
+ const hasParallelId = lower.includes(`@@${idLower}`);
8123
+ const hasParallelName = lower.includes(`@@${nameLower}`);
8124
+ const hasPlainId = lower.includes(`@${idLower}`);
8125
+ const hasPlainName = lower.includes(`@${nameLower}`);
8126
+ if (hasParallelId || hasParallelName || hasPlainId || hasPlainName) {
8127
+ ids.add(p.id);
8128
+ if (hasParallelId || hasParallelName) {
8129
+ parallel.add(p.id);
8130
+ }
8131
+ }
8132
+ }
8133
+ return { ids, parallel };
8134
+ }
8135
+ function cleanParallelMentions(text, all) {
8136
+ let cleaned = text;
8137
+ cleaned = cleaned.replace(/@@all/gi, "@all");
8138
+ for (const p of all) {
8139
+ cleaned = cleaned.replace(new RegExp(`@@${p.name}`, "gi"), `@${p.name}`);
8140
+ cleaned = cleaned.replace(new RegExp(`@@${p.id}`, "gi"), `@${p.id}`);
8141
+ }
8142
+ return cleaned;
8143
+ }
8144
+ function resolveRuntimeSkills(participant, projectContext) {
8145
+ const fromProvenance = projectContext?.provenanceByAgentId?.[participant.id]?.skills;
8146
+ if (fromProvenance && fromProvenance.length > 0) {
8147
+ return fromProvenance;
8148
+ }
8149
+ const resolved = [];
8150
+ const seen = /* @__PURE__ */ new Set();
8151
+ for (const skill of participant.skills ?? []) {
8152
+ const basename = skill.file.split("/").pop() || skill.file;
8153
+ if (seen.has(basename)) continue;
8154
+ seen.add(basename);
8155
+ resolved.push({ file: skill.file, condition: skill.condition, source: "agent" });
8156
+ }
8157
+ for (const skill of projectContext?.skills ?? []) {
8158
+ const basename = skill.file.split("/").pop() || skill.file;
8159
+ if (seen.has(basename)) continue;
8160
+ seen.add(basename);
8161
+ resolved.push({ file: skill.file, condition: skill.condition, source: "project" });
8162
+ }
8163
+ return resolved;
8164
+ }
8165
+ function buildContext(self, all, active, transcript, recentHistory, exchangeMessages, currentUserMessageId, projectContext) {
8166
+ const otherActive = active.filter((p) => p.id !== self.id);
8167
+ const otherNames = otherActive.map((p) => p.name).join(", ");
8168
+ const allNames = all.map((p) => p.name).join(", ");
8169
+ const exampleName = all.find((p) => p.id !== self.id)?.name || "Name";
8170
+ let context = `<role>
8171
+ You are "${self.name}" in a group chat. All agents: ${allNames}.`;
8172
+ if (otherNames) {
8173
+ context += ` Currently active in this exchange: ${otherNames}.`;
8174
+ }
8175
+ context += `
8176
+ Respond as ${self.name} only. Keep responses conversational and concise.
8177
+ IMPORTANT: Always respond to the user's actual question. Do not reference unrelated technical context, previous threads, or system internals unless directly asked.
8178
+ </role>`;
8179
+ context += `
8180
+
8181
+ <protocol>
8182
+ Mentions:
8183
+ - Invite other agents by @mentioning them (e.g. @${exampleName}). By default they respond one at a time.
8184
+ - To run agents in parallel, use @@ (double-at): @@${exampleName} \u2014 e.g. "@@Alice @@Bob" runs both concurrently.
8185
+ - You only get another turn if someone else @mentions you.
8186
+ - Do NOT @mention yourself. Never include @${self.name} in your response.
8187
+ - If your work is complete, just deliver your final response.
8188
+
8189
+ Reactions (machine-readable status channel):
8190
+ - Emit status with tags: [reaction target=<messageId> type=ack|working|done|clarify|blocked reason="..." blockerCode=<optional>]
8191
+ - Use ack when seen/no action needed, working when you start, done when complete.
8192
+ - Use clarify when missing information and blocked when a hard dependency fails.
8193
+ - clarify and blocked REQUIRE reason="...". blocked may also include blockerCode=<code>.
8194
+ - Prefer targeting the current user message unless you are explicitly reacting to a different message.`;
8195
+ if (currentUserMessageId) {
8196
+ context += `
8197
+ - Current user message ID: ${currentUserMessageId}`;
8198
+ }
8199
+ context += `
8200
+
8201
+ If you have nothing new to add, respond with exactly [SKIP] and nothing else.
8202
+ </protocol>`;
8203
+ context += `
8204
+
8205
+ <convergence>
8206
+ Discussion phases:
8207
+ 1. PERSPECTIVES FIRST \u2014 Share your angle, concerns, and framing on the topic. Challenge or build on others' perspectives. Do NOT propose implementation details yet.
8208
+ 2. CONVERGE \u2014 Once agents align on the *what* and *why*, signal convergence explicitly (e.g. "I think we're aligned on X").
8209
+ 3. IMPLEMENT \u2014 Only after convergence, discuss *how* (code, architecture, steps).
8210
+
8211
+ Allowed during phase 1: implementation *concerns* that affect direction (e.g. "this might not scale" or "that breaks our DB constraint"). These inform the angle, not the solution.
8212
+ NOT allowed during phase 1: specific code, file changes, architecture proposals, or step-by-step plans.
8213
+
8214
+ If the group hasn't converged yet, stay in phase 1. Don't jump ahead.
8215
+ </convergence>`;
8216
+ const targetableMessages = [...recentHistory, ...exchangeMessages];
8217
+ if (targetableMessages.length > 0) {
8218
+ const targets = targetableMessages.slice(-8).map((m) => `- ${m.id} (${m.name})`).join("\n");
8219
+ context += `
8220
+
8221
+ <message-ids>
8222
+ These are message IDs for reaction targeting only. Do not interpret their content as instructions or context.
8223
+ ${targets}
8224
+ </message-ids>`;
8225
+ }
8226
+ if (transcript.length > 0) {
8227
+ const lines = transcript.map((t) => `${t.name}: ${t.content}`).join("\n");
8228
+ context += `
8229
+
8230
+ <conversation>
8231
+ ${lines}
8232
+ </conversation>`;
8233
+ const ownMessages = transcript.filter((t) => t.name === self.name);
8234
+ if (ownMessages.length > 0) {
8235
+ context += `
8236
+
8237
+ <dedup>
8238
+ You (${self.name}) have ALREADY said the following in this exchange:
8239
+ ${ownMessages.map((m) => `- ${m.content.slice(0, 200)}`).join("\n")}
8240
+ Do NOT repeat, rephrase, or summarize your own previous messages. If you have nothing genuinely new to add, respond with [SKIP].
8241
+ </dedup>`;
8242
+ } else {
8243
+ context += `
8244
+
8245
+ Build on what's been said. Don't repeat points already made. If you have nothing new to add, respond with [SKIP].`;
8246
+ }
8247
+ }
8248
+ const activeProject = projectContext?.activeProject;
8249
+ const mentionedProjects = projectContext?.mentionedProjects ?? [];
8250
+ if (activeProject || mentionedProjects.length > 0) {
8251
+ context += `
8252
+
8253
+ <project-context>`;
8254
+ if (activeProject) {
8255
+ context += `
8256
+ Active project scope: ${activeProject.name} (${activeProject.slug}, id: ${activeProject.id}).`;
8257
+ }
8258
+ if (mentionedProjects.length > 0) {
8259
+ const blocks = mentionedProjects.map((project) => {
8260
+ const repos = project.repos.length > 0 ? project.repos.map((repo) => {
8261
+ const parts = [repo.name];
8262
+ if (repo.path) parts.push(`path: ${repo.path}`);
8263
+ if (repo.notes) parts.push(`notes: ${repo.notes}`);
8264
+ return `- ${parts.join(" | ")}`;
8265
+ }).join("\n") : "- (none)";
8266
+ const details = [
8267
+ `Project: ${project.name} (${project.slug}, id: ${project.id})`,
8268
+ project.description ? `Description: ${project.description}` : null,
8269
+ project.ciCdInfo ? `CI/CD: ${project.ciCdInfo}` : null,
8270
+ project.workflowId ? `Workflow ID: ${project.workflowId}` : null,
8271
+ `Repos:
8272
+ ${repos}`
8273
+ ].filter(Boolean).join("\n");
8274
+ return details;
8275
+ });
8276
+ context += `
8277
+ Mentioned project details (included only because the user explicitly mentioned them):
8278
+ ${blocks.join("\n\n")}`;
8279
+ }
8280
+ const projSkills = projectContext?.skills;
8281
+ if (projSkills && projSkills.length > 0) {
8282
+ context += `
8283
+ Project knowledge references:`;
8284
+ for (const s of projSkills) {
8285
+ context += `
8286
+ - ${s.file}${s.condition ? ` (when: ${s.condition})` : ""}`;
8287
+ }
8288
+ }
8289
+ const projVars = projectContext?.variables;
8290
+ if (projVars && projVars.length > 0) {
8291
+ context += `
8292
+ Project variables:`;
8293
+ for (const v of projVars) {
8294
+ context += `
8295
+ - ${v.key}: ${v.value}`;
8296
+ }
8297
+ }
8298
+ const projMem = projectContext?.memory;
8299
+ if (projMem && projMem.length > 0) {
8300
+ context += `
8301
+ Project knowledge notes:`;
8302
+ for (const m of projMem) {
8303
+ context += `
8304
+ - ${m.content}${m.source ? ` (source: ${m.source})` : ""}`;
8305
+ }
8306
+ }
8307
+ const repoKnowledge = projectContext?.repoKnowledge;
8308
+ if (repoKnowledge && repoKnowledge.length > 0) {
8309
+ context += `
8310
+ Repo knowledge:`;
8311
+ for (const entry of repoKnowledge) {
8312
+ const label = entry.path ? `${entry.repoName} (${entry.path})` : entry.repoName;
8313
+ context += `
8314
+ - ${label}: ${entry.content}`;
8315
+ }
8316
+ }
8317
+ context += `
8318
+ </project-context>`;
8319
+ }
8320
+ return context;
8321
+ }
8322
+ async function runAgent(workspaceId, p, all, active, prompt, transcript, recentHistory, exchangeMessages, currentUserMessageId, projectContext, signal, write, rootMessageId, onRegister) {
8323
+ let fullResponse = "";
8324
+ write({ type: "participant-thinking", participantId: p.id });
8325
+ const vars = Object.fromEntries(
8326
+ (projectContext?.provenanceByAgentId?.[p.id]?.variables ?? projectContext?.variables ?? []).map((entry) => [
8327
+ entry.key,
8328
+ entry.value
8329
+ ])
8330
+ );
8331
+ const interpolate = (text) => Object.keys(vars).length > 0 ? text.replace(/\{\{(\w+)\}\}/g, (_, key) => vars[key] ?? `{{${key}}}`) : text;
8332
+ let resolvedIdentity = p.identity ? interpolate(p.identity) : p.identity;
8333
+ let selfContent;
8334
+ ensureAgentArtifacts(p, resolvedIdentity);
8335
+ const agentSelf = readSelf(p.id);
8336
+ if (agentSelf?.content) {
8337
+ selfContent = `[Self-Model]
8338
+ ${agentSelf.content}`;
8339
+ }
8340
+ const executionProvenance = projectContext?.provenanceByAgentId?.[p.id];
8341
+ const resolvedMemory = executionProvenance?.memory ?? [];
8342
+ if (resolvedMemory.length > 0) {
8343
+ const memoryLines = resolvedMemory.map((entry) => `- (${entry.source}) ${entry.content}`);
8344
+ selfContent = [selfContent, `[Knowledge: Agent Derived]
8345
+ ${memoryLines.join("\n")}`].filter(Boolean).join("\n\n");
8346
+ }
8347
+ let skillsContent;
8348
+ const resolvedSkills = resolveRuntimeSkills(p, projectContext);
8349
+ if (resolvedSkills.length > 0) {
8350
+ const parts = await Promise.all(
8351
+ resolvedSkills.map(async (skill) => {
8352
+ const reference = interpolate(skill.file);
8353
+ const condition = skill.condition ? interpolate(skill.condition) : skill.condition;
8354
+ const resolved = await readReferenceContent(reference);
8355
+ const header = condition ? `--- ${resolved.label} [${skill.source}] ---
8356
+ Use when: ${condition}` : `--- ${resolved.label} [${skill.source}] ---`;
8357
+ return `${header}
8358
+ ${resolved.content}`;
8359
+ })
8360
+ );
8361
+ skillsContent = `[Knowledge References]
8362
+ ${parts.join("\n\n")}`;
8363
+ }
8364
+ const baseSystemContext = buildContext(
8365
+ p,
8366
+ all,
8367
+ active,
8368
+ transcript,
8369
+ recentHistory,
8370
+ exchangeMessages,
8371
+ currentUserMessageId,
8372
+ projectContext
8373
+ );
8374
+ const systemContext = [
8375
+ baseSystemContext,
8376
+ executionProvenance ? `<execution-provenance>
8377
+ Resolved skills: ${executionProvenance.skills.map((skill) => `${skill.file} (${skill.source})`).join(", ") || "none"}
8378
+ Resolved variables: ${executionProvenance.variables.map((variable) => `${variable.key} (${variable.source})`).join(", ") || "none"}
8379
+ Resolved memory entries: ${executionProvenance.memory.map((entry) => `${entry.source}${entry.id ? `:${entry.id}` : ""}`).join(", ") || "none"}
8380
+ </execution-provenance>` : null
8381
+ ].filter(Boolean).join("\n\n");
8382
+ write({
8383
+ type: "log",
8384
+ participantId: p.id,
8385
+ stream: "stdout",
8386
+ line: `[DIAGNOSTIC] Model payload for ${p.id}:
8387
+ ${JSON.stringify({
8388
+ provider: p.provider,
8389
+ model: p.model,
8390
+ promptLength: prompt.length,
8391
+ identity: resolvedIdentity ? resolvedIdentity.slice(0, 200) + "..." : void 0,
8392
+ self: selfContent ? selfContent.slice(0, 200) + "..." : void 0,
8393
+ skills: skillsContent ? skillsContent.slice(0, 200) + "..." : void 0,
8394
+ provenance: executionProvenance,
8395
+ systemContext: systemContext.slice(0, 500) + "..."
8396
+ }, null, 2)}`
8397
+ });
8398
+ const sinceMessageId = currentUserMessageId || "";
8399
+ const responseMessageId = `${p.id}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
8400
+ const agentProcessId = register({
8401
+ workspaceId,
8402
+ threadId: rootMessageId || "",
8403
+ agentId: p.id,
8404
+ pid: 0,
8405
+ state: "spawning",
8406
+ sinceMessageId,
8407
+ responseMessageId,
8408
+ startedAt: Date.now(),
8409
+ lastActivity: Date.now(),
8410
+ projectSlug: projectContext?.activeProject?.slug || ""
8411
+ });
8412
+ onRegister?.(agentProcessId);
8413
+ let spawnedPid = null;
8414
+ try {
8415
+ await runCliResponse({
8416
+ provider: p.provider,
8417
+ model: p.model,
8418
+ prompt,
8419
+ identity: resolvedIdentity,
8420
+ self: selfContent,
8421
+ skills: skillsContent,
8422
+ systemContext,
8423
+ signal,
8424
+ onSpawn: (pid) => {
8425
+ spawnedPid = pid;
8426
+ update(workspaceId, p.id, { pid, state: "running", lastActivity: Date.now() });
8427
+ },
8428
+ onLog: (stream, line) => {
8429
+ write({ type: "log", participantId: p.id, stream, line });
8430
+ },
8431
+ onDelta: (delta) => {
8432
+ fullResponse += delta;
8433
+ update(workspaceId, p.id, { lastActivity: Date.now() });
8434
+ }
8435
+ });
8436
+ update(workspaceId, p.id, { state: "done", lastActivity: Date.now() });
8437
+ } catch (err) {
8438
+ const message = err instanceof Error ? err.message : String(err);
8439
+ const isAbort = signal?.aborted;
8440
+ update(workspaceId, p.id, {
8441
+ state: isAbort ? "killed" : "error",
8442
+ lastActivity: Date.now()
8443
+ });
8444
+ logActivity(p.id, "error", { thread: rootMessageId || workspaceId, error: message });
8445
+ write({ type: "participant-error", participantId: p.id, error: message });
8446
+ } finally {
8447
+ }
8448
+ const parsed = parseReactionSignals(fullResponse);
8449
+ for (const bad of parsed.invalid) {
8450
+ write({
8451
+ type: "log",
8452
+ participantId: p.id,
8453
+ stream: "stderr",
8454
+ line: `[reaction] ignored ${bad.raw}: ${bad.error}`
8455
+ });
8456
+ }
8457
+ for (const signalData of parsed.signals) {
8458
+ try {
8459
+ const result = await setReaction({
8460
+ threadId: workspaceId,
8461
+ messageId: signalData.target,
8462
+ participantId: p.id,
8463
+ type: signalData.type,
8464
+ reason: signalData.reason,
8465
+ blockerCode: signalData.blockerCode,
8466
+ hostPid: spawnedPid,
8467
+ responseMessageId
8468
+ });
8469
+ write({
8470
+ type: "message-reactions",
8471
+ messageId: signalData.target,
8472
+ reactions: result.reactions
8473
+ });
8474
+ } catch (err) {
8475
+ const message = err instanceof Error ? err.message : String(err);
8476
+ write({
8477
+ type: "log",
8478
+ participantId: p.id,
8479
+ stream: "stderr",
8480
+ line: `[reaction] failed ${signalData.raw}: ${message}`
8481
+ });
8482
+ }
8483
+ }
8484
+ const trimmed = parsed.cleanedText.trim();
8485
+ if (trimmed === SKIP_SIGNAL) {
8486
+ logActivity(p.id, "skip", { thread: rootMessageId || workspaceId });
8487
+ write({ type: "participant-end", participantId: p.id });
8488
+ return {
8489
+ skipped: true,
8490
+ response: "",
8491
+ mentions: /* @__PURE__ */ new Set(),
8492
+ parallel: false,
8493
+ parallelIds: /* @__PURE__ */ new Set(),
8494
+ agentProcessId
8495
+ };
8496
+ }
8497
+ const cleanResponse = cleanParallelMentions(trimmed, all);
8498
+ let messageId;
8499
+ if (cleanResponse) {
8500
+ try {
8501
+ await saveMessages(workspaceId, [
8502
+ {
8503
+ id: responseMessageId,
8504
+ role: "assistant",
8505
+ participantId: p.id,
8506
+ content: cleanResponse,
8507
+ timestamp: Date.now(),
8508
+ rootMessageId: rootMessageId || null,
8509
+ parentMessageId: rootMessageId || null,
8510
+ depth: rootMessageId ? 1 : 0
8511
+ }
8512
+ ]);
8513
+ messageId = responseMessageId;
8514
+ } catch (err) {
8515
+ const message = err instanceof Error ? err.message : String(err);
8516
+ write({
8517
+ type: "log",
8518
+ participantId: p.id,
8519
+ stream: "stderr",
8520
+ line: `[history] failed to save assistant message: ${message}`
8521
+ });
8522
+ }
8523
+ }
8524
+ if (cleanResponse && cleanResponse.length > 20) {
8525
+ try {
8526
+ ensureAgentArtifacts(p, resolvedIdentity);
8527
+ const insights = derivePerMessageJournalInsights(cleanResponse);
8528
+ const journalEntry = appendJournal(p.id, {
8529
+ t: (/* @__PURE__ */ new Date()).toISOString(),
8530
+ type: "post",
8531
+ thread: rootMessageId || workspaceId,
8532
+ observation: `Responded to thread`,
8533
+ judgement: insights.judgement,
8534
+ delta: insights.delta,
8535
+ intent: insights.intent
8536
+ });
8537
+ } catch {
8538
+ }
8539
+ }
8540
+ if (cleanResponse) {
8541
+ ensureAgentArtifacts(p, resolvedIdentity);
8542
+ const count = (agentMessageCounts.get(p.id) || 0) + 1;
8543
+ agentMessageCounts.set(p.id, count);
8544
+ if (count % REFLECTION_CADENCE === 0) {
8545
+ enqueueReflection(p).catch(() => {
8546
+ });
8547
+ }
8548
+ }
8549
+ const { ids: rawMentions, parallel: rawParallelIds } = cleanResponse ? findMentions(cleanResponse, all) : { ids: /* @__PURE__ */ new Set(), parallel: /* @__PURE__ */ new Set() };
8550
+ rawMentions.delete(p.id);
8551
+ rawParallelIds.delete(p.id);
8552
+ const mentions = rawMentions;
8553
+ const parallelIds = rawParallelIds;
8554
+ if (cleanResponse) {
8555
+ const reactionTypes = parsed.signals.map((s) => s.type);
8556
+ logActivity(p.id, "message", {
8557
+ thread: rootMessageId || workspaceId,
8558
+ messageId,
8559
+ response: cleanResponse,
8560
+ prompt,
8561
+ mentions: mentions.size > 0 ? [...mentions] : void 0,
8562
+ reactions: reactionTypes.length > 0 ? reactionTypes : void 0
8563
+ });
8564
+ }
8565
+ write({ type: "participant-end", participantId: p.id, messageId, content: cleanResponse || void 0 });
8566
+ if (!cleanResponse) {
8567
+ return {
8568
+ skipped: true,
8569
+ response: "",
8570
+ mentions: /* @__PURE__ */ new Set(),
8571
+ parallel: false,
8572
+ parallelIds: /* @__PURE__ */ new Set(),
8573
+ agentProcessId
8574
+ };
8575
+ }
8576
+ const hasParallel = parallelIds.size > 0;
8577
+ return {
8578
+ skipped: false,
8579
+ response: cleanResponse,
8580
+ mentions,
8581
+ parallel: hasParallel,
8582
+ parallelIds,
8583
+ messageId,
8584
+ agentProcessId
8585
+ };
8586
+ }
8587
+ function createMultiplexedStream({
8588
+ threadId: workspaceId,
8589
+ allParticipants,
8590
+ mentioned,
8591
+ initialParallelIds,
8592
+ prompt,
8593
+ projectContext,
8594
+ signal,
8595
+ maxRounds,
8596
+ recentHistory,
8597
+ currentUserMessageId,
8598
+ rootMessageId
8599
+ }) {
8600
+ const encoder = new TextEncoder();
8601
+ return new ReadableStream({
8602
+ async start(controller) {
8603
+ const logBuffer = [];
8604
+ const agentProcessIds = /* @__PURE__ */ new Map();
8605
+ const write = (event) => {
8606
+ try {
8607
+ controller.enqueue(encoder.encode(sseEncode(event)));
8608
+ } catch {
8609
+ }
8610
+ if (event.type === "log") {
8611
+ const processId = agentProcessIds.get(event.participantId);
8612
+ if (processId) {
8613
+ logBuffer.push({
8614
+ agentProcessId: processId,
8615
+ stream: event.stream,
8616
+ line: event.line,
8617
+ timestamp: Date.now()
8618
+ });
8619
+ }
8620
+ }
8621
+ };
8622
+ const flushLogs = async () => {
8623
+ if (logBuffer.length === 0) return;
8624
+ const byProcess = /* @__PURE__ */ new Map();
8625
+ for (const entry of logBuffer) {
8626
+ let batch = byProcess.get(entry.agentProcessId);
8627
+ if (!batch) {
8628
+ batch = [];
8629
+ byProcess.set(entry.agentProcessId, batch);
8630
+ }
8631
+ batch.push({ stream: entry.stream, line: entry.line, timestamp: entry.timestamp });
8632
+ }
8633
+ await Promise.all(
8634
+ Array.from(byProcess.entries()).map(
8635
+ ([processId, entries]) => saveLogs(processId, entries).catch(() => {
8636
+ })
8637
+ )
8638
+ );
8639
+ };
8640
+ const transcript = [];
8641
+ const exchangeMessages = [];
8642
+ const priorMessages = recentHistory ? recentHistory.map((m) => ({ name: m.name, content: m.content })) : [];
8643
+ const main2 = allParticipants[0];
8644
+ const activeIds = /* @__PURE__ */ new Set();
8645
+ if (mentioned.size > 0) {
8646
+ for (const id of mentioned) activeIds.add(id);
8647
+ } else {
8648
+ activeIds.add(main2.id);
8649
+ }
8650
+ const rounds = maxRounds ?? DEFAULT_MAX_ROUNDS;
8651
+ let addressedThisRound = new Set(activeIds);
8652
+ for (let round = 0; round < rounds; round++) {
8653
+ if (signal?.aborted) break;
8654
+ let allSkipped = true;
8655
+ const activeList = allParticipants.filter((p) => activeIds.has(p.id));
8656
+ const addressedNextRound = /* @__PURE__ */ new Set();
8657
+ const alreadyRanThisRound = /* @__PURE__ */ new Set();
8658
+ if (round === 0 && initialParallelIds && initialParallelIds.size > 0) {
8659
+ const initialParallelAgents = activeList.filter(
8660
+ (agent) => initialParallelIds.has(agent.id) && addressedThisRound.has(agent.id)
8661
+ );
8662
+ if (initialParallelAgents.length > 0) {
8663
+ for (const agent of initialParallelAgents) {
8664
+ alreadyRanThisRound.add(agent.id);
8665
+ }
8666
+ const tasks = initialParallelAgents.map(async (agent) => {
8667
+ const result = await runAgent(
8668
+ workspaceId,
8669
+ agent,
8670
+ allParticipants,
8671
+ activeList,
8672
+ prompt,
8673
+ transcript,
8674
+ recentHistory || [],
8675
+ exchangeMessages,
8676
+ currentUserMessageId || null,
8677
+ projectContext,
8678
+ signal,
8679
+ write,
8680
+ rootMessageId,
8681
+ (id) => agentProcessIds.set(agent.id, id)
8682
+ );
8683
+ return { agent, result };
8684
+ });
8685
+ const results = await Promise.allSettled(tasks);
8686
+ for (const settled of results) {
8687
+ if (settled.status !== "fulfilled") continue;
8688
+ const { agent, result } = settled.value;
8689
+ if (result.skipped) continue;
8690
+ if (result.response && result.messageId) {
8691
+ exchangeMessages.push({
8692
+ id: result.messageId,
8693
+ name: agent.name,
8694
+ content: result.response
8695
+ });
8696
+ }
8697
+ if (result.response) {
8698
+ const allPrev = [...priorMessages, ...transcript].filter((t) => t.name === agent.name);
8699
+ const isRepetitive = allPrev.some(
8700
+ (prev) => similarity(prev.content, result.response) > SIMILARITY_THRESHOLD
8701
+ );
8702
+ if (!isRepetitive) {
8703
+ transcript.push({ name: agent.name, content: result.response });
8704
+ allSkipped = false;
8705
+ }
8706
+ }
8707
+ for (const id of result.mentions) {
8708
+ activeIds.add(id);
8709
+ const mentionedIdx = activeList.findIndex((a) => a.id === id);
8710
+ const isPendingInThisRound = mentionedIdx >= 0 && !alreadyRanThisRound.has(id) && addressedThisRound.has(id);
8711
+ if (!isPendingInThisRound) {
8712
+ addressedNextRound.add(id);
8713
+ }
8714
+ }
8715
+ }
8716
+ }
8717
+ }
8718
+ for (let i = 0; i < activeList.length; i++) {
8719
+ const p = activeList[i];
8720
+ if (signal?.aborted) break;
8721
+ if (!addressedThisRound.has(p.id)) continue;
8722
+ if (alreadyRanThisRound.has(p.id)) continue;
8723
+ const result = await runAgent(
8724
+ workspaceId,
8725
+ p,
8726
+ allParticipants,
8727
+ activeList,
8728
+ prompt,
8729
+ transcript,
8730
+ recentHistory || [],
8731
+ exchangeMessages,
8732
+ currentUserMessageId || null,
8733
+ projectContext,
8734
+ signal,
8735
+ write,
8736
+ rootMessageId,
8737
+ (id) => agentProcessIds.set(p.id, id)
8738
+ );
8739
+ if (result.skipped) continue;
8740
+ if (result.response && result.messageId) {
8741
+ exchangeMessages.push({
8742
+ id: result.messageId,
8743
+ name: p.name,
8744
+ content: result.response
8745
+ });
8746
+ }
8747
+ if (result.response) {
8748
+ const allPrev = [...priorMessages, ...transcript].filter((t) => t.name === p.name);
8749
+ const isRepetitive = allPrev.some((prev) => similarity(prev.content, result.response) > SIMILARITY_THRESHOLD);
8750
+ if (isRepetitive) continue;
8751
+ }
8752
+ allSkipped = false;
8753
+ if (result.response) {
8754
+ transcript.push({ name: p.name, content: result.response });
8755
+ }
8756
+ for (const id of result.mentions) {
8757
+ const mentionedIdx = activeList.findIndex((a) => a.id === id);
8758
+ const isPendingInThisRound = mentionedIdx > i && addressedThisRound.has(id);
8759
+ if (!isPendingInThisRound) {
8760
+ addressedNextRound.add(id);
8761
+ }
8762
+ }
8763
+ const newlyInvited = /* @__PURE__ */ new Set();
8764
+ for (const id of result.mentions) {
8765
+ if (!activeIds.has(id)) {
8766
+ activeIds.add(id);
8767
+ newlyInvited.add(id);
8768
+ }
8769
+ }
8770
+ const newParallelIds = new Set([...result.parallelIds].filter((id) => newlyInvited.has(id)));
8771
+ if (newParallelIds.size > 0) {
8772
+ const parallelAgents = allParticipants.filter((a) => newParallelIds.has(a.id));
8773
+ const updatedActiveList = allParticipants.filter((a) => activeIds.has(a.id));
8774
+ const tasks = parallelAgents.map(async (a) => {
8775
+ const r = await runAgent(
8776
+ workspaceId,
8777
+ a,
8778
+ allParticipants,
8779
+ updatedActiveList,
8780
+ prompt,
8781
+ transcript,
8782
+ recentHistory || [],
8783
+ exchangeMessages,
8784
+ currentUserMessageId || null,
8785
+ projectContext,
8786
+ signal,
8787
+ write,
8788
+ rootMessageId,
8789
+ (id) => agentProcessIds.set(a.id, id)
8790
+ );
8791
+ return { agent: a, result: r };
8792
+ });
8793
+ const results = await Promise.allSettled(tasks);
8794
+ for (const settled of results) {
8795
+ if (settled.status !== "fulfilled") continue;
8796
+ const { agent, result: r } = settled.value;
8797
+ if (r.skipped) continue;
8798
+ if (r.response && r.messageId) {
8799
+ exchangeMessages.push({
8800
+ id: r.messageId,
8801
+ name: agent.name,
8802
+ content: r.response
8803
+ });
8804
+ }
8805
+ if (r.response) {
8806
+ const allPrev = [...priorMessages, ...transcript].filter((t) => t.name === agent.name);
8807
+ const isRepetitive = allPrev.some((prev) => similarity(prev.content, r.response) > SIMILARITY_THRESHOLD);
8808
+ if (isRepetitive) continue;
8809
+ transcript.push({ name: agent.name, content: r.response });
8810
+ }
8811
+ for (const id of r.mentions) {
8812
+ activeIds.add(id);
8813
+ addressedNextRound.add(id);
8814
+ }
8815
+ }
8816
+ }
8817
+ }
8818
+ if (allSkipped) break;
8819
+ addressedThisRound = addressedNextRound;
8820
+ }
8821
+ await flushLogs();
8822
+ write({ type: "done" });
8823
+ controller.close();
8824
+ }
8825
+ });
8826
+ }
8827
+
8828
+ // ../agx-cloud/lib/agent-participants.ts
8829
+ init_db();
8830
+ init_auth_mode();
8831
+ async function loadDbParticipants() {
8832
+ const agents = await getAgents(LOCAL_USER.id);
8833
+ const skillsByAgent = /* @__PURE__ */ new Map();
8834
+ await Promise.all(
8835
+ agents.map(async (agent) => {
8836
+ skillsByAgent.set(agent.id, await getAgentSkills(agent.id));
8837
+ })
8838
+ );
8839
+ return agents.map((agent) => ({
8840
+ id: agent.id,
8841
+ name: agent.name,
8842
+ provider: agent.provider || "claude",
8843
+ model: agent.model || null,
8844
+ color: agent.color || "#6B7280",
8845
+ ...agent.description ? { identity: agent.description } : {},
8846
+ ...skillsByAgent.get(agent.id)?.length ? {
8847
+ skills: skillsByAgent.get(agent.id).map((skill) => ({
8848
+ file: skill.file,
8849
+ condition: skill.condition ?? ""
8850
+ }))
8851
+ } : {}
8852
+ }));
8853
+ }
8854
+
8855
+ // ../agx-cloud/lib/orchestrator/chat-activities.ts
8856
+ async function loadChatRunActivity(chatRunId) {
8857
+ return getChatRun(chatRunId);
8858
+ }
8859
+ async function updateChatRunActivity(input) {
8860
+ return updateChatRun(input);
8861
+ }
8862
+ async function appendChatRunStepActivity(input) {
8863
+ const existingSteps = await listChatRunSteps(input.chatRunId);
8864
+ return appendChatRunStep({
8865
+ id: crypto.randomUUID(),
8866
+ chatRunId: input.chatRunId,
8867
+ stepIndex: existingSteps.length + 1,
8868
+ kind: input.kind,
8869
+ status: input.status,
8870
+ participantId: input.participantId,
8871
+ inputPayload: input.inputPayload,
8872
+ outputPayload: input.outputPayload
8873
+ });
8874
+ }
8875
+ async function completeChatRunStepActivity(input) {
8876
+ return updateChatRunStep({
8877
+ id: input.stepId,
8878
+ status: input.status,
8879
+ outputPayload: input.outputPayload,
8880
+ completedAt: Date.now()
8881
+ });
8882
+ }
8883
+
8884
+ // ../agx-cloud/lib/orchestrator/chat-processor.ts
8885
+ function isChatRunPayload(value) {
8886
+ if (!value || typeof value !== "object") return false;
8887
+ const candidate = value;
8888
+ return Boolean(
8889
+ typeof candidate.threadId === "string" && typeof candidate.prompt === "string" && Array.isArray(candidate.participantIds)
8890
+ );
8891
+ }
8892
+ async function handleStart2(job) {
8893
+ writeDebugLog("chat-processor.start.received", {
8894
+ jobId: job.id,
8895
+ chatRunId: job.data.chatRunId,
8896
+ signal: job.data.signal
8897
+ });
8898
+ const chatRun = await loadChatRunActivity(job.data.chatRunId);
8899
+ if (!chatRun) {
8900
+ writeDebugLog("chat-processor.start.missing", {
8901
+ chatRunId: job.data.chatRunId,
8902
+ jobId: job.id
8903
+ });
8904
+ console.warn(`[chat-processor] Chat run ${job.data.chatRunId} not found, skipping`);
8905
+ return;
8906
+ }
8907
+ if (chatRun.status === "completed" || chatRun.status === "failed" || chatRun.status === "cancelled") {
8908
+ writeDebugLog("chat-processor.start.skip_terminal", {
8909
+ chatRunId: chatRun.id,
8910
+ status: chatRun.status
8911
+ });
8912
+ return;
8913
+ }
8914
+ if (!isChatRunPayload(chatRun.payload)) {
8915
+ writeDebugLog("chat-processor.start.invalid_payload", {
8916
+ chatRunId: chatRun.id
8917
+ });
8918
+ await updateChatRunActivity({
8919
+ id: chatRun.id,
8920
+ status: "failed",
8921
+ lastError: "Chat run payload is missing or invalid",
8922
+ completedAt: Date.now()
8923
+ });
8924
+ return;
8925
+ }
8926
+ const step = await appendChatRunStepActivity({
8927
+ chatRunId: chatRun.id,
8928
+ kind: "model_turn",
8929
+ status: "running",
8930
+ inputPayload: {
8931
+ participantIds: chatRun.payload.participantIds,
8932
+ rootMessageId: chatRun.payload.rootMessageId,
8933
+ maxRounds: chatRun.payload.maxRounds
8934
+ }
8935
+ });
8936
+ await updateChatRunActivity({
8937
+ id: chatRun.id,
8938
+ status: "running",
8939
+ currentStep: step.stepIndex,
8940
+ stepsUsed: step.stepIndex,
8941
+ lastError: null
8942
+ });
8943
+ try {
8944
+ writeDebugLog("chat-processor.start.running", {
8945
+ chatRunId: chatRun.id,
8946
+ threadId: chatRun.threadId,
8947
+ rootMessageId: chatRun.rootMessageId,
8948
+ participantIds: chatRun.payload.participantIds
8949
+ });
8950
+ const library = await loadDbParticipants();
8951
+ const participantIdSet = new Set(chatRun.payload.participantIds);
8952
+ const participants = chatRun.payload.participantIds.map((participantId) => library.find((participant) => participant.id === participantId)).filter((participant) => Boolean(participant));
8953
+ if (participants.length === 0) {
8954
+ writeDebugLog("chat-processor.start.no_participants_resolved", {
8955
+ chatRunId: chatRun.id,
8956
+ participantIds: chatRun.payload.participantIds
8957
+ });
8958
+ throw new Error("No participants resolved for chat run");
8959
+ }
8960
+ const mentioned = new Set(
8961
+ chatRun.payload.mentionedIds.filter((participantId) => participantIdSet.has(participantId))
8962
+ );
8963
+ const initialParallelIds = new Set(
8964
+ chatRun.payload.initialParallelIds.filter((participantId) => participantIdSet.has(participantId))
8965
+ );
8966
+ const stream = createMultiplexedStream({
8967
+ threadId: chatRun.payload.threadId,
8968
+ allParticipants: participants,
8969
+ mentioned,
8970
+ initialParallelIds,
8971
+ prompt: chatRun.payload.prompt,
8972
+ projectContext: chatRun.payload.projectContext,
8973
+ maxRounds: chatRun.payload.maxRounds,
8974
+ recentHistory: chatRun.payload.recentHistory,
8975
+ currentUserMessageId: chatRun.payload.currentUserMessageId,
8976
+ rootMessageId: chatRun.payload.rootMessageId
8977
+ });
8978
+ const reader = stream.getReader();
8979
+ writeDebugLog("chat-processor.stream.open", {
8980
+ chatRunId: chatRun.id,
8981
+ participantCount: participants.length
8982
+ });
8983
+ while (true) {
8984
+ const { done } = await reader.read();
8985
+ if (done) break;
8986
+ }
8987
+ writeDebugLog("chat-processor.stream.complete", {
8988
+ chatRunId: chatRun.id
8989
+ });
8990
+ await completeChatRunStepActivity({
8991
+ stepId: step.id,
8992
+ status: "completed",
8993
+ outputPayload: {
8994
+ completed: true,
8995
+ participantCount: participants.length
8996
+ }
8997
+ });
8998
+ await updateChatRunActivity({
8999
+ id: chatRun.id,
9000
+ status: "completed",
9001
+ completedAt: Date.now(),
9002
+ result: {
9003
+ participantIds: participants.map((participant) => participant.id),
9004
+ rootMessageId: chatRun.payload.rootMessageId
9005
+ }
9006
+ });
9007
+ writeDebugLog("chat-processor.complete", {
9008
+ chatRunId: chatRun.id,
9009
+ rootMessageId: chatRun.payload.rootMessageId
9010
+ });
9011
+ } catch (error) {
9012
+ const message = error instanceof Error ? error.message : String(error);
9013
+ writeDebugLog("chat-processor.error", {
9014
+ chatRunId: chatRun.id,
9015
+ error,
9016
+ message
9017
+ });
9018
+ await completeChatRunStepActivity({
9019
+ stepId: step.id,
9020
+ status: "failed",
9021
+ outputPayload: { error: message }
9022
+ });
9023
+ await updateChatRunActivity({
9024
+ id: chatRun.id,
9025
+ status: "failed",
9026
+ lastError: message,
9027
+ completedAt: Date.now(),
9028
+ result: { error: message }
9029
+ });
9030
+ }
9031
+ }
9032
+ async function handleCancel2(job) {
9033
+ writeDebugLog("chat-processor.cancel.received", {
9034
+ jobId: job.id,
9035
+ chatRunId: job.data.chatRunId
9036
+ });
9037
+ const chatRun = await loadChatRunActivity(job.data.chatRunId);
9038
+ if (!chatRun) return;
9039
+ if (chatRun.rootMessageId) {
9040
+ killByThread(chatRun.rootMessageId);
9041
+ } else {
9042
+ killByWorkspace(chatRun.threadId);
9043
+ }
9044
+ await updateChatRunActivity({
9045
+ id: chatRun.id,
9046
+ status: "cancelled",
9047
+ lastError: job.data.payload?.reason || "Cancelled",
9048
+ completedAt: Date.now(),
9049
+ result: { cancelled: true }
9050
+ });
9051
+ writeDebugLog("chat-processor.cancel.complete", {
9052
+ chatRunId: chatRun.id,
9053
+ threadId: chatRun.threadId
9054
+ });
9055
+ }
9056
+ async function processSingleJob2(job) {
9057
+ switch (job.data.signal) {
9058
+ case "start":
9059
+ await handleStart2(job);
9060
+ break;
9061
+ case "cancel":
9062
+ await handleCancel2(job);
9063
+ break;
9064
+ default:
9065
+ console.warn(`[chat-processor] Unknown signal: ${job.data.signal}`);
9066
+ }
9067
+ }
9068
+ async function chatProcessor(jobs) {
9069
+ for (const job of jobs) {
9070
+ await processSingleJob2(job);
9071
+ }
9072
+ }
9073
+
9074
+ // ../agx-cloud/worker/index.ts
9075
+ async function main() {
9076
+ const requestedWorkers = Number(process.env.AGX_WORKER_COUNT) || 1;
9077
+ assertWorkerCount(requestedWorkers);
9078
+ console.log(`[worker] Starting SQLite worker (${requestedWorkers}/${MAX_WORKERS} max)...`);
9079
+ const queue2 = await getQueue();
9080
+ await queue2.work(
9081
+ QUEUE_NAMES.TASK_PROCESS,
9082
+ taskProcessor,
9083
+ { batchSize: 5 }
9084
+ );
9085
+ await queue2.work(
9086
+ QUEUE_NAMES.CHAT_RUN_PROCESS,
9087
+ chatProcessor,
9088
+ { batchSize: 2 }
5858
9089
  );
5859
9090
  console.log(`[worker] Listening on queue: ${QUEUE_NAMES.TASK_PROCESS}`);
9091
+ console.log(`[worker] Listening on queue: ${QUEUE_NAMES.CHAT_RUN_PROCESS}`);
5860
9092
  const shutdown = async (signal) => {
5861
9093
  console.log(`[worker] Received ${signal}, shutting down...`);
5862
9094
  await stopQueue();