@sapienx/agentos 0.5.9 → 0.6.2

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 (248) hide show
  1. package/README.md +1 -1
  2. package/bin/agentos.js +297 -9
  3. package/bundle/.next/BUILD_ID +1 -1
  4. package/bundle/.next/app-path-routes-manifest.json +10 -9
  5. package/bundle/.next/build-manifest.json +2 -2
  6. package/bundle/.next/prerender-manifest.json +3 -3
  7. package/bundle/.next/required-server-files.json +1 -1
  8. package/bundle/.next/routes-manifest.json +8 -0
  9. package/bundle/.next/server/app/_global-error/page.js +2 -2
  10. package/bundle/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  11. package/bundle/.next/server/app/_global-error.html +1 -1
  12. package/bundle/.next/server/app/_global-error.rsc +1 -1
  13. package/bundle/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  14. package/bundle/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  15. package/bundle/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  16. package/bundle/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  17. package/bundle/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  18. package/bundle/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  19. package/bundle/.next/server/app/_not-found/page.js +2 -2
  20. package/bundle/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  21. package/bundle/.next/server/app/_not-found.html +1 -1
  22. package/bundle/.next/server/app/_not-found.rsc +2 -2
  23. package/bundle/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  24. package/bundle/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  25. package/bundle/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  26. package/bundle/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  27. package/bundle/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  28. package/bundle/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  29. package/bundle/.next/server/app/agents/page.js +2 -2
  30. package/bundle/.next/server/app/agents/page.js.nft.json +1 -1
  31. package/bundle/.next/server/app/agents/page_client-reference-manifest.js +1 -1
  32. package/bundle/.next/server/app/api/agents/[agentId]/chat/route.js +2 -2
  33. package/bundle/.next/server/app/api/agents/[agentId]/chat/route.js.nft.json +1 -1
  34. package/bundle/.next/server/app/api/agents/route.js +1 -1
  35. package/bundle/.next/server/app/api/agents/route.js.nft.json +1 -1
  36. package/bundle/.next/server/app/api/diagnostics/route.js +1 -1
  37. package/bundle/.next/server/app/api/diagnostics/route.js.nft.json +1 -1
  38. package/bundle/.next/server/app/api/files/reveal/route.js +1 -1
  39. package/bundle/.next/server/app/api/gateway/control/route.js +1 -1
  40. package/bundle/.next/server/app/api/gateway/control/route.js.nft.json +1 -1
  41. package/bundle/.next/server/app/api/integrations/[integrationId]/status/route.js +1 -1
  42. package/bundle/.next/server/app/api/integrations/[integrationId]/status/route.js.nft.json +1 -1
  43. package/bundle/.next/server/app/api/mission/route.js +1 -1
  44. package/bundle/.next/server/app/api/mission/route.js.nft.json +1 -1
  45. package/bundle/.next/server/app/api/models/catalog/route.js +2 -2
  46. package/bundle/.next/server/app/api/models/catalog/route.js.nft.json +1 -1
  47. package/bundle/.next/server/app/api/models/providers/route.js +2 -2
  48. package/bundle/.next/server/app/api/models/providers/route.js.nft.json +1 -1
  49. package/bundle/.next/server/app/api/onboarding/models/route.js +3 -3
  50. package/bundle/.next/server/app/api/onboarding/models/route.js.nft.json +1 -1
  51. package/bundle/.next/server/app/api/onboarding/route.js +2 -2
  52. package/bundle/.next/server/app/api/onboarding/route.js.nft.json +1 -1
  53. package/bundle/.next/server/app/api/openclaw/capabilities/route.js +1 -1
  54. package/bundle/.next/server/app/api/openclaw/compatibility-smoke/route.js +1 -1
  55. package/bundle/.next/server/app/api/openclaw/compatibility-smoke/route.js.nft.json +1 -1
  56. package/bundle/.next/server/app/api/planner/[planId]/deploy/route.js +2 -2
  57. package/bundle/.next/server/app/api/planner/[planId]/deploy/route.js.nft.json +1 -1
  58. package/bundle/.next/server/app/api/planner/[planId]/document-rewrite/route.js +1 -1
  59. package/bundle/.next/server/app/api/planner/[planId]/document-rewrite/route.js.nft.json +1 -1
  60. package/bundle/.next/server/app/api/planner/[planId]/route.js +1 -1
  61. package/bundle/.next/server/app/api/planner/[planId]/route.js.nft.json +1 -1
  62. package/bundle/.next/server/app/api/planner/[planId]/simulate/route.js +1 -1
  63. package/bundle/.next/server/app/api/planner/[planId]/simulate/route.js.nft.json +1 -1
  64. package/bundle/.next/server/app/api/planner/[planId]/turn/route.js +1 -1
  65. package/bundle/.next/server/app/api/planner/[planId]/turn/route.js.nft.json +1 -1
  66. package/bundle/.next/server/app/api/planner/route.js +1 -1
  67. package/bundle/.next/server/app/api/planner/route.js.nft.json +1 -1
  68. package/bundle/.next/server/app/api/reset/route.js +2 -2
  69. package/bundle/.next/server/app/api/reset/route.js.nft.json +1 -1
  70. package/bundle/.next/server/app/api/runtimes/[runtimeId]/route.js +1 -1
  71. package/bundle/.next/server/app/api/runtimes/[runtimeId]/route.js.nft.json +1 -1
  72. package/bundle/.next/server/app/api/settings/gateway/route.js +1 -1
  73. package/bundle/.next/server/app/api/settings/gateway/route.js.nft.json +1 -1
  74. package/bundle/.next/server/app/api/settings/openclaw-binary/route.js +1 -1
  75. package/bundle/.next/server/app/api/settings/openclaw-binary/route.js.nft.json +1 -1
  76. package/bundle/.next/server/app/api/settings/workspace-root/route.js +1 -1
  77. package/bundle/.next/server/app/api/settings/workspace-root/route.js.nft.json +1 -1
  78. package/bundle/.next/server/app/api/snapshot/route.js +1 -1
  79. package/bundle/.next/server/app/api/snapshot/route.js.nft.json +1 -1
  80. package/bundle/.next/server/app/api/stream/route.js +2 -2
  81. package/bundle/.next/server/app/api/stream/route.js.nft.json +1 -1
  82. package/bundle/.next/server/app/api/system/open-terminal/route.js +1 -1
  83. package/bundle/.next/server/app/api/tasks/[taskId]/abort/route.js +1 -1
  84. package/bundle/.next/server/app/api/tasks/[taskId]/abort/route.js.nft.json +1 -1
  85. package/bundle/.next/server/app/api/tasks/[taskId]/control/route.js +1 -1
  86. package/bundle/.next/server/app/api/tasks/[taskId]/control/route.js.nft.json +1 -1
  87. package/bundle/.next/server/app/api/tasks/[taskId]/stream/route.js +2 -2
  88. package/bundle/.next/server/app/api/tasks/[taskId]/stream/route.js.nft.json +1 -1
  89. package/bundle/.next/server/app/api/update/route.js +2 -2
  90. package/bundle/.next/server/app/api/update/route.js.nft.json +1 -1
  91. package/bundle/.next/server/app/api/workspaces/[workspaceId]/channels/discovered-groups/route.js +1 -1
  92. package/bundle/.next/server/app/api/workspaces/[workspaceId]/channels/discovered-groups/route.js.nft.json +1 -1
  93. package/bundle/.next/server/app/api/workspaces/[workspaceId]/channels/route.js +1 -1
  94. package/bundle/.next/server/app/api/workspaces/[workspaceId]/channels/route.js.nft.json +1 -1
  95. package/bundle/.next/server/app/api/workspaces/[workspaceId]/edit-draft/route.js +1 -1
  96. package/bundle/.next/server/app/api/workspaces/[workspaceId]/edit-draft/route.js.nft.json +1 -1
  97. package/bundle/.next/server/app/api/workspaces/[workspaceId]/files/route.js +1 -1
  98. package/bundle/.next/server/app/api/workspaces/[workspaceId]/files/route.js.nft.json +1 -1
  99. package/bundle/.next/server/app/api/workspaces/[workspaceId]/surfaces/discovery/route.js +1 -1
  100. package/bundle/.next/server/app/api/workspaces/[workspaceId]/surfaces/discovery/route.js.nft.json +1 -1
  101. package/bundle/.next/server/app/api/workspaces/[workspaceId]/surfaces/reconcile/route.js +1 -0
  102. package/bundle/.next/server/app/api/workspaces/[workspaceId]/surfaces/reconcile/route.js.nft.json +1 -0
  103. package/bundle/.next/server/app/api/workspaces/[workspaceId]/surfaces/reconcile/route_client-reference-manifest.js +1 -0
  104. package/bundle/.next/server/app/api/workspaces/route.js +2 -2
  105. package/bundle/.next/server/app/api/workspaces/route.js.nft.json +1 -1
  106. package/bundle/.next/server/app/files/page.js +2 -2
  107. package/bundle/.next/server/app/files/page.js.nft.json +1 -1
  108. package/bundle/.next/server/app/files/page_client-reference-manifest.js +1 -1
  109. package/bundle/.next/server/app/integrations/page.js +2 -2
  110. package/bundle/.next/server/app/integrations/page.js.nft.json +1 -1
  111. package/bundle/.next/server/app/integrations/page_client-reference-manifest.js +1 -1
  112. package/bundle/.next/server/app/models/page.js +2 -2
  113. package/bundle/.next/server/app/models/page.js.nft.json +1 -1
  114. package/bundle/.next/server/app/models/page_client-reference-manifest.js +1 -1
  115. package/bundle/.next/server/app/page.js +2 -2
  116. package/bundle/.next/server/app/page.js.nft.json +1 -1
  117. package/bundle/.next/server/app/page_client-reference-manifest.js +1 -1
  118. package/bundle/.next/server/app/settings/page.js +2 -2
  119. package/bundle/.next/server/app/settings/page.js.nft.json +1 -1
  120. package/bundle/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  121. package/bundle/.next/server/app/tasks/page.js +2 -2
  122. package/bundle/.next/server/app/tasks/page.js.nft.json +1 -1
  123. package/bundle/.next/server/app/tasks/page_client-reference-manifest.js +1 -1
  124. package/bundle/.next/server/app-paths-manifest.json +10 -9
  125. package/bundle/.next/server/chunks/1718.js +3 -3
  126. package/bundle/.next/server/chunks/2082.js +183 -0
  127. package/bundle/.next/server/chunks/262.js +1 -0
  128. package/bundle/.next/server/chunks/4391.js +2 -2
  129. package/bundle/.next/server/chunks/4767.js +7 -6
  130. package/bundle/.next/server/chunks/4983.js +1 -1
  131. package/bundle/.next/server/chunks/6476.js +3 -3
  132. package/bundle/.next/server/chunks/707.js +1 -0
  133. package/bundle/.next/server/chunks/7661.js +1 -1
  134. package/bundle/.next/server/functions-config-manifest.json +2 -1
  135. package/bundle/.next/server/middleware-build-manifest.js +1 -1
  136. package/bundle/.next/server/pages/404.html +1 -1
  137. package/bundle/.next/server/pages/500.html +1 -1
  138. package/bundle/.next/server/server-reference-manifest.json +1 -1
  139. package/bundle/.next/static/chunks/{2083-7a341dd360f54c8b.js → 2083-d45e8f4c93715147.js} +1 -1
  140. package/bundle/.next/static/chunks/6672-b36e3759495f9ac7.js +1 -0
  141. package/bundle/.next/static/chunks/{7442-b2286cbca8c413fd.js → 7442-2dc44f100f1573ea.js} +2 -2
  142. package/bundle/.next/static/chunks/app/_global-error/{page-8443c62570b9a078.js → page-a5154759aeb4c2c4.js} +1 -1
  143. package/bundle/.next/static/chunks/app/_not-found/{page-8443c62570b9a078.js → page-a5154759aeb4c2c4.js} +1 -1
  144. package/bundle/.next/static/chunks/app/agents/page-8acb55d794d87f71.js +1 -0
  145. package/bundle/.next/static/chunks/app/api/agents/[agentId]/chat/{route-8443c62570b9a078.js → route-a5154759aeb4c2c4.js} +1 -1
  146. package/bundle/.next/static/chunks/app/api/agents/{route-8443c62570b9a078.js → route-a5154759aeb4c2c4.js} +1 -1
  147. package/bundle/.next/static/chunks/app/api/diagnostics/route-a5154759aeb4c2c4.js +1 -0
  148. package/bundle/.next/static/chunks/app/api/files/reveal/route-a5154759aeb4c2c4.js +1 -0
  149. package/bundle/.next/static/chunks/app/api/gateway/control/route-a5154759aeb4c2c4.js +1 -0
  150. package/bundle/.next/static/chunks/app/api/integrations/[integrationId]/status/route-a5154759aeb4c2c4.js +1 -0
  151. package/bundle/.next/static/chunks/app/api/mission/route-a5154759aeb4c2c4.js +1 -0
  152. package/bundle/.next/static/chunks/app/api/models/catalog/route-a5154759aeb4c2c4.js +1 -0
  153. package/bundle/.next/static/chunks/app/api/models/providers/route-a5154759aeb4c2c4.js +1 -0
  154. package/bundle/.next/static/chunks/app/api/onboarding/models/route-a5154759aeb4c2c4.js +1 -0
  155. package/bundle/.next/static/chunks/app/api/onboarding/route-a5154759aeb4c2c4.js +1 -0
  156. package/bundle/.next/static/chunks/app/api/openclaw/capabilities/route-a5154759aeb4c2c4.js +1 -0
  157. package/bundle/.next/static/chunks/app/api/openclaw/compatibility-smoke/route-a5154759aeb4c2c4.js +1 -0
  158. package/bundle/.next/static/chunks/app/api/planner/[planId]/deploy/route-a5154759aeb4c2c4.js +1 -0
  159. package/bundle/.next/static/chunks/app/api/planner/[planId]/document-rewrite/route-a5154759aeb4c2c4.js +1 -0
  160. package/bundle/.next/static/chunks/app/api/planner/[planId]/route-a5154759aeb4c2c4.js +1 -0
  161. package/bundle/.next/static/chunks/app/api/planner/[planId]/simulate/route-a5154759aeb4c2c4.js +1 -0
  162. package/bundle/.next/static/chunks/app/api/planner/[planId]/turn/route-a5154759aeb4c2c4.js +1 -0
  163. package/bundle/.next/static/chunks/app/api/planner/route-a5154759aeb4c2c4.js +1 -0
  164. package/bundle/.next/static/chunks/app/api/reset/route-a5154759aeb4c2c4.js +1 -0
  165. package/bundle/.next/static/chunks/app/api/runtimes/[runtimeId]/route-a5154759aeb4c2c4.js +1 -0
  166. package/bundle/.next/static/chunks/app/api/settings/gateway/route-a5154759aeb4c2c4.js +1 -0
  167. package/bundle/.next/static/chunks/app/api/settings/openclaw-binary/route-a5154759aeb4c2c4.js +1 -0
  168. package/bundle/.next/static/chunks/app/api/settings/workspace-root/route-a5154759aeb4c2c4.js +1 -0
  169. package/bundle/.next/static/chunks/app/api/snapshot/route-a5154759aeb4c2c4.js +1 -0
  170. package/bundle/.next/static/chunks/app/api/stream/route-a5154759aeb4c2c4.js +1 -0
  171. package/bundle/.next/static/chunks/app/api/system/open-terminal/route-a5154759aeb4c2c4.js +1 -0
  172. package/bundle/.next/static/chunks/app/api/tasks/[taskId]/abort/route-a5154759aeb4c2c4.js +1 -0
  173. package/bundle/.next/static/chunks/app/api/tasks/[taskId]/control/route-a5154759aeb4c2c4.js +1 -0
  174. package/bundle/.next/static/chunks/app/api/tasks/[taskId]/stream/route-a5154759aeb4c2c4.js +1 -0
  175. package/bundle/.next/static/chunks/app/api/update/route-a5154759aeb4c2c4.js +1 -0
  176. package/bundle/.next/static/chunks/app/api/workspaces/[workspaceId]/channels/discovered-groups/route-a5154759aeb4c2c4.js +1 -0
  177. package/bundle/.next/static/chunks/app/api/workspaces/[workspaceId]/channels/route-a5154759aeb4c2c4.js +1 -0
  178. package/bundle/.next/static/chunks/app/api/workspaces/[workspaceId]/edit-draft/route-a5154759aeb4c2c4.js +1 -0
  179. package/bundle/.next/static/chunks/app/api/workspaces/[workspaceId]/files/route-a5154759aeb4c2c4.js +1 -0
  180. package/bundle/.next/static/chunks/app/api/workspaces/[workspaceId]/surfaces/discovery/route-a5154759aeb4c2c4.js +1 -0
  181. package/bundle/.next/static/chunks/app/api/workspaces/[workspaceId]/surfaces/reconcile/route-a5154759aeb4c2c4.js +1 -0
  182. package/bundle/.next/static/chunks/app/api/workspaces/route-a5154759aeb4c2c4.js +1 -0
  183. package/bundle/.next/static/chunks/app/files/page-3e166ac1009662a0.js +1 -0
  184. package/bundle/.next/static/chunks/app/integrations/page-a58f85dfc4c23468.js +1 -0
  185. package/bundle/.next/static/chunks/app/models/page-45a41bff0c708600.js +1 -0
  186. package/bundle/.next/static/chunks/app/not-found-a5154759aeb4c2c4.js +1 -0
  187. package/bundle/.next/static/chunks/app/page-78b8c43dceba02d6.js +1 -0
  188. package/bundle/.next/static/chunks/app/settings/page-dc8c5f99e93317b5.js +1 -0
  189. package/bundle/.next/static/chunks/app/tasks/page-4c8cc3fefa0a18bb.js +1 -0
  190. package/bundle/.next/static/chunks/next/dist/client/components/builtin/app-error-a5154759aeb4c2c4.js +1 -0
  191. package/bundle/.next/static/chunks/next/dist/client/components/builtin/forbidden-a5154759aeb4c2c4.js +1 -0
  192. package/bundle/.next/static/chunks/next/dist/client/components/builtin/unauthorized-a5154759aeb4c2c4.js +1 -0
  193. package/bundle/.next/static/css/dabe7b13ad484ddd.css +3 -0
  194. package/bundle/package.json +4 -1
  195. package/bundle/server.js +1 -1
  196. package/package.json +2 -2
  197. package/bundle/.next/server/chunks/5151.js +0 -183
  198. package/bundle/.next/server/chunks/8849.js +0 -1
  199. package/bundle/.next/static/chunks/2396-395f5ed99e66819d.js +0 -1
  200. package/bundle/.next/static/chunks/app/agents/page-a48b3909fe8cc49b.js +0 -1
  201. package/bundle/.next/static/chunks/app/api/diagnostics/route-8443c62570b9a078.js +0 -1
  202. package/bundle/.next/static/chunks/app/api/files/reveal/route-8443c62570b9a078.js +0 -1
  203. package/bundle/.next/static/chunks/app/api/gateway/control/route-8443c62570b9a078.js +0 -1
  204. package/bundle/.next/static/chunks/app/api/integrations/[integrationId]/status/route-8443c62570b9a078.js +0 -1
  205. package/bundle/.next/static/chunks/app/api/mission/route-8443c62570b9a078.js +0 -1
  206. package/bundle/.next/static/chunks/app/api/models/catalog/route-8443c62570b9a078.js +0 -1
  207. package/bundle/.next/static/chunks/app/api/models/providers/route-8443c62570b9a078.js +0 -1
  208. package/bundle/.next/static/chunks/app/api/onboarding/models/route-8443c62570b9a078.js +0 -1
  209. package/bundle/.next/static/chunks/app/api/onboarding/route-8443c62570b9a078.js +0 -1
  210. package/bundle/.next/static/chunks/app/api/openclaw/capabilities/route-8443c62570b9a078.js +0 -1
  211. package/bundle/.next/static/chunks/app/api/openclaw/compatibility-smoke/route-8443c62570b9a078.js +0 -1
  212. package/bundle/.next/static/chunks/app/api/planner/[planId]/deploy/route-8443c62570b9a078.js +0 -1
  213. package/bundle/.next/static/chunks/app/api/planner/[planId]/document-rewrite/route-8443c62570b9a078.js +0 -1
  214. package/bundle/.next/static/chunks/app/api/planner/[planId]/route-8443c62570b9a078.js +0 -1
  215. package/bundle/.next/static/chunks/app/api/planner/[planId]/simulate/route-8443c62570b9a078.js +0 -1
  216. package/bundle/.next/static/chunks/app/api/planner/[planId]/turn/route-8443c62570b9a078.js +0 -1
  217. package/bundle/.next/static/chunks/app/api/planner/route-8443c62570b9a078.js +0 -1
  218. package/bundle/.next/static/chunks/app/api/reset/route-8443c62570b9a078.js +0 -1
  219. package/bundle/.next/static/chunks/app/api/runtimes/[runtimeId]/route-8443c62570b9a078.js +0 -1
  220. package/bundle/.next/static/chunks/app/api/settings/gateway/route-8443c62570b9a078.js +0 -1
  221. package/bundle/.next/static/chunks/app/api/settings/openclaw-binary/route-8443c62570b9a078.js +0 -1
  222. package/bundle/.next/static/chunks/app/api/settings/workspace-root/route-8443c62570b9a078.js +0 -1
  223. package/bundle/.next/static/chunks/app/api/snapshot/route-8443c62570b9a078.js +0 -1
  224. package/bundle/.next/static/chunks/app/api/stream/route-8443c62570b9a078.js +0 -1
  225. package/bundle/.next/static/chunks/app/api/system/open-terminal/route-8443c62570b9a078.js +0 -1
  226. package/bundle/.next/static/chunks/app/api/tasks/[taskId]/abort/route-8443c62570b9a078.js +0 -1
  227. package/bundle/.next/static/chunks/app/api/tasks/[taskId]/control/route-8443c62570b9a078.js +0 -1
  228. package/bundle/.next/static/chunks/app/api/tasks/[taskId]/stream/route-8443c62570b9a078.js +0 -1
  229. package/bundle/.next/static/chunks/app/api/update/route-8443c62570b9a078.js +0 -1
  230. package/bundle/.next/static/chunks/app/api/workspaces/[workspaceId]/channels/discovered-groups/route-8443c62570b9a078.js +0 -1
  231. package/bundle/.next/static/chunks/app/api/workspaces/[workspaceId]/channels/route-8443c62570b9a078.js +0 -1
  232. package/bundle/.next/static/chunks/app/api/workspaces/[workspaceId]/edit-draft/route-8443c62570b9a078.js +0 -1
  233. package/bundle/.next/static/chunks/app/api/workspaces/[workspaceId]/files/route-8443c62570b9a078.js +0 -1
  234. package/bundle/.next/static/chunks/app/api/workspaces/[workspaceId]/surfaces/discovery/route-8443c62570b9a078.js +0 -1
  235. package/bundle/.next/static/chunks/app/api/workspaces/route-8443c62570b9a078.js +0 -1
  236. package/bundle/.next/static/chunks/app/files/page-a0e2fdb9c72008d3.js +0 -1
  237. package/bundle/.next/static/chunks/app/integrations/page-fbeb03fb416b56e4.js +0 -1
  238. package/bundle/.next/static/chunks/app/models/page-a22fedc08112e7a0.js +0 -1
  239. package/bundle/.next/static/chunks/app/not-found-8443c62570b9a078.js +0 -1
  240. package/bundle/.next/static/chunks/app/page-4f990fddc5f18dcf.js +0 -1
  241. package/bundle/.next/static/chunks/app/settings/page-28f1484e79b1be1f.js +0 -1
  242. package/bundle/.next/static/chunks/app/tasks/page-89536b0bec007ced.js +0 -1
  243. package/bundle/.next/static/chunks/next/dist/client/components/builtin/app-error-8443c62570b9a078.js +0 -1
  244. package/bundle/.next/static/chunks/next/dist/client/components/builtin/forbidden-8443c62570b9a078.js +0 -1
  245. package/bundle/.next/static/chunks/next/dist/client/components/builtin/unauthorized-8443c62570b9a078.js +0 -1
  246. package/bundle/.next/static/css/288b13e5308447b9.css +0 -3
  247. /package/bundle/.next/static/{C5KQaZvAavAtZzYvH3CPw → 0BcJbvZncZCzzyzha3Yje}/_buildManifest.js +0 -0
  248. /package/bundle/.next/static/{C5KQaZvAavAtZzYvH3CPw → 0BcJbvZncZCzzyzha3Yje}/_ssgManifest.js +0 -0
@@ -1,5 +1,5 @@
1
1
  "use strict";exports.id=4767,exports.ids=[4767],exports.modules={185:(a,b,c)=>{c.d(b,{o:()=>l});var d=c(51455),e=c(48161),f=c.n(e),g=c(76760),h=c.n(g),i=c(39503),j=c(11782);let k=new Map;async function l({agentId:a,modelId:b,agentDir:c}){let d;if(!a.trim()||!b||!(0,j.JC)(b))return{repaired:!1,reason:"not-codex-model"};try{d=await (0,i.rw)().getAgentModelStatus({agentId:a},{timeoutMs:8e3})}catch(b){let a=c?await o(c).catch(()=>[]):[];return{repaired:a.length>0,reason:a.length>0?"profile-copy-fallback":"status-failed",profileIds:a,error:b}}let e=function(a){let b=a.auth?.oauth?.providers?.find(a=>"openai-codex"===a.provider),c=(Array.isArray(b?.profiles)?b.profiles:[]).filter(s).map(a=>t(a.profileId)).filter(u);if(0===c.length)return{needsRepair:!1,profileIds:[],reason:"no-usable-profile"};let d=(Array.isArray(b?.effectiveProfiles)?b.effectiveProfiles:[]).find(v),e=d?t(d.profileId):null;return"ok"===t(b?.status)?.toLowerCase()&&e&&c.includes(e)?{needsRepair:!1,profileIds:c,reason:"not-needed"}:{needsRepair:!0,profileIds:c,reason:"needs-order"}}(d);if(!e.needsRepair)return{repaired:!1,reason:e.reason};let f=e.profileIds.join("\n"),g=`${a}:${f}`,h=k.get(g);if(h&&h.expiresAt>Date.now())return{repaired:!1,reason:"recently-repaired"};let p=t(d.agentDir)??c??null;p&&await n(p,e.profileIds).catch(()=>void 0);try{return"main"!==a&&await m("main",e.profileIds).catch(()=>void 0),await m(a,e.profileIds),k.set(g,{expiresAt:Date.now()+3e5,profileKey:f}),{repaired:!0,reason:"order-set",profileIds:e.profileIds}}catch(a){return{repaired:!1,reason:"repair-failed",error:a}}}async function m(a,b){let c=null;for(let d of[0,750,1500]){d>0&&await function(a){return new Promise(b=>globalThis.setTimeout(b,a))}(d);try{await (0,i.rw)().setModelAuthOrder({provider:"openai-codex",agentId:a,profileIds:b},{timeoutMs:8e3});return}catch(a){c=a}}throw c}async function n(a,b){let c=await q(p()),e=h().join(a,"auth-profiles.json"),f=await q(e),g=!1;for(let a of(f.version=1,f.profiles=f.profiles??{},b)){let b=c.profiles?.[a];r(b)&&JSON.stringify(f.profiles[a])!==JSON.stringify(b)&&(f.profiles[a]=b,g=!0)}g&&(await (0,d.mkdir)(h().dirname(e),{recursive:!0}),await (0,d.writeFile)(e,`${JSON.stringify(f,null,2)}
2
- `,"utf8"))}async function o(a){let b=Object.entries((await q(p())).profiles??{}).filter(([,a])=>r(a)).map(([a])=>a);return 0===b.length?[]:(await n(a,b),b)}function p(){return h().join(f().homedir(),".openclaw","agents","main","agent","auth-profiles.json")}async function q(a){try{let b=await (0,d.readFile)(a,"utf8"),c=JSON.parse(b);if(v(c))return{version:"number"==typeof c.version?c.version:1,profiles:v(c.profiles)?Object.fromEntries(Object.entries(c.profiles).filter(a=>v(a[1]))):{}}}catch{}return{version:1,profiles:{}}}function r(a){return v(a)&&"oauth"===a.type&&"openai-codex"===a.provider&&v(a.oauthRef)}function s(a){if(!v(a)||!t(a.profileId))return!1;let b=t(a.status)?.toLowerCase();return!b||!["expired","missing","invalid","error","disabled","revoked"].includes(b)}function t(a){return"string"==typeof a&&a.trim()?a.trim():null}function u(a){return!!a}function v(a){return!!a&&"object"==typeof a&&!Array.isArray(a)}},3334:(a,b,c)=>{c.d(b,{Z:()=>o});var d=c(27091),e=c(39802),f=c(93628);function g(a){return Array.from(new Set(a.filter(Boolean)))}function h(a){let b=new Map;for(let c of a)c.chatId&&b.set(c.chatId,c);return Array.from(b.values())}function i(a){return a.title&&a.title!==a.chatId?`${a.title} (\`${a.chatId}\`)`:`\`${a.chatId}\``}function j(a){if(!a)return"no capability snapshot";let b=[(0,f._P)(a.policy.preset)],c=a.profile.purpose?.trim();c&&b.push(c);let d=g(a.skills).slice(0,2);d.length>0&&b.push(`skills: ${d.join(", ")}`);let e=g(a.tools).slice(0,2);return e.length>0&&b.push(`tools: ${e.join(", ")}`),b.join(" \xb7 ")}function k(a){return Array.from(new Set(a.filter(Boolean)))}function l(a){let b=new Map;for(let c of a)c.chatId&&b.set(c.chatId,c);return Array.from(b.values())}function m(a,b,c){let e=new Map(a?.agents.map(a=>[a.id,(0,d.CK)(a)])??[]),f=new Map(a?.agents.map(a=>[a.id,a])??[]);return k(b.filter(a=>!c.includes(a))).map(a=>{let b=f.get(a)??null;return{agentId:a,name:e.get(a)??a,summary:function(a){if(!a)return"no capability snapshot";let b=[(0,d.CK)(a)],c=a.profile.purpose?.trim();c&&b.push(c);let e=k(a.skills).slice(0,2);e.length>0&&b.push(`skills: ${e.join(", ")}`);let f=k(a.tools).slice(0,2);return f.length>0&&b.push(`tools: ${f.join(", ")}`),b.join(" \xb7 ")}(b)}})}function n(a){let b=(0,e.S)(a.chatId),c=b?.kind==="role"?`@${b.targetId}`:b?.kind==="thread"?`Thread ${b.targetId}`:b?.kind==="channel"?`#${b.targetId}`:a.chatId;return{routeId:a.chatId,label:a.title?.trim()||c,kind:b?.kind??"channel",guildId:b?.guildId??null}}function o(a,b,c=b?.channelRegistry??null){let e=[function(a){if(!a||0===a.primaryChannels.length&&0===a.ownedGroups.length&&0===a.delegateChannels.length)return null;let b=["## Telegram coordination"];if(b.push("- Telegram credentials are managed by OpenClaw for the listed channels. Do not ask the operator for `TELEGRAM_BOT_TOKEN` or `channels.telegram.botToken` when sending to listed groups."),b.push('- To send or post, call the `message` tool with `action: "send"`, `channel: "telegram"`, `target: "<chatId>"`, and the exact message text. Use the listed chat id as `target`.'),b.push("- If sending fails, report the actual tool error instead of inventing a missing-token error."),a.primaryChannels.length>0){for(let c of(b.push("- You are the public Telegram fallback for these channels:"),a.primaryChannels)){let a=c.groups.length>0?c.groups.map(i).join(", "):"no allowed groups yet";if(b.push(` - ${c.channelName} (\`${c.channelId}\`) \xb7 fallback groups: ${a}.`),c.peers.length>0)for(let a of(b.push(" - Internal assistants:"),c.peers))b.push(` - ${a.name} (\`${a.agentId}\`) \xb7 ${a.summary}.`)}b.push("- Keep public Telegram replies under your own voice for unassigned groups, even when you ask another agent for help."),b.push("- For specialist help, call another agent from the workspace terminal with:"),b.push("```bash"),b.push('node .openclaw/tools/telegram-delegate-agent.mjs --agent <delegate-agent-id> --message "Summarize what I need from you"'),b.push("```"),b.push("- Use delegate turns for internal research, drafting, or analysis only. Do not ask them to answer Telegram directly."),b.push("- After a delegate responds, decide what to share publicly and send the final Telegram reply yourself.")}if(a.ownedGroups.length>0){for(let c of(b.push("- You are the public Telegram voice for these assigned groups:"),a.ownedGroups))if(b.push(` - ${c.channelName} (\`${c.channelId}\`) \xb7 ${c.title??c.chatId} (\`${c.chatId}\`) \xb7 primary ${c.primaryAgentName} (\`${c.primaryAgentId}\`).`),c.peers.length>0)for(let a of(b.push(" - Internal assistants for this group:"),c.peers))b.push(` - ${a.name} (\`${a.agentId}\`) \xb7 ${a.summary}.`);b.push("- Reply directly to those groups as the public voice. Use other agents only for internal help.")}if(a.delegateChannels.length>0){for(let c of(b.push("- You can assist these Telegram admin channels when the primary agent asks:"),a.delegateChannels)){let a=c.groups.length>0?c.groups.map(i).join(", "):"no allowed groups yet";if(b.push(` - ${c.channelName} (\`${c.channelId}\`) \xb7 primary ${c.primaryAgentName} (\`${c.primaryAgentId}\`) \xb7 groups: ${a}.`),c.peers.length>0)for(let a of(b.push(" - Nearby assistants:"),c.peers))b.push(` - ${a.name} (\`${a.agentId}\`) \xb7 ${a.summary}.`)}b.push("- When helping with Telegram work for groups not assigned to you, return concise internal findings or draft language. Do not speak as the public Telegram agent for those unassigned groups.")}return b.join("\n")}(function(a,b,c=b?.channelRegistry??null){if(!c)return null;let e=new Map(b?.agents.map(a=>[a.id,(0,d.CK)(a)])??[]),f=new Map(b?.agents.map(a=>[a.id,a])??[]),i=f.get(a)??null,k=i?.workspaceId??null,l=[],m=[],n=[];for(let b of c.channels.filter(a=>"telegram"===a.type)){let c=b.workspaces.filter(a=>a.workspaceId===k);if(0===c.length)continue;let i=h(c.flatMap(a=>a.groupAssignments.filter(a=>!1!==a.enabled))).map(a=>({chatId:a.chatId,title:a.title??null})),o=h(c.flatMap(b=>b.groupAssignments.filter(b=>!1!==b.enabled&&b.agentId===a))),p=i.filter(a=>!o.some(b=>b.chatId===a.chatId)&&!c.some(b=>b.groupAssignments.some(b=>!1!==b.enabled&&b.chatId===a.chatId&&b.agentId)));if(b.primaryAgentId===a){let d=g(c.flatMap(b=>b.agentIds.filter(b=>b!==a))).map(a=>{let b=f.get(a)??null;return{agentId:a,name:e.get(a)??a,summary:j(b)}});l.push({channelId:b.id,channelName:b.name,groups:p,peers:d})}for(let d of o){let h=g(c.flatMap(c=>c.agentIds.filter(c=>c!==a&&c!==b.primaryAgentId))).map(a=>{let b=f.get(a)??null;return{agentId:a,name:e.get(a)??a,summary:j(b)}});m.push({channelId:b.id,channelName:b.name,chatId:d.chatId,title:d.title??null,primaryAgentId:b.primaryAgentId??a,primaryAgentName:e.get(b.primaryAgentId??a)??b.primaryAgentId??a,peers:h})}if(b.primaryAgentId&&b.primaryAgentId!==a&&0===o.length){let h=f.get(b.primaryAgentId)??null,i=g(c.flatMap(c=>c.agentIds.filter(c=>c!==b.primaryAgentId&&c!==a))).map(a=>{let b=f.get(a)??null;return{agentId:a,name:e.get(a)??a,summary:j(b)}});n.push({channelId:b.id,channelName:b.name,groups:p,peers:i,primaryAgentId:b.primaryAgentId,primaryAgentName:e.get(b.primaryAgentId)??(h?(0,d.CK)(h):b.primaryAgentId)})}}return{primaryChannels:l.sort((a,b)=>a.channelName.localeCompare(b.channelName)),ownedGroups:m.sort((a,b)=>{let c=`${a.channelName}:${a.title??a.chatId}`,d=`${b.channelName}:${b.title??b.chatId}`;return c.localeCompare(d)}),delegateChannels:n.sort((a,b)=>a.channelName.localeCompare(b.channelName))}}(a,b,c)),function(a){if(!a||0===a.primaryChannels.length&&0===a.ownedRoutes.length&&0===a.delegateChannels.length)return null;let b=["## Discord coordination"];if(a.primaryChannels.length>0){for(let c of(b.push("- You are the public Discord fallback for these channels:"),a.primaryChannels)){let a=c.routes.length>0?c.routes.map(a=>`${a.label} (\`${a.routeId}\`)`).join(", "):"no allowed routes yet";if(b.push(` - ${c.channelName} (\`${c.channelId}\`) \xb7 fallback routes: ${a}.`),c.peers.length>0)for(let a of(b.push(" - Internal assistants:"),c.peers))b.push(` - ${a.name} (\`${a.agentId}\`) \xb7 ${a.summary}.`)}b.push("- Keep public Discord replies under your own voice for unassigned routes, even when you ask another agent for help.")}if(a.ownedRoutes.length>0){for(let c of(b.push("- You are the public Discord voice for these assigned routes:"),a.ownedRoutes))if(b.push(` - ${c.channelName} (\`${c.channelId}\`) \xb7 ${c.label} (\`${c.routeId}\`) \xb7 primary ${c.primaryAgentName} (\`${c.primaryAgentId}\`).`),c.peers.length>0)for(let a of(b.push(" - Internal assistants for this route:"),c.peers))b.push(` - ${a.name} (\`${a.agentId}\`) \xb7 ${a.summary}.`);b.push("- Reply directly to those routes as the public voice. Use other agents only for internal help.")}if(a.delegateChannels.length>0){for(let c of(b.push("- You can assist these Discord admin channels when the primary agent asks:"),a.delegateChannels)){let a=c.routes.length>0?c.routes.map(a=>`${a.label} (\`${a.routeId}\`)`).join(", "):"no allowed routes yet";if(b.push(` - ${c.channelName} (\`${c.channelId}\`) \xb7 primary ${c.primaryAgentName} (\`${c.primaryAgentId}\`) \xb7 routes: ${a}.`),c.peers.length>0)for(let a of(b.push(" - Nearby assistants:"),c.peers))b.push(` - ${a.name} (\`${a.agentId}\`) \xb7 ${a.summary}.`)}b.push("- When helping with Discord work, return concise internal findings or draft language. Do not speak as the public Discord agent.")}return b.join("\n")}(function(a,b,c=b?.channelRegistry??null){if(!c)return null;let e=b?.agents.find(b=>b.id===a)??null,f=e?.workspaceId??null,g=[],h=[],i=[];for(let e of c.channels.filter(a=>"discord"===a.type)){var j,k,o,p;let c=e.workspaces.filter(a=>a.workspaceId===f);if(0===c.length)continue;let q=l(c.flatMap(a=>a.groupAssignments.filter(a=>!1!==a.enabled))).map(n),r=l(c.flatMap(b=>b.groupAssignments.filter(b=>!1!==b.enabled&&b.agentId===a))).map(n),s=q.filter(a=>!r.some(b=>b.routeId===a.routeId)&&!c.some(b=>b.groupAssignments.some(b=>!1!==b.enabled&&b.chatId===a.routeId&&b.agentId)));if(e.primaryAgentId===a){let d=m(b,c.flatMap(b=>b.agentIds.filter(b=>b!==a)),[a]);g.push({channelId:e.id,channelName:e.name,routes:s,peers:d})}for(let f of r){let g=m(b,c.flatMap(b=>b.agentIds.filter(b=>b!==a&&b!==e.primaryAgentId)),[a,e.primaryAgentId??""]);h.push({channelId:e.id,channelName:e.name,routeId:f.routeId,label:f.label,kind:f.kind,guildId:f.guildId,primaryAgentId:e.primaryAgentId??a,primaryAgentName:(j=b?.agents.find(b=>b.id===(e.primaryAgentId??a))??null,k=e.primaryAgentId??a,j?(0,d.CK)(j):k),peers:g})}if(e.primaryAgentId&&e.primaryAgentId!==a){let f=m(b,c.flatMap(b=>b.agentIds.filter(b=>b!==e.primaryAgentId&&b!==a)),[a,e.primaryAgentId]);i.push({channelId:e.id,channelName:e.name,routes:s,peers:f,primaryAgentId:e.primaryAgentId,primaryAgentName:(o=b?.agents.find(a=>a.id===e.primaryAgentId)??null,p=e.primaryAgentId,o?(0,d.CK)(o):p)})}}return{primaryChannels:g.sort((a,b)=>a.channelName.localeCompare(b.channelName)),ownedRoutes:h.sort((a,b)=>{let c=`${a.channelName}:${a.label}`,d=`${b.channelName}:${b.label}`;return c.localeCompare(d)}),delegateChannels:i.sort((a,b)=>a.channelName.localeCompare(b.channelName))}}(a,b,c))].filter(a=>!!a);return e.length>0?e.join("\n\n"):null}},24767:(a,b,c)=>{c.d(b,{yw:()=>bU,DM:()=>b7,er:()=>d.er,us:()=>bV,Sn:()=>aj,MP:()=>ca,zw:()=>bq,RB:()=>an,kd:()=>b4,qu:()=>bt,B5:()=>b3,H6:()=>b_.H6,lC:()=>b_.lC,dM:()=>bk,MQ:()=>b$.MQ,W6:()=>b$.W6,GM:()=>cJ,Y9:()=>bl,pf:()=>bm,FJ:()=>bu,f5:()=>b$.f5,MG:()=>b$.MG,W9:()=>b6,lT:()=>b5,xE:()=>bT,ct:()=>bj,o6:()=>b8,x4:()=>am,Vg:()=>b$.Vg,sQ:()=>bs,PR:()=>b$.PR,Oz:()=>b2});var d=c(5151),e=c(51455),f=c(76760),g=c.n(f),h=c(93628);function i(a,b){let c="monitoring"===a?{enabled:!0,every:"30m"}:{enabled:!1,every:"30m"},d="string"==typeof b?.every&&b.every.trim()&&"disabled"!==b.every?b.every.trim():c.every;return"boolean"==typeof b?.enabled?{enabled:b.enabled,every:d}:b?.every==="disabled"?{enabled:!1,every:d}:c}function j(a){return a?.enabled?{every:"string"==typeof a.every&&a.every.trim()?a.every.trim():"30m"}:null}var k=c(39503),l=c(71065),m=c(27091),n=c(98752),o=c(31421),p=c(57975),q=c(14853),r=c(15612),s=c(54252);let t=(0,p.promisify)(o.execFile);function u(a){return"string"==typeof a&&a.trim().length>0?a.trim():null}function v(a){return Array.from(new Set(a.filter(Boolean)))}function w(a){return v([...(a.skillIds??[]).map(a=>u(a)??""),u(a.skillId)??""])}function x(a){return a.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}async function y(a){try{return await (0,e.access)(a),!0}catch{return!1}}async function z(a,b,c={}){try{await t(a,b,{cwd:c.cwd??process.cwd(),timeout:c.timeoutMs??12e4,maxBuffer:8388608})}catch(a){throw Error("object"==typeof a&&a&&"stderr"in a&&"string"==typeof a.stderr&&a.stderr.trim()?a.stderr.trim():a instanceof Error?a.message:"Unknown system command failure.")}}async function A(a,b){try{await (0,e.access)(a)}catch{await (0,e.mkdir)(g().dirname(a),{recursive:!0}),await (0,e.writeFile)(a,b,"utf8")}}async function B(a,b){await (0,e.mkdir)(g().dirname(a),{recursive:!0}),await (0,e.writeFile)(a,b,"utf8")}async function C(a){try{throw await (0,e.access)(a),Error("Target workspace directory already exists.")}catch(a){if("ENOENT"===("object"==typeof a&&a&&"code"in a?a.code:void 0))return;if(a instanceof Error)throw a;throw Error("Unable to verify target workspace directory.")}}async function D(a){try{if(!(await (0,e.stat)(a)).isDirectory())throw Error("Target workspace path exists and is not a directory.");if((await (0,e.readdir)(a)).length>0)throw Error("Target workspace directory already contains files. Use Existing folder instead.")}catch(b){if("ENOENT"===("object"==typeof b&&b&&"code"in b?b.code:void 0))return void await (0,e.mkdir)(a,{recursive:!0});if(b instanceof Error)throw b;throw Error("Unable to prepare the workspace directory.")}await (0,e.mkdir)(a,{recursive:!0})}async function E(a){try{if(!(await (0,e.stat)(a)).isDirectory())throw Error("The selected existing path is not a directory.")}catch(a){if("ENOENT"===("object"==typeof a&&a&&"code"in a?a.code:void 0))throw Error("The selected existing folder does not exist.");if(a instanceof Error)throw a;throw Error("Unable to access the selected existing folder.")}}async function F(a,b){let c=u(b);return c?c.split("@")[0]:await y(g().join(a,"pnpm-lock.yaml"))?"pnpm":await y(g().join(a,"yarn.lock"))?"yarn":"npm"}async function G(a){let b=g().join(a,"package.json");try{let c=await (0,e.readFile)(b,"utf8"),d=JSON.parse(c),f=d.scripts??{},g=await F(a,d.packageManager),h=[`Use \`${g} install\` before the first local run.`];for(let a of["dev","start","test","lint","build"])f[a]&&h.push(`Use \`${"yarn"===g?`yarn ${a}`:`${g} run ${a}`}\` for the ${a} workflow.`);return h}catch{return[]}}async function H(a){let b=g().join(a,"Makefile");try{return((await (0,e.readFile)(b,"utf8")).match(/^(dev|test|lint|build|run):/gm)??[]).map(a=>`Use \`make ${a.replace(/:$/,"")}\` if the Makefile is the primary entry point.`)}catch{return[]}}async function I(a){let b=[];return await y(g().join(a,"pyproject.toml"))&&b.push("Use `pytest` for Python verification if the project exposes a test suite."),await y(g().join(a,"requirements.txt"))&&b.push("Install Python dependencies in a virtualenv before running project commands."),b}async function J(a){let b=[],c=await G(a),d=await H(a),e=await I(a);return b.push(...c,...d,...e),0===b.length&&b.push("Use repository-local scripts or documented commands for repeatable workflows.","Update this file when the project exposes a cleaner build, test, or release path."),v(b).slice(0,6)}function K(a,b){switch(a){case"project-builder":return`# Project Builder
2
+ `,"utf8"))}async function o(a){let b=Object.entries((await q(p())).profiles??{}).filter(([,a])=>r(a)).map(([a])=>a);return 0===b.length?[]:(await n(a,b),b)}function p(){return h().join(f().homedir(),".openclaw","agents","main","agent","auth-profiles.json")}async function q(a){try{let b=await (0,d.readFile)(a,"utf8"),c=JSON.parse(b);if(v(c))return{version:"number"==typeof c.version?c.version:1,profiles:v(c.profiles)?Object.fromEntries(Object.entries(c.profiles).filter(a=>v(a[1]))):{}}}catch{}return{version:1,profiles:{}}}function r(a){return v(a)&&"oauth"===a.type&&"openai-codex"===a.provider&&v(a.oauthRef)}function s(a){if(!v(a)||!t(a.profileId))return!1;let b=t(a.status)?.toLowerCase();return!b||!["expired","missing","invalid","error","disabled","revoked"].includes(b)}function t(a){return"string"==typeof a&&a.trim()?a.trim():null}function u(a){return!!a}function v(a){return!!a&&"object"==typeof a&&!Array.isArray(a)}},3334:(a,b,c)=>{c.d(b,{Z:()=>o});var d=c(27091),e=c(39802),f=c(93628);function g(a){return Array.from(new Set(a.filter(Boolean)))}function h(a){let b=new Map;for(let c of a)c.chatId&&b.set(c.chatId,c);return Array.from(b.values())}function i(a){return a.title&&a.title!==a.chatId?`${a.title} (\`${a.chatId}\`)`:`\`${a.chatId}\``}function j(a){if(!a)return"no capability snapshot";let b=[(0,f._P)(a.policy.preset)],c=a.profile.purpose?.trim();c&&b.push(c);let d=g(a.skills).slice(0,2);d.length>0&&b.push(`skills: ${d.join(", ")}`);let e=g(a.tools).slice(0,2);return e.length>0&&b.push(`tools: ${e.join(", ")}`),b.join(" \xb7 ")}function k(a){return Array.from(new Set(a.filter(Boolean)))}function l(a){let b=new Map;for(let c of a)c.chatId&&b.set(c.chatId,c);return Array.from(b.values())}function m(a,b,c){let e=new Map(a?.agents.map(a=>[a.id,(0,d.CK)(a)])??[]),f=new Map(a?.agents.map(a=>[a.id,a])??[]);return k(b.filter(a=>!c.includes(a))).map(a=>{let b=f.get(a)??null;return{agentId:a,name:e.get(a)??a,summary:function(a){if(!a)return"no capability snapshot";let b=[(0,d.CK)(a)],c=a.profile.purpose?.trim();c&&b.push(c);let e=k(a.skills).slice(0,2);e.length>0&&b.push(`skills: ${e.join(", ")}`);let f=k(a.tools).slice(0,2);return f.length>0&&b.push(`tools: ${f.join(", ")}`),b.join(" \xb7 ")}(b)}})}function n(a){let b=(0,e.S)(a.chatId),c=b?.kind==="role"?`@${b.targetId}`:b?.kind==="thread"?`Thread ${b.targetId}`:b?.kind==="channel"?`#${b.targetId}`:a.chatId;return{routeId:a.chatId,label:a.title?.trim()||c,kind:b?.kind??"channel",guildId:b?.guildId??null}}function o(a,b,c=b?.channelRegistry??null){let e=[function(a){if(!a||0===a.primaryChannels.length&&0===a.ownedGroups.length&&0===a.delegateChannels.length)return null;let b=["## Telegram coordination"];if(b.push("- Telegram credentials are managed by OpenClaw for the listed channels. Do not ask the operator for `TELEGRAM_BOT_TOKEN` or `channels.telegram.botToken` when sending to listed groups."),b.push('- To send or post, call the `message` tool with `action: "send"`, `channel: "telegram"`, `target: "<chatId>"`, and the exact message text. Use the listed chat id as `target`.'),b.push("- If sending fails, report the actual tool error instead of inventing a missing-token error."),a.primaryChannels.length>0){for(let c of(b.push("- You are the public Telegram fallback for these channels:"),a.primaryChannels)){let a=c.groups.length>0?c.groups.map(i).join(", "):"no allowed groups yet";if(b.push(` - ${c.channelName} (\`${c.channelId}\`) \xb7 fallback groups: ${a}.`),c.peers.length>0)for(let a of(b.push(" - Internal assistants:"),c.peers))b.push(` - ${a.name} (\`${a.agentId}\`) \xb7 ${a.summary}.`)}b.push("- Keep public Telegram replies under your own voice for unassigned groups, even when you ask another agent for help."),b.push("- For specialist help, call another agent from the workspace terminal with:"),b.push("```bash"),b.push('node .openclaw/tools/telegram-delegate-agent.mjs --agent <delegate-agent-id> --message "Summarize what I need from you"'),b.push("```"),b.push("- Use delegate turns for internal research, drafting, or analysis only. Do not ask them to answer Telegram directly."),b.push("- After a delegate responds, decide what to share publicly and send the final Telegram reply yourself.")}if(a.ownedGroups.length>0){for(let c of(b.push("- You are the public Telegram voice for these assigned groups:"),a.ownedGroups))if(b.push(` - ${c.channelName} (\`${c.channelId}\`) \xb7 ${c.title??c.chatId} (\`${c.chatId}\`) \xb7 primary ${c.primaryAgentName} (\`${c.primaryAgentId}\`).`),c.peers.length>0)for(let a of(b.push(" - Internal assistants for this group:"),c.peers))b.push(` - ${a.name} (\`${a.agentId}\`) \xb7 ${a.summary}.`);b.push("- Reply directly to those groups as the public voice. Use other agents only for internal help.")}if(a.delegateChannels.length>0){for(let c of(b.push("- You can assist these Telegram admin channels when the primary agent asks:"),a.delegateChannels)){let a=c.groups.length>0?c.groups.map(i).join(", "):"no allowed groups yet";if(b.push(` - ${c.channelName} (\`${c.channelId}\`) \xb7 primary ${c.primaryAgentName} (\`${c.primaryAgentId}\`) \xb7 groups: ${a}.`),c.peers.length>0)for(let a of(b.push(" - Nearby assistants:"),c.peers))b.push(` - ${a.name} (\`${a.agentId}\`) \xb7 ${a.summary}.`)}b.push("- When helping with Telegram work for groups not assigned to you, return concise internal findings or draft language. Do not speak as the public Telegram agent for those unassigned groups.")}return b.join("\n")}(function(a,b,c=b?.channelRegistry??null){if(!c)return null;let e=new Map(b?.agents.map(a=>[a.id,(0,d.CK)(a)])??[]),f=new Map(b?.agents.map(a=>[a.id,a])??[]),i=f.get(a)??null,k=i?.workspaceId??null,l=[],m=[],n=[];for(let b of c.channels.filter(a=>"telegram"===a.type)){let c=b.workspaces.filter(a=>a.workspaceId===k);if(0===c.length)continue;let i=h(c.flatMap(a=>a.groupAssignments.filter(a=>!1!==a.enabled))).map(a=>({chatId:a.chatId,title:a.title??null})),o=h(c.flatMap(b=>b.groupAssignments.filter(b=>!1!==b.enabled&&b.agentId===a))),p=i.filter(a=>!o.some(b=>b.chatId===a.chatId)&&!c.some(b=>b.groupAssignments.some(b=>!1!==b.enabled&&b.chatId===a.chatId&&b.agentId)));if(b.primaryAgentId===a){let d=g(c.flatMap(b=>b.agentIds.filter(b=>b!==a))).map(a=>{let b=f.get(a)??null;return{agentId:a,name:e.get(a)??a,summary:j(b)}});l.push({channelId:b.id,channelName:b.name,groups:p,peers:d})}for(let d of o){let h=g(c.flatMap(c=>c.agentIds.filter(c=>c!==a&&c!==b.primaryAgentId))).map(a=>{let b=f.get(a)??null;return{agentId:a,name:e.get(a)??a,summary:j(b)}});m.push({channelId:b.id,channelName:b.name,chatId:d.chatId,title:d.title??null,primaryAgentId:b.primaryAgentId??a,primaryAgentName:e.get(b.primaryAgentId??a)??b.primaryAgentId??a,peers:h})}if(b.primaryAgentId&&b.primaryAgentId!==a&&0===o.length){let h=f.get(b.primaryAgentId)??null,i=g(c.flatMap(c=>c.agentIds.filter(c=>c!==b.primaryAgentId&&c!==a))).map(a=>{let b=f.get(a)??null;return{agentId:a,name:e.get(a)??a,summary:j(b)}});n.push({channelId:b.id,channelName:b.name,groups:p,peers:i,primaryAgentId:b.primaryAgentId,primaryAgentName:e.get(b.primaryAgentId)??(h?(0,d.CK)(h):b.primaryAgentId)})}}return{primaryChannels:l.sort((a,b)=>a.channelName.localeCompare(b.channelName)),ownedGroups:m.sort((a,b)=>{let c=`${a.channelName}:${a.title??a.chatId}`,d=`${b.channelName}:${b.title??b.chatId}`;return c.localeCompare(d)}),delegateChannels:n.sort((a,b)=>a.channelName.localeCompare(b.channelName))}}(a,b,c)),function(a){if(!a||0===a.primaryChannels.length&&0===a.ownedRoutes.length&&0===a.delegateChannels.length)return null;let b=["## Discord coordination"];if(a.primaryChannels.length>0){for(let c of(b.push("- You are the public Discord fallback for these channels:"),a.primaryChannels)){let a=c.routes.length>0?c.routes.map(a=>`${a.label} (\`${a.routeId}\`)`).join(", "):"no allowed routes yet";if(b.push(` - ${c.channelName} (\`${c.channelId}\`) \xb7 fallback routes: ${a}.`),c.peers.length>0)for(let a of(b.push(" - Internal assistants:"),c.peers))b.push(` - ${a.name} (\`${a.agentId}\`) \xb7 ${a.summary}.`)}b.push("- Keep public Discord replies under your own voice for unassigned routes, even when you ask another agent for help.")}if(a.ownedRoutes.length>0){for(let c of(b.push("- You are the public Discord voice for these assigned routes:"),a.ownedRoutes))if(b.push(` - ${c.channelName} (\`${c.channelId}\`) \xb7 ${c.label} (\`${c.routeId}\`) \xb7 primary ${c.primaryAgentName} (\`${c.primaryAgentId}\`).`),c.peers.length>0)for(let a of(b.push(" - Internal assistants for this route:"),c.peers))b.push(` - ${a.name} (\`${a.agentId}\`) \xb7 ${a.summary}.`);b.push("- Reply directly to those routes as the public voice. Use other agents only for internal help.")}if(a.delegateChannels.length>0){for(let c of(b.push("- You can assist these Discord admin channels when the primary agent asks:"),a.delegateChannels)){let a=c.routes.length>0?c.routes.map(a=>`${a.label} (\`${a.routeId}\`)`).join(", "):"no allowed routes yet";if(b.push(` - ${c.channelName} (\`${c.channelId}\`) \xb7 primary ${c.primaryAgentName} (\`${c.primaryAgentId}\`) \xb7 routes: ${a}.`),c.peers.length>0)for(let a of(b.push(" - Nearby assistants:"),c.peers))b.push(` - ${a.name} (\`${a.agentId}\`) \xb7 ${a.summary}.`)}b.push("- When helping with Discord work, return concise internal findings or draft language. Do not speak as the public Discord agent.")}return b.join("\n")}(function(a,b,c=b?.channelRegistry??null){if(!c)return null;let e=b?.agents.find(b=>b.id===a)??null,f=e?.workspaceId??null,g=[],h=[],i=[];for(let e of c.channels.filter(a=>"discord"===a.type)){var j,k,o,p;let c=e.workspaces.filter(a=>a.workspaceId===f);if(0===c.length)continue;let q=l(c.flatMap(a=>a.groupAssignments.filter(a=>!1!==a.enabled))).map(n),r=l(c.flatMap(b=>b.groupAssignments.filter(b=>!1!==b.enabled&&b.agentId===a))).map(n),s=q.filter(a=>!r.some(b=>b.routeId===a.routeId)&&!c.some(b=>b.groupAssignments.some(b=>!1!==b.enabled&&b.chatId===a.routeId&&b.agentId)));if(e.primaryAgentId===a){let d=m(b,c.flatMap(b=>b.agentIds.filter(b=>b!==a)),[a]);g.push({channelId:e.id,channelName:e.name,routes:s,peers:d})}for(let f of r){let g=m(b,c.flatMap(b=>b.agentIds.filter(b=>b!==a&&b!==e.primaryAgentId)),[a,e.primaryAgentId??""]);h.push({channelId:e.id,channelName:e.name,routeId:f.routeId,label:f.label,kind:f.kind,guildId:f.guildId,primaryAgentId:e.primaryAgentId??a,primaryAgentName:(j=b?.agents.find(b=>b.id===(e.primaryAgentId??a))??null,k=e.primaryAgentId??a,j?(0,d.CK)(j):k),peers:g})}if(e.primaryAgentId&&e.primaryAgentId!==a){let f=m(b,c.flatMap(b=>b.agentIds.filter(b=>b!==e.primaryAgentId&&b!==a)),[a,e.primaryAgentId]);i.push({channelId:e.id,channelName:e.name,routes:s,peers:f,primaryAgentId:e.primaryAgentId,primaryAgentName:(o=b?.agents.find(a=>a.id===e.primaryAgentId)??null,p=e.primaryAgentId,o?(0,d.CK)(o):p)})}}return{primaryChannels:g.sort((a,b)=>a.channelName.localeCompare(b.channelName)),ownedRoutes:h.sort((a,b)=>{let c=`${a.channelName}:${a.label}`,d=`${b.channelName}:${b.label}`;return c.localeCompare(d)}),delegateChannels:i.sort((a,b)=>a.channelName.localeCompare(b.channelName))}}(a,b,c))].filter(a=>!!a);return e.length>0?e.join("\n\n"):null}},24767:(a,b,c)=>{c.d(b,{yw:()=>bU,DM:()=>ca,er:()=>d.er,us:()=>bV,Sn:()=>aj,MP:()=>cd,zw:()=>bq,RB:()=>an,kd:()=>b6,qu:()=>bt,B5:()=>b5,H6:()=>b_.H6,lC:()=>b_.lC,dM:()=>bk,MQ:()=>b$.MQ,W6:()=>b$.W6,GM:()=>cT,Y9:()=>bl,pf:()=>bm,FJ:()=>bu,tq:()=>b7,f5:()=>b$.f5,MG:()=>b$.MG,W9:()=>b9,lT:()=>b8,xE:()=>bT,ct:()=>bj,o6:()=>cb,x4:()=>am,Vg:()=>b$.Vg,sQ:()=>bs,PR:()=>b$.PR,Oz:()=>b4});var d=c(52082),e=c(51455),f=c(76760),g=c.n(f),h=c(93628);function i(a,b){let c="monitoring"===a?{enabled:!0,every:"30m"}:{enabled:!1,every:"30m"},d="string"==typeof b?.every&&b.every.trim()&&"disabled"!==b.every?b.every.trim():c.every;return"boolean"==typeof b?.enabled?{enabled:b.enabled,every:d}:b?.every==="disabled"?{enabled:!1,every:d}:c}function j(a){return a?.enabled?{every:"string"==typeof a.every&&a.every.trim()?a.every.trim():"30m"}:null}var k=c(39503),l=c(71065),m=c(27091),n=c(98752),o=c(31421),p=c(57975),q=c(14853),r=c(15612),s=c(54252);let t=(0,p.promisify)(o.execFile);function u(a){return"string"==typeof a&&a.trim().length>0?a.trim():null}function v(a){return Array.from(new Set(a.filter(Boolean)))}function w(a){return v([...(a.skillIds??[]).map(a=>u(a)??""),u(a.skillId)??""])}function x(a){return a.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}async function y(a){try{return await (0,e.access)(a),!0}catch{return!1}}async function z(a,b,c={}){try{await t(a,b,{cwd:c.cwd??process.cwd(),timeout:c.timeoutMs??12e4,maxBuffer:8388608})}catch(a){throw Error("object"==typeof a&&a&&"stderr"in a&&"string"==typeof a.stderr&&a.stderr.trim()?a.stderr.trim():a instanceof Error?a.message:"Unknown system command failure.")}}async function A(a,b){try{await (0,e.access)(a)}catch{await (0,e.mkdir)(g().dirname(a),{recursive:!0}),await (0,e.writeFile)(a,b,"utf8")}}async function B(a,b){await (0,e.mkdir)(g().dirname(a),{recursive:!0}),await (0,e.writeFile)(a,b,"utf8")}async function C(a){try{throw await (0,e.access)(a),Error("Target workspace directory already exists.")}catch(a){if("ENOENT"===("object"==typeof a&&a&&"code"in a?a.code:void 0))return;if(a instanceof Error)throw a;throw Error("Unable to verify target workspace directory.")}}async function D(a){try{if(!(await (0,e.stat)(a)).isDirectory())throw Error("Target workspace path exists and is not a directory.");if((await (0,e.readdir)(a)).length>0)throw Error("Target workspace directory already contains files. Use Existing folder instead.")}catch(b){if("ENOENT"===("object"==typeof b&&b&&"code"in b?b.code:void 0))return void await (0,e.mkdir)(a,{recursive:!0});if(b instanceof Error)throw b;throw Error("Unable to prepare the workspace directory.")}await (0,e.mkdir)(a,{recursive:!0})}async function E(a){try{if(!(await (0,e.stat)(a)).isDirectory())throw Error("The selected existing path is not a directory.")}catch(a){if("ENOENT"===("object"==typeof a&&a&&"code"in a?a.code:void 0))throw Error("The selected existing folder does not exist.");if(a instanceof Error)throw a;throw Error("Unable to access the selected existing folder.")}}async function F(a,b){let c=u(b);return c?c.split("@")[0]:await y(g().join(a,"pnpm-lock.yaml"))?"pnpm":await y(g().join(a,"yarn.lock"))?"yarn":"npm"}async function G(a){let b=g().join(a,"package.json");try{let c=await (0,e.readFile)(b,"utf8"),d=JSON.parse(c),f=d.scripts??{},g=await F(a,d.packageManager),h=[`Use \`${g} install\` before the first local run.`];for(let a of["dev","start","test","lint","build"])f[a]&&h.push(`Use \`${"yarn"===g?`yarn ${a}`:`${g} run ${a}`}\` for the ${a} workflow.`);return h}catch{return[]}}async function H(a){let b=g().join(a,"Makefile");try{return((await (0,e.readFile)(b,"utf8")).match(/^(dev|test|lint|build|run):/gm)??[]).map(a=>`Use \`make ${a.replace(/:$/,"")}\` if the Makefile is the primary entry point.`)}catch{return[]}}async function I(a){let b=[];return await y(g().join(a,"pyproject.toml"))&&b.push("Use `pytest` for Python verification if the project exposes a test suite."),await y(g().join(a,"requirements.txt"))&&b.push("Install Python dependencies in a virtualenv before running project commands."),b}async function J(a){let b=[],c=await G(a),d=await H(a),e=await I(a);return b.push(...c,...d,...e),0===b.length&&b.push("Use repository-local scripts or documented commands for repeatable workflows.","Update this file when the project exposes a cleaner build, test, or release path."),v(b).slice(0,6)}function K(a,b){switch(a){case"project-builder":return`# Project Builder
3
3
 
4
4
  Use this skill when implementing changes in the current project.
5
5
 
@@ -269,10 +269,11 @@ async function main() {
269
269
 
270
270
  await main();
271
271
  `}
272
- `)}function ac(a){if(!a)return"no capability snapshot";let b=[(0,h._P)(a.policy.preset)],c=a.profile.purpose?.trim();c&&b.push(c);let d=V(a.skills).slice(0,2);d.length>0&&b.push(`skills: ${d.join(", ")}`);let e=V(a.tools).slice(0,2);return e.length>0&&b.push(`tools: ${e.join(", ")}`),b.join(" \xb7 ")}async function ad(a,b,c){if(!c)return null;let d=c.agents.find(a=>a.id===b);if(!d)return null;let e=new Map((await (0,S.OL)(a)).agents.map(a=>[a.id,a])),f=c.agents.filter(a=>a.workspaceId===d.workspaceId).sort((a,c)=>{if(a.id===b&&c.id!==b)return -1;if(c.id===b&&a.id!==b)return 1;let d=e.get(a.id),f=e.get(c.id),g=d?.isPrimary??!1;return g!==(f?.isPrimary??!1)?g?-1:1:(0,m.CK)(a).localeCompare((0,m.CK)(c))}).map(a=>{let c=e.get(a.id);return{agentId:a.id,name:(0,m.CK)(a),role:c?.role?.trim()||(0,h._P)(a.policy.preset),isPrimary:c?.isPrimary??!1,isCurrent:a.id===b}});return f.length>0?{members:f}:null}var ae=c(21916),af=c(97450),ag=c(96109),ah=c(55828);let ai=["project-researcher","project-builder","project-analyst"];async function aj(a){var b,c,e;let f,m=az(a.id.trim());if(!m)throw Error("Agent id is required.");let n=await (0,d.GM)({includeHidden:!0}),o=ay(n,a.workspaceId),p=(0,ae.Nk)(a.workspacePath)??o?.path;p||(o=ay(n=await (0,d.GM)({force:!0,includeHidden:!0}),a.workspaceId),p=(0,ae.Nk)(a.workspacePath)??o?.path);let q=o?.id??(p?(0,ag.S_)(p):a.workspaceId||null);if(function(a,b,c){var d,e;let f=a.agents.find(a=>a.id===b);if(!f)return;let h=(d=a,e=f,d.workspaces.find(a=>a.id===e.workspaceId)?.name??g().basename(e.workspacePath));if(f.workspaceId===c)throw Error(`Agent id "${b}" already exists in workspace "${h}".`);throw Error(`Agent id "${b}" is already used by workspace "${h}". Choose a different id.`)}(n,m,q),!p||!q)throw Error("Workspace was not found for this agent.");let r=(0,ae.Nk)(a.modelId)??ao(n)??(b=n,c=q,b.agents.filter(a=>a.workspaceId===c).map(a=>(0,ae.Nk)(a.modelId)).find(a=>a&&"unassigned"!==a&&ap(b,a)))??(e=n,(f=(0,ae.Nk)(e.diagnostics.modelReadiness.recommendedModelId))&&ap(e,f)?f:e.models.map(a=>(0,ae.Nk)(a.id)).find(a=>a&&ap(e,a))),t=(0,ah.tP)(n,r);if(t)throw Error(t);let u=(0,h.g0)(a.policy?.preset??h.iN,a.policy),v=(0,h.Cf)(u.preset),w=(0,h._Y)(v.skillIds),x=(0,h.X0)(v.tools),y=void 0===a.skills?w:(0,l.H5)(a.skills),z=void 0===a.tools?x:(0,l.at)(a.tools),A=(0,ae.Nk)(a.name)??v.defaultName,B=(0,ae.Nk)(a.emoji)??v.defaultEmoji,C=(0,ae.Nk)(a.theme)??v.defaultTheme,D=(0,ae.Nk)(a.avatar),E=j(i(u.preset,a.heartbeat)),F=n.agents.find(a=>a.workspaceId===q&&"setup"===a.policy.preset)?.id??null,G=(0,l.N2)(p,m),H=[];await (0,k.rw)().addAgent({id:m,workspace:p,agentDir:G,model:r,name:A,emoji:B,avatar:D});let I=await Z({workspacePath:p,agentId:m,agentName:A,policy:u,setupAgentId:F,snapshot:n});for(let a of y)await $(p,a);try{await ar(m,p,{agentDir:G,name:A,model:r,heartbeat:E,skills:aw([...y,I]),tools:"workspace-only"===u.fileAccess?{fs:{workspaceOnly:!0}}:null,identity:{name:A,emoji:B,theme:C,avatar:D}},n)}catch(a){H.push(al(a))}await au(p,{id:m,name:A,role:(0,h._P)(u.preset),emoji:B,theme:C,enabled:!0,skillId:y[0]??null,skillIds:y,toolIds:z,modelId:r,isPrimary:!1,policy:u,channelIds:a.channelIds??[]}),await (0,s.u)(p),await _(p,ax(n,p,new Map([[m,y]]))),await (0,l.rH)(m,p,G),(0,d.ZZ)();try{await at(p)}catch(a){H.push(al(a))}return{agentId:m,workspaceId:q,warnings:aw(H)}}function ak(a){var b,c;return!(!(c=(b=a)instanceof Error?b.message:"string"==typeof b?b:"")||/Refusing to write a redacted OpenClaw secret|path traversal|Workspace was not found|already exists/i.test(c))&&/Timed out waiting for OpenClaw Gateway method "config\.(?:patch|apply|set)"|UNAVAILABLE:.*config\.(?:patch|apply|set)|Gateway-native operation failed; CLI fallback disabled/i.test(c)?"AgentOS created the agent, but OpenClaw could not finish the config sync in time. Restart or refresh the OpenClaw Gateway if the agent profile looks incomplete, then refresh AgentOS.":null}function al(a){let b=ak(a);if(!b)throw a;return b}async function am(a){var b,c;let e,f,g=a.id.trim();if(!g)throw Error("Agent id is required.");let m=await (0,d.GM)({includeHidden:!0}),n=m.agents.find(a=>a.id===g);if(n||(n=(m=await (0,d.GM)({force:!0,includeHidden:!0})).agents.find(a=>a.id===g)),!n)throw Error("Agent was not found.");let o=ay(m,a.workspaceId||n.workspaceId),p=(0,ae.Nk)(a.workspacePath)??o?.path??n.workspacePath,q=o?.id??(p?(0,ag.S_)(p):a.workspaceId||n.workspaceId);if(!p||!q)throw Error("Workspace was not found for this agent.");let r=(0,h.g0)(a.policy?.preset??n.policy.preset,a.policy??n.policy),t=(0,h.Cf)(r.preset),u=(0,h._Y)(t.skillIds),v=(0,h.X0)(t.tools),w=(0,ae.Nk)(n.name),x=(0,ae.Nk)(n.identity.emoji),y=(0,ae.Nk)(n.identity.theme),z=j(i(r.preset,a.heartbeat??(0,l.D9)(n.heartbeat))),A=m.agents.find(a=>a.workspaceId===q&&"setup"===a.policy.preset&&a.id!==g)?.id??null,B=void 0!==a.modelId?(0,ae.Nk)(a.modelId):"unassigned"===n.modelId?ao(m):n.modelId;if(void 0!==a.modelId&&void 0===a.name&&void 0===a.emoji&&void 0===a.theme&&void 0===a.avatar&&void 0===a.policy&&void 0===a.heartbeat&&void 0===a.channelIds&&void 0===a.skills&&void 0===a.tools)return await as("updating the agent model",()=>(0,k.rw)().updateAgent({id:g,workspace:p,model:B},{timeoutMs:15e3})),await ar(g,p,{agentDir:n.agentDir??(0,l.N2)(p,g),model:B},m),await au(p,{id:g,name:w??n.name??g,emoji:x,theme:y,enabled:!0,modelId:B,isPrimary:n.isDefault,policy:r}),await (0,s.u)(p),await (0,l.rH)(g,p,n.agentDir??(0,l.N2)(p,g)),(0,d.ZZ)(),{agentId:g,workspaceId:q};let C=await Z({workspacePath:p,agentId:g,agentName:(0,ae.Nk)(a.name)??w??g,policy:r,setupAgentId:A,snapshot:m}),D=(0,l.AB)(n.skills),E=(0,l.at)(n.tools),F=r.preset!==n.policy.preset||0===D.length,G=r.preset!==n.policy.preset||0===E.length,H=void 0===a.skills&&"custom"===r.preset&&(b=D,c=ai,e=new Set(b),f=new Set(c),e.size===f.size&&Array.from(e).every(a=>f.has(a))),I=void 0===a.skills?H?[]:F?u:D:(0,l.H5)(a.skills);for(let a of I)await $(p,a);await as("updating the agent",()=>(0,k.rw)().updateAgent({id:g,workspace:p,model:B},{timeoutMs:15e3}));let J=await ar(g,p,{agentDir:n.agentDir??(0,l.N2)(p,g),name:void 0!==a.name?(0,ae.Nk)(a.name):void 0,model:B,heartbeat:z,skills:aw([...I,C]),tools:"workspace-only"===r.fileAccess?{fs:{workspaceOnly:!0}}:null,identity:{name:(0,ae.Nk)(a.name)??w??g,emoji:(0,ae.Nk)(a.emoji)??x,theme:(0,ae.Nk)(a.theme)??y,avatar:(0,ae.Nk)(a.avatar)}},m),K=void 0===a.tools?G?v:void 0:(0,l.at)(a.tools);return await au(p,{id:g,name:(0,ae.Nk)(a.name)??w??J.name??g,emoji:(0,ae.Nk)(a.emoji)??x,theme:(0,ae.Nk)(a.theme)??y,enabled:!0,modelId:B,isPrimary:n.isDefault,policy:r,channelIds:a.channelIds,skillId:I[0]??null,skillIds:I,toolIds:K}),await (0,s.u)(p),await _(p,ax(m,p,new Map([[g,I]]))),await (0,l.rH)(g,p,n.agentDir??(0,l.N2)(p,g)),(0,d.ZZ)(),await at(p),{agentId:g,workspaceId:q}}async function an(a){let b=a.agentId.trim();if(!b)throw Error("Agent id is required.");let c=await (0,d.GM)({includeHidden:!0}),f=c.agents.find(a=>a.id===b);if(f||(f=(c=await (0,d.GM)({force:!0,includeHidden:!0})).agents.find(a=>a.id===b)),!f)throw Error("Agent was not found.");let h=c.workspaces.find(a=>a.id===f.workspaceId)??null,i=c.runtimes.filter(a=>a.agentId===f.id).length;await (0,k.rw)().deleteAgent(f.id);try{let a=await (0,l.CI)(c),b=a.filter(a=>a.id!==f.id);b.length!==a.length&&await (0,l.ZF)(b)}catch{}if(h){await av(h.path,f.id),await (0,s.u)(h.path),await _(h.path,ax(c,h.path,new Map([[f.id,[]]]))),await (0,l.rH)(f.id,h.path,f.agentDir);try{await (0,e.rm)(g().join(h.path,"skills",(0,l.Uo)(f.id)),{recursive:!0,force:!0})}catch{}(0,d.ZZ)(),await at(h.path)}return(0,d.b7)(),{agentId:f.id,workspaceId:f.workspaceId,workspacePath:f.workspacePath,deletedRuntimeCount:i}}function ao(a){if(a.diagnostics.modelReadiness.defaultModelReady)return(0,ae.Nk)(a.diagnostics.modelReadiness.resolvedDefaultModel)??(0,ae.Nk)(a.diagnostics.modelReadiness.defaultModel)??void 0}function ap(a,b){let c=a.models.find(a=>a.id===b);return!!c&&!0!==c.missing&&!1!==c.available}async function aq(a,b){let c=aw(a);if(0===c.length)return;let e=b??await (0,d.GM)({includeHidden:!0});for(let a of c){let b=e.agents.find(b=>b.id===a);if(!b)continue;let c=e.agents.find(a=>a.workspaceId===b.workspaceId&&"setup"===a.policy.preset&&a.id!==b.id)?.id??null,d=await Z({workspacePath:b.workspacePath,agentId:b.id,agentName:b.name,policy:b.policy,setupAgentId:c,snapshot:e});await ar(b.id,b.workspacePath,{agentDir:b.agentDir??(0,l.N2)(b.workspacePath,b.id),name:b.name,model:(0,ae.Nk)(b.modelId),heartbeat:b.heartbeat.enabled&&b.heartbeat.every?{every:b.heartbeat.every}:null,skills:[...(0,l.AB)(b.skills),d],tools:b.tools.includes("fs.workspaceOnly")?{fs:{workspaceOnly:!0}}:null,identity:{name:b.identityName??b.name,emoji:b.identity.emoji,theme:b.identity.theme,avatar:b.identity.avatar}},e)}}async function ar(...a){return as("syncing the agent config",()=>(0,l.jq)(...a))}async function as(a,b){return(await (0,af.g7)(b,{operationLabel:a})).value}async function at(a,b){let c=b??await (0,d.GM)({includeHidden:!0}),e=c.agents.filter(b=>b.workspacePath===a).map(a=>a.id);await aq(e,c)}async function au(a,b){let c=g().join(a,".openclaw","project.json"),d={},f=null;try{let a=await (0,e.readFile)(c,"utf8"),g=JSON.parse(a);d=aA(g)?g:{},Array.isArray(d.agents)&&(f=d.agents.map(a=>(0,S.aW)(a)).filter(a=>!!a).find(a=>a.id===b.id)??null)}catch{d={}}let h=Array.isArray(b.skillIds)?aw(b.skillIds.map(a=>a.trim()).filter(Boolean)):void 0!==b.skillId?[(0,ae.Nk)(b.skillId)].filter(a=>!!a):f?.skillIds??(f?.skillId?[f.skillId]:[]),i={id:b.id,name:b.name??f?.name??null,role:b.role??f?.role??null,isPrimary:b.isPrimary??f?.isPrimary??!1,enabled:b.enabled??f?.enabled??!0,emoji:b.emoji??f?.emoji??null,theme:b.theme??f?.theme??null,skillId:h[0]??null,skillIds:h,toolIds:Array.isArray(b.toolIds)?aw(b.toolIds.map(a=>a.trim()).filter(a=>!!a&&"fs.workspaceOnly"!==a)):f?.toolIds??[],modelId:b.modelId??f?.modelId??null,policy:b.policy,channelIds:Array.isArray(b.channelIds)?Array.from(new Set(b.channelIds.filter(a=>"string"==typeof a&&a.trim()))):f?.channelIds??[]},j=Array.isArray(d.agents)?d.agents.filter(a=>aA(a)&&"string"==typeof a.id&&a.id!==b.id):[];j.push(i),d.version="number"==typeof d.version?d.version:1,d.slug="string"==typeof d.slug?d.slug:az(g().basename(a)),d.name="string"==typeof d.name?d.name:g().basename(a),d.updatedAt=new Date().toISOString(),d.agents=j,await B(c,`${JSON.stringify(d,null,2)}
272
+ `)}function ac(a){if(!a)return"no capability snapshot";let b=[(0,h._P)(a.policy.preset)],c=a.profile.purpose?.trim();c&&b.push(c);let d=V(a.skills).slice(0,2);d.length>0&&b.push(`skills: ${d.join(", ")}`);let e=V(a.tools).slice(0,2);return e.length>0&&b.push(`tools: ${e.join(", ")}`),b.join(" \xb7 ")}async function ad(a,b,c){if(!c)return null;let d=c.agents.find(a=>a.id===b);if(!d)return null;let e=new Map((await (0,S.OL)(a)).agents.map(a=>[a.id,a])),f=c.agents.filter(a=>a.workspaceId===d.workspaceId).sort((a,c)=>{if(a.id===b&&c.id!==b)return -1;if(c.id===b&&a.id!==b)return 1;let d=e.get(a.id),f=e.get(c.id),g=d?.isPrimary??!1;return g!==(f?.isPrimary??!1)?g?-1:1:(0,m.CK)(a).localeCompare((0,m.CK)(c))}).map(a=>{let c=e.get(a.id);return{agentId:a.id,name:(0,m.CK)(a),role:c?.role?.trim()||(0,h._P)(a.policy.preset),isPrimary:c?.isPrimary??!1,isCurrent:a.id===b}});return f.length>0?{members:f}:null}var ae=c(21916),af=c(31273),ag=c(96109),ah=c(55828);let ai=["project-researcher","project-builder","project-analyst"];async function aj(a){var b,c,e;let f,m=az(a.id.trim());if(!m)throw Error("Agent id is required.");let n=await (0,d.GM)({includeHidden:!0}),o=ay(n,a.workspaceId),p=(0,ae.Nk)(a.workspacePath)??o?.path;p||(o=ay(n=await (0,d.GM)({force:!0,includeHidden:!0}),a.workspaceId),p=(0,ae.Nk)(a.workspacePath)??o?.path);let q=o?.id??(p?(0,ag.S_)(p):a.workspaceId||null);if(function(a,b,c){var d,e;let f=a.agents.find(a=>a.id===b);if(!f)return;let h=(d=a,e=f,d.workspaces.find(a=>a.id===e.workspaceId)?.name??g().basename(e.workspacePath));if(f.workspaceId===c)throw Error(`Agent id "${b}" already exists in workspace "${h}".`);throw Error(`Agent id "${b}" is already used by workspace "${h}". Choose a different id.`)}(n,m,q),!p||!q)throw Error("Workspace was not found for this agent.");let r=(0,ae.Nk)(a.modelId)??ao(n)??(b=n,c=q,b.agents.filter(a=>a.workspaceId===c).map(a=>(0,ae.Nk)(a.modelId)).find(a=>a&&"unassigned"!==a&&ap(b,a)))??(e=n,(f=(0,ae.Nk)(e.diagnostics.modelReadiness.recommendedModelId))&&ap(e,f)?f:e.models.map(a=>(0,ae.Nk)(a.id)).find(a=>a&&ap(e,a))),t=(0,ah.tP)(n,r);if(t)throw Error(t);let u=(0,h.g0)(a.policy?.preset??h.iN,a.policy),v=(0,h.Cf)(u.preset),w=(0,h._Y)(v.skillIds),x=(0,h.X0)(v.tools),y=void 0===a.skills?w:(0,l.H5)(a.skills),z=void 0===a.tools?x:(0,l.at)(a.tools),A=(0,ae.Nk)(a.name)??v.defaultName,B=(0,ae.Nk)(a.emoji)??v.defaultEmoji,C=(0,ae.Nk)(a.theme)??v.defaultTheme,D=(0,ae.Nk)(a.avatar),E=j(i(u.preset,a.heartbeat)),F=n.agents.find(a=>a.workspaceId===q&&"setup"===a.policy.preset)?.id??null,G=(0,l.N2)(p,m),H=[];await (0,k.rw)().addAgent({id:m,workspace:p,agentDir:G,model:r,name:A,emoji:B,avatar:D});let I=await Z({workspacePath:p,agentId:m,agentName:A,policy:u,setupAgentId:F,snapshot:n});for(let a of y)await $(p,a);try{await ar(m,p,{agentDir:G,name:A,model:r,heartbeat:E,skills:aw([...y,I]),tools:"workspace-only"===u.fileAccess?{fs:{workspaceOnly:!0}}:null,identity:{name:A,emoji:B,theme:C,avatar:D}},n)}catch(a){H.push(al(a))}await au(p,{id:m,name:A,role:(0,h._P)(u.preset),emoji:B,theme:C,enabled:!0,skillId:y[0]??null,skillIds:y,toolIds:z,modelId:r,isPrimary:!1,policy:u,channelIds:a.channelIds??[]}),await (0,s.u)(p),await _(p,ax(n,p,new Map([[m,y]]))),await (0,l.rH)(m,p,G),(0,d.ZZ)();try{await at(p)}catch(a){H.push(al(a))}return{agentId:m,workspaceId:q,warnings:aw(H)}}function ak(a){var b,c;return!(!(c=(b=a)instanceof Error?b.message:"string"==typeof b?b:"")||/Refusing to write a redacted OpenClaw secret|path traversal|Workspace was not found|already exists/i.test(c))&&/Timed out waiting for OpenClaw Gateway method "config\.(?:patch|apply|set)"|UNAVAILABLE:.*config\.(?:patch|apply|set)|Gateway-native operation failed; CLI fallback disabled/i.test(c)?"AgentOS created the agent, but OpenClaw could not finish the config sync in time. Restart or refresh the OpenClaw Gateway if the agent profile looks incomplete, then refresh AgentOS.":null}function al(a){let b=ak(a);if(!b)throw a;return b}async function am(a){var b,c;let e,f,g=a.id.trim();if(!g)throw Error("Agent id is required.");let m=await (0,d.GM)({includeHidden:!0}),n=m.agents.find(a=>a.id===g);if(n||(n=(m=await (0,d.GM)({force:!0,includeHidden:!0})).agents.find(a=>a.id===g)),!n)throw Error("Agent was not found.");let o=ay(m,a.workspaceId||n.workspaceId),p=(0,ae.Nk)(a.workspacePath)??o?.path??n.workspacePath,q=o?.id??(p?(0,ag.S_)(p):a.workspaceId||n.workspaceId);if(!p||!q)throw Error("Workspace was not found for this agent.");let r=(0,h.g0)(a.policy?.preset??n.policy.preset,a.policy??n.policy),t=(0,h.Cf)(r.preset),u=(0,h._Y)(t.skillIds),v=(0,h.X0)(t.tools),w=(0,ae.Nk)(n.name),x=(0,ae.Nk)(n.identity.emoji),y=(0,ae.Nk)(n.identity.theme),z=j(i(r.preset,a.heartbeat??(0,l.D9)(n.heartbeat))),A=m.agents.find(a=>a.workspaceId===q&&"setup"===a.policy.preset&&a.id!==g)?.id??null,B=void 0!==a.modelId?(0,ae.Nk)(a.modelId):"unassigned"===n.modelId?ao(m):n.modelId;if(void 0!==a.modelId&&void 0===a.name&&void 0===a.emoji&&void 0===a.theme&&void 0===a.avatar&&void 0===a.policy&&void 0===a.heartbeat&&void 0===a.channelIds&&void 0===a.skills&&void 0===a.tools)return await as("updating the agent model",()=>(0,k.rw)().updateAgent({id:g,workspace:p,model:B},{timeoutMs:15e3})),await ar(g,p,{agentDir:n.agentDir??(0,l.N2)(p,g),model:B},m),await au(p,{id:g,name:w??n.name??g,emoji:x,theme:y,enabled:!0,modelId:B,isPrimary:n.isDefault,policy:r}),await (0,s.u)(p),await (0,l.rH)(g,p,n.agentDir??(0,l.N2)(p,g)),(0,d.ZZ)(),{agentId:g,workspaceId:q};let C=await Z({workspacePath:p,agentId:g,agentName:(0,ae.Nk)(a.name)??w??g,policy:r,setupAgentId:A,snapshot:m}),D=(0,l.AB)(n.skills),E=(0,l.at)(n.tools),F=r.preset!==n.policy.preset||0===D.length,G=r.preset!==n.policy.preset||0===E.length,H=void 0===a.skills&&"custom"===r.preset&&(b=D,c=ai,e=new Set(b),f=new Set(c),e.size===f.size&&Array.from(e).every(a=>f.has(a))),I=void 0===a.skills?H?[]:F?u:D:(0,l.H5)(a.skills);for(let a of I)await $(p,a);await as("updating the agent",()=>(0,k.rw)().updateAgent({id:g,workspace:p,model:B},{timeoutMs:15e3}));let J=await ar(g,p,{agentDir:n.agentDir??(0,l.N2)(p,g),name:void 0!==a.name?(0,ae.Nk)(a.name):void 0,model:B,heartbeat:z,skills:aw([...I,C]),tools:"workspace-only"===r.fileAccess?{fs:{workspaceOnly:!0}}:null,identity:{name:(0,ae.Nk)(a.name)??w??g,emoji:(0,ae.Nk)(a.emoji)??x,theme:(0,ae.Nk)(a.theme)??y,avatar:(0,ae.Nk)(a.avatar)}},m),K=void 0===a.tools?G?v:void 0:(0,l.at)(a.tools);return await au(p,{id:g,name:(0,ae.Nk)(a.name)??w??J.name??g,emoji:(0,ae.Nk)(a.emoji)??x,theme:(0,ae.Nk)(a.theme)??y,enabled:!0,modelId:B,isPrimary:n.isDefault,policy:r,channelIds:a.channelIds,skillId:I[0]??null,skillIds:I,toolIds:K}),await (0,s.u)(p),await _(p,ax(m,p,new Map([[g,I]]))),await (0,l.rH)(g,p,n.agentDir??(0,l.N2)(p,g)),(0,d.ZZ)(),await at(p),{agentId:g,workspaceId:q}}async function an(a){let b=a.agentId.trim();if(!b)throw Error("Agent id is required.");let c=await (0,d.GM)({includeHidden:!0}),f=c.agents.find(a=>a.id===b);if(f||(f=(c=await (0,d.GM)({force:!0,includeHidden:!0})).agents.find(a=>a.id===b)),!f)throw Error("Agent was not found.");let h=c.workspaces.find(a=>a.id===f.workspaceId)??null,i=c.runtimes.filter(a=>a.agentId===f.id).length;await (0,k.rw)().deleteAgent(f.id);try{let a=await (0,l.CI)(c),b=a.filter(a=>a.id!==f.id);b.length!==a.length&&await (0,l.ZF)(b)}catch{}if(h){await av(h.path,f.id),await (0,s.u)(h.path),await _(h.path,ax(c,h.path,new Map([[f.id,[]]]))),await (0,l.rH)(f.id,h.path,f.agentDir);try{await (0,e.rm)(g().join(h.path,"skills",(0,l.Uo)(f.id)),{recursive:!0,force:!0})}catch{}(0,d.ZZ)(),await at(h.path)}return(0,d.b7)(),{agentId:f.id,workspaceId:f.workspaceId,workspacePath:f.workspacePath,deletedRuntimeCount:i}}function ao(a){if(a.diagnostics.modelReadiness.defaultModelReady)return(0,ae.Nk)(a.diagnostics.modelReadiness.resolvedDefaultModel)??(0,ae.Nk)(a.diagnostics.modelReadiness.defaultModel)??void 0}function ap(a,b){let c=a.models.find(a=>a.id===b);return!!c&&!0!==c.missing&&!1!==c.available}async function aq(a,b){let c=aw(a);if(0===c.length)return;let e=b??await (0,d.GM)({includeHidden:!0});for(let a of c){let b=e.agents.find(b=>b.id===a);if(!b)continue;let c=e.agents.find(a=>a.workspaceId===b.workspaceId&&"setup"===a.policy.preset&&a.id!==b.id)?.id??null,d=await Z({workspacePath:b.workspacePath,agentId:b.id,agentName:b.name,policy:b.policy,setupAgentId:c,snapshot:e});await ar(b.id,b.workspacePath,{agentDir:b.agentDir??(0,l.N2)(b.workspacePath,b.id),name:b.name,model:(0,ae.Nk)(b.modelId),heartbeat:b.heartbeat.enabled&&b.heartbeat.every?{every:b.heartbeat.every}:null,skills:[...(0,l.AB)(b.skills),d],tools:b.tools.includes("fs.workspaceOnly")?{fs:{workspaceOnly:!0}}:null,identity:{name:b.identityName??b.name,emoji:b.identity.emoji,theme:b.identity.theme,avatar:b.identity.avatar}},e)}}async function ar(...a){return as("syncing the agent config",()=>(0,l.jq)(...a))}async function as(a,b){return(await (0,af.g7)(b,{operationLabel:a})).value}async function at(a,b){let c=b??await (0,d.GM)({includeHidden:!0}),e=c.agents.filter(b=>b.workspacePath===a).map(a=>a.id);await aq(e,c)}async function au(a,b){let c=g().join(a,".openclaw","project.json"),d={},f=null;try{let a=await (0,e.readFile)(c,"utf8"),g=JSON.parse(a);d=aA(g)?g:{},Array.isArray(d.agents)&&(f=d.agents.map(a=>(0,S.aW)(a)).filter(a=>!!a).find(a=>a.id===b.id)??null)}catch{d={}}let h=Array.isArray(b.skillIds)?aw(b.skillIds.map(a=>a.trim()).filter(Boolean)):void 0!==b.skillId?[(0,ae.Nk)(b.skillId)].filter(a=>!!a):f?.skillIds??(f?.skillId?[f.skillId]:[]),i={id:b.id,name:b.name??f?.name??null,role:b.role??f?.role??null,isPrimary:b.isPrimary??f?.isPrimary??!1,enabled:b.enabled??f?.enabled??!0,emoji:b.emoji??f?.emoji??null,theme:b.theme??f?.theme??null,skillId:h[0]??null,skillIds:h,toolIds:Array.isArray(b.toolIds)?aw(b.toolIds.map(a=>a.trim()).filter(a=>!!a&&"fs.workspaceOnly"!==a)):f?.toolIds??[],modelId:b.modelId??f?.modelId??null,policy:b.policy,channelIds:Array.isArray(b.channelIds)?Array.from(new Set(b.channelIds.filter(a=>"string"==typeof a&&a.trim()))):f?.channelIds??[]},j=Array.isArray(d.agents)?d.agents.filter(a=>aA(a)&&"string"==typeof a.id&&a.id!==b.id):[];j.push(i),d.version="number"==typeof d.version?d.version:1,d.slug="string"==typeof d.slug?d.slug:az(g().basename(a)),d.name="string"==typeof d.name?d.name:g().basename(a),d.updatedAt=new Date().toISOString(),d.agents=j,await B(c,`${JSON.stringify(d,null,2)}
273
273
  `)}async function av(a,b){let c=g().join(a,".openclaw","project.json"),d={};try{let a=await (0,e.readFile)(c,"utf8"),b=JSON.parse(a);d=aA(b)?b:{}}catch{return}if(!Array.isArray(d.agents))return;let f=d.agents.map(a=>(0,S.aW)(a)).filter(a=>!!a),h=f.filter(a=>a.id!==b);h.length!==f.length&&(h.length>0&&!h.some(a=>a.isPrimary)&&(h[0]={...h[0],isPrimary:!0}),d.updatedAt=new Date().toISOString(),d.agents=h,await B(c,`${JSON.stringify(d,null,2)}
274
274
  `))}function aw(a){return Array.from(new Set(a.filter(Boolean)))}function ax(a,b,c){return aw([...a.agents.flatMap(a=>a.workspacePath!==b?[]:c.has(a.id)?c.get(a.id)??[]:a.skills),...Array.from(c.values()).flat()])}function ay(a,b){if(b)return a.workspaces.find(a=>a.id===b)??a.workspaces.find(a=>(0,ag.xV)(a.path,b))}function az(a){return a.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function aA(a){return"object"==typeof a&&null!==a}var aB=c(48161),aC=c.n(aB),aD=c(57419),aE=c(9443),aF=c(185),aG=c(78446),aH=c(14414),aI=c(25793);let aJ=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi;function aK(a){if(!a)return!1;let b=a.trim().toLowerCase();return"ready"===b||"completed"===b||"complete"===b||"ok"===b||"success"===b}async function aL(a){var b,c,d,e;let f,{task:g,dispatchRecord:h,createdFiles:i,snapshot:j}=a,k=await aO(h?.outputDir??null),l=h?await aM(h,j,a.runs):[],m=g.mission||h?.mission||null,n=m&&l.length>0?l.filter(a=>(0,aH.Dm)(a.prompt,m)):l,o=[...n].sort((a,b)=>Date.parse(b.updatedAt)-Date.parse(a.updatedAt))[0]??null,p=o?.finalText?.trim()||null,q=h?aK(f=((b=h.result)&&"object"==typeof b?(Array.isArray(b.result?.payloads)?b.result.payloads:Array.isArray(b.payloads)?b.payloads:[]).filter(a=>!!a&&"string"==typeof a.text):[]).find(a=>a.text.trim().length>0)?.text.trim()??null)?null:f:null,r=p||q||null,s=p?"runtime":q?"dispatch":"none",t=!!(h&&l.length>0&&0===n.length),u=(0,aI.xZ)(n),v=function(a){let b=new Set;for(let c of a)if(c)for(let a of c.match(aJ)??[])b.add(a.toLowerCase());return[...b]}([r,q,...n.flatMap(a=>a.items.map(a=>a.text))]),w=[],x=aK(r),y=!!(c=m)&&(/\.(txt|md|json|csv|html|pdf|docx?)\b/i.test(c)||/\b(file|files|artifact|artifacts|report|document|save|export|attachment)\b/i.test(c)||/\b(dosya|dosyasi|kaydet|kaydi|cikti)\b/i.test(c)),z=!!(d=m)&&/\b(email|e-mail|mail|mail address|mail adres|eposta|e-posta)\b/i.test(d),A=!!(e=m)&&(/https?:\/\//i.test(e)||/\b[a-z0-9-]+\.(com|net|org|io|ai|co|tr|app|dev|me|info|biz|edu|gov)\b/i.test(e)||/\b(site|website|web|browser|browse|fetch|sitesine|siteye|siteyi)\b/i.test(e));return h?.outputDir&&!k.exists&&w.push({id:"missing-output-dir",severity:"warning",title:"Output folder is missing",detail:`The dispatch points at ${h.outputDirRelative||h.outputDir}, but that folder is not accessible now.`}),"completed"===g.status&&y&&h?.outputDir&&k.exists&&0===k.fileCount&&0===i.length&&w.push({id:"empty-output-dir",severity:"error",title:"Deliverables folder is empty",detail:"The task asked for a file deliverable, but the assigned deliverables folder does not contain any files."}),"completed"===g.status&&0===l.length&&w.push({id:"missing-transcript",severity:"warning",title:"No runtime transcript was captured",detail:"AgentOS could not verify what the agent actually did because no transcript was recovered for this dispatch."}),"cancelled"===g.status&&w.push({id:"task-cancelled",severity:"warning",title:"Task was cancelled by the operator",detail:h?.error||"The mission dispatch was stopped before completion, so the captured evidence is intentionally incomplete."}),t&&h?.agentId&&w.push({id:"session-mismatch",severity:"error",title:"Recovered session does not match the mission",detail:"The linked transcript session exists, but none of its user turns match this task mission. The dispatch likely reused or attached the wrong session."}),"completed"!==g.status||r?"stalled"===g.status&&r&&o?.status!=="completed"?w.push({id:"partial-final-response",severity:"warning",title:"Final response came from an incomplete runtime",detail:"The assistant produced output, but the runtime stalled before the task completed. Treat this as the last captured response, not a verified completion."}):"completed"===g.status&&x&&r&&w.push({id:"placeholder-final-response",severity:0===k.fileCount&&0===i.length&&0===n.length?"error":"warning",title:"Completion response looks like a placeholder",detail:`The captured final response was "${r}", which is not enough evidence that the requested work actually finished.`}):w.push({id:"missing-final-response",severity:"warning",title:"No final answer was captured",detail:"The task completed without a final assistant response in either the runtime transcript or the dispatch payload."}),"completed"===g.status&&A&&n.length>0&&0===u.length&&w.push({id:"missing-tool-evidence",severity:"warning",title:"No tool usage was recovered",detail:"This mission looks like it needed external lookup or browsing, but the matching transcript turn does not show any recovered tool calls."}),"completed"===g.status&&z&&0===v.length&&w.push({id:"missing-email",severity:"warning",title:"Requested email address was not captured",detail:"The task appears to ask for an email address, but none was detected in the final response or the matching transcript."}),{status:w.some(a=>"error"===a.severity)?"error":w.length>0?"warning":"verified",outputDir:h?.outputDir??null,outputDirRelative:h?.outputDirRelative??null,outputDirExists:k.exists,outputFileCount:k.fileCount,transcriptTurnCount:l.length,matchingTranscriptTurnCount:n.length,finalResponseText:r,finalResponseSource:s,dispatchSessionId:h?aN(h,a.runs)[0]??null:null,sessionMismatch:t,toolNames:u,emails:v,issues:w}}async function aM(a,b,c){let d=aN(a,c);if(0===d.length)return[];let f=b.agents.find(b=>b.id===a.agentId);for(let b of d){let c=await (0,aI.WU)(a.agentId,b,a.workspacePath??f?.workspacePath);if(c)try{let d=await (0,e.readFile)(c,"utf8"),g={id:`runtime:dispatch:${a.id}`,sessionId:b,agentId:a.agentId,taskId:a.id,metadata:{dispatchSubmittedAt:a.submittedAt}},h=(0,aI.qv)(g,(0,aI.SI)(d,g,a.workspacePath??f?.workspacePath));if(h.length>0)return h}catch{continue}}return[]}function aN(a,b){var c;let d;return Array.from(new Set([...b.filter(b=>{var c,d;let e,f;return c=a,e="string"==typeof(d=b).metadata.dispatchId?d.metadata.dispatchId.trim():"",f=d.runId?.trim()||"",e===c.id||f===c.id}).map(a=>a.sessionId?.trim()||null),(a.sessionId?.trim()||null)??(c=function(a){var b;let c=((b=a).result&&"object"==typeof b.result?b.result:null)?.meta;if(!c||"object"!=typeof c){let b=a.meta;return b&&"object"==typeof b?aQ(b):null}return aQ(c)}(a),"string"==typeof(d=c?.sessionId)&&d.trim().length>0?d:null)??function(a){let b=a?.trim();if(!b?.startsWith("runtime:"))return null;let c=b.split(":")[1];return c&&"dispatch"!==c?c:null}(a.observation.runtimeId)].filter(a=>!!a)))}async function aO(a){if(!a)return{exists:!1,fileCount:0};try{if(!(await (0,e.stat)(a)).isDirectory())return{exists:!0,fileCount:1};return{exists:!0,fileCount:await aP(a)}}catch{return{exists:!1,fileCount:0}}}async function aP(a){let b=await (0,e.readdir)(a,{withFileTypes:!0}),c=0;for(let d of b){let b=g().join(a,d.name);if(d.isDirectory()){c+=await aP(b);continue}d.isFile()&&(c+=1)}return c}function aQ(a){if(!a||"object"!=typeof a)return null;let b=a.agentMeta;return b&&"object"==typeof b?b:null}var aR=c(69699);let aS=new Set(["cause","code","details","error","message","reason","stack","stderr","stdout","warning"]);async function aT(a,b=18){let c=a.runner.logPath?.trim();if(!c)return[];try{return(await (0,e.readFile)(c,"utf8")).split(/\r?\n/).map(a=>(function(a){let b=a.trim();if(!b)return null;try{var c;let a=JSON.parse(b);if(!a||"string"!=typeof a.id||"string"!=typeof a.timestamp||"string"!=typeof a.text||(c=a.stream,"status"!==c&&"stdout"!==c&&"stderr"!==c))return null;return{id:a.id,timestamp:a.timestamp,stream:a.stream,text:a.text}}catch{return null}})(a)).filter(a=>!!a).map(a=>{var b;let c;return b=a,(c=aU(b.text))?{...b,text:c}:null}).filter(a=>!!a).slice(-b)}catch{return[]}}function aU(a){let b=a.trim();if(!b||function(a){if(/^[\[\]{}(),]+$/.test(a))return!0;let b=a.match(/^"([^"]+)"\s*:\s*(.+?)(,)?$/);return b?!aS.has(b[1].toLowerCase()):(a.match(/^([A-Za-z0-9_.-]+)\s*:\s*(.+)$/),!1)}(b))return null;let c=b.match(/^"([^"]+)"\s*:\s*(.+?)(,)?$/);if(c){let[,a,b]=c;return aS.has(a.toLowerCase())?`${aV(a)}: ${aW(b)}`:null}let d=b.match(/^([A-Za-z0-9_.-]+)\s*:\s*(.+)$/);return d&&aS.has(d[1].toLowerCase())?`${aV(d[1])}: ${aW(d[2])}`:b}function aV(a){return a.charAt(0).toUpperCase()+a.slice(1)}function aW(a){let b=a.trim().replace(/,$/,"");if(!b)return"";try{let a=JSON.parse(b);if("string"==typeof a)return a;if("number"==typeof a||"boolean"==typeof a)return String(a)}catch{}return b.replace(/^"(.*)"$/,"$1")}var aX=c(80410),aY=c(28182);async function aZ(a,b,c){if(!b)return[];let d=(0,m.CK)(c.agents.find(b=>b.id===a.primaryAgentId)??{name:"OpenClaw"}),e=await aT(b),f=b.runner.logPath&&b.runner.logPath.trim()?{path:b.runner.logPath,displayPath:g().basename(b.runner.logPath)}:null,h=[a$({id:`${b.id}:accepted`,kind:"user",timestamp:b.submittedAt,title:"Mission accepted",detail:a3(a.mission||b.mission||"Mission queued for dispatch.",220),agentId:a.primaryAgentId},{urlSources:[a.mission,b.mission,b.routedMission]})];if((b.runner.startedAt||b.runner.pid)&&h.push(a$({id:`${b.id}:runner-started`,kind:"status",timestamp:b.runner.startedAt??b.updatedAt,title:"Dispatch runner started",detail:b.outputDirRelative?`Preparing the first OpenClaw runtime in ${b.outputDirRelative}.`:"Preparing the first OpenClaw runtime."},{file:b.outputDir&&b.outputDirRelative?{path:b.outputDir,displayPath:b.outputDirRelative}:null})),b.runner.lastHeartbeatAt&&(b.observation.observedAt||"completed"===b.status||h.push(a$({id:`${b.id}:heartbeat`,kind:"status",timestamp:b.runner.lastHeartbeatAt,title:"Heartbeat received",detail:`${d} is online. Waiting for the first runtime session.`},{urlSources:[d,b.outputDirRelative]}))),b.observation.observedAt&&"completed"!==b.status&&h.push(a$({id:`${b.id}:runtime-observed`,kind:"status",timestamp:b.observation.observedAt,title:"Runtime observed",detail:"The task is now live. Runtime updates will continue below."},{urlSources:[b.outputDirRelative]})),"completed"===b.status){let c="string"==typeof a.metadata.finalResponseText?a.metadata.finalResponseText.trim():"",d=(0,aR.Bx)(b)||(0,aR.v0)(b)||c,e=(0,aR.E_)(b);h.push(a$({id:`${b.id}:completed`,kind:"status",timestamp:b.runner.finishedAt??b.updatedAt,title:d?"Mission finished":"Dispatch runner finished",detail:a3(d||(0,aR.kc)(b),220)},{urlSources:[d,(0,aR.kc)(b),b.outputDirRelative],file:e??(b.outputDir&&b.outputDirRelative?{path:b.outputDir,displayPath:b.outputDirRelative}:null)}))}"cancelled"===b.status&&h.push(a$({id:`${b.id}:cancelled`,kind:"warning",timestamp:b.runner.finishedAt??b.updatedAt,title:"Mission cancelled",detail:a3((0,aR.kc)(b),220),isError:!1},{urlSources:[b.error,b.outputDirRelative],file:b.outputDir&&b.outputDirRelative?{path:b.outputDir,displayPath:b.outputDirRelative}:null}));let i=(0,aR.gv)(b);if(i&&h.push(a$({id:`${b.id}:integrity-warning`,kind:"warning",timestamp:b.runner.finishedAt??b.updatedAt,title:"Result needs review",detail:a3(i,220),isError:!0},{urlSources:[b.outputDirRelative],file:b.outputDir&&b.outputDirRelative?{path:b.outputDir,displayPath:b.outputDirRelative}:null})),"stalled"===b.status){var j,k;let a,c,e=(j=b,k=d,a=a0(j.error),c=!!(j.observation.observedAt||j.runner.lastHeartbeatAt),a||!j.error&&c?{kind:"status",title:a?"Waiting for output":"Working silently",detail:a?`${k} has a runtime, but AgentOS has not captured transcript output yet. Updates will stream here when the session writes its first entry.`:`${k} is still being observed, but no transcript output has arrived yet. AgentOS will keep the feed attached.`,isError:!1}:{kind:"warning",title:"Needs attention",detail:j.error||(j.runner.lastHeartbeatAt?"OpenClaw stopped reporting progress while waiting for the first runtime.":"OpenClaw did not produce the first heartbeat in time."),isError:!0});h.push(a$({id:`${b.id}:stalled`,kind:e.kind,timestamp:b.updatedAt,title:e.title,detail:a3(e.detail,220),isError:e.isError},{urlSources:[b.error,b.outputDirRelative]}))}for(let b of e){let c=function(a){let b=aU(a.text);if(!b)return null;if("status"===a.stream)return{kind:"status",title:"Dispatch runner",detail:b,isError:!1};if("stdout"===a.stream)return{kind:"status",title:"Runner output",detail:b,isError:!1};let c=function(a){let b=a.trim().toLowerCase();return!(!b||b.includes("exited successfully")||b.includes("booted for agent")||b.includes("launched openclaw agent process"))&&/(aborted|denied|enoent|eacces|error|exception|failed|failure|invalid|killed|not found|panic|refused|stalled|timeout|timed out|traceback)/i.test(a)}(b);return{kind:c?"warning":"status",title:c?"Runner warning":"Runner note",detail:b,isError:c}}(b);c&&h.push(a$({id:b.id,kind:c.kind,timestamp:b.timestamp,title:c.title,detail:a3(c.detail,220),agentId:a.primaryAgentId,isError:c.isError},{file:f}))}return h}function a$(a,b){let c=function(a){for(let b of a){if("string"!=typeof b)continue;let a=b.match(/https?:\/\/[^\s<>"'`]+/i);if(!a)continue;let c=a[0].replace(/[)\].,;:!?]+$/g,"");if(c)return c}return null}(b?.urlSources??[]);return{...a,...c?{url:c}:{},...b?.file?{filePath:b.file.path,displayPath:b.file.displayPath}:{}}}function a_(a){return"available"===a.status||a.items.length>0||!!a.finalText?.trim()||a.createdFiles.length>0}function a0(a){return"string"==typeof a&&(/No transcript file was found for this runtime session/i.test(a)||/No transcript entries were found for this runtime/i.test(a))}function a1(a){return a.map(a=>(a??"").replace(/\s+/g," ").trim().toLowerCase()).join("|")}function a2(a){return"number"==typeof a&&Number.isFinite(a)?new Date(a).toISOString():new Date().toISOString()}function a3(a,b){let c=a.replace(/\s+/g," ").trim();return c.length<=b?c:`${c.slice(0,Math.max(b-1,1)).trimEnd()}…`}var a4=c(37110);async function a5(a,b,c){let d=a.runtimeIds.map(a=>b.runtimes.find(b=>b.id===a)).filter(a=>!!a).sort(ba);return a7(a,d,b,c)}async function a6(a,b){let c=new Map(b.agents.map(a=>[a.id,(0,m.CK)(a)])),d=b.runtimes.filter(b=>(function(a,b){if(("string"==typeof a.metadata.dispatchId?a.metadata.dispatchId.trim():"")===b.id)return!0;let c=(0,aR.Xy)(b);return!!c&&a.sessionId===c&&a.agentId===b.agentId})(b,a)).sort(ba),e=d[0]??await (0,a4.DO)(a)??(0,aX.Bi)(a,Date.now()),f=d.length>0?d:[e];return a7((0,aY.bE)(`dispatch:${a.id}`,f,c),f,b,a)}async function a7(a,b,c,d){var e,f,g,h,i,j;let k,l,n,o,p,q,r,s,t=await Promise.all(b.map(a=>(0,aI.pY)(a,c))),u=new Map(t.map(a=>[a.runtimeId,a])),v=(0,aY.T$)(t.flatMap(a=>a.createdFiles).concat(b.flatMap(a=>(0,aY.Y8)(a)))),w=Array.from(new Set(t.flatMap(a=>a.warnings).concat(b.flatMap(a=>(0,aY.qA)(a))).map(a=>a.trim()).filter(Boolean))),x=(e=d?(0,aR.Ck)(a,d):a,f=t,g=v,h=w,n=(k=(i=f).filter(a=>a.finalText?.trim()).sort(a8)).length>0?k[0]??null:i.filter(a=>{var b;return a.errorMessage?.trim()&&!("string"==typeof(b=a.errorMessage)&&(/No transcript file was found for this runtime session/i.test(b)||/No transcript entries were found for this runtime/i.test(b)))}).sort(a8)[0]??null,p=(o=n?.finalText?.trim()||null)||("string"==typeof e.metadata.resultPreview?e.metadata.resultPreview.trim():"")||e.subtitle,q=f.filter(a=>a.items.length>0).length,r="stalled"===e.status&&!!n&&(j=n,l=j.stopReason?.trim(),!!(j.finalText?.trim()&&"available"===j.status&&!j.errorMessage&&l&&"toolUse"!==l&&"error"!==l&&"aborted"!==l)),{...e,status:r?"completed":e.status,subtitle:o?(s=o.replace(/\s+/g," ").trim()).length<=160?s:`${s.slice(0,Math.max(159,1)).trimEnd()}…`:e.subtitle,artifactCount:g.length,warningCount:h.length,metadata:{...e.metadata,resultPreview:p,turnCount:q||e.metadata.turnCount,finalResponseText:o,finalResponseRuntimeId:n?.runtimeId??null}}),y=await aZ(x,d,c),z=function(a,b,c,d){var e,f,g,h,i,j;let k=new Map(d.agents.map(a=>[a.id,(0,m.CK)(a)])),l=[],n=[...b].sort((a,b)=>(a.updatedAt??0)-(b.updatedAt??0)),o=Array.from(c.values()).some(a_),p=null,q=new Set,r=new Set,s=new Set,t=new Set;for(let b of n){if(a.dispatchId&&(0,aX.U8)(b))continue;let d=c.get(b.id),j=b.agentId?k.get(b.agentId)??null:null,m=(e=b,(f=d?.finalTimestamp)||a2(e.updatedAt));if(d?.items.length)for(let a of d.items){let c=a3(a.text.trim()||d.errorMessage||b.subtitle,220),e=a1(["item",a.role,a.toolName??"",a.timestamp,c]);q.has(e)||(q.add(e),l.push(a$({id:`${b.id}:${a.id}`,kind:"assistant"===a.role?"assistant":"toolCall"===a.role||"toolResult"===a.role?"tool":"user",timestamp:a.timestamp,title:"assistant"===a.role?j||"Agent update":"toolCall"===a.role||"toolResult"===a.role?a.toolName?`Tool \xb7 ${a.toolName}`:"Tool update":"Mission",detail:c,runtimeId:b.id,agentId:b.agentId,toolName:a.toolName,isError:a.isError},{urlSources:[a.text,d?.finalText,d?.errorMessage,b.subtitle]})))}else{let a=a3(d?.errorMessage||b.subtitle,220);if(g=d,h=a,g?.status==="missing"||a0(h)){o||"queued"!==(i=b).status&&"running"!==i.status&&"stalled"!==i.status||(p={runtime:b,agentName:j,timestamp:m});continue}let c=a1(["status",b.status,a]);if(r.has(c))continue;r.add(c);let e=function(a,b,c){let d=b||"Run";return"stalled"===a.status?{kind:"warning",title:`${d} \xb7 needs attention`,detail:c,isError:!0}:{kind:"status",title:`${d} \xb7 ${a.status}`,detail:c,isError:!1}}(b,j,a);l.push(a$({id:`${b.id}:status`,kind:e.kind,timestamp:m,title:e.title,detail:e.detail,runtimeId:b.id,agentId:b.agentId,isError:e.isError},{urlSources:[d?.errorMessage,b.subtitle]}))}for(let a of Array.from(new Set((d?.warnings??[]).concat((0,aY.qA)(b)).map(a=>a.trim()).filter(Boolean)))){let c=a1(["warning",a]);s.has(c)||(s.add(c),l.push(a$({id:`${b.id}:warning:${(0,aY.vC)(a)}`,kind:"warning",timestamp:m,title:"Fallback",detail:a3(a,220),runtimeId:b.id,agentId:b.agentId},{urlSources:[a]})))}for(let a of function(a){let b=new Set,c=[];for(let d of a)!d.path||b.has(d.path)||(b.add(d.path),c.push(d));return c}((d?.createdFiles??[]).concat((0,aY.Y8)(b))))t.has(a.path)||(t.add(a.path),l.push(a$({id:`${b.id}:artifact:${(0,aY.vC)(a.path)}`,kind:"artifact",timestamp:m,title:"Created file",detail:a.displayPath,runtimeId:b.id,agentId:b.agentId},{file:a})))}if(p&&!l.some(a=>{var b;return"assistant"===(b=a).kind||"tool"===b.kind||"artifact"===b.kind})){let a,b=(j=p.runtime,a=p.agentName||"Agent","running"===j.status?{title:`${a} \xb7 working silently`,detail:"The runtime is live, but no transcript output has been captured yet. The first assistant, tool, or file update will stream here."}:{title:`${a} \xb7 waiting for output`,detail:"AgentOS has not captured transcript output yet. This can happen while the agent is starting, attaching a session, or writing its first update."});l.push(a$({id:`${p.runtime.id}:waiting-for-output`,kind:"status",timestamp:p.timestamp,title:b.title,detail:b.detail,runtimeId:p.runtime.id,agentId:p.runtime.agentId,isError:!1},{urlSources:[p.runtime.subtitle]}))}return 0===l.length&&a.mission&&!a.dispatchId&&l.push(a$({id:`${a.id}:mission`,kind:"user",timestamp:a2(a.updatedAt),title:"Mission",detail:a3(a.mission,220),agentId:a.primaryAgentId},{urlSources:[a.mission]})),l.sort((a,b)=>Date.parse(a.timestamp)-Date.parse(b.timestamp)).slice(-36)}(x,b,u,c),A=await aL({task:x,runs:b,outputs:t,createdFiles:v,dispatchRecord:d,snapshot:c});return{task:x,runs:b,outputs:t,liveFeed:function(...a){let b=new Map;for(let c of a.flat())b.set(c.id,c);return[...b.values()].sort((a,b)=>Date.parse(a.timestamp)-Date.parse(b.timestamp)).slice(-48)}(y,z),createdFiles:v,warnings:w,integrity:A}}function a8(a,b){return a9(b.finalTimestamp)-a9(a.finalTimestamp)}function a9(a){let b=a?Date.parse(a):NaN;return Number.isNaN(b)?0:b}function ba(a,b){return(b.updatedAt??0)-(a.updatedAt??0)}var bb=c(35456),bc=c(49922),bd=c(88366),be=c(75402),bf=c(88978);function bg(){(0,d.ZZ)()}function bh(){(0,d.b7)()}async function bi(a,b){let c=await (0,bf.t)(be.wh,a?[a]:[],{agentDirs:a?{[a]:b}:void 0,touch:!0});if(c.issues.length>0)throw bg(),Error(`OpenClaw runtime state is not writable. AgentOS needs write access to ${c.stateRoot} and the agent session store before missions can run.`)}async function bj(a={}){await bi(a.agentId??null,a.agentDir),bg()}async function bk(a={}){var b;let c=await (0,d.GM)({force:!0,includeHidden:!0}),e=(b=a.agentId)&&c.agents.some(a=>a.id===b)?b:c.agents.find(a=>a.isDefault)?.id||c.agents[0]?.id||null;if(!e)return{status:"not-run",checkedAt:null,agentId:null,runId:null,summary:null,error:"AgentOS could not find an OpenClaw agent for the runtime smoke test."};let f=await (0,bb.tl)(),g=(0,bb.Yt)(f,e);if(!a.force&&(0,bb.SK)(g))return(0,bb.Az)(e,g);let h=c.agents.find(a=>a.id===e);await bi(e,h?.agentDir);try{await (0,aF.o)({agentId:e,modelId:h?.modelId,agentDir:h?.agentDir});let a=await (0,k.rw)().runAgentTurn({agentId:e,message:"AgentOS runtime smoke test. Reply with a brief READY status.",thinking:"off",timeoutSeconds:45},{timeoutMs:5e4}),b={status:"passed",checkedAt:new Date().toISOString(),agentId:e,runId:a.runId??null,summary:a.summary||(0,aR.Ym)(a)[0]?.text||"AgentOS verified a real OpenClaw turn.",error:null};return await (0,bb.go)(b),bg(),b}catch(d){let a=(0,aG.t)(d)||"OpenClaw runtime smoke test failed.",b=(0,bc.YG)(a)?(0,bc.ox)((0,bc.MF)(await (0,bd.XP)().catch(()=>"openclaw"))):a,c={status:"failed",checkedAt:new Date().toISOString(),agentId:e,runId:null,summary:null,error:b};return await (0,bb.go)(c),bg(),c}}async function bl(a){let b=await (0,d.GM)({includeHidden:!0}),c=b.runtimes.find(b=>b.id===a);return(c||(c=(b=await (0,d.GM)({force:!0,includeHidden:!0})).runtimes.find(b=>b.id===a)),c)?(0,aI.pY)(c,b):{runtimeId:a,status:"missing",finalText:null,finalTimestamp:null,stopReason:null,errorMessage:"Runtime was not found in the current OpenClaw snapshot.",items:[],createdFiles:[],warnings:[],warningSummary:null}}async function bm(a,b={}){let c=await (0,d.GM)({includeHidden:!0}),e=c.tasks.find(b=>b.id===a);if(!e&&b.dispatchId&&(e=c.tasks.find(a=>a.dispatchId===b.dispatchId)),!e&&((e=(c=await (0,d.GM)({force:!0,includeHidden:!0})).tasks.find(b=>b.id===a))||!b.dispatchId||(e=c.tasks.find(a=>a.dispatchId===b.dispatchId))),!e){let a="string"==typeof b.dispatchId?b.dispatchId.trim():"";if(a){let b=await (0,a4.O1)(a);if(b)return a6(b,c)}throw Error("Task was not found in the current OpenClaw snapshot.")}let f=e.dispatchId?await (0,a4.O1)(e.dispatchId):null;return a5(e,c,f)}var bn=c(37037),bo=c(16588);function bp(){(0,d.ZZ)()}async function bq(a,b={}){var c,e,f,j;let k,l,m,n,o=function(a){let b=a.name.trim();if(!b)throw Error("Workspace name is required.");let c=x(b);if(!c)throw Error("Workspace name must include letters or numbers.");let d=a.template??"software",e=a.teamPreset??"core",f=a.sourceMode??"empty",g=a.modelProfile??"balanced",j={...r.eY,...a.rules??{}},k=(a.agents?.length?a.agents:(0,r.P0)(d,e,b)).map(a=>{let c=w(a),d=a.policy?.preset??(0,h.qF)({skills:c,id:a.id,name:a.name});return{id:x(a.id)||"agent",role:a.role.trim()||R(a.id),name:u(a.name)??(a.isPrimary?(0,r.sg)(b,a.role,R(a.id)):R(a.id)),enabled:!1!==a.enabled,emoji:u(a.emoji)??void 0,theme:u(a.theme)??void 0,skillId:c[0]??void 0,skillIds:c,modelId:u(a.modelId)??void 0,isPrimary:!!a.isPrimary,heartbeat:i(d,a.heartbeat),policy:(0,h.g0)(d,{...a.policy,fileAccess:j.workspaceOnly?a.policy?.fileAccess??"workspace-only":"extended"})}});if(!k.some(a=>a.enabled&&a.isPrimary)){let a=k.find(a=>a.enabled);a&&(a.isPrimary=!0)}let l=function(a){let b=new Set,c=new Set;for(let d of a){if(b.has(d)){c.add(d);continue}b.add(d)}return Array.from(c).sort((a,b)=>a.localeCompare(b))}(k.filter(a=>a.enabled).map(a=>a.id));if(l.length>0)throw Error(`Enabled agents must have unique ids. Conflicts: ${l.join(", ")}.`);return{name:b,slug:c,brief:u(a.brief)??void 0,directory:u(a.directory)??void 0,modelId:u(a.modelId)??void 0,repoUrl:u(a.repoUrl)??void 0,existingPath:u(a.existingPath)??void 0,sourceMode:f,template:d,teamPreset:e,modelProfile:g,rules:j,docOverrides:(0,q.Iy)(a.docOverrides),agents:k,contextSources:(a.contextSources??[]).flatMap(a=>{var b;if(!a||"object"!=typeof a)return[];let c="prompt"===(b=a.kind)||"website"===b||"repo"===b||"folder"===b?a.kind:"prompt",d=u(a.label)??c,e=u(a.summary)??d,f="error"===a.status?"error":"ready",g=u(a.createdAt)??new Date().toISOString();if(!d||!e)return[];let h={id:u(a.id)??`${c}-${x(d)||"context"}`,kind:c,label:d,summary:e,details:Array.isArray(a.details)?a.details.map(a=>u(a)??"").filter(a=>!!a):[],status:f,createdAt:g},i="number"==typeof a.confidence?a.confidence:void 0,j=u(a.error)??void 0,k=u(a.url)??void 0;return void 0!==i&&(h.confidence=i),void 0!==j&&(h.error=j),void 0!==k&&(h.url=k),[h]})}}(a),p=o.agents.filter(a=>a.enabled),t=(0,bn.X6)({template:(0,bn.fV)({sourceMode:o.sourceMode,agentCount:p.length,kickoffMission:o.rules.kickoffMission}),onProgress:b.onProgress});if(0===p.length)throw Error("Enable at least one agent for the workspace.");await t.startStep("validate","Resolving workspace settings and reserving the target directory."),await t.addActivity("validate",`Validated workspace name "${o.name}".`);let v=await function(a,b){if("existing"===a.sourceMode){let b=a.existingPath||a.directory;if(!b)throw Error("Choose an existing folder for this workspace.");return g().isAbsolute(b)?b:g().resolve(b)}return a.directory?g().isAbsolute(a.directory)?a.directory:g().join(b,a.directory):g().join(b,a.slug)}(o,await (0,bb.wL)()||g().join(aC().homedir(),"Documents","Shared","projects"));await t.updateStep("validate",{percent:38,detail:`Reserved target directory at ${v}.`}),await t.addActivity("validate",`Reserved target directory ${v}.`,"done");let y=await (0,d.GM)({force:!0,includeHidden:!0}),z=o.modelId??(f=y,p.map(a=>(0,ae.Nk)(a.modelId)).find(a=>a&&bC(f,a)))??function(a){if(a.diagnostics.modelReadiness.defaultModelReady)return(0,ae.Nk)(a.diagnostics.modelReadiness.resolvedDefaultModel)??(0,ae.Nk)(a.diagnostics.modelReadiness.defaultModel)??void 0}(y)??(j=y,(k=(0,ae.Nk)(j.diagnostics.modelReadiness.recommendedModelId))&&bC(j,k)?k:j.models.map(a=>(0,ae.Nk)(a.id)).find(a=>a&&bC(j,a))),A=(0,ah.d9)(y,z);if(A)throw Error(A);await t.updateStep("validate",{percent:72,detail:"Checking current OpenClaw snapshot and agent ids."}),function(a,b,c){let d=c.map(a=>X(b,a.id)),e=function(a){let b=new Set,c=new Set;for(let d of a){if(b.has(d)){c.add(d);continue}b.add(d)}return Array.from(c).sort((a,b)=>a.localeCompare(b))}(d);if(e.length>0)throw Error(`Workspace bootstrap would create duplicate agent ids: ${e.join(", ")}.`);for(let b of d){let c=a.agents.find(a=>a.id===b);if(c)throw Error(`Workspace bootstrap would create agent id "${b}", but it already exists in workspace "${function(a,b){return a.workspaces.find(a=>a.id===b.workspaceId)?.name??g().basename(b.workspacePath)}(a,c)}". Rename the workspace or adjust the agent ids.`)}}(y,o.slug,p),await t.completeStep("validate",`Workspace input and ${p.length} agent configuration${1===p.length?"":"s"} are ready.`);let B=await bF(v,y,o.slug);if(B)return await t.startStep("source",O(o.sourceMode,v)),await t.addActivity("source","Workspace already exists. Reusing the existing folder.","done"),await t.completeStep("source","Existing workspace folder reused."),await t.startStep("scaffold","Writing the initial workspace scaffold and local metadata."),await t.addActivity("scaffold","Workspace scaffold already exists. Reusing existing files.","done"),await t.completeStep("scaffold","Workspace files and starter docs are already in place."),await t.startStep("agents",1===B.agentIds.length?"Reusing the existing workspace agent.":`Reusing ${B.agentIds.length} workspace agents.`),await t.addActivity("agents",`${B.agentIds.length} agent${1===B.agentIds.length?"":"s"} already linked to the workspace.`,"done"),await t.completeStep("agents",`${B.agentIds.length} agent${1===B.agentIds.length?"":"s"} already linked to the workspace.`),await t.startStep("kickoff","Finalizing workspace bootstrap."),await t.addActivity("kickoff","Kickoff was already handled by the existing workspace.","done"),await t.completeStep("kickoff","Workspace bootstrap is already complete."),bp(),bh(),B;await t.startStep("source",O(o.sourceMode,v)),await t.addActivity("source",(c=o.sourceMode,"clone"===c?o.repoUrl?`Cloning ${o.repoUrl}.`:"Cloning the requested repository.":"existing"===c?o.existingPath?`Attaching ${o.existingPath}.`:"Attaching the requested folder.":"Preparing an empty workspace scaffold."),"active"),await M({targetDir:v,sourceMode:o.sourceMode,repoUrl:o.repoUrl}),await t.completeStep("source",(e=o.sourceMode,"clone"===e?`Repository content is available at ${v}.`:"existing"===e?`Existing folder linked and ready at ${v}.`:`Fresh workspace folder created at ${v}.`)),await t.startStep("scaffold","Writing the initial workspace scaffold and local metadata."),await t.addActivity("scaffold","Generating workspace docs, memory, and configuration files."),await N(v,{name:o.name,brief:o.brief,template:o.template,teamPreset:o.teamPreset,modelProfile:o.modelProfile,rules:o.rules,docOverrides:o.docOverrides,sourceMode:o.sourceMode,agents:p,contextSources:o.contextSources}),await t.completeStep("scaffold","Workspace files and starter docs are in place.");let C=[],D=[];for(let a of(await t.startStep("agents",1===p.length?"Provisioning the first workspace agent.":`Provisioning ${p.length} workspace agents.`),p)){let b,c=C.length,d=c+1;await t.updateStep("agents",{percent:Math.round(c/p.length*100),detail:`Creating agent ${d} of ${p.length}: ${a.name}.`}),await t.addActivity("agents",`Creating ${a.name} (${a.role}).`);let e=X(o.slug,a.id),f=null;try{b=await Y({workspacePath:v,workspaceSlug:o.slug,workspaceModelId:z,agent:a})}catch(a){f=br(a),D.push(f),b=e}C.push(b),await t.addActivity("agents",f?`Created ${a.name} as ${b}; config sync needs a Gateway refresh.`:`Created ${a.name} as ${b}.`,"done"),await t.updateStep("agents",{percent:Math.round(C.length/p.length*100),detail:`${C.length} of ${p.length} agent${1===p.length?"":"s"} ready.`})}await t.completeStep("agents",`${C.length} agent${1===C.length?"":"s"} linked to the workspace.`),bp();try{await bH(v)}catch(a){D.push(br(a)),await t.addActivity("agents","Agent policy config sync needs a Gateway refresh.","done")}await (0,s.u)(v);let E=C.find(a=>p.some(b=>b.isPrimary&&X(o.slug,b.id)===a))??C[0];if(o.rules.kickoffMission){await t.startStep("kickoff",`Dispatching the kickoff mission to ${E}.`),await t.addActivity("kickoff",`Selected ${E} as the primary agent.`);try{let a=await bI({agentId:E,brief:o.brief,modelProfile:o.modelProfile,template:o.template,rules:o.rules},{onProgress:async({message:a,percent:b})=>{await t.updateStep("kickoff",{percent:b,detail:a}),await t.addActivity("kickoff",a,b>=100?"done":"active")}});l=a.runId,m=a.status,await t.completeStep("kickoff",`Kickoff mission finished with status ${m||"unknown"}.`)}catch(a){n=a instanceof Error?a.message:"Kickoff mission could not be started.",await t.addActivity("kickoff",n,"error"),await t.failStep("kickoff",n)}}else await t.startStep("kickoff","Finalizing workspace bootstrap."),await t.addActivity("kickoff","Kickoff mission is disabled for this workspace.","done"),await t.completeStep("kickoff","Workspace bootstrap finished without kickoff.");return bp(),bh(),{workspaceId:bA(y.workspaces,v),workspacePath:v,agentIds:C,primaryAgentId:E,kickoffRunId:l,kickoffStatus:m,kickoffError:n,warnings:bw(D)}}function br(a){let b=ak(a)?"AgentOS created the workspace, but OpenClaw could not finish the agent config sync in time. Restart or refresh the OpenClaw Gateway if the workspace agent profile looks incomplete, then refresh AgentOS.":null;if(!b)throw a;return b}async function bs(a){let b=a.workspaceId.trim();if(!b)throw Error("Workspace id is required.");if(a.plan){let c=a.baseline??await bu(b);return by((0,bo.co)(c),a.plan,{name:a.name,directory:a.directory,baseline:c})}let c=await (0,d.GM)({force:!0}),f=bz(c.workspaces,b);if(!f)throw Error("Workspace was not found.");let h=bE(f.path,a.name,a.directory);if(h!==f.path){await bD(h,f.path);try{await (0,e.rename)(f.path,h)}catch(a){throw Error(a instanceof Error?`Unable to move workspace directory. ${a.message}`:"Unable to move workspace directory.")}let a=(await (0,l.CI)(c)).map(a=>a.workspace===f.path?{...a,workspace:h,agentDir:"string"==typeof a.agentDir&&a.agentDir.startsWith(`${f.path}${g().sep}`)?g().join(h,g().relative(f.path,a.agentDir)):a.agentDir}:a);await (0,l.ZF)(a)}return bp(),bh(),{workspaceId:bA(c.workspaces,h,f.path),previousWorkspaceId:f.id,workspacePath:h}}async function bt(a){let b=a.workspaceId.trim();if(!b)throw Error("Workspace id is required.");let c=await (0,d.GM)({force:!0,includeHidden:!0}),f=bz(c.workspaces,b);if(!f)throw Error("Workspace was not found.");let g=c.agents.filter(a=>a.workspaceId===f.id),h=c.runtimes.filter(a=>a.workspaceId===f.id).length;for(let a of g)await (0,k.rw)().deleteAgent(a.id);try{let a=await (0,l.CI)(c),b=a.filter(a=>a.workspace!==f.path&&!g.some(b=>b.id===a.id));b.length!==a.length&&await (0,l.ZF)(b)}catch{}return await (0,e.rm)(f.path,{recursive:!0,force:!0}),(0,d.er)(),{workspaceId:f.id,workspacePath:f.path,deletedAgentIds:g.map(a=>a.id),deletedRuntimeCount:h}}async function bu(a){let b=await (0,d.GM)({force:!0,includeHidden:!0}),c=bz(b.workspaces,a);if(!c)throw Error("Workspace was not found.");let f=await (0,S.OL)(c.path),i=f.name??c.name,j=b.agents.filter(a=>a.workspaceId===c.id),k=bw(j.flatMap(a=>a.skills)),l=bw(j.flatMap(a=>a.tools)),m=f.template??c.bootstrap.template??"software",n=f.sourceMode??c.bootstrap.sourceMode??"empty",o=f.teamPreset??(j.length<=1?"solo":"core"),p=f.modelProfile??"balanced",s=f.rules??r.eY,t=await (0,aE.xL)(c.path,f.template,f.rules??r.eY),u=await (0,aD.L)(c.path,{agentId:j[0]?.id??c.id,agentName:j[0]?.name??i,configuredSkills:k,configuredTools:l,template:m,rules:s,workspaceBootstrapProfile:t}),v=f.agents.length>0?f.agents.map(a=>{let b=bv(j,c.slug,a.id),d=(0,h.g0)(a.policy?.preset??b?.policy.preset??h.iN,a.policy??b?.policy);return{id:a.id,role:a.role??(0,h._P)(d.preset),name:a.name??b?.name??a.role??a.id,enabled:a.enabled,emoji:a.emoji??b?.identity.emoji,theme:a.theme??b?.identity.theme,skillId:a.skillId??void 0,modelId:a.modelId??(b?.modelId&&"unassigned"!==b.modelId?b.modelId:void 0),isPrimary:a.isPrimary,policy:d,channelIds:a.channelIds??[],heartbeat:{enabled:b?.heartbeat.enabled??!1,...b?.heartbeat.every?{every:b.heartbeat.every}:{}}}}):(0,r.P0)(m,o,i),w=(0,q.Q5)({name:i,brief:u.purpose||i,template:m,sourceMode:n,rules:s,agents:v,toolExamples:await J(c.path),docOverrides:[],contextSources:f.contextSources??[]}),x=[],y=new Set(w.map(a=>a.path)),z=await (0,bo.wZ)(c.path);for(let a of w){let b=g().join(c.path,a.path);try{let c=await (0,e.readFile)(b,"utf8");c!==a.baseContent&&x.push({path:a.path,content:c})}catch{continue}}for(let a of z){if(y.has(a))continue;let b=g().join(c.path,a);try{let c=await (0,e.readFile)(b,"utf8");x.push({path:a,content:c})}catch{continue}}return{workspaceId:c.id,workspacePath:c.path,name:i,directory:c.path,template:m,sourceMode:n,teamPreset:o,modelProfile:p,modelId:c.modelIds[0]&&"unassigned"!==c.modelIds[0]?c.modelIds[0]:void 0,rules:s,docOverrides:x,agents:v,brief:u.purpose||i,contextSources:f.contextSources??[]}}function bv(a,b,c){let d=bx(c),e=`${b}-`;return a.find(a=>{var d,e;return a.id===(d=b,e=c,`${d}-${bx(e)||"agent"}`)})??a.find(a=>a.id===`${e}${d}`)??a.find(a=>d.length>0&&a.id.endsWith(`-${d}`))??a.find(a=>a.id===d)??null}function bw(a){return Array.from(new Set(a.filter(Boolean)))}function bx(a){return a.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}async function by(a,b,c){let f=(0,ae.Nk)(c.name)??(0,ae.Nk)(b.workspace.name)??a.name,h=(0,ae.Nk)(c.directory),i=(0,ae.Nk)(c.baseline.directory)??a.path,j=(0,ae.Nk)(c.baseline.name)??a.name,k=(0,ae.Nk)(c.baseline.brief)??"",m=(0,ae.Nk)(b.company.mission)??(0,ae.Nk)(b.product.offer)??"",n=(0,q.Iy)(b.workspace.docOverrides),o=(0,q.Iy)(c.baseline.docOverrides),p=new Map(n.map(a=>[a.path,a.content])),t=new Map(o.map(a=>[a.path,a.content])),u=b.team.persistentAgents.filter(a=>a.enabled),v=c.baseline.agents.filter(a=>a.enabled),w=f.trim()!==j.trim(),x=w||m!==k||b.workspace.template!==c.baseline.template||b.workspace.sourceMode!==c.baseline.sourceMode||!(0,bo.Rp)(b.workspace.rules,c.baseline.rules)||!(0,bo.cD)(u,v),y=h&&h!==i?bE(a.path,void 0,h):w?bE(a.path,f,void 0):a.path,z=y!==a.path,A=z?await (0,d.GM)({force:!0,includeHidden:!0}):null;if(z){await bD(y,a.path);try{await (0,e.rename)(a.path,y)}catch(a){throw Error(a instanceof Error?`Unable to move workspace directory. ${a.message}`:"Unable to move workspace directory.")}let b=(await (0,l.CI)(A??void 0)).map(b=>b.workspace===a.path?{...b,workspace:y,agentDir:"string"==typeof b.agentDir&&b.agentDir.startsWith(`${a.path}${g().sep}`)?g().join(y,g().relative(a.path,b.agentDir)):b.agentDir}:b);await (0,l.ZF)(b)}let C=g().join(y,".openclaw","project.json"),D=new Date().toISOString(),E=!1,F=null;try{var G;let a=await (0,e.readFile)(C,"utf8"),b=JSON.parse(a);G=b,"object"!=typeof G||null===G||Array.isArray(G)||(D="string"==typeof b.createdAt?b.createdAt:D,E=!0===b.hidden,F="string"==typeof b.systemTag?b.systemTag:null)}catch{}let H=b.team.persistentAgents.map(a=>({id:a.id,name:a.name,role:a.role,enabled:a.enabled,emoji:(0,ae.Nk)(a.emoji)??null,theme:(0,ae.Nk)(a.theme)??null,isPrimary:!!a.isPrimary,skillId:(0,ae.Nk)(a.skillId)??null,modelId:(0,ae.Nk)(a.modelId)??null,policy:a.policy??null,channelIds:Array.from(new Set((a.channelIds??[]).map(a=>"string"==typeof a?a.trim():"").filter(a=>!!a)))})),I=H.length<=1?"solo":H.every(a=>a.enabled)?"core":"custom",K={version:1,slug:bx(g().basename(y)),name:f,directory:y,icon:(0,r.hh)(b.workspace.template).icon,createdAt:D,updatedAt:new Date().toISOString(),template:b.workspace.template,sourceMode:b.workspace.sourceMode,teamPreset:I,modelProfile:b.workspace.modelProfile,agentTemplate:"solo"===I?"solo":"core-team",rules:{workspaceOnly:b.workspace.rules.workspaceOnly,generateStarterDocs:b.workspace.rules.generateStarterDocs,generateMemory:b.workspace.rules.generateMemory,kickoffMission:b.workspace.rules.kickoffMission},contextSources:b.intake.sources,hidden:E,systemTag:F,agents:H};if(x){let a=(0,q.Q5)({name:f,brief:m||f,template:b.workspace.template,sourceMode:b.workspace.sourceMode,rules:b.workspace.rules,agents:u,toolExamples:await J(y),docOverrides:n,contextSources:b.intake.sources}),c=new Set(a.map(a=>a.path));for(let b of a)await B(g().join(y,b.path),b.content);for(let a of n)c.has(a.path)||await B(g().join(y,a.path),a.content)}else{let a=(0,q.Q5)({name:j,brief:k||j,template:c.baseline.template,sourceMode:c.baseline.sourceMode,rules:c.baseline.rules,agents:v,toolExamples:[],docOverrides:[],contextSources:c.baseline.contextSources??[]}),b=new Set(a.map(a=>a.path));for(let a of n)t.get(a.path)!==a.content&&await B(g().join(y,a.path),a.content);for(let c of o){if(p.has(c.path))continue;let d=a.find(a=>a.path===c.path);d&&b.has(d.path)&&await B(g().join(y,d.path),d.baseContent)}}if(z||!(0,bo.cD)(u,v)){let d=z?bA(A?.workspaces??[],y,a.path):a.id,e={...a,id:d,path:y};await bB({currentWorkspace:e,desiredAgents:b.team.persistentAgents,workspaceSlug:bx(g().basename(y)),previousWorkspaceId:c.baseline.workspaceId,previousWorkspacePath:c.baseline.workspacePath})}return await B(C,`${JSON.stringify(K,null,2)}
275
- `),await (0,s.u)(y),bp(),bh(),{workspaceId:z?bA(A?.workspaces??[],y,a.path):a.id,previousWorkspaceId:a.id,workspacePath:y}}function bz(a,b){return a.find(a=>a.id===b)??a.find(a=>(0,ag.xV)(a.path,b))}function bA(a,b,c){let d=c?g().resolve(c):null,e=[...a.map(a=>a.path).filter(a=>!d||g().resolve(a)!==d),b];return(0,ag.hv)(b,e)}async function bB(a){let b=Array.from(new Map((await (0,d.GM)({force:!0,includeHidden:!0})).agents.filter(b=>b.workspaceId===a.currentWorkspace.id||!!a.previousWorkspaceId&&b.workspaceId===a.previousWorkspaceId||!!(a.previousWorkspacePath&&b.workspacePath===a.previousWorkspacePath)).map(a=>[a.id,a])).values()),c=new Set;for(let d of a.desiredAgents){let e=bv(b,a.workspaceSlug,d.id);if(!d.enabled){e&&(c.add(e.id),await an({agentId:e.id}));continue}if(e){c.add(e.id),await am({id:e.id,workspaceId:a.currentWorkspace.id,workspacePath:a.currentWorkspace.path,name:(0,ae.Nk)(d.name)??e.name,emoji:(0,ae.Nk)(d.emoji)??e.identity.emoji,theme:(0,ae.Nk)(d.theme)??e.identity.theme,modelId:(0,ae.Nk)(d.modelId)??("unassigned"===e.modelId?void 0:e.modelId),policy:d.policy,heartbeat:d.heartbeat,channelIds:d.channelIds});continue}let f=await aj({id:X(a.workspaceSlug,d.id),workspaceId:a.currentWorkspace.id,workspacePath:a.currentWorkspace.path,name:(0,ae.Nk)(d.name)??void 0,emoji:(0,ae.Nk)(d.emoji)??void 0,theme:(0,ae.Nk)(d.theme)??void 0,modelId:(0,ae.Nk)(d.modelId)??void 0,policy:d.policy,heartbeat:d.heartbeat,channelIds:d.channelIds});c.add(f.agentId)}for(let a of b)c.has(a.id)||await an({agentId:a.id})}function bC(a,b){let c=a.models.find(a=>a.id===b);return!!c&&!0!==c.missing&&!1!==c.available}async function bD(a,b){if(a!==b)try{throw await (0,e.access)(a),Error("Target workspace directory already exists.")}catch(a){if("ENOENT"===("object"==typeof a&&a&&"code"in a?a.code:void 0))return;if(a instanceof Error)throw a;throw Error("Unable to verify target workspace directory.")}}function bE(a,b,c){let d=(0,ae.Nk)(c);if(d)return g().isAbsolute(d)?d:g().join(g().dirname(a),d);let e=(0,ae.Nk)(b);if(!e)return a;let f=bx(e);if(!f)throw Error("Workspace name is required.");return g().join(g().dirname(a),f)}async function bF(a,b,c){let d=await (0,S.OL)(a),e=d.agents.filter(a=>a.enabled);if(!(d.name||d.template||d.sourceMode||d.agentTemplate||e.length>0||d.channels.length>0||d.contextSources.length>0))return null;let f=bA(b.workspaces,a),h=bz(b.workspaces,f)??b.workspaces.find(b=>g().resolve(b.path)===g().resolve(a))??null,i=h?.id??f,j=b.agents.filter(b=>b.workspaceId===i||g().resolve(b.workspacePath)===g().resolve(a)),k=new Set(j.map(a=>a.id)),l=e.map(a=>bG(c,a)),m=[];for(let b of l){if(k.has(b.agentId))continue;let d=await Y({workspacePath:a,workspaceSlug:c,workspaceModelId:b.agent.modelId,agent:b.agent});m.push(d),k.add(d)}let n=bw(l.map(a=>a.agentId)),o=bw([...j.map(a=>a.id),...m,...n]);if(0===o.length)return null;let p=d.agents.find(a=>a.enabled&&a.isPrimary)??null,q=p?bG(c,p):null,r=j[0]?.id??q?.agentId??o[0];return{workspaceId:h?.id??i,workspacePath:h?.path??a,agentIds:o,primaryAgentId:r,kickoffRunId:void 0,kickoffStatus:void 0,kickoffError:void 0}}function bG(a,b){let c=`${a}-`,d=(b.id.startsWith(c)?b.id.slice(c.length):b.id)||b.id;return{agentId:b.id.startsWith(c)?b.id:X(a,b.id),agent:{id:d,name:b.name??d,role:b.role??"Agent",enabled:b.enabled,emoji:b.emoji??void 0,theme:b.theme??void 0,skillId:b.skillId??void 0,skillIds:b.skillIds,modelId:b.modelId??void 0,isPrimary:b.isPrimary,policy:b.policy??void 0,channelIds:b.channelIds}}}async function bH(a){let b=await (0,d.GM)({includeHidden:!0});for(let c of bw(b.agents.filter(b=>b.workspacePath===a).map(a=>a.id))){let a=b.agents.find(a=>a.id===c);if(!a)continue;let d=b.agents.find(b=>b.workspaceId===a.workspaceId&&"setup"===b.policy.preset&&b.id!==a.id)?.id??null,e=await Z({workspacePath:a.workspacePath,agentId:a.id,agentName:a.name,policy:a.policy,setupAgentId:d,snapshot:b});await (0,l.jq)(a.id,a.workspacePath,{name:a.name,model:(0,ae.Nk)(a.modelId),heartbeat:a.heartbeat.enabled&&a.heartbeat.every?{every:a.heartbeat.every}:null,skills:[...(0,l.AB)(a.skills),e],tools:a.tools.includes("fs.workspaceOnly")?{fs:{workspaceOnly:!0}}:null},b)}}async function bI(a,b={}){var c,d,e;let f,g,h=(c=a.template,d=a.brief,e=a.rules,f=(0,r.hh)(c),g=(0,q.Q4)(c,e).sections.map(a=>{let b=a.resources.map(a=>a.label).join(", ");return a.enabled?`${a.title}: ${b||"none"}`:`${a.title}: disabled by workspace rules`}).join("\n"),[`You are bootstrapping a newly created ${f.label.toLowerCase()} workspace.`,d?`Project brief: ${d}`:"No detailed project brief was provided yet.","Inspect the current files and improve the starter workspace without rewriting files that already had meaningful content.","Treat the following workspace context manifest as the source of truth:",g,"If those docs exist, refine the brief, architecture, memory, and deliverables guidance based on the real repository state instead of guessing.","Leave the workspace with a concise first task batch and any critical unknowns clearly called out.","Prefer concrete workspace-grounded edits over verbose chat output."].join("\n\n")),i="fast"===a.modelProfile?"low":"quality"===a.modelProfile?"high":"medium",j=new Set;await b.onProgress?.({message:"Submitting the kickoff brief to the primary agent.",percent:18});let l=await (0,k.rw)().streamAgentTurn({agentId:a.agentId,message:h,thinking:i,timeoutSeconds:90},{onStdout:async a=>{let c,d=(c=a.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,"").trim())?Array.from(new Set(c.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).map(a=>a.replace(/^[>•*-]\s*/,"")).filter(a=>!a.startsWith("{")&&!a.startsWith("[")).filter(a=>!/auth-profiles/i.test(a)))).slice(0,3):[];if(0===d.length&&a.trim())return void await b.onProgress?.({message:"Primary agent responded. Finalizing kickoff output.",percent:82});for(let a of d)await b.onProgress?.({message:a,percent:72})},onStderr:async a=>{let c=a.trim();if(!c)return;let d=function(a){let b,c=a.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,"").split(/\r?\n/).map(a=>a.trim()).filter(Boolean).join(" ");if(!c)return null;let d=c.toLowerCase();return d.includes("scope upgrade pending approval")||d.includes("pairing required")||d.includes("more scopes than currently approved")?"Gateway permissions need approval; continuing with the embedded runtime.":d.includes("falling back to embedded")?"Gateway agent is unavailable; continuing with the embedded runtime.":d.includes("gateway connect failed")?"Gateway connection is not ready; continuing with the embedded runtime.":`Runtime notice: ${(b=c.replace(/\(requestId:\s*[^)]+\)/gi,"").replace(/\brequestId:\s*\S+/gi,"").replace(/\s+/g," ").trim()).length>160?`${b.slice(0,157).trim()}...`:b}`}(c);!d||j.has(d)||(j.add(d),await b.onProgress?.({message:d,percent:64}))}},{timeoutMs:12e4});return await b.onProgress?.({message:"Kickoff mission completed. Recording the resulting run metadata.",percent:100}),l}function bJ(a){return a.split(g().sep).join("/")}async function bK(a,b){var c;let d,f,h,i=(c=b,f=[(d=new Date).getFullYear(),String(d.getMonth()+1).padStart(2,"0"),String(d.getDate()).padStart(2,"0"),String(d.getHours()).padStart(2,"0"),String(d.getMinutes()).padStart(2,"0"),String(d.getSeconds()).padStart(2,"0")].join("-"),h=c.replace(/^\[[^\]]+\]\s*/i,"").trim().normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48).replace(/^-+|-+$/g,"")||"task",`${f}-${h}`),j=g().join(a,"deliverables",i),k=bJ(g().join("deliverables",i)),l=bJ("memory");return await (0,e.mkdir)(j,{recursive:!0}),await (0,e.mkdir)(g().join(a,"memory"),{recursive:!0}),{runFolder:i,absoluteOutputDir:j,relativeOutputDir:k,notesDirRelative:l}}var bL=c(25303),bM=c(3334);async function bN(a,b){var c,d;let e,f,g=a.mission.trim();if(!g)throw Error("Mission text is required.");let i=await b.getMissionControlSnapshot({includeHidden:!0}),j=a.agentId||b.resolveAgentForMission(i,a.workspaceId);if(!j)throw Error("No OpenClaw agent is available for mission dispatch. Finish OpenClaw setup, create a workspace, then create or select an agent.");let l=i.agents.find(a=>a.id===j),m=i.workspaces.find(b=>b.id===(a.workspaceId||l?.workspaceId))??(l?{id:l.workspaceId,path:l.workspacePath}:null),n=m?i.agents.filter(a=>a.workspaceId===m.id):[],o=n.find(a=>"setup"===a.policy.preset&&a.id!==l?.id)?.id??null,p=m?await bK(m.path,g):null,q=a.thinking??"medium",r=(0,bM.Z)(j,i),s=p?(c=l?.policy,d=l?{id:l.id,name:l.name}:null,e=c??(0,h.g0)(h.iN),[g,...(f=d?["Agent workspace context:",`- Your current OpenClaw agent id is \`${d.id}\`${d.name?` and your AgentOS display name is ${d.name}`:""}.`,"- Use the matching subsection in workspace root `AGENTS.md` as your agent-specific role/persona.","- Treat other `AGENTS.md` agent subsections as teammates in the same workspace.","- Use root `SOUL.md`, `USER.md`, `TOOLS.md`, `MEMORY.md`, `memory/*.md`, and `docs/*.md` as shared workspace/project context."]:[]).length>0?["",...f]:[],"","Task output routing:",`- Put substantial outputs, drafts, reports, docs, and file deliverables under \`${p.relativeOutputDir}/\`.`,`- If a file is requested, default to \`${p.relativeOutputDir}/<descriptive-file-name>\` unless the user explicitly asks for another path.`,`- Use \`${p.notesDirRelative}/\` only for temporary notes or durable workspace memory, not final deliverables.`,"- Avoid writing final artifacts to the workspace root.","- Only update shared workspace docs when the change is durable and workspace-wide; task-specific docs should stay inside this run folder.","","Agent operating policy:",...L(e,o),...r?["",r]:[]].join("\n")):g,t=(0,ah.l9)(i,l?.modelId==="unassigned"?null:l?.modelId),u=(0,a4._z)({agentId:j,mission:g,routedMission:s,thinking:q,workspaceId:m?.id??null,workspacePath:m?.path??null,outputDir:p?.absoluteOutputDir??null,outputDirRelative:p?.relativeOutputDir??null,notesDirRelative:p?.notesDirRelative??null});if(await (0,a4.lm)(u),t)return u={...u,status:"stalled",updatedAt:new Date().toISOString(),error:t},await (0,a4.lm)(u),b.invalidateMissionControlCaches(),{dispatchId:u.id,runId:null,agentId:j,status:u.status,summary:t,payloads:[],meta:{outputDir:p?.absoluteOutputDir,outputDirRelative:p?.relativeOutputDir,notesDirRelative:p?.notesDirRelative}};try{let a=await (0,bL.N3)().catch(()=>null);if(a?.nativeMissionDispatch!=="unsupported"){let a=await (0,k.rw)().runAgentTurn({agentId:j,sessionId:u.sessionId??void 0,message:s,thinking:q,timeoutSeconds:45,workspace:m?.path??null,dispatchId:u.id},{timeoutMs:6e4}),b=new Date().toISOString();u={...u,status:"completed"===a.status?"completed":"stalled"===a.status?"stalled":"running",updatedAt:b,runner:{...u.runner,startedAt:b,finishedAt:"completed"===a.status||"stalled"===a.status?b:null,lastHeartbeatAt:b},observation:{runtimeId:a.runId?`runtime:gateway:${a.runId}`:u.observation.runtimeId,observedAt:b},result:a,error:"stalled"===a.status?a.summary??"OpenClaw Gateway dispatch stalled.":null},await (0,a4.lm)(u)}else u=await (0,a4.gb)(u)}catch(a){throw u={...u,status:"stalled",updatedAt:new Date().toISOString(),error:(0,aG.t)(a)||"Mission dispatch runner could not be started."},await (0,a4.lm)(u),b.invalidateMissionControlCaches(),Error(u.error??"Mission dispatch runner could not be started.")}return b.invalidateMissionControlCaches(),{dispatchId:u.id,runId:u.result?.runId??null,agentId:j,status:u.status,summary:"Mission accepted and queued for OpenClaw execution.",payloads:[],meta:{outputDir:p?.absoluteOutputDir,outputDirRelative:p?.relativeOutputDir,notesDirRelative:p?.notesDirRelative}}}async function bO(a,b,c,d){let e=(await d.getMissionControlSnapshot({includeHidden:!0})).tasks.find(b=>b.id===a),f=e?await (0,a4.ji)(e):c?await (0,a4.O1)(c):null;if(!e&&!f)throw Error("Task was not found in the current OpenClaw snapshot.");if(!f)return bQ(e,a,b,d);if((0,a4.VW)(f.status))return{taskId:a,dispatchId:f.id,status:f.status,summary:(0,aR.kc)(f),reason:f.error,runnerPid:f.runner.pid,childPid:f.runner.childPid,abortedAt:f.runner.finishedAt??f.updatedAt};let g=new Date().toISOString(),h=(0,a4.GG)(b),i={...f,status:"cancelled",updatedAt:g,error:h,runner:{...f.runner,finishedAt:g,lastHeartbeatAt:g}};await (0,a4.lm)(i),d.invalidateMissionControlCaches();let j=null,l=f.result?.runId??null,m=(0,k.rw)();for(let a of bP(e,f))await m.cancelTask({taskId:a,reason:h},{timeoutMs:15e3}).catch(()=>null);return(l||f.sessionId)&&await m.abortAgentTurn({runId:l,sessionId:f.sessionId,agentId:f.agentId,reason:h},{timeoutMs:15e3}).catch(()=>null),j=await (0,a4.e4)(i),{taskId:a,dispatchId:i.id,status:i.status,summary:h,reason:h,runnerPid:i.runner.pid,childPid:j??i.runner.childPid,abortedAt:g}}function bP(a,b){let c=[bR(b?.result),bR(b?.result?.task),bR(a?.metadata),a?.metadata.gatewayObjectKind==="task"?a.metadata.taskId:null,a?.metadata.gatewayObjectKind==="task"?a?.key:null],d=new Set;for(let a of c)"string"==typeof a&&a.trim()&&a!==b?.id&&d.add(a.trim());return[...d]}async function bQ(a,b,c,d){if(!a)throw Error("Task was not found in the current OpenClaw snapshot.");if("completed"===a.status||"stalled"===a.status||"cancelled"===a.status)return{taskId:b,dispatchId:null,status:a.status,summary:a.subtitle||"Task is already terminal.",reason:null,runnerPid:null,childPid:null,abortedAt:new Date().toISOString()};let e=(0,a4.GG)(c),f=bP(a,null);if(0===f.length)throw Error("Mission dispatch record was not found and the task does not expose a Gateway task id.");for(let a of f)await (0,k.rw)().cancelTask({taskId:a,reason:e},{timeoutMs:15e3});return d.invalidateMissionControlCaches(),{taskId:b,dispatchId:null,status:"cancelled",summary:e,reason:e,runnerPid:null,childPid:null,abortedAt:new Date().toISOString()}}function bR(a){if(!a||"object"!=typeof a||Array.isArray(a))return null;let b=a.gatewayTaskId??a.openClawTaskId??a.taskId??a.id;return"string"==typeof b&&b.trim()?b.trim():null}function bS(a,b){if(!b)return a.agents.find(a=>a.isDefault)?.id||a.agents[0]?.id;let c=a.agents.filter(a=>a.workspaceId===b);return c.find(a=>a.isDefault)?.id||c.find(a=>"engaged"===a.status)?.id||c[0]?.id}async function bT(a){return bN(a,{getMissionControlSnapshot:d.GM,resolveAgentForMission:bS,invalidateMissionControlCaches:d.er})}async function bU(a,b,c){return bO(a,b,c,{getMissionControlSnapshot:d.GM,resolveAgentForMission:bS,invalidateMissionControlCaches:d.er})}async function bV(a,b,c={}){var e,f,g,h;let i,j,l,m,n,o=b.message.trim();if(!o)throw Error("Control message is required.");let p=c.getTaskDetail??bm,q=await p(a,{dispatchId:b.dispatchId??null}),r=(i=(e=q).task,j=e.runs.find(a=>bX(a.status))??e.runs[0]??null,l=j?.agentId?.trim()||i.primaryAgentId?.trim()||bY(i.agentIds)||null,m=j?.sessionId?.trim()||bY(i.sessionIds)||bZ(i.metadata,"sessionId")||bZ(i.metadata,"gatewaySessionId")||bZ(i.metadata,"openClawSessionId")||null,n=(bZ(i.metadata,"sessionKey")||bZ(i.metadata,"gatewaySessionKey")||(j?.key.trim().startsWith("agent:")?j.key.trim():null))??(f=l,(g=m)?g.startsWith("agent:")?g:f?`agent:${f}:explicit:${g}`:null:null),{agentId:l,sessionId:m,sessionKey:n,runId:j?.runId?.trim()||bY(i.runIds)||null}),s=c.adapter??(0,k.rw)();if("continue"===b.action){let a=await bW(q,r,o,s,c);return(c.invalidateMissionControlSnapshotCache??d.ZZ)(),{ok:!0,action:b.action,taskId:q.task.id,target:r,result:a}}if(!(bX((h=q).task.status)||h.task.liveRunCount>0||h.runs.some(a=>bX(a.status))))throw Error("Task is not currently running.");if(!r.sessionKey&&!r.sessionId)throw Error("Task does not expose an active OpenClaw session.");let t="steer"===b.action?await s.steerSession({key:r.sessionKey,sessionId:r.sessionKey?null:r.sessionId,message:o},{timeoutMs:1e4}):await s.injectChat({sessionKey:r.sessionKey,sessionId:r.sessionKey?null:r.sessionId,message:o},{timeoutMs:1e4});return(c.invalidateMissionControlSnapshotCache??d.ZZ)(),{ok:!0,action:b.action,taskId:q.task.id,target:r,result:t}}async function bW(a,b,c,e,f){var g,h;let i,j;if(!b.agentId)throw Error("Task does not expose an OpenClaw agent.");if(!e.runAgentTurn)throw Error("Task continuation requires OpenClaw mission dispatch support.");let k=await (f.getMissionControlSnapshot??d.GM)({includeHidden:!0}).catch(()=>null),l=a.task.dispatchId??null,m=b.sessionId??b.sessionKey??void 0;return await e.runAgentTurn({agentId:b.agentId,sessionId:m??void 0,message:c,thinking:"medium",timeoutSeconds:45,workspace:(g=a,h=k,i=g.task,j=i.workspaceId?.trim(),h&&j?h.workspaces.find(a=>a.id===j)?.path??h.agents.find(a=>a.id===i.primaryAgentId)?.workspacePath??null:null),dispatchId:l,idempotencyKey:l?`${l}:continue:${Date.now()}`:void 0},{timeoutMs:6e4})}function bX(a){return"running"===a||"queued"===a}function bY(a){return a.find(a=>a.trim().length>0)?.trim()??null}function bZ(a,b){let c=a[b];return"string"==typeof c&&c.trim().length>0?c.trim():null}var b$=c(1718),b_=c(99254),b0=c(74497);function b1(){(0,d.ZZ)()}async function b2(a,b){let c=cC(a.channelId);if(!c)throw Error("Channel id is required.");return await (0,n.rh)(b,"workspace-channel.registry-upsert",()=>cA(b=>{let d=b.channels.find(a=>a.id===c)??{id:c,type:a.type,name:a.name.trim()||c,primaryAgentId:(0,ae.Nk)(a.primaryAgentId)??null,workspaces:[]},e=a.workspaceId.trim(),f=a.workspacePath.trim(),g=d.workspaces.find(a=>a.workspaceId===e)??{workspaceId:e,workspacePath:f,agentIds:[],groupAssignments:[]},h=cB([...g.agentIds,...(a.agentIds??[]).map(a=>a.trim()).filter(Boolean)]),i=(0,S.qc)([...g.groupAssignments,...(a.groupAssignments??[]).filter(a=>!!a.chatId)]),j={...g,workspacePath:f,agentIds:h,groupAssignments:i},k=d.workspaces.filter(a=>a.workspaceId!==e);k.push(j);let l=(0,ae.Nk)(a.primaryAgentId)??d.primaryAgentId;b.channels=[...b.channels.filter(a=>a.id!==c),{...d,id:c,type:a.type,name:a.name.trim()||d.name||c,primaryAgentId:l||j.agentIds[0]||j.groupAssignments.find(a=>a.agentId)?.agentId||null,workspaces:k}]},{},b)),b1(),(0,b_.VW)()}async function b3(a,b){let c=cC(a.channelId);if(!c)throw Error("Channel id is required.");return await (0,n.rh)(b,"channel-registry.disconnect",()=>cA(b=>{b.channels=b.channels.map(b=>{if(b.id!==c)return b;let d=b.workspaces.filter(b=>b.workspaceId!==a.workspaceId),e=cB([...d.flatMap(a=>a.agentIds),...d.flatMap(a=>a.groupAssignments.filter(a=>!1!==a.enabled&&a.agentId).map(a=>a.agentId))]);return{...b,primaryAgentId:b.primaryAgentId&&e.includes(b.primaryAgentId)?b.primaryAgentId:e[0]??null,workspaces:d}}).filter(a=>a.workspaces.length>0||a.primaryAgentId)},{},b)),b1(),(0,b_.VW)()}async function b4(a,b){let c=cC(a.channelId);if(!c)throw Error("Channel id is required.");let d=(await (0,n.rh)(b,"channel-registry.read-before-delete",()=>(0,b_.vg)())).channels.find(a=>a.id===c);if(!d)throw Error("Channel was not found.");let e=cB(d.workspaces.flatMap(a=>a.groupAssignments.filter(a=>!!a.chatId).map(a=>a.chatId))),f=cB(d.workspaces.map(a=>a.workspacePath));return cD(d.type)&&"internal"!==d.type&&await (0,n.rh)(b,"channel.delete-openclaw-remove",()=>(0,k.rw)().removeChannelAccount({channel:d.type,account:c,delete:!0},{timeoutMs:6e4})),await (0,n.rh)(b,"channel.delete-registry-sync",()=>cA(a=>{a.channels=a.channels.filter(a=>a.id!==c)},{removedAccountIds:[c],removedGroupIds:e},b)),await (0,n.rh)(b,"channel.delete-project-cleanup",()=>Promise.all(f.map(a=>cd(a,c,b)))),b1(),(0,n.rh)(b,"channel.delete-read-final-registry",()=>(0,b_.VW)())}async function b5(a,b){let c=cC(a.channelId);if(!c)throw Error("Channel id is required.");return await (0,n.rh)(b,"channel.primary-update",()=>cA(b=>{let d=b.channels.find(a=>a.id===c);if(!d)throw Error("Channel was not found.");d.primaryAgentId=(0,ae.Nk)(a.primaryAgentId)??null},{},b)),b1(),(0,b_.VW)()}async function b6(a,b){let c=cC(a.channelId);if(!c)throw Error("Channel id is required.");let d=[];return await (0,n.rh)(b,"channel.groups-update",()=>cA(b=>{let e=b.channels.find(a=>a.id===c);if(!e)throw Error("Channel was not found.");let f=e.workspaces.find(b=>b.workspaceId===a.workspaceId);if(!f)throw Error("Workspace binding was not found for this channel.");let g=new Set(f.groupAssignments.filter(a=>!1!==a.enabled&&!!a.chatId).map(a=>a.chatId));f.groupAssignments=(0,S.qc)(a.groupAssignments.map(a=>({chatId:a.chatId.trim(),agentId:(0,ae.Nk)(a.agentId)??null,title:(0,ae.Nk)(a.title)??null,enabled:!1!==a.enabled}))),f.agentIds=cB([...f.agentIds,...f.groupAssignments.filter(a=>!1!==a.enabled&&a.agentId).map(a=>a.agentId)]);let h=new Set(f.groupAssignments.filter(a=>!1!==a.enabled&&!!a.chatId).map(a=>a.chatId));for(let a of g)h.has(a)||d.push(a)},{removedGroupIds:d},b)),b1(),(0,b_.VW)()}async function b7(a,b){let c=cC(a.channelId),d=cE(a.agentId.trim());if(!c||!d)throw Error("Channel id and agent id are required.");return await (0,n.rh)(b,"channel.bind-agent",()=>cA(b=>{let e=b.channels.find(a=>a.id===c);if(!e)throw Error("Channel was not found.");let f=e.workspaces.find(b=>b.workspaceId===a.workspaceId)??{workspaceId:a.workspaceId,workspacePath:a.workspacePath,agentIds:[],groupAssignments:[]};f.agentIds=cB([...f.agentIds,d]),f.workspacePath=a.workspacePath,e.workspaces=[...e.workspaces.filter(b=>b.workspaceId!==a.workspaceId),f],e.primaryAgentId||(e.primaryAgentId=d)},{},b)),b1(),(0,b_.VW)()}async function b8(a,b){let c=cC(a.channelId),d=cE(a.agentId.trim());if(!c||!d)throw Error("Channel id and agent id are required.");return await (0,n.rh)(b,"channel.unbind-agent",()=>cA(b=>{let e=b.channels.find(a=>a.id===c);if(!e)throw Error("Channel was not found.");let f=e.workspaces.find(b=>b.workspaceId===a.workspaceId);if(f){if(f.agentIds=f.agentIds.filter(a=>a!==d),f.groupAssignments=f.groupAssignments.filter(a=>a.agentId!==d),e.primaryAgentId===d){let a=f.agentIds[0]??f.groupAssignments.find(a=>!1!==a.enabled&&a.agentId)?.agentId??e.workspaces.flatMap(a=>a.agentIds).find(a=>a!==d)??e.workspaces.flatMap(a=>a.groupAssignments).find(a=>!1!==a.enabled&&a.agentId&&a.agentId!==d)?.agentId??null;e.primaryAgentId=a}e.workspaces=[...e.workspaces.filter(b=>b.workspaceId!==a.workspaceId),{...f,agentIds:f.agentIds,groupAssignments:f.groupAssignments}]}},{},b)),b1(),(0,b_.VW)()}async function b9(a,b){if("telegram"===a.provider){if(!a.token?.trim())throw Error("Telegram bot token is required.");return cb({name:a.name,token:a.token,accountId:a.accountId},b)}let c=(0,ae.Nk)(a.accountId)??await cf(a.provider,a.name,b),d=new Set((await (0,n.rh)(b,`managed-chat.${a.provider}.read-before`,()=>(0,b_.QT)())).filter(b=>b.type===a.provider).map(a=>a.id)),e=(()=>{switch(a.provider){case"discord":if(!a.token?.trim())throw Error("Discord bot token is required.");return{channel:"discord",account:c,token:a.token,name:a.name};case"slack":if(!a.botToken?.trim())throw Error("Slack bot token is required.");return{channel:"slack",account:c,botToken:a.botToken,name:a.name};case"googlechat":if(!a.webhookUrl?.trim())throw Error("Google Chat webhook URL is required.");return{channel:"googlechat",account:c,webhookUrl:a.webhookUrl,name:a.name};default:throw Error(`OpenClaw provisioning is not implemented for ${a.provider}.`)}})();await (0,n.rh)(b,`managed-chat.${a.provider}.provision-openclaw`,()=>(0,k.rw)().provisionChannelAccount(e,{timeoutMs:6e4}));let f=(await (0,n.rh)(b,`managed-chat.${a.provider}.read-after`,()=>(0,b_.QT)())).filter(b=>b.type===a.provider);return f.find(a=>a.id===c)??f.find(b=>!d.has(b.id)&&b.name===a.name)??f.find(a=>!d.has(a.id))??null??{id:c,type:a.provider,kind:(0,b0.Yx)(a.provider),name:a.name.trim()||c,enabled:!0}}async function ca(a,b){var c;if("telegram"===(c=a.provider)||"discord"===c||"slack"===c||"googlechat"===c)return b9({provider:a.provider,name:a.name,accountId:a.accountId,token:a.token,botToken:a.botToken,webhookUrl:a.webhookUrl},b);let d=function(a){let b={};if(!ce(a))return b;for(let[c,d]of Object.entries(a))cl(b,c,cm(d));return b}(a.config),e=a.name.trim(),f=function(a,b){switch(a){case"gmail":return cn(b.account)??cn(b.email)??cn(b.address);case"email":return cn(b.address)??cn(b.email);case"webhook":case"cron":return cn(b.accountId)??cn(b.name);default:return null}}(a.provider,d),g=(0,ae.Nk)(a.accountId)??f??await cf(a.provider,a.name,b),h=function(a){switch(a){case"gmail":return"hooks.gmail";case"email":return"email";case"webhook":return"hooks";case"cron":return"cron";default:throw Error(`OpenClaw provisioning is not implemented for ${a}.`)}}(a.provider);switch(a.provider){case"gmail":{let a=(0,ae.Nk)(d.account??d.email??d.address);if(!a)throw Error("Gmail account email is required.");await (0,n.rh)(b,"managed-surface.gmail.setup-openclaw",()=>(0,k.rw)().setupGmailWebhook({account:a,config:d},{timeoutMs:6e4}));let c=await (0,n.rh)(b,"managed-surface.gmail.read-config",()=>(0,k.rw)().getConfig(h,{timeoutMs:6e4})),f=await (0,n.rh)(b,"managed-surface.gmail.read-hooks",()=>(0,k.rw)().getConfig("hooks",{timeoutMs:6e4})),i=f?.presets,j=ck(f,{enabled:!0,presets:cB([...Array.isArray(i)?i.filter(a=>"string"==typeof a):[],"gmail"])});await (0,n.rh)(b,"managed-surface.gmail.write-hooks",()=>(0,k.rw)().setConfig("hooks",j,{strictJson:!0,timeoutMs:6e4}));let l=ck(c,{enabled:!0,name:e||a,label:e||a,accountId:g,account:a,email:a,address:a,...d});await (0,n.rh)(b,"managed-surface.gmail.write-config",()=>(0,k.rw)().setConfig(h,l,{strictJson:!0,timeoutMs:6e4}));break}case"webhook":{let a=await (0,n.rh)(b,"managed-surface.webhook.read-config",()=>(0,k.rw)().getConfig(h,{timeoutMs:6e4})),c=cn(d.token);if(!c)throw Error("Webhook token is required.");let f=ck(a,{enabled:!0,name:e||g,label:e||g,accountId:g,token:c,...d});await (0,n.rh)(b,"managed-surface.webhook.write-config",()=>(0,k.rw)().setConfig(h,f,{strictJson:!0,timeoutMs:6e4}));break}case"cron":{let a=await (0,n.rh)(b,"managed-surface.cron.read-config",()=>(0,k.rw)().getConfig(h,{timeoutMs:6e4})),c=cn(d.webhookToken);if(!c)throw Error("Cron webhook token is required.");let f=ck(a,{enabled:!0,name:e||g,label:e||g,accountId:g,webhookToken:c,...d});await (0,n.rh)(b,"managed-surface.cron.write-config",()=>(0,k.rw)().setConfig(h,f,{strictJson:!0,timeoutMs:6e4}));break}case"email":{let a=await (0,n.rh)(b,"managed-surface.email.read-config",()=>(0,k.rw)().getConfig(h,{timeoutMs:6e4})),c=cn(d.address??d.email);if(!c)throw Error("Email address is required.");let f=ck(a,{enabled:!0,name:e||c,label:e||c,accountId:g,address:c,email:c,...d});await (0,n.rh)(b,"managed-surface.email.write-config",()=>(0,k.rw)().setConfig(h,f,{strictJson:!0,timeoutMs:6e4}));break}default:throw Error(`OpenClaw provisioning is not implemented for ${a.provider}.`)}let i=(await (0,n.rh)(b,`managed-surface.${a.provider}.read-after`,()=>(0,b_.QT)())).filter(b=>b.type===a.provider);return i.find(a=>a.id===g)??i.find(b=>b.name.trim().toLowerCase()===a.name.trim().toLowerCase())??i[0]??null??{id:g,type:a.provider,kind:(0,b0.Yx)(a.provider),name:e||g,enabled:!0}}async function cb(a,b){let c=(0,ae.Nk)(a.accountId)??await cg(a.name,b),d=new Set((await (0,n.rh)(b,"telegram.read-before",()=>(0,b_.QT)())).filter(a=>"telegram"===a.type).map(a=>a.id));await (0,n.rh)(b,"telegram.openclaw-add",()=>(0,k.rw)().provisionChannelAccount({channel:"telegram",account:c,token:a.token,name:a.name},{timeoutMs:6e4}));let e={id:c,type:"telegram",name:a.name.trim()||c,enabled:!0},f=(await (0,n.rh)(b,"telegram.read-after",()=>(0,b_.QT)())).filter(a=>"telegram"===a.type).find(a=>a.id===c);if(f)return{...f,name:a.name.trim()||f.name};let g=Date.now()+8e3,h=null,i=0;for(;Date.now()<g;){i+=1;let e=(await (0,n.rh)(b,`telegram.resolve.${i}.read-channel-accounts`,()=>(0,b_.QT)())).filter(a=>"telegram"===a.type);if(h=e.find(a=>a.id===c)??e.find(b=>!d.has(b.id)&&b.name===a.name)??e.find(a=>!d.has(a.id))??e.find(b=>b.name===a.name)??null)break;let f=await (0,n.rh)(b,`telegram.resolve.${i}.read-pairing-accounts`,()=>ch());if(h=f.find(b=>!d.has(b.id)&&b.name===a.name)??f.find(a=>!d.has(a.id))??f.find(b=>b.name===a.name)??null)break;await (0,n.rh)(b,`telegram.resolve.${i}.sleep`,()=>new Promise(a=>setTimeout(a,750)))}if(!h){let c=await (0,n.rh)(b,"telegram.resolve.token-lookup",async()=>cj(a.token,(await (0,n.rh)(b,"telegram.resolve.token-lookup.read-channel-accounts",()=>(0,b_.QT)())).filter(a=>"telegram"===a.type),b));h=c||e}return{...h,name:a.name.trim()||h.name}}async function cc(a){await B(be.q6,`${JSON.stringify(a,null,2)}
276
- `)}async function cd(a,b,c){let d=g().join(a,".openclaw","project.json"),f={};try{let b=await (0,n.rh)(c,`workspace-project.${g().basename(a)}.read`,()=>(0,e.readFile)(d,"utf8")),h=JSON.parse(b);f=ce(h)?h:{}}catch{return}if(!Array.isArray(f.agents))return;let h=!1,i=f.agents.map(a=>{if(!ce(a)||"string"!=typeof a.id)return a;let c=Array.isArray(a.channelIds)?a.channelIds.filter(a=>"string"==typeof a):[],d=c.filter(a=>a!==b);return d.length===c.length?a:(h=!0,{...a,channelIds:d})});h&&(f.updatedAt=new Date().toISOString(),f.agents=i,await (0,n.rh)(c,`workspace-project.${g().basename(a)}.write`,()=>B(d,`${JSON.stringify(f,null,2)}
277
- `)))}function ce(a){return"object"==typeof a&&null!==a}async function cf(a,b,c){let d=cE(b.trim())||a,e=`${a}-${d}`,f=await (0,n.rh)(c,`managed-surface.${a}.read-channel-registry`,()=>(0,b_.vg)()),g=await (0,n.rh)(c,`managed-surface.${a}.read-channel-accounts`,()=>(0,b_.QT)()),h=new Set([...f.channels.filter(b=>b.type===a).map(a=>a.id),...g.filter(b=>b.type===a).map(a=>a.id)]);if(!h.has(e))return e;let i=2;for(;h.has(`${e}-${i}`);)i+=1;return`${e}-${i}`}async function cg(a,b){return cf("telegram",a,b)}async function ch(){try{let a=await (0,e.readFile)(g().join(be.wh,"credentials","telegram-pairing.json"),"utf8"),b=JSON.parse(a),c=Array.isArray(b?.requests)?b.requests:[],d=new Map;for(let a of c){let b=(0,ae.Nk)(a.meta?.accountId);b&&d.set(b,{id:b,type:"telegram",name:(0,ae.Nk)(a.meta?.username)??(0,ae.Nk)(a.meta?.firstName)??b,enabled:!0})}return Array.from(d.values())}catch{return[]}}async function ci(a){try{let b=g().join(be.wh,"telegram"),c=await (0,n.rh)(a,"telegram.resolve.read-bot-id-files",()=>(0,e.readdir)(b)),d=await Promise.all(c.filter(a=>a.startsWith("update-offset-")&&a.endsWith(".json")).map(async c=>{try{let d=await (0,n.rh)(a,`telegram.resolve.read-bot-id-file.${c}`,()=>(0,e.readFile)(g().join(b,c),"utf8")),f=JSON.parse(d),h=(0,ae.Nk)(f?.botId),i=c.slice(14,-5);if(!h||!i)return null;return[i,h]}catch{return null}}));return new Map(d.filter(a=>!!a))}catch{return new Map}}async function cj(a,b,c){let d=(0,ae.Nk)(a.split(":",1)[0]);if(!d)return null;let e=await (0,n.rh)(c,"telegram.resolve.read-bot-ids",()=>ci(c));return b.find(a=>e.get(a.id)===d)??null}function ck(a,b){var c;let d=ce(c=a)?JSON.parse(JSON.stringify(c)):{};for(let[a,c]of Object.entries(b))cl(d,a,cm(c));return d}function cl(a,b,c){if(void 0===c)return;let d=b.split(".").map(a=>a.trim()).filter(Boolean);if(0===d.length)return;let e=a;for(let a=0;a<d.length-1;a+=1){let b=d[a];ce(e[b])||(e[b]={}),e=e[b]}e[d[d.length-1]]=c}function cm(a){if("string"==typeof a){let b=a.trim();if(!b)return;if(b.startsWith("{")&&b.endsWith("}")||b.startsWith("[")&&b.endsWith("]"))try{return JSON.parse(b)}catch{}return b}if(Array.isArray(a))return a.map(a=>cm(a)).filter(a=>void 0!==a);if(ce(a)){let b={};for(let[c,d]of Object.entries(a)){let a=cm(d);void 0!==a&&(b[c]=a)}return b}return a}function cn(a){return"string"==typeof a&&a.trim().length>0?a.trim():null}function co(a){return(0,S._E)({version:1,channels:a.channels.map(a=>({...a,workspaces:a.workspaces.map(a=>({...a,agentIds:[...a.agentIds],groupAssignments:a.groupAssignments.map(a=>({...a}))}))}))})}async function cp(a){await cc((0,S._E)(a))}async function cq(a,b={},c){var d;let e,f=await (0,n.rh)(c,"routing.read-bindings",()=>(0,k.rw)().getConfig("bindings").then(a=>a??[])),g=a.channels.filter(a=>cD(a.type)&&"internal"!==a.type),h=new Set(b.removedAccountIds??[]),i=new Set(b.removedGroupIds??[]),j=new Map;for(let a of g){let b=j.get(a.type)??new Set;b.add(a.id),j.set(a.type,b)}let l=g.filter(a=>"telegram"===a.type),m=g.filter(a=>"discord"===a.type),o=(d=[...f.filter(a=>{if(!ce(a))return!0;let b=ce(a.match)?a.match:null;if(!b||"string"!=typeof b.channel)return!0;let c=j.get(b.channel);return!(c&&"string"==typeof b.accountId&&(c.has(b.accountId)||h.has(b.accountId))||"telegram"===b.channel&&ce(b.peer)&&"string"==typeof b.peer.id&&i.has(b.peer.id))}),...g.filter(a=>!!a.primaryAgentId).map(a=>({agentId:a.primaryAgentId,match:{channel:a.type,accountId:a.id}})),...l.flatMap(a=>a.workspaces.flatMap(b=>b.groupAssignments.filter(a=>!1!==a.enabled&&a.agentId).flatMap(b=>{let c=b.agentId;return[{agentId:c,match:{channel:"telegram",accountId:a.id}},{agentId:c,match:{channel:"telegram",accountId:a.id,peer:{kind:"group",id:b.chatId}}}]}))),...m.flatMap(a=>a.workspaces.flatMap(b=>b.groupAssignments.filter(a=>!1!==a.enabled&&a.agentId).map(b=>(0,b_.$T)(a.id,b)).filter(a=>!!a)))],e=new Set,d.filter(a=>{let b=JSON.stringify(a);return!e.has(b)&&(e.add(b),!0)}));await (0,n.rh)(c,"routing.write-bindings",()=>(0,k.rw)().setConfig("bindings",o,{strictJson:!0})),await (0,n.rh)(c,"routing.sync-telegram-settings",()=>cr(l,c)),await (0,n.rh)(c,"routing.sync-discord-settings",()=>cv(m,c))}async function cr(a,b){await (0,n.rh)(b,"telegram-settings.enabled",()=>(0,k.rw)().setConfig("channels.telegram.enabled",a.length>0,{strictJson:!0}));let c=await (0,n.rh)(b,"telegram-settings.default-account-resolve",()=>cu(a,b));c?await (0,n.rh)(b,"telegram-settings.default-account",()=>(0,k.rw)().setConfig("channels.telegram.defaultAccount",c,{strictJson:!0})):await (0,n.rh)(b,"telegram-settings.default-account-unset",()=>(0,k.rw)().unsetConfig("channels.telegram.defaultAccount").catch(()=>{}));let d=Object.fromEntries(a.flatMap(a=>a.workspaces.flatMap(a=>a.groupAssignments.filter(a=>!1!==a.enabled).map(a=>[a.chatId,{requireMention:!0}]))));await (0,n.rh)(b,"telegram-settings.groups",()=>(0,k.rw)().setConfig("channels.telegram.groups",d,{strictJson:!0})),c&&await (0,n.rh)(b,"telegram-settings.reconcile-session-stores",()=>ct(a,c,b))}async function cs(a,b,c,d){try{let f=await (0,n.rh)(d,`telegram-settings.read-session-store.${g().basename(a)}`,()=>(0,e.readFile)(a,"utf8")),h=JSON.parse(f);if(!ce(h))return!1;let i=!1;for(let a of Object.values(h)){if(!function(a){if(!ce(a))return!1;if("telegram"===a.channel||"telegram"===a.lastChannel)return!0;let b=ce(a.deliveryContext)?a.deliveryContext:null;if(b?.channel==="telegram")return!0;let c=ce(a.origin)?a.origin:null;return c?.provider==="telegram"}(a))continue;let d=function(a){let b=(0,ae.Nk)("string"==typeof a.lastAccountId?a.lastAccountId:null);if(b)return b;let c=ce(a.deliveryContext)?a.deliveryContext:null,d=(0,ae.Nk)("string"==typeof c?.accountId?c.accountId:null);if(d)return d;let e=ce(a.origin)?a.origin:null;return(0,ae.Nk)("string"==typeof e?.accountId?e.accountId:null)}(a);!(d&&c.has(d))&&(a.lastAccountId!==b&&(a.lastAccountId=b,i=!0),ce(a.deliveryContext)&&a.deliveryContext.accountId!==b&&(a.deliveryContext.accountId=b,i=!0),ce(a.origin)&&a.origin.accountId!==b&&(a.origin.accountId=b,i=!0))}if(!i)return!1;return await (0,n.rh)(d,`telegram-settings.write-session-store.${g().basename(a)}`,()=>B(a,`${JSON.stringify(h,null,2)}
278
- `)),!0}catch{return!1}}async function ct(a,b,c){let d=new Set((await (0,b_.QT)()).filter(a=>"telegram"===a.type).map(a=>a.id));for(let f of(d.add(b),cB([g().join(aC().homedir(),".openclaw","agents"),...a.flatMap(a=>a.workspaces.map(a=>g().join(a.workspacePath,".openclaw","agents")))]))){let a;try{a=await (0,n.rh)(c,`telegram-settings.read-agent-root.${g().basename(f)}`,()=>(0,e.readdir)(f,{withFileTypes:!0}))}catch{continue}for(let h of a){if(!h.isDirectory())continue;let a=g().join(f,h.name,"sessions","sessions.json");try{await (0,e.access)(a)}catch{continue}await cs(a,b,d,c)}}}async function cu(a,b){let c=(await (0,n.rh)(b,"telegram-settings.read-channel-accounts",()=>(0,b_.QT)())).filter(a=>"telegram"===a.type),d=c.filter(a=>"string"==typeof a.metadata?.botId&&a.metadata.botId.trim().length>0),e=new Set(a.map(a=>a.id));for(let b of a){let a=d.find(a=>a.id===b.id)??null;if(a)return a.id}if(1===d.length)return d[0].id;if(d.length>1){let a=c.find(a=>e.has(a.id)&&"string"==typeof a.metadata?.botId&&a.metadata.botId.trim().length>0)??null;return a?a.id:d[0].id}return a.find(a=>!!a.primaryAgentId)?.id??a[0]?.id??null}async function cv(a,b){if(0===a.length)return;let c=await (0,n.rh)(b,"discord-settings.read-guilds",()=>(0,k.rw)().getConfig("channels.discord.guilds").then(a=>a??{})),d={};for(let[a,b]of Object.entries(c??{}))d[a]=ce(b)?{...b}:{};let e=!1;for(let b of a)for(let a of b.workspaces)for(let b of a.groupAssignments.filter(a=>!1!==a.enabled)){let a=(0,b_.S4)(b.chatId);if(!a?.guildId)continue;let c=d[a.guildId]??{},f=Array.isArray(c.roles)?c.roles.filter(a=>"string"==typeof a||"number"==typeof a).map(a=>String(a)).map(a=>a.trim()).filter(Boolean):[],g=ce(c.channels)?{...c.channels}:{};if(void 0===c.requireMention&&(c.requireMention=!0,e=!0),"role"===a.kind)f.includes(a.targetId)||(f.push(a.targetId),e=!0),c.roles=f;else{for(let b of cB([a.targetId,"thread"===a.kind?a.parentId??"":""].filter(Boolean))){let a=ce(g[b])?g[b]:{};!0!==a.allow&&(a.allow=!0,e=!0),void 0===a.requireMention&&(a.requireMention=!0,e=!0),g[b]=a}c.channels=g}d[a.guildId]=c}e&&await (0,n.rh)(b,"discord-settings.write-guilds",()=>(0,k.rw)().setConfig("channels.discord.guilds",d,{strictJson:!0}))}function cw(a){return a?cB([a.primaryAgentId??"",...a.workspaces.flatMap(a=>[...a.agentIds,...a.groupAssignments.filter(a=>!1!==a.enabled&&a.agentId).map(a=>a.agentId)])]):[]}function cx(a){return a?{id:a.id,name:a.name,primaryAgentId:a.primaryAgentId??null,workspaces:a.workspaces.map(a=>({workspaceId:a.workspaceId,workspacePath:a.workspacePath,agentIds:cB([...a.agentIds]).sort(),groupAssignments:a.groupAssignments.map(a=>({chatId:a.chatId,agentId:a.agentId??null,title:a.title??null,enabled:!1!==a.enabled})).sort((a,b)=>{let c=`${a.chatId}:${a.agentId??""}:${a.title??""}:${a.enabled}`,d=`${b.chatId}:${b.agentId??""}:${b.title??""}:${b.enabled}`;return c.localeCompare(d)})})).sort((a,b)=>a.workspaceId.localeCompare(b.workspaceId))}:null}async function cy(a,b={}){let c=cB(a);if(0===c.length)return;let e=b.snapshot??await (0,n.rh)(b.timings,"agent-policy.snapshot",()=>(0,d.GM)({includeHidden:!0})),f=b.channelRegistry?{...e,channelRegistry:b.channelRegistry}:e;for(let a of c)await (0,n.rh)(b.timings,`agent-policy.sync-agent.${a}`,async()=>{let c=f.agents.find(b=>b.id===a);if(!c)return;let d=f.agents.find(a=>a.workspaceId===c.workspaceId&&"setup"===a.policy.preset&&a.id!==c.id)?.id??null,e=await Z({workspacePath:c.workspacePath,agentId:c.id,agentName:c.name,policy:c.policy,setupAgentId:d,snapshot:f,channelRegistry:b.channelRegistry,timings:b.timings});await (0,l.jq)(c.id,c.workspacePath,{name:c.name,model:(0,ae.Nk)(c.modelId),heartbeat:c.heartbeat.enabled&&c.heartbeat.every?{every:c.heartbeat.every}:null,skills:[...(0,l.AB)(c.skills),e],tools:c.tools.includes("fs.workspaceOnly")?{fs:{workspaceOnly:!0}}:null},f,b.timings)})}async function cz(a,b,c){let e=await (0,n.rh)(c,"telegram-coordination.collect-changes",()=>{let c=new Map(a.channels.filter(a=>"telegram"===a.type).map(a=>[a.id,a])),d=new Map(b.channels.filter(a=>"telegram"===a.type).map(a=>[a.id,a]));return cB(cB([...c.keys(),...d.keys()]).flatMap(a=>{let b=c.get(a)??null,e=d.get(a)??null;return JSON.stringify(cx(b))===JSON.stringify(cx(e))?[]:[...cw(b),...cw(e)]}))});if(0===e.length)return;let f=await (0,n.rh)(c,"telegram-coordination.snapshot",()=>(0,d.GM)({includeHidden:!0}));await (0,n.rh)(c,"telegram-coordination.sync-agent-policies",()=>cy(e,{snapshot:f,channelRegistry:b,timings:c}))}async function cA(a,b={},c){let d=co(await (0,n.rh)(c,"channel-registry.read",()=>(0,b_.vg)())),e=co(d);await (0,n.rh)(c,"channel-registry.mutate",()=>a(d)),await (0,n.rh)(c,"channel-registry.save",()=>cp(d)),await (0,n.rh)(c,"channel-registry.update-routing",()=>cq(d,b,c)),b1(),await (0,n.rh)(c,"channel-registry.sync-telegram-coordination",()=>cz(e,d,c))}function cB(a){return Array.from(new Set(a.filter(Boolean)))}function cC(a){return(0,ae.Nk)(a)??""}function cD(a){return"internal"===a||"slack"===a||"telegram"===a||"discord"===a||"googlechat"===a}function cE(a){return a.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}var cF=c(96972);function cG(a){return Array.from(new Set(a.map(a=>cI(a)).filter(a=>!!a)))}function cH(a){return"string"==typeof a?a.trim():""}function cI(a){if("string"!=typeof a)return null;let b=a.trim();return b.length>0?b:null}let cJ=async function(a={}){var b;let c;return b=await (0,d.GM)(a),{...c=(0,cF.fp)(structuredClone(b)),missionPresets:cG(c.missionPresets),channelAccounts:function(a){let b=new Map;for(let c of a){let a=cH(c.id),d=cH(c.type);if(!a||!d)continue;let e={...c,id:a,type:d,name:cH(c.name)||a,enabled:!1!==c.enabled,metadata:c.metadata?{...c.metadata}:void 0,capabilities:cG(c.capabilities??[])},f=`${d}:${a}`,g=b.get(f);if(!g){b.set(f,e);continue}b.set(f,{...g,name:g.name||e.name,enabled:!1!==g.enabled,kind:g.kind??e.kind,capabilities:cG([...g.capabilities??[],...e.capabilities??[]]),metadata:{...e.metadata??{},...g.metadata??{}}})}return Array.from(b.values())}(c.channelAccounts),channelRegistry:function(a){let b=a.channels.map(a=>{var b;let c,d;return c=cH((b=a).id),d=cH(b.type),c&&d?{...b,id:c,type:d,name:cH(b.name)||c,primaryAgentId:cI(b.primaryAgentId),workspaces:b.workspaces.map(a=>({...a,workspaceId:cH(a.workspaceId),workspacePath:cH(a.workspacePath),agentIds:cG(a.agentIds),groupAssignments:a.groupAssignments.map(a=>({...a,chatId:cH(a.chatId),agentId:cI(a.agentId),title:cI(a.title),enabled:!1!==a.enabled})).filter(a=>!!a.chatId)})).filter(a=>!!a.workspaceId&&!!a.workspacePath)}:null}).filter(a=>!!a),c=new Map;for(let a of b){let b=c.get(a.id);if(!b){c.set(a.id,a);continue}let d=new Map;for(let a of b.workspaces)d.set(a.workspaceId,a);for(let b of a.workspaces){let a=d.get(b.workspaceId);if(!a){d.set(b.workspaceId,b);continue}d.set(b.workspaceId,{...a,agentIds:cG([...a.agentIds,...b.agentIds]),groupAssignments:function(a){let b=new Map;for(let c of a)c.chatId&&b.set(c.chatId,c);return Array.from(b.values())}([...a.groupAssignments,...b.groupAssignments])})}c.set(a.id,{...b,name:b.name||a.name,primaryAgentId:b.primaryAgentId||a.primaryAgentId,workspaces:Array.from(d.values())})}return{version:1,channels:Array.from(c.values())}}(c.channelRegistry)}}},37037:(a,b,c)=>{function d(a){let b="clone"===a.sourceMode?{label:"Cloning repository",description:"The repository is being cloned before workspace files are added."}:"existing"===a.sourceMode?{label:"Attaching existing folder",description:"AgentOS is validating the existing directory and preparing it for bootstrap."}:{label:"Preparing workspace folder",description:"A fresh workspace directory is being created inside the configured workspace root."};return{title:"Provisioning workspace",description:"AgentOS is creating the workspace and reporting each real bootstrap step as it finishes.",steps:[{id:"validate",label:"Checking input and target path",description:"Workspace input, agent ids, and the destination directory are being validated."},{id:"source",label:b.label,description:b.description},{id:"scaffold",label:"Scaffolding workspace files",description:"Core docs, local state, starter memory, and shared workspace metadata are being written."},{id:"agents",label:1===a.agentCount?"Creating the first agent":"Creating workspace agents",description:1===a.agentCount?"The primary agent is being provisioned and linked to the workspace.":"Each enabled agent is being provisioned and linked to the workspace."},{id:"kickoff",label:a.kickoffMission?"Running kickoff mission":"Finalizing workspace",description:a.kickoffMission?"The primary agent is inspecting the new workspace and refining the initial setup.":"Workspace bootstrap is wrapping up without a kickoff mission."}]}}function e(a){return{title:"Deploying workspace",description:"The planner is turning the blueprint into a live workspace and streaming each deploy stage.",steps:[{id:"plan",label:"Locking deploy plan",description:"Deploy blockers are being checked and the planner state is being locked for launch."},...d({sourceMode:a.sourceMode,agentCount:a.agentCount,kickoffMission:a.kickoffMission}).steps,{id:"blueprint",label:"Writing planner files",description:"Planner blueprint, company notes, and workflow docs are being written into the workspace."},{id:"channels",label:a.hasChannels?"Provisioning channels":"Checking channels",description:a.hasChannels?"Enabled external channels are being provisioned and connected.":"No external channels are enabled, so this stage will pass quickly."},{id:"automations",label:a.hasAutomations?"Provisioning automations":"Checking automation loops",description:a.hasAutomations?"Enabled recurring loops are being attached to their target agents.":"No recurring automations are enabled, so this stage is mostly validation."},{id:"planner-kickoff",label:a.hasPlannerKickoffs?"Running planner kickoff missions":"Finalizing deploy",description:a.hasPlannerKickoffs?"The first missions are being dispatched so the new workspace starts with clear momentum.":"The workspace is being finalized and the deploy request is wrapping up."}]}}function f({template:a,onProgress:b}){let c={title:a.title,description:a.description,percent:0,steps:a.steps.map(a=>({...a,status:"pending",percent:0,activities:[]}))},d=0,e=a=>{let b=c.steps.find(b=>b.id===a);if(!b)throw Error(`Unknown operation progress step: ${a}`);return b},i=async()=>{c.percent=g(c.steps),await b?.(structuredClone(c))},j=(a,b)=>{let c=e(a);"string"==typeof b.label&&(c.label=b.label),"string"==typeof b.description&&(c.description=b.description),"string"==typeof b.detail&&(c.detail=b.detail),"number"==typeof b.percent&&(c.percent=h(b.percent)),b.status&&(c.status=b.status)};return{snapshot:()=>(c.percent=g(c.steps),structuredClone(c)),async startStep(a,b){j(a,{status:"active",percent:Math.max(e(a).percent,2),detail:b}),await i()},async updateStep(a,b){j(a,b),await i()},async addActivity(a,b,c="active"){let f=e(a),g={id:`${a}-${d}`,message:b,status:c};d+=1,f.activities.push(g),"pending"===f.status&&"active"===c&&(f.status="active"),await i()},async completeStep(a,b){j(a,{status:"done",percent:100,detail:b}),await i()},async failStep(a,b){j(a,{status:"error",percent:100,detail:b}),await i()},async syncStep(a){let b=e(a.id);b.label=a.label,b.description=a.description,b.status=a.status,b.percent=h(a.percent),b.detail=a.detail,b.activities=structuredClone(a.activities),await i()}}}function g(a){return 0===a.length?0:Math.round(a.reduce((a,b)=>a+h(b.percent),0)/a.length)}function h(a){return Number.isFinite(a)?Math.min(100,Math.max(0,Math.round(a))):0}c.d(b,{Bb:()=>e,X6:()=>f,fV:()=>d})},55828:(a,b,c)=>{c.d(b,{Bt:()=>g,d9:()=>i,h6:()=>e,iN:()=>f,l9:()=>h,tP:()=>j});var d=c(96972);function e(a){return a.diagnostics.installed&&a.diagnostics.rpcOk}function f(a){var b;return a.diagnostics.installed&&a.diagnostics.rpcOk&&(b=a).diagnostics.runtime.stateWritable&&b.diagnostics.runtime.sessionStoreWritable}function g(a){var b;return f(a)&&e(b=a)&&(b.diagnostics.modelReadiness.ready||!!n(b))&&"passed"===a.diagnostics.runtime.smokeTest.status}function h(a,b){let c=k(a);if(c)return`${c} Mission dispatch is blocked until OpenClaw system readiness is healthy.`;let d=l(a,b);return d?`${d} Mission dispatch is blocked until a usable model is ready.`:null}function i(a,b){let c=k(a);if(c)return`${c} Workspace creation is blocked before any files are written.`;let d=l(a,b);return d?`${d} Choose a model before creating the first workspace.`:null}function j(a,b){let c=k(a);if(c)return`${c} Agent creation is blocked until OpenClaw is ready.`;let d=l(a,b);return d?`${d} Choose a ready model before creating the agent.`:null}function k(a){let b=a.diagnostics;if(!b.installed)return"OpenClaw CLI is not installed or not on PATH. Install OpenClaw, then run agentos doctor and agentos start --open.";if(!b.rpcOk){let a=b.transport,c=m(a?.recovery),d=m(a?.lastNativeError),e=c||d?` ${c||d}`:"";return a?.gatewayMode==="cli-forced"?`OpenClaw Gateway native transport is disabled by CLI-forced mode.${e||" Unset CLI-forced Gateway mode and restart AgentOS."}`:a?.gatewayMode==="unreachable"?`OpenClaw Gateway is unreachable.${e||" Start or restart the Gateway, then retry."}`:a?.gatewayMode==="fallback-active"||a?.gatewayMode==="degraded"?`OpenClaw Gateway is not fully ready (${a.statusLabel}).${e||" Inspect Gateway diagnostics, repair auth/device access, and retry."}`:b.loaded?"OpenClaw Gateway service is registered, but RPC is not ready. Restart the Gateway and inspect diagnostics if it stays offline.":"OpenClaw Gateway is not running. Start or repair the local Gateway before using write actions."}if(!b.runtime.stateWritable||!b.runtime.sessionStoreWritable){let a=b.runtime.issues.map(d.bS).find(Boolean);return a?`OpenClaw runtime state is not writable. ${a}`:`OpenClaw runtime state is not writable at ${b.runtime.stateRoot}. Check permissions and retry.`}return null}function l(a,b){let c=a.diagnostics.modelReadiness,e=o(b);if(e){var f,g;let b,d=p(a,e);return d?q(d)?null:`OpenClaw model setup is incomplete. Requested model ${e} is not ready.`:c.ready&&(f=a,g=e,[o((b=f.diagnostics.modelReadiness).resolvedDefaultModel),o(b.defaultModel),o(b.recommendedModelId),...f.agents.map(a=>o(a.modelId))].includes(g))?null:`OpenClaw model setup is incomplete. Requested model ${e} is not ready.`}if(c.ready||n(a))return null;let h=c.issues.map(d.bS).find(Boolean);return h?`OpenClaw model setup is incomplete. ${h}`:0===c.totalModelCount?"OpenClaw model setup is incomplete. No models are configured yet.":0===c.availableModelCount?"OpenClaw model setup is incomplete. Models are configured, but none are currently available.":c.defaultModel&&!c.defaultModelReady?`OpenClaw model setup is incomplete. Default model ${c.defaultModel} is not ready.`:"OpenClaw model setup is incomplete. Configure a usable default model in Add Models."}function m(a){return("string"==typeof a?(0,d.bS)(a).trim():"")||null}function n(a){return a.agents.map(a=>o(a.modelId)).find(b=>{let c;return b&&!!(c=p(a,b))&&q(c)})}function o(a){let b=a?.trim();return b&&"unassigned"!==b?b:null}function p(a,b){return a.models.find(a=>a.id===b)}function q(a){return!0!==a.missing&&!1!==a.available}},97450:(a,b,c)=>{c.d(b,{sE:()=>p,dz:()=>k,l:()=>m,VZ:()=>o,BI:()=>n,g7:()=>l});var d=c(38610);function e(a){let b=a?.trim()??"";return!!b&&(/scope upgrade pending approval/i.test(b)||/pairing_pending/i.test(b)||/device token scope mismatch/i.test(b)||/connected_no_operator_scope/i.test(b)||/more scopes than currently approved/i.test(b)||/\bmissing scope:\s*operator\.(?:read|write|admin)\b/i.test(b)||/\bmissing operator\.(?:read|write|admin) scope\b/i.test(b))}function f(a){let b=a?.trim()??"";return!!b&&(/\bgateway\b[\s\S]*\btoken mismatch\b/i.test(b)||/\btoken mismatch\b[\s\S]*\bgateway\b/i.test(b)||/\bprovide gateway auth token\b/i.test(b))}var g=c(1718),h=c(24117),i=c(96972);class j extends Error{constructor(a,b){super(a),this.name="GatewayAuthSetupRecoveryError",this.originalError=b}}function k(a){return a instanceof j}async function l(a,b){try{return{value:await a(),repaired:null}}catch(f){let e=t(y(f))??await (b.resolveGatewayAuthIssue?.(f)??v(f));if(!e)throw f;await b.onStatus?.(q(e.kind,b.operationLabel));try{await (b.repairGatewayAuth??w)(e.kind)}catch(a){throw new j(s(e.kind,b.operationLabel,a),a)}await b.onStatus?.(r(e.kind,b.operationLabel));try{return{value:await a(),repaired:e}}catch(f){var c,d;let a;throw new j((c=e.kind,d=b.operationLabel,a=x(c,f),"gateway-token"===c?`Gateway token was repaired, but OpenClaw still rejected ${d}. Restart the OpenClaw Gateway, run agentos doctor, then retry ${d}. ${a}`:`Gateway device access was repaired, but OpenClaw still rejected ${d}. Run agentos doctor, then retry ${d}. ${a}`),f)}}}async function m(a,b){let c=n(a)??await u();if(!c)return null;await b.onStatus?.(q(c.kind,b.operationLabel));try{await (b.repairGatewayAuth??w)(c.kind)}catch(a){throw new j(s(c.kind,b.operationLabel,a),a)}return await b.onStatus?.(r(c.kind,b.operationLabel)),c}function n(a){let b=a.diagnostics,c=b.transport,e=(0,d.aH)(c),f=(0,d.wi)(b.gatewayFallbackDiagnostics??[],c),g=e?b.gatewayFallbackReasons??[]:[],h=e?b.capabilityMatrix?.fallbackDiagnostics??[]:[],i=e?b.capabilityMatrix?.fallbackReasons??[]:[];for(let a of[...e?[c?.lastNativeError,c?.recovery]:[],...b.issues,...g,...f.flatMap(a=>[a.issue,a.recovery]),...b.capabilityMatrix?.diagnostics??[],...i,...h.flatMap(a=>[a.issue,a.recovery])]){let b=t(a);if(b)return b}return null}function o(a){let b=Array.isArray(a?.rpc?.auth?.scopes)?a.rpc.auth.scopes.filter(a=>"string"==typeof a):[];for(let c of[a?.lastError,a?.rpc?.error,a?.rpc?.capability,a?.rpc?.auth?.capability,b.join(" ")]){let a=t("string"==typeof c?c:null);if(a)return a}return a?.rpc?.ok===!0&&a.rpc.auth?.role==="operator"&&b.length>0&&!h.Tv.every(a=>b.includes(a))?{kind:"device-access",detail:"Gateway device access needs operator scope."}:null}function p(a,b){return"gateway-token"===a.kind?`AgentOS cannot continue ${b} because its local Gateway token no longer matches OpenClaw. AgentOS will rotate the token and restart the Gateway automatically; if this repeats, run agentos doctor and retry setup.`:`AgentOS cannot continue ${b} because the local device is missing OpenClaw operator access. Repair device access in Gateway settings, then retry setup.`}function q(a,b){return"gateway-token"===a?`Gateway auth changed during setup. Repairing the local Gateway token before ${b}...`:`Gateway device access needs operator scope. Repairing local device access before ${b}...`}function r(a,b){return"gateway-token"===a?`Gateway token repaired. Retrying ${b}...`:`Gateway device access repaired. Retrying ${b}...`}function s(a,b,c){let d=x(a,c);return"gateway-token"===a?`AgentOS could not repair the local Gateway token before ${b}. Open Gateway settings, run Repair token, then retry ${b}. ${d}`:`AgentOS could not repair local device access before ${b}. Open Gateway settings, run Repair access, then retry ${b}. ${d}`}function t(a){return f(a)?{kind:"gateway-token",detail:"Gateway token mismatch."}:e(a)?{kind:"device-access",detail:"Gateway device access needs operator scope."}:null}async function u(){let a=await (0,g.W6)().catch(()=>null);return a?t([a.native.issue,a.recommendation].filter(Boolean).join("\n")):null}async function v(a){let b;return(b=y(a),/Gateway-native operation failed|Timed out|timeout|unreachable|failed to connect|connection closed|gateway starting|retry shortly/i.test(b))?u():null}async function w(a){if("gateway-token"===a){let a=await (0,g.MQ)();if(!a.verified)throw Error(a.verificationIssue||a.restartIssue||"Gateway token was rotated, but the new token did not verify after restarting OpenClaw.");return a}return(0,g.f5)()}function x(a,b){let c=y(b);return"gateway-token"===a||f(c)?"Gateway reported a token mismatch.":"device-access"===a||e(c)?"Gateway reported missing operator device access.":(0,i.n3)(b,"Gateway auth repair failed.")}function y(a){return a instanceof Error?a.message:String(a||"")}}};
275
+ `),await (0,s.u)(y),bp(),bh(),{workspaceId:z?bA(A?.workspaces??[],y,a.path):a.id,previousWorkspaceId:a.id,workspacePath:y}}function bz(a,b){return a.find(a=>a.id===b)??a.find(a=>(0,ag.xV)(a.path,b))}function bA(a,b,c){let d=c?g().resolve(c):null,e=[...a.map(a=>a.path).filter(a=>!d||g().resolve(a)!==d),b];return(0,ag.hv)(b,e)}async function bB(a){let b=Array.from(new Map((await (0,d.GM)({force:!0,includeHidden:!0})).agents.filter(b=>b.workspaceId===a.currentWorkspace.id||!!a.previousWorkspaceId&&b.workspaceId===a.previousWorkspaceId||!!(a.previousWorkspacePath&&b.workspacePath===a.previousWorkspacePath)).map(a=>[a.id,a])).values()),c=new Set;for(let d of a.desiredAgents){let e=bv(b,a.workspaceSlug,d.id);if(!d.enabled){e&&(c.add(e.id),await an({agentId:e.id}));continue}if(e){c.add(e.id),await am({id:e.id,workspaceId:a.currentWorkspace.id,workspacePath:a.currentWorkspace.path,name:(0,ae.Nk)(d.name)??e.name,emoji:(0,ae.Nk)(d.emoji)??e.identity.emoji,theme:(0,ae.Nk)(d.theme)??e.identity.theme,modelId:(0,ae.Nk)(d.modelId)??("unassigned"===e.modelId?void 0:e.modelId),policy:d.policy,heartbeat:d.heartbeat,channelIds:d.channelIds});continue}let f=await aj({id:X(a.workspaceSlug,d.id),workspaceId:a.currentWorkspace.id,workspacePath:a.currentWorkspace.path,name:(0,ae.Nk)(d.name)??void 0,emoji:(0,ae.Nk)(d.emoji)??void 0,theme:(0,ae.Nk)(d.theme)??void 0,modelId:(0,ae.Nk)(d.modelId)??void 0,policy:d.policy,heartbeat:d.heartbeat,channelIds:d.channelIds});c.add(f.agentId)}for(let a of b)c.has(a.id)||await an({agentId:a.id})}function bC(a,b){let c=a.models.find(a=>a.id===b);return!!c&&!0!==c.missing&&!1!==c.available}async function bD(a,b){if(a!==b)try{throw await (0,e.access)(a),Error("Target workspace directory already exists.")}catch(a){if("ENOENT"===("object"==typeof a&&a&&"code"in a?a.code:void 0))return;if(a instanceof Error)throw a;throw Error("Unable to verify target workspace directory.")}}function bE(a,b,c){let d=(0,ae.Nk)(c);if(d)return g().isAbsolute(d)?d:g().join(g().dirname(a),d);let e=(0,ae.Nk)(b);if(!e)return a;let f=bx(e);if(!f)throw Error("Workspace name is required.");return g().join(g().dirname(a),f)}async function bF(a,b,c){let d=await (0,S.OL)(a),e=d.agents.filter(a=>a.enabled);if(!(d.name||d.template||d.sourceMode||d.agentTemplate||e.length>0||d.channels.length>0||d.contextSources.length>0))return null;let f=bA(b.workspaces,a),h=bz(b.workspaces,f)??b.workspaces.find(b=>g().resolve(b.path)===g().resolve(a))??null,i=h?.id??f,j=b.agents.filter(b=>b.workspaceId===i||g().resolve(b.workspacePath)===g().resolve(a)),k=new Set(j.map(a=>a.id)),l=e.map(a=>bG(c,a)),m=[];for(let b of l){if(k.has(b.agentId))continue;let d=await Y({workspacePath:a,workspaceSlug:c,workspaceModelId:b.agent.modelId,agent:b.agent});m.push(d),k.add(d)}let n=bw(l.map(a=>a.agentId)),o=bw([...j.map(a=>a.id),...m,...n]);if(0===o.length)return null;let p=d.agents.find(a=>a.enabled&&a.isPrimary)??null,q=p?bG(c,p):null,r=j[0]?.id??q?.agentId??o[0];return{workspaceId:h?.id??i,workspacePath:h?.path??a,agentIds:o,primaryAgentId:r,kickoffRunId:void 0,kickoffStatus:void 0,kickoffError:void 0}}function bG(a,b){let c=`${a}-`,d=(b.id.startsWith(c)?b.id.slice(c.length):b.id)||b.id;return{agentId:b.id.startsWith(c)?b.id:X(a,b.id),agent:{id:d,name:b.name??d,role:b.role??"Agent",enabled:b.enabled,emoji:b.emoji??void 0,theme:b.theme??void 0,skillId:b.skillId??void 0,skillIds:b.skillIds,modelId:b.modelId??void 0,isPrimary:b.isPrimary,policy:b.policy??void 0,channelIds:b.channelIds}}}async function bH(a){let b=await (0,d.GM)({includeHidden:!0});for(let c of bw(b.agents.filter(b=>b.workspacePath===a).map(a=>a.id))){let a=b.agents.find(a=>a.id===c);if(!a)continue;let d=b.agents.find(b=>b.workspaceId===a.workspaceId&&"setup"===b.policy.preset&&b.id!==a.id)?.id??null,e=await Z({workspacePath:a.workspacePath,agentId:a.id,agentName:a.name,policy:a.policy,setupAgentId:d,snapshot:b});await (0,l.jq)(a.id,a.workspacePath,{name:a.name,model:(0,ae.Nk)(a.modelId),heartbeat:a.heartbeat.enabled&&a.heartbeat.every?{every:a.heartbeat.every}:null,skills:[...(0,l.AB)(a.skills),e],tools:a.tools.includes("fs.workspaceOnly")?{fs:{workspaceOnly:!0}}:null},b)}}async function bI(a,b={}){var c,d,e;let f,g,h=(c=a.template,d=a.brief,e=a.rules,f=(0,r.hh)(c),g=(0,q.Q4)(c,e).sections.map(a=>{let b=a.resources.map(a=>a.label).join(", ");return a.enabled?`${a.title}: ${b||"none"}`:`${a.title}: disabled by workspace rules`}).join("\n"),[`You are bootstrapping a newly created ${f.label.toLowerCase()} workspace.`,d?`Project brief: ${d}`:"No detailed project brief was provided yet.","Inspect the current files and improve the starter workspace without rewriting files that already had meaningful content.","Treat the following workspace context manifest as the source of truth:",g,"If those docs exist, refine the brief, architecture, memory, and deliverables guidance based on the real repository state instead of guessing.","Leave the workspace with a concise first task batch and any critical unknowns clearly called out.","Prefer concrete workspace-grounded edits over verbose chat output."].join("\n\n")),i="fast"===a.modelProfile?"low":"quality"===a.modelProfile?"high":"medium",j=new Set;await b.onProgress?.({message:"Submitting the kickoff brief to the primary agent.",percent:18});let l=await (0,k.rw)().streamAgentTurn({agentId:a.agentId,message:h,thinking:i,timeoutSeconds:90},{onStdout:async a=>{let c,d=(c=a.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,"").trim())?Array.from(new Set(c.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).map(a=>a.replace(/^[>•*-]\s*/,"")).filter(a=>!a.startsWith("{")&&!a.startsWith("[")).filter(a=>!/auth-profiles/i.test(a)))).slice(0,3):[];if(0===d.length&&a.trim())return void await b.onProgress?.({message:"Primary agent responded. Finalizing kickoff output.",percent:82});for(let a of d)await b.onProgress?.({message:a,percent:72})},onStderr:async a=>{let c=a.trim();if(!c)return;let d=function(a){let b,c=a.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,"").split(/\r?\n/).map(a=>a.trim()).filter(Boolean).join(" ");if(!c)return null;let d=c.toLowerCase();return d.includes("scope upgrade pending approval")||d.includes("pairing required")||d.includes("more scopes than currently approved")?"Gateway permissions need approval; continuing with the embedded runtime.":d.includes("falling back to embedded")?"Gateway agent is unavailable; continuing with the embedded runtime.":d.includes("gateway connect failed")?"Gateway connection is not ready; continuing with the embedded runtime.":`Runtime notice: ${(b=c.replace(/\(requestId:\s*[^)]+\)/gi,"").replace(/\brequestId:\s*\S+/gi,"").replace(/\s+/g," ").trim()).length>160?`${b.slice(0,157).trim()}...`:b}`}(c);!d||j.has(d)||(j.add(d),await b.onProgress?.({message:d,percent:64}))}},{timeoutMs:12e4});return await b.onProgress?.({message:"Kickoff mission completed. Recording the resulting run metadata.",percent:100}),l}function bJ(a){return a.split(g().sep).join("/")}async function bK(a,b){var c;let d,f,h,i=(c=b,f=[(d=new Date).getFullYear(),String(d.getMonth()+1).padStart(2,"0"),String(d.getDate()).padStart(2,"0"),String(d.getHours()).padStart(2,"0"),String(d.getMinutes()).padStart(2,"0"),String(d.getSeconds()).padStart(2,"0")].join("-"),h=c.replace(/^\[[^\]]+\]\s*/i,"").trim().normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48).replace(/^-+|-+$/g,"")||"task",`${f}-${h}`),j=g().join(a,"deliverables",i),k=bJ(g().join("deliverables",i)),l=bJ("memory");return await (0,e.mkdir)(j,{recursive:!0}),await (0,e.mkdir)(g().join(a,"memory"),{recursive:!0}),{runFolder:i,absoluteOutputDir:j,relativeOutputDir:k,notesDirRelative:l}}var bL=c(25303),bM=c(3334);async function bN(a,b){var c,d;let e,f,g=a.mission.trim();if(!g)throw Error("Mission text is required.");let i=await b.getMissionControlSnapshot({includeHidden:!0}),j=a.agentId||b.resolveAgentForMission(i,a.workspaceId);if(!j)throw Error("No OpenClaw agent is available for mission dispatch. Finish OpenClaw setup, create a workspace, then create or select an agent.");let l=i.agents.find(a=>a.id===j),m=i.workspaces.find(b=>b.id===(a.workspaceId||l?.workspaceId))??(l?{id:l.workspaceId,path:l.workspacePath}:null),n=m?i.agents.filter(a=>a.workspaceId===m.id):[],o=n.find(a=>"setup"===a.policy.preset&&a.id!==l?.id)?.id??null,p=m?await bK(m.path,g):null,q=a.thinking??"medium",r=(0,bM.Z)(j,i),s=p?(c=l?.policy,d=l?{id:l.id,name:l.name}:null,e=c??(0,h.g0)(h.iN),[g,...(f=d?["Agent workspace context:",`- Your current OpenClaw agent id is \`${d.id}\`${d.name?` and your AgentOS display name is ${d.name}`:""}.`,"- Use the matching subsection in workspace root `AGENTS.md` as your agent-specific role/persona.","- Treat other `AGENTS.md` agent subsections as teammates in the same workspace.","- Use root `SOUL.md`, `USER.md`, `TOOLS.md`, `MEMORY.md`, `memory/*.md`, and `docs/*.md` as shared workspace/project context."]:[]).length>0?["",...f]:[],"","Task output routing:",`- Put substantial outputs, drafts, reports, docs, and file deliverables under \`${p.relativeOutputDir}/\`.`,`- If a file is requested, default to \`${p.relativeOutputDir}/<descriptive-file-name>\` unless the user explicitly asks for another path.`,`- Use \`${p.notesDirRelative}/\` only for temporary notes or durable workspace memory, not final deliverables.`,"- Avoid writing final artifacts to the workspace root.","- Only update shared workspace docs when the change is durable and workspace-wide; task-specific docs should stay inside this run folder.","","Agent operating policy:",...L(e,o),...r?["",r]:[]].join("\n")):g,t=(0,ah.l9)(i,l?.modelId==="unassigned"?null:l?.modelId),u=(0,a4._z)({agentId:j,mission:g,routedMission:s,thinking:q,workspaceId:m?.id??null,workspacePath:m?.path??null,outputDir:p?.absoluteOutputDir??null,outputDirRelative:p?.relativeOutputDir??null,notesDirRelative:p?.notesDirRelative??null});if(await (0,a4.lm)(u),t)return u={...u,status:"stalled",updatedAt:new Date().toISOString(),error:t},await (0,a4.lm)(u),b.invalidateMissionControlCaches(),{dispatchId:u.id,runId:null,agentId:j,status:u.status,summary:t,payloads:[],meta:{outputDir:p?.absoluteOutputDir,outputDirRelative:p?.relativeOutputDir,notesDirRelative:p?.notesDirRelative}};try{let a=await (0,bL.N3)().catch(()=>null);if(a?.nativeMissionDispatch!=="unsupported"){let a=await (0,k.rw)().runAgentTurn({agentId:j,sessionId:u.sessionId??void 0,message:s,thinking:q,timeoutSeconds:45,workspace:m?.path??null,dispatchId:u.id},{timeoutMs:6e4}),b=new Date().toISOString();u={...u,status:"completed"===a.status?"completed":"stalled"===a.status?"stalled":"running",updatedAt:b,runner:{...u.runner,startedAt:b,finishedAt:"completed"===a.status||"stalled"===a.status?b:null,lastHeartbeatAt:b},observation:{runtimeId:a.runId?`runtime:gateway:${a.runId}`:u.observation.runtimeId,observedAt:b},result:a,error:"stalled"===a.status?a.summary??"OpenClaw Gateway dispatch stalled.":null},await (0,a4.lm)(u)}else u=await (0,a4.gb)(u)}catch(a){throw u={...u,status:"stalled",updatedAt:new Date().toISOString(),error:(0,aG.t)(a)||"Mission dispatch runner could not be started."},await (0,a4.lm)(u),b.invalidateMissionControlCaches(),Error(u.error??"Mission dispatch runner could not be started.")}return b.invalidateMissionControlCaches(),{dispatchId:u.id,runId:u.result?.runId??null,agentId:j,status:u.status,summary:"Mission accepted and queued for OpenClaw execution.",payloads:[],meta:{outputDir:p?.absoluteOutputDir,outputDirRelative:p?.relativeOutputDir,notesDirRelative:p?.notesDirRelative}}}async function bO(a,b,c,d){let e=(await d.getMissionControlSnapshot({includeHidden:!0})).tasks.find(b=>b.id===a),f=e?await (0,a4.ji)(e):c?await (0,a4.O1)(c):null;if(!e&&!f)throw Error("Task was not found in the current OpenClaw snapshot.");if(!f)return bQ(e,a,b,d);if((0,a4.VW)(f.status))return{taskId:a,dispatchId:f.id,status:f.status,summary:(0,aR.kc)(f),reason:f.error,runnerPid:f.runner.pid,childPid:f.runner.childPid,abortedAt:f.runner.finishedAt??f.updatedAt};let g=new Date().toISOString(),h=(0,a4.GG)(b),i={...f,status:"cancelled",updatedAt:g,error:h,runner:{...f.runner,finishedAt:g,lastHeartbeatAt:g}};await (0,a4.lm)(i),d.invalidateMissionControlCaches();let j=null,l=f.result?.runId??null,m=(0,k.rw)();for(let a of bP(e,f))await m.cancelTask({taskId:a,reason:h},{timeoutMs:15e3}).catch(()=>null);return(l||f.sessionId)&&await m.abortAgentTurn({runId:l,sessionId:f.sessionId,agentId:f.agentId,reason:h},{timeoutMs:15e3}).catch(()=>null),j=await (0,a4.e4)(i),{taskId:a,dispatchId:i.id,status:i.status,summary:h,reason:h,runnerPid:i.runner.pid,childPid:j??i.runner.childPid,abortedAt:g}}function bP(a,b){let c=[bR(b?.result),bR(b?.result?.task),bR(a?.metadata),a?.metadata.gatewayObjectKind==="task"?a.metadata.taskId:null,a?.metadata.gatewayObjectKind==="task"?a?.key:null],d=new Set;for(let a of c)"string"==typeof a&&a.trim()&&a!==b?.id&&d.add(a.trim());return[...d]}async function bQ(a,b,c,d){if(!a)throw Error("Task was not found in the current OpenClaw snapshot.");if("completed"===a.status||"stalled"===a.status||"cancelled"===a.status)return{taskId:b,dispatchId:null,status:a.status,summary:a.subtitle||"Task is already terminal.",reason:null,runnerPid:null,childPid:null,abortedAt:new Date().toISOString()};let e=(0,a4.GG)(c),f=bP(a,null);if(0===f.length)throw Error("Mission dispatch record was not found and the task does not expose a Gateway task id.");for(let a of f)await (0,k.rw)().cancelTask({taskId:a,reason:e},{timeoutMs:15e3});return d.invalidateMissionControlCaches(),{taskId:b,dispatchId:null,status:"cancelled",summary:e,reason:e,runnerPid:null,childPid:null,abortedAt:new Date().toISOString()}}function bR(a){if(!a||"object"!=typeof a||Array.isArray(a))return null;let b=a.gatewayTaskId??a.openClawTaskId??a.taskId??a.id;return"string"==typeof b&&b.trim()?b.trim():null}function bS(a,b){if(!b)return a.agents.find(a=>a.isDefault)?.id||a.agents[0]?.id;let c=a.agents.filter(a=>a.workspaceId===b);return c.find(a=>a.isDefault)?.id||c.find(a=>"engaged"===a.status)?.id||c[0]?.id}async function bT(a){return bN(a,{getMissionControlSnapshot:d.GM,resolveAgentForMission:bS,invalidateMissionControlCaches:d.er})}async function bU(a,b,c){return bO(a,b,c,{getMissionControlSnapshot:d.GM,resolveAgentForMission:bS,invalidateMissionControlCaches:d.er})}async function bV(a,b,c={}){var e,f,g,h;let i,j,l,m,n,o=b.message.trim();if(!o)throw Error("Control message is required.");let p=c.getTaskDetail??bm,q=await p(a,{dispatchId:b.dispatchId??null}),r=(i=(e=q).task,j=e.runs.find(a=>bX(a.status))??e.runs[0]??null,l=j?.agentId?.trim()||i.primaryAgentId?.trim()||bY(i.agentIds)||null,m=j?.sessionId?.trim()||bY(i.sessionIds)||bZ(i.metadata,"sessionId")||bZ(i.metadata,"gatewaySessionId")||bZ(i.metadata,"openClawSessionId")||null,n=(bZ(i.metadata,"sessionKey")||bZ(i.metadata,"gatewaySessionKey")||(j?.key.trim().startsWith("agent:")?j.key.trim():null))??(f=l,(g=m)?g.startsWith("agent:")?g:f?`agent:${f}:explicit:${g}`:null:null),{agentId:l,sessionId:m,sessionKey:n,runId:j?.runId?.trim()||bY(i.runIds)||null}),s=c.adapter??(0,k.rw)();if("continue"===b.action){let a=await bW(q,r,o,s,c);return(c.invalidateMissionControlSnapshotCache??d.ZZ)(),{ok:!0,action:b.action,taskId:q.task.id,target:r,result:a}}if(!(bX((h=q).task.status)||h.task.liveRunCount>0||h.runs.some(a=>bX(a.status))))throw Error("Task is not currently running.");if(!r.sessionKey&&!r.sessionId)throw Error("Task does not expose an active OpenClaw session.");let t="steer"===b.action?await s.steerSession({key:r.sessionKey,sessionId:r.sessionKey?null:r.sessionId,message:o},{timeoutMs:1e4}):await s.injectChat({sessionKey:r.sessionKey,sessionId:r.sessionKey?null:r.sessionId,message:o},{timeoutMs:1e4});return(c.invalidateMissionControlSnapshotCache??d.ZZ)(),{ok:!0,action:b.action,taskId:q.task.id,target:r,result:t}}async function bW(a,b,c,e,f){var g,h;let i,j;if(!b.agentId)throw Error("Task does not expose an OpenClaw agent.");if(!e.runAgentTurn)throw Error("Task continuation requires OpenClaw mission dispatch support.");let k=await (f.getMissionControlSnapshot??d.GM)({includeHidden:!0}).catch(()=>null),l=a.task.dispatchId??null,m=b.sessionId??b.sessionKey??void 0;return await e.runAgentTurn({agentId:b.agentId,sessionId:m??void 0,message:c,thinking:"medium",timeoutSeconds:45,workspace:(g=a,h=k,i=g.task,j=i.workspaceId?.trim(),h&&j?h.workspaces.find(a=>a.id===j)?.path??h.agents.find(a=>a.id===i.primaryAgentId)?.workspacePath??null:null),dispatchId:l,idempotencyKey:l?`${l}:continue:${Date.now()}`:void 0},{timeoutMs:6e4})}function bX(a){return"running"===a||"queued"===a}function bY(a){return a.find(a=>a.trim().length>0)?.trim()??null}function bZ(a,b){let c=a[b];return"string"==typeof c&&c.trim().length>0?c.trim():null}var b$=c(1718),b_=c(99254),b0=c(74497),b1=c(70262),b2=c(96972);function b3(){(0,d.ZZ)()}async function b4(a,b){let c=cN(a.channelId);if(!c)throw Error("Channel id is required.");return await (0,n.rh)(b,"workspace-channel.registry-upsert",()=>cL(b=>{let d=b.channels.find(a=>a.id===c)??{id:c,type:a.type,name:a.name.trim()||c,primaryAgentId:(0,ae.Nk)(a.primaryAgentId)??null,workspaces:[]},e=a.workspaceId.trim(),f=a.workspacePath.trim(),g=d.workspaces.find(a=>a.workspaceId===e)??{workspaceId:e,workspacePath:f,agentIds:[],groupAssignments:[]},h=cM([...g.agentIds,...(a.agentIds??[]).map(a=>a.trim()).filter(Boolean)]),i=(0,S.qc)([...g.groupAssignments,...(a.groupAssignments??[]).filter(a=>!!a.chatId)]),j={...g,workspacePath:f,agentIds:h,groupAssignments:i},k=d.workspaces.filter(a=>a.workspaceId!==e);k.push(j);let l=(0,ae.Nk)(a.primaryAgentId)??d.primaryAgentId;b.channels=[...b.channels.filter(a=>a.id!==c),{...d,id:c,type:a.type,name:a.name.trim()||d.name||c,primaryAgentId:l||j.agentIds[0]||j.groupAssignments.find(a=>a.agentId)?.agentId||null,workspaces:k}]},{},b)),b3(),(0,b_.VW)()}async function b5(a,b){let c=cN(a.channelId);if(!c)throw Error("Channel id is required.");return await (0,n.rh)(b,"channel-registry.disconnect",()=>cL(b=>{b.channels=b.channels.map(b=>{if(b.id!==c)return b;let d=b.workspaces.filter(b=>b.workspaceId!==a.workspaceId),e=cM([...d.flatMap(a=>a.agentIds),...d.flatMap(a=>a.groupAssignments.filter(a=>!1!==a.enabled&&a.agentId).map(a=>a.agentId))]);return{...b,primaryAgentId:b.primaryAgentId&&e.includes(b.primaryAgentId)?b.primaryAgentId:e[0]??null,workspaces:d}}).filter(a=>a.workspaces.length>0||a.primaryAgentId)},{},b)),b3(),(0,b_.VW)()}async function b6(a,b){let c=cN(a.channelId);if(!c)throw Error("Channel id is required.");let d=(await (0,n.rh)(b,"channel-registry.read-before-delete",()=>(0,b_.vg)())).channels.find(a=>a.id===c);if(!d)throw Error("Channel was not found.");let e=cM(d.workspaces.flatMap(a=>a.groupAssignments.filter(a=>!!a.chatId).map(a=>a.chatId))),f=cM(d.workspaces.map(a=>a.workspacePath));return cO(d.type)&&"internal"!==d.type&&await (0,n.rh)(b,"channel.delete-openclaw-remove",()=>(0,k.rw)().removeChannelAccount({channel:d.type,account:c,delete:!0},{timeoutMs:6e4})),await (0,n.rh)(b,"channel.delete-registry-sync",()=>cL(a=>{a.channels=a.channels.filter(a=>a.id!==c)},{removedAccountIds:[c],removedGroupIds:e},b)),await (0,n.rh)(b,"channel.delete-project-cleanup",()=>Promise.all(f.map(a=>cg(a,c,b)))),b3(),(0,n.rh)(b,"channel.delete-read-final-registry",()=>(0,b_.VW)())}async function b7(a,b){var c;let d,e,f,h=a.scope??"workspace",i=!0===a.dryRun,j=(0,ae.Nk)(a.workspaceId)??null;if("workspace"===h&&!j)throw Error("Workspace id is required.");let l=await (0,n.rh)(b,"surface-reconcile.registry-read",()=>(0,b_.vg)());if("workspace"===h&&!l.channels.some(a=>a.workspaces.some(a=>a.workspaceId===j)))throw Error("Workspace binding was not found for any surface.");let m=await (0,n.rh)(b,"surface-reconcile.bindings-read",()=>(0,k.rw)().getConfig("bindings").then(a=>Array.isArray(a)?a:[])),o=(0,b1.xC)({registry:l,currentBindings:m,scope:h,workspaceId:j}),p=l.channels.filter(a=>cO(a.type)&&"internal"!==a.type),q="all"===h?await (0,n.rh)(b,"surface-reconcile.telegram-settings-plan",()=>cB(p.filter(a=>"telegram"===a.type),b)):{patch:null,defaultAccountId:null},r=ck({bindings:o},q.patch),s=r?cn(r).map(a=>a.path):[],t=(d=new Date().toISOString().replace(/[:.]/g,"-"),e=Math.random().toString(36).slice(2,8),`surface-reconcile-${d}-${e}`),u=g().join(be.BY,"surface-reconcile",`${t}.json`),v=(f=Array.from(new Set((c={auditId:t,createdAt:new Date().toISOString(),configPaths:s}).configPaths)).sort(),{auditId:c.auditId,createdAt:c.createdAt,configPaths:f,instructions:f.length>0?f.map(a=>`Review audit ${c.auditId}, verify the previous ${a} value, then restore only that OpenClaw config path if rollback is required.`):[`Review audit ${c.auditId}; no OpenClaw config path changes were planned.`]}),w=i?void 0:await (0,n.rh)(b,"surface-reconcile.config-write",()=>cm(r,b));if("all"===h&&!i){let a=p.filter(a=>"telegram"===a.type);await (0,n.rh)(b,"surface-reconcile.telegram-settings-side-effects",()=>cC(a,q.defaultAccountId,b)),await (0,n.rh)(b,"surface-reconcile.discord-settings",()=>cG(p.filter(a=>"discord"===a.type),b))}let x=await (0,n.rh)(b,"surface-reconcile.accounts-read",()=>(0,b_.QT)()),y=(0,b1.U$)(x,l),z=(0,b1.LB)({registry:l,currentBindings:o,surfaceRuntime:y,configuredAccounts:x,workspaceId:"workspace"===h?j:null}),A=(0,b1.Pe)({scope:h,workspaceId:"workspace"===h?j:null,registry:l,previousBindings:m,nextBindings:o,configMutations:w,dryRun:i,applied:!i,auditId:t,auditPath:u,restorePlan:v,drift:z});return await cl({auditPath:u,repair:A,previousBindings:m,nextBindings:o,reconcilePatch:r,plannedConfigPaths:s},b),i||b3(),A}async function b8(a,b){let c=cN(a.channelId);if(!c)throw Error("Channel id is required.");return await (0,n.rh)(b,"channel.primary-update",()=>cL(b=>{let d=b.channels.find(a=>a.id===c);if(!d)throw Error("Channel was not found.");d.primaryAgentId=(0,ae.Nk)(a.primaryAgentId)??null},{},b)),b3(),(0,b_.VW)()}async function b9(a,b){let c=cN(a.channelId);if(!c)throw Error("Channel id is required.");let d=[];return await (0,n.rh)(b,"channel.groups-update",()=>cL(b=>{let e=b.channels.find(a=>a.id===c);if(!e)throw Error("Channel was not found.");let f=e.workspaces.find(b=>b.workspaceId===a.workspaceId);if(!f)throw Error("Workspace binding was not found for this channel.");let g=new Set(f.groupAssignments.filter(a=>!1!==a.enabled&&!!a.chatId).map(a=>a.chatId));f.groupAssignments=(0,S.qc)(a.groupAssignments.map(a=>({chatId:a.chatId.trim(),agentId:(0,ae.Nk)(a.agentId)??null,title:(0,ae.Nk)(a.title)??null,enabled:!1!==a.enabled}))),f.agentIds=cM([...f.agentIds,...f.groupAssignments.filter(a=>!1!==a.enabled&&a.agentId).map(a=>a.agentId)]);let h=new Set(f.groupAssignments.filter(a=>!1!==a.enabled&&!!a.chatId).map(a=>a.chatId));for(let a of g)h.has(a)||d.push(a)},{removedGroupIds:d},b)),b3(),(0,b_.VW)()}async function ca(a,b){let c=cN(a.channelId),d=cP(a.agentId.trim());if(!c||!d)throw Error("Channel id and agent id are required.");return await (0,n.rh)(b,"channel.bind-agent",()=>cL(b=>{let e=b.channels.find(a=>a.id===c);if(!e)throw Error("Channel was not found.");let f=e.workspaces.find(b=>b.workspaceId===a.workspaceId)??{workspaceId:a.workspaceId,workspacePath:a.workspacePath,agentIds:[],groupAssignments:[]};f.agentIds=cM([...f.agentIds,d]),f.workspacePath=a.workspacePath,e.workspaces=[...e.workspaces.filter(b=>b.workspaceId!==a.workspaceId),f],e.primaryAgentId||(e.primaryAgentId=d)},{},b)),b3(),(0,b_.VW)()}async function cb(a,b){let c=cN(a.channelId),d=cP(a.agentId.trim());if(!c||!d)throw Error("Channel id and agent id are required.");return await (0,n.rh)(b,"channel.unbind-agent",()=>cL(b=>{let e=b.channels.find(a=>a.id===c);if(!e)throw Error("Channel was not found.");let f=e.workspaces.find(b=>b.workspaceId===a.workspaceId);if(f){if(f.agentIds=f.agentIds.filter(a=>a!==d),f.groupAssignments=f.groupAssignments.filter(a=>a.agentId!==d),e.primaryAgentId===d){let a=f.agentIds[0]??f.groupAssignments.find(a=>!1!==a.enabled&&a.agentId)?.agentId??e.workspaces.flatMap(a=>a.agentIds).find(a=>a!==d)??e.workspaces.flatMap(a=>a.groupAssignments).find(a=>!1!==a.enabled&&a.agentId&&a.agentId!==d)?.agentId??null;e.primaryAgentId=a}e.workspaces=[...e.workspaces.filter(b=>b.workspaceId!==a.workspaceId),{...f,agentIds:f.agentIds,groupAssignments:f.groupAssignments}]}},{},b)),b3(),(0,b_.VW)()}async function cc(a,b){if("telegram"===a.provider){if(!a.token?.trim())throw Error("Telegram bot token is required.");return ce({name:a.name,token:a.token,accountId:a.accountId},b)}let c=(0,ae.Nk)(a.accountId)??await cp(a.provider,a.name,b),d=new Set((await (0,n.rh)(b,`managed-chat.${a.provider}.read-before`,()=>(0,b_.QT)())).filter(b=>b.type===a.provider).map(a=>a.id)),e=(()=>{switch(a.provider){case"discord":if(!a.token?.trim())throw Error("Discord bot token is required.");return{channel:"discord",account:c,token:a.token,name:a.name};case"slack":if(!a.botToken?.trim())throw Error("Slack bot token is required.");return{channel:"slack",account:c,botToken:a.botToken,name:a.name};case"googlechat":if(!a.webhookUrl?.trim())throw Error("Google Chat webhook URL is required.");return{channel:"googlechat",account:c,webhookUrl:a.webhookUrl,name:a.name};default:throw Error(`OpenClaw provisioning is not implemented for ${a.provider}.`)}})();await (0,n.rh)(b,`managed-chat.${a.provider}.provision-openclaw`,()=>(0,k.rw)().provisionChannelAccount(e,{timeoutMs:6e4}));let f=(await (0,n.rh)(b,`managed-chat.${a.provider}.read-after`,()=>(0,b_.QT)())).filter(b=>b.type===a.provider);return f.find(a=>a.id===c)??f.find(b=>!d.has(b.id)&&b.name===a.name)??f.find(a=>!d.has(a.id))??null??{id:c,type:a.provider,kind:(0,b0.Yx)(a.provider),name:a.name.trim()||c,enabled:!0}}async function cd(a,b){var c;if("telegram"===(c=a.provider)||"discord"===c||"slack"===c||"googlechat"===c)return cc({provider:a.provider,name:a.name,accountId:a.accountId,token:a.token,botToken:a.botToken,webhookUrl:a.webhookUrl},b);let d=function(a){let b={};if(!ch(a))return b;for(let[c,d]of Object.entries(a))cv(b,c,cw(d));return b}(a.config),e=a.name.trim(),f=function(a,b){switch(a){case"gmail":return cx(b.account)??cx(b.email)??cx(b.address);case"email":return cx(b.address)??cx(b.email);case"webhook":case"cron":return cx(b.accountId)??cx(b.name);default:return null}}(a.provider,d),g=(0,ae.Nk)(a.accountId)??f??await cp(a.provider,a.name,b),h=function(a){switch(a){case"gmail":return"hooks.gmail";case"email":return"email";case"webhook":return"hooks";case"cron":return"cron";default:throw Error(`OpenClaw provisioning is not implemented for ${a}.`)}}(a.provider);switch(a.provider){case"gmail":{let a=(0,ae.Nk)(d.account??d.email??d.address);if(!a)throw Error("Gmail account email is required.");await (0,n.rh)(b,"managed-surface.gmail.setup-openclaw",()=>(0,k.rw)().setupGmailWebhook({account:a,config:d},{timeoutMs:6e4}));let c=await (0,n.rh)(b,"managed-surface.gmail.read-config",()=>(0,k.rw)().getConfig(h,{timeoutMs:6e4})),f=await (0,n.rh)(b,"managed-surface.gmail.read-hooks",()=>(0,k.rw)().getConfig("hooks",{timeoutMs:6e4})),i=f?.presets,j=cu(f,{enabled:!0,presets:cM([...Array.isArray(i)?i.filter(a=>"string"==typeof a):[],"gmail"])});await (0,n.rh)(b,"managed-surface.gmail.write-hooks",()=>(0,k.rw)().setConfig("hooks",j,{strictJson:!0,timeoutMs:6e4}));let l=cu(c,{enabled:!0,name:e||a,label:e||a,accountId:g,account:a,email:a,address:a,...d});await (0,n.rh)(b,"managed-surface.gmail.write-config",()=>(0,k.rw)().setConfig(h,l,{strictJson:!0,timeoutMs:6e4}));break}case"webhook":{let a=await (0,n.rh)(b,"managed-surface.webhook.read-config",()=>(0,k.rw)().getConfig(h,{timeoutMs:6e4})),c=cx(d.token);if(!c)throw Error("Webhook token is required.");let f=cu(a,{enabled:!0,name:e||g,label:e||g,accountId:g,token:c,...d});await (0,n.rh)(b,"managed-surface.webhook.write-config",()=>(0,k.rw)().setConfig(h,f,{strictJson:!0,timeoutMs:6e4}));break}case"cron":{let a=await (0,n.rh)(b,"managed-surface.cron.read-config",()=>(0,k.rw)().getConfig(h,{timeoutMs:6e4})),c=cx(d.webhookToken);if(!c)throw Error("Cron webhook token is required.");let f=cu(a,{enabled:!0,name:e||g,label:e||g,accountId:g,webhookToken:c,...d});await (0,n.rh)(b,"managed-surface.cron.write-config",()=>(0,k.rw)().setConfig(h,f,{strictJson:!0,timeoutMs:6e4}));break}case"email":{let a=await (0,n.rh)(b,"managed-surface.email.read-config",()=>(0,k.rw)().getConfig(h,{timeoutMs:6e4})),c=cx(d.address??d.email);if(!c)throw Error("Email address is required.");let f=cu(a,{enabled:!0,name:e||c,label:e||c,accountId:g,address:c,email:c,...d});await (0,n.rh)(b,"managed-surface.email.write-config",()=>(0,k.rw)().setConfig(h,f,{strictJson:!0,timeoutMs:6e4}));break}default:throw Error(`OpenClaw provisioning is not implemented for ${a.provider}.`)}let i=(await (0,n.rh)(b,`managed-surface.${a.provider}.read-after`,()=>(0,b_.QT)())).filter(b=>b.type===a.provider);return i.find(a=>a.id===g)??i.find(b=>b.name.trim().toLowerCase()===a.name.trim().toLowerCase())??i[0]??null??{id:g,type:a.provider,kind:(0,b0.Yx)(a.provider),name:e||g,enabled:!0}}async function ce(a,b){let c=(0,ae.Nk)(a.accountId)??await cq(a.name,b),d=new Set((await (0,n.rh)(b,"telegram.read-before",()=>(0,b_.QT)())).filter(a=>"telegram"===a.type).map(a=>a.id));await (0,n.rh)(b,"telegram.openclaw-add",()=>(0,k.rw)().provisionChannelAccount({channel:"telegram",account:c,token:a.token,name:a.name},{timeoutMs:6e4}));let e={id:c,type:"telegram",name:a.name.trim()||c,enabled:!0},f=(await (0,n.rh)(b,"telegram.read-after",()=>(0,b_.QT)())).filter(a=>"telegram"===a.type).find(a=>a.id===c);if(f)return{...f,name:a.name.trim()||f.name};let g=Date.now()+8e3,h=null,i=0;for(;Date.now()<g;){i+=1;let e=(await (0,n.rh)(b,`telegram.resolve.${i}.read-channel-accounts`,()=>(0,b_.QT)())).filter(a=>"telegram"===a.type);if(h=e.find(a=>a.id===c)??e.find(b=>!d.has(b.id)&&b.name===a.name)??e.find(a=>!d.has(a.id))??e.find(b=>b.name===a.name)??null)break;let f=await (0,n.rh)(b,`telegram.resolve.${i}.read-pairing-accounts`,()=>cr());if(h=f.find(b=>!d.has(b.id)&&b.name===a.name)??f.find(a=>!d.has(a.id))??f.find(b=>b.name===a.name)??null)break;await (0,n.rh)(b,`telegram.resolve.${i}.sleep`,()=>new Promise(a=>setTimeout(a,750)))}if(!h){let c=await (0,n.rh)(b,"telegram.resolve.token-lookup",async()=>ct(a.token,(await (0,n.rh)(b,"telegram.resolve.token-lookup.read-channel-accounts",()=>(0,b_.QT)())).filter(a=>"telegram"===a.type),b));h=c||e}return{...h,name:a.name.trim()||h.name}}async function cf(a){await B(be.q6,`${JSON.stringify(a,null,2)}
276
+ `)}async function cg(a,b,c){let d=g().join(a,".openclaw","project.json"),f={};try{let b=await (0,n.rh)(c,`workspace-project.${g().basename(a)}.read`,()=>(0,e.readFile)(d,"utf8")),h=JSON.parse(b);f=ch(h)?h:{}}catch{return}if(!Array.isArray(f.agents))return;let h=!1,i=f.agents.map(a=>{if(!ch(a)||"string"!=typeof a.id)return a;let c=Array.isArray(a.channelIds)?a.channelIds.filter(a=>"string"==typeof a):[],d=c.filter(a=>a!==b);return d.length===c.length?a:(h=!0,{...a,channelIds:d})});h&&(f.updatedAt=new Date().toISOString(),f.agents=i,await (0,n.rh)(c,`workspace-project.${g().basename(a)}.write`,()=>B(d,`${JSON.stringify(f,null,2)}
277
+ `)))}function ch(a){return"object"==typeof a&&null!==a}function ci(a){return null==a||ch(a)&&!Array.isArray(a)&&0===Object.keys(a).length}function cj(a,b){return JSON.stringify(co(a??null))===JSON.stringify(co(b??null))}function ck(...a){let b=null;for(let c of a)c&&0!==Object.keys(c).length&&(b=function a(b,c){let d={...b};for(let[b,e]of Object.entries(c)){let c=d[b];ch(c)&&!Array.isArray(c)&&ch(e)&&!Array.isArray(e)?d[b]=a(c,e):d[b]=e}return d}(b??{},c));return b}async function cl(a,b){let c=(0,b2.fp)({id:a.repair.auditId,createdAt:a.repair.checkedAt,kind:"surface-reconcile",dryRun:a.repair.dryRun,applied:a.repair.applied,scope:a.repair.scope,workspaceId:a.repair.workspaceId,changed:a.repair.changed,previousBindingCount:a.repair.previousBindingCount,nextBindingCount:a.repair.nextBindingCount,addedBindingCount:a.repair.addedBindingCount,removedBindingCount:a.repair.removedBindingCount,plannedConfigPaths:a.plannedConfigPaths,configMutations:a.repair.configMutations??[],restorePlan:a.repair.restorePlan,previousBindings:a.previousBindings,nextBindings:a.nextBindings,reconcilePatch:a.reconcilePatch,drift:a.repair.drift});await (0,n.rh)(b,"surface-reconcile.audit-write",()=>B(a.auditPath,`${JSON.stringify(c,null,2)}
278
+ `))}async function cm(a,b){let c=(0,k.rw)(),d=[];for(let e of cn(a)){let a=await (0,n.rh)(b,`surface-repair.set-config.${e.path}`,()=>c.setConfig(e.path,e.value,{strictJson:!0,timeoutMs:6e4}));d.push(function(a,b){var c;let d=function(a){try{let b=JSON.parse(a.stdout||"{}");return ch(b)?b:null}catch{return null}}(b),e=ch(d?.configMutation)?d.configMutation:null,f=ch(d?.metadata)&&ch(d.metadata.openClawConfig)?d.metadata.openClawConfig:null,g=e??f;if(!g)return{path:a,appliedVia:"cli"};let h="config.patch"===(c=g.appliedVia)||"config.apply"===c||"config.set"===c?c:"cli";return{path:"string"==typeof g.path&&g.path.trim()?g.path:a,appliedVia:h,..."string"==typeof g.baseHash&&g.baseHash.trim()?{baseHash:g.baseHash}:{},..."string"==typeof g.reloadKind&&g.reloadKind.trim()?{reloadKind:g.reloadKind}:{},..."boolean"==typeof g.restartRequired?{restartRequired:g.restartRequired}:{},..."boolean"==typeof g.hotReloaded?{hotReloaded:g.hotReloaded}:{}}}(e.path,a))}return d}function cn(a){let b=[];for(let[c,d]of Object.entries(a)){if("bindings"===c){b.push({path:"bindings",value:d});continue}if("channels"===c&&ch(d)){let a=ch(d.telegram)?d.telegram:null;if(!a)throw Error("Surface repair only supports managed channels.telegram config paths.");for(let[c,d]of Object.entries(a)){if(!["enabled","defaultAccount","groups"].includes(c))throw Error(`Surface repair does not support channels.telegram.${c} config writes.`);b.push({path:`channels.telegram.${c}`,value:d})}continue}throw Error(`Surface repair does not support ${c} config writes.`)}return b}function co(a){return Array.isArray(a)?a.map(co):!ch(a)||Array.isArray(a)?a:Object.fromEntries(Object.entries(a).sort(([a],[b])=>a.localeCompare(b)).map(([a,b])=>[a,co(b)]))}async function cp(a,b,c){let d=cP(b.trim())||a,e=`${a}-${d}`,f=await (0,n.rh)(c,`managed-surface.${a}.read-channel-registry`,()=>(0,b_.vg)()),g=await (0,n.rh)(c,`managed-surface.${a}.read-channel-accounts`,()=>(0,b_.QT)()),h=new Set([...f.channels.filter(b=>b.type===a).map(a=>a.id),...g.filter(b=>b.type===a).map(a=>a.id)]);if(!h.has(e))return e;let i=2;for(;h.has(`${e}-${i}`);)i+=1;return`${e}-${i}`}async function cq(a,b){return cp("telegram",a,b)}async function cr(){try{let a=await (0,e.readFile)(g().join(be.wh,"credentials","telegram-pairing.json"),"utf8"),b=JSON.parse(a),c=Array.isArray(b?.requests)?b.requests:[],d=new Map;for(let a of c){let b=(0,ae.Nk)(a.meta?.accountId);b&&d.set(b,{id:b,type:"telegram",name:(0,ae.Nk)(a.meta?.username)??(0,ae.Nk)(a.meta?.firstName)??b,enabled:!0})}return Array.from(d.values())}catch{return[]}}async function cs(a){try{let b=g().join(be.wh,"telegram"),c=await (0,n.rh)(a,"telegram.resolve.read-bot-id-files",()=>(0,e.readdir)(b)),d=await Promise.all(c.filter(a=>a.startsWith("update-offset-")&&a.endsWith(".json")).map(async c=>{try{let d=await (0,n.rh)(a,`telegram.resolve.read-bot-id-file.${c}`,()=>(0,e.readFile)(g().join(b,c),"utf8")),f=JSON.parse(d),h=(0,ae.Nk)(f?.botId),i=c.slice(14,-5);if(!h||!i)return null;return[i,h]}catch{return null}}));return new Map(d.filter(a=>!!a))}catch{return new Map}}async function ct(a,b,c){let d=(0,ae.Nk)(a.split(":",1)[0]);if(!d)return null;let e=await (0,n.rh)(c,"telegram.resolve.read-bot-ids",()=>cs(c));return b.find(a=>e.get(a.id)===d)??null}function cu(a,b){var c;let d=ch(c=a)?JSON.parse(JSON.stringify(c)):{};for(let[a,c]of Object.entries(b))cv(d,a,cw(c));return d}function cv(a,b,c){if(void 0===c)return;let d=b.split(".").map(a=>a.trim()).filter(Boolean);if(0===d.length)return;let e=a;for(let a=0;a<d.length-1;a+=1){let b=d[a];ch(e[b])||(e[b]={}),e=e[b]}e[d[d.length-1]]=c}function cw(a){if("string"==typeof a){let b=a.trim();if(!b)return;if(b.startsWith("{")&&b.endsWith("}")||b.startsWith("[")&&b.endsWith("]"))try{return JSON.parse(b)}catch{}return b}if(Array.isArray(a))return a.map(a=>cw(a)).filter(a=>void 0!==a);if(ch(a)){let b={};for(let[c,d]of Object.entries(a)){let a=cw(d);void 0!==a&&(b[c]=a)}return b}return a}function cx(a){return"string"==typeof a&&a.trim().length>0?a.trim():null}function cy(a){return(0,S._E)({version:1,channels:a.channels.map(a=>({...a,workspaces:a.workspaces.map(a=>({...a,agentIds:[...a.agentIds],groupAssignments:a.groupAssignments.map(a=>({...a}))}))}))})}async function cz(a){await cf((0,S._E)(a))}async function cA(a,b={},c){let d=await (0,n.rh)(c,"routing.read-bindings",()=>(0,k.rw)().getConfig("bindings").then(a=>a??[])),e=a.channels.filter(a=>cO(a.type)&&"internal"!==a.type),f=new Set(b.removedAccountIds??[]),g=new Set(b.removedGroupIds??[]),h=e.filter(a=>"telegram"===a.type),i=e.filter(a=>"discord"===a.type),j=(0,b1.xC)({registry:a,currentBindings:d,scope:"all"}).filter(a=>{if(!ch(a))return!0;let b=ch(a.match)?a.match:null;return!b||"string"!=typeof b.channel||!("string"==typeof b.accountId&&f.has(b.accountId)||"telegram"===b.channel&&ch(b.peer)&&"string"==typeof b.peer.id&&g.has(b.peer.id))}),l=await (0,n.rh)(c,"routing.plan-telegram-settings",()=>cB(h,c)),m=ck(cj(d,j)?null:{bindings:j},l.patch);m&&await (0,n.rh)(c,"routing.write-openclaw-config",()=>cm(m,c)),await (0,n.rh)(c,"routing.reconcile-telegram-session-stores",()=>cC(h,l.defaultAccountId,c)),await (0,n.rh)(c,"routing.sync-discord-settings",()=>cG(i,c))}async function cB(a,b){let c=a.length>0,d=await (0,n.rh)(b,"telegram-settings.read-enabled",()=>(0,k.rw)().getConfig("channels.telegram.enabled")),e={},f=await (0,n.rh)(b,"telegram-settings.default-account-resolve",()=>cF(a,b)),g=await (0,n.rh)(b,"telegram-settings.read-default-account",()=>(0,k.rw)().getConfig("channels.telegram.defaultAccount"));d!==c&&(e.enabled=c),f&&g!==f?e.defaultAccount=f:f||null===g||(e.defaultAccount=null);let h=Object.fromEntries(a.flatMap(a=>a.workspaces.flatMap(a=>a.groupAssignments.filter(a=>!1!==a.enabled).map(a=>[a.chatId,{requireMention:!0}])))),i=await (0,n.rh)(b,"telegram-settings.read-groups",()=>(0,k.rw)().getConfig("channels.telegram.groups"));return ci(h)&&ci(i)||cj(i??{},h)||(e.groups=h),{patch:Object.keys(e).length>0?{channels:{telegram:e}}:null,defaultAccountId:f}}async function cC(a,b,c){b&&await (0,n.rh)(c,"telegram-settings.reconcile-session-stores",()=>cE(a,b,c))}async function cD(a,b,c,d){try{let f=await (0,n.rh)(d,`telegram-settings.read-session-store.${g().basename(a)}`,()=>(0,e.readFile)(a,"utf8")),h=JSON.parse(f);if(!ch(h))return!1;let i=!1;for(let a of Object.values(h)){if(!function(a){if(!ch(a))return!1;if("telegram"===a.channel||"telegram"===a.lastChannel)return!0;let b=ch(a.deliveryContext)?a.deliveryContext:null;if(b?.channel==="telegram")return!0;let c=ch(a.origin)?a.origin:null;return c?.provider==="telegram"}(a))continue;let d=function(a){let b=(0,ae.Nk)("string"==typeof a.lastAccountId?a.lastAccountId:null);if(b)return b;let c=ch(a.deliveryContext)?a.deliveryContext:null,d=(0,ae.Nk)("string"==typeof c?.accountId?c.accountId:null);if(d)return d;let e=ch(a.origin)?a.origin:null;return(0,ae.Nk)("string"==typeof e?.accountId?e.accountId:null)}(a);!(d&&c.has(d))&&(a.lastAccountId!==b&&(a.lastAccountId=b,i=!0),ch(a.deliveryContext)&&a.deliveryContext.accountId!==b&&(a.deliveryContext.accountId=b,i=!0),ch(a.origin)&&a.origin.accountId!==b&&(a.origin.accountId=b,i=!0))}if(!i)return!1;return await (0,n.rh)(d,`telegram-settings.write-session-store.${g().basename(a)}`,()=>B(a,`${JSON.stringify(h,null,2)}
279
+ `)),!0}catch{return!1}}async function cE(a,b,c){let d=new Set((await (0,b_.QT)()).filter(a=>"telegram"===a.type).map(a=>a.id));for(let f of(d.add(b),cM([g().join(aC().homedir(),".openclaw","agents"),...a.flatMap(a=>a.workspaces.map(a=>g().join(a.workspacePath,".openclaw","agents")))]))){let a;try{a=await (0,n.rh)(c,`telegram-settings.read-agent-root.${g().basename(f)}`,()=>(0,e.readdir)(f,{withFileTypes:!0}))}catch{continue}for(let h of a){if(!h.isDirectory())continue;let a=g().join(f,h.name,"sessions","sessions.json");try{await (0,e.access)(a)}catch{continue}await cD(a,b,d,c)}}}async function cF(a,b){let c=(await (0,n.rh)(b,"telegram-settings.read-channel-accounts",()=>(0,b_.QT)())).filter(a=>"telegram"===a.type),d=c.filter(a=>"string"==typeof a.metadata?.botId&&a.metadata.botId.trim().length>0),e=new Set(a.map(a=>a.id));for(let b of a){let a=d.find(a=>a.id===b.id)??null;if(a)return a.id}if(1===d.length)return d[0].id;if(d.length>1){let a=c.find(a=>e.has(a.id)&&"string"==typeof a.metadata?.botId&&a.metadata.botId.trim().length>0)??null;return a?a.id:d[0].id}return a.find(a=>!!a.primaryAgentId)?.id??a[0]?.id??null}async function cG(a,b){if(0===a.length)return;let c=await (0,n.rh)(b,"discord-settings.read-guilds",()=>(0,k.rw)().getConfig("channels.discord.guilds").then(a=>a??{})),d={};for(let[a,b]of Object.entries(c??{}))d[a]=ch(b)?{...b}:{};let e=!1;for(let b of a)for(let a of b.workspaces)for(let b of a.groupAssignments.filter(a=>!1!==a.enabled)){let a=(0,b_.S4)(b.chatId);if(!a?.guildId)continue;let c=d[a.guildId]??{},f=Array.isArray(c.roles)?c.roles.filter(a=>"string"==typeof a||"number"==typeof a).map(a=>String(a)).map(a=>a.trim()).filter(Boolean):[],g=ch(c.channels)?{...c.channels}:{};if(void 0===c.requireMention&&(c.requireMention=!0,e=!0),"role"===a.kind)f.includes(a.targetId)||(f.push(a.targetId),e=!0),c.roles=f;else{for(let b of cM([a.targetId,"thread"===a.kind?a.parentId??"":""].filter(Boolean))){let a=ch(g[b])?g[b]:{};!0!==a.allow&&(a.allow=!0,e=!0),void 0===a.requireMention&&(a.requireMention=!0,e=!0),g[b]=a}c.channels=g}d[a.guildId]=c}e&&await (0,n.rh)(b,"discord-settings.write-guilds",()=>(0,k.rw)().setConfig("channels.discord.guilds",d,{strictJson:!0}))}function cH(a){return a?cM([a.primaryAgentId??"",...a.workspaces.flatMap(a=>[...a.agentIds,...a.groupAssignments.filter(a=>!1!==a.enabled&&a.agentId).map(a=>a.agentId)])]):[]}function cI(a){return a?{id:a.id,name:a.name,primaryAgentId:a.primaryAgentId??null,workspaces:a.workspaces.map(a=>({workspaceId:a.workspaceId,workspacePath:a.workspacePath,agentIds:cM([...a.agentIds]).sort(),groupAssignments:a.groupAssignments.map(a=>({chatId:a.chatId,agentId:a.agentId??null,title:a.title??null,enabled:!1!==a.enabled})).sort((a,b)=>{let c=`${a.chatId}:${a.agentId??""}:${a.title??""}:${a.enabled}`,d=`${b.chatId}:${b.agentId??""}:${b.title??""}:${b.enabled}`;return c.localeCompare(d)})})).sort((a,b)=>a.workspaceId.localeCompare(b.workspaceId))}:null}async function cJ(a,b={}){let c=cM(a);if(0===c.length)return;let e=b.snapshot??await (0,n.rh)(b.timings,"agent-policy.snapshot",()=>(0,d.GM)({includeHidden:!0})),f=b.channelRegistry?{...e,channelRegistry:b.channelRegistry}:e;for(let a of c)await (0,n.rh)(b.timings,`agent-policy.sync-agent.${a}`,async()=>{let c=f.agents.find(b=>b.id===a);if(!c)return;let d=f.agents.find(a=>a.workspaceId===c.workspaceId&&"setup"===a.policy.preset&&a.id!==c.id)?.id??null,e=await Z({workspacePath:c.workspacePath,agentId:c.id,agentName:c.name,policy:c.policy,setupAgentId:d,snapshot:f,channelRegistry:b.channelRegistry,timings:b.timings});await (0,l.jq)(c.id,c.workspacePath,{name:c.name,model:(0,ae.Nk)(c.modelId),heartbeat:c.heartbeat.enabled&&c.heartbeat.every?{every:c.heartbeat.every}:null,skills:[...(0,l.AB)(c.skills),e],tools:c.tools.includes("fs.workspaceOnly")?{fs:{workspaceOnly:!0}}:null},f,b.timings)})}async function cK(a,b,c){let e=await (0,n.rh)(c,"telegram-coordination.collect-changes",()=>{let c=new Map(a.channels.filter(a=>"telegram"===a.type).map(a=>[a.id,a])),d=new Map(b.channels.filter(a=>"telegram"===a.type).map(a=>[a.id,a]));return cM(cM([...c.keys(),...d.keys()]).flatMap(a=>{let b=c.get(a)??null,e=d.get(a)??null;return JSON.stringify(cI(b))===JSON.stringify(cI(e))?[]:[...cH(b),...cH(e)]}))});if(0===e.length)return;let f=await (0,n.rh)(c,"telegram-coordination.snapshot",()=>(0,d.GM)({includeHidden:!0}));await (0,n.rh)(c,"telegram-coordination.sync-agent-policies",()=>cJ(e,{snapshot:f,channelRegistry:b,timings:c}))}async function cL(a,b={},c){let d=cy(await (0,n.rh)(c,"channel-registry.read",()=>(0,b_.vg)())),e=cy(d);await (0,n.rh)(c,"channel-registry.mutate",()=>a(d)),await (0,n.rh)(c,"channel-registry.save",()=>cz(d)),await (0,n.rh)(c,"channel-registry.update-routing",()=>cA(d,b,c)),b3(),await (0,n.rh)(c,"channel-registry.sync-telegram-coordination",()=>cK(e,d,c))}function cM(a){return Array.from(new Set(a.filter(Boolean)))}function cN(a){return(0,ae.Nk)(a)??""}function cO(a){return"internal"===a||"slack"===a||"telegram"===a||"discord"===a||"googlechat"===a}function cP(a){return a.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function cQ(a){return Array.from(new Set(a.map(a=>cS(a)).filter(a=>!!a)))}function cR(a){return"string"==typeof a?a.trim():""}function cS(a){if("string"!=typeof a)return null;let b=a.trim();return b.length>0?b:null}let cT=async function(a={}){var b;let c;return b=await (0,d.GM)(a),{...c=(0,b2.fp)(structuredClone(b)),missionPresets:cQ(c.missionPresets),channelAccounts:function(a){let b=new Map;for(let c of a){let a=cR(c.id),d=cR(c.type);if(!a||!d)continue;let e={...c,id:a,type:d,name:cR(c.name)||a,enabled:!1!==c.enabled,metadata:c.metadata?{...c.metadata}:void 0,capabilities:cQ(c.capabilities??[])},f=`${d}:${a}`,g=b.get(f);if(!g){b.set(f,e);continue}b.set(f,{...g,name:g.name||e.name,enabled:!1!==g.enabled,kind:g.kind??e.kind,capabilities:cQ([...g.capabilities??[],...e.capabilities??[]]),metadata:{...e.metadata??{},...g.metadata??{}}})}return Array.from(b.values())}(c.channelAccounts),channelRegistry:function(a){let b=a.channels.map(a=>{var b;let c,d;return c=cR((b=a).id),d=cR(b.type),c&&d?{...b,id:c,type:d,name:cR(b.name)||c,primaryAgentId:cS(b.primaryAgentId),workspaces:b.workspaces.map(a=>({...a,workspaceId:cR(a.workspaceId),workspacePath:cR(a.workspacePath),agentIds:cQ(a.agentIds),groupAssignments:a.groupAssignments.map(a=>({...a,chatId:cR(a.chatId),agentId:cS(a.agentId),title:cS(a.title),enabled:!1!==a.enabled})).filter(a=>!!a.chatId)})).filter(a=>!!a.workspaceId&&!!a.workspacePath)}:null}).filter(a=>!!a),c=new Map;for(let a of b){let b=c.get(a.id);if(!b){c.set(a.id,a);continue}let d=new Map;for(let a of b.workspaces)d.set(a.workspaceId,a);for(let b of a.workspaces){let a=d.get(b.workspaceId);if(!a){d.set(b.workspaceId,b);continue}d.set(b.workspaceId,{...a,agentIds:cQ([...a.agentIds,...b.agentIds]),groupAssignments:function(a){let b=new Map;for(let c of a)c.chatId&&b.set(c.chatId,c);return Array.from(b.values())}([...a.groupAssignments,...b.groupAssignments])})}c.set(a.id,{...b,name:b.name||a.name,primaryAgentId:b.primaryAgentId||a.primaryAgentId,workspaces:Array.from(d.values())})}return{version:1,channels:Array.from(c.values())}}(c.channelRegistry)}}},31273:(a,b,c)=>{c.d(b,{BI:()=>m,VZ:()=>n,dz:()=>j,g7:()=>k,l:()=>l,sE:()=>o});var d=c(38610),e=c(12491),f=c(1718),g=c(24117),h=c(96972);class i extends Error{constructor(a,b){super(a),this.name="GatewayAuthSetupRecoveryError",this.originalError=b}}function j(a){return a instanceof i}async function k(a,b){try{return{value:await a(),repaired:null}}catch(f){let e=s(x(f))??await (b.resolveGatewayAuthIssue?.(f)??u(f));if(!e)throw f;await b.onStatus?.(p(e.kind,b.operationLabel));try{await (b.repairGatewayAuth??v)(e.kind)}catch(a){throw new i(r(e.kind,b.operationLabel,a),a)}await b.onStatus?.(q(e.kind,b.operationLabel));try{return{value:await a(),repaired:e}}catch(f){var c,d;let a;throw new i((c=e.kind,d=b.operationLabel,a=w(c,f),"gateway-token"===c?`Gateway token was repaired, but OpenClaw still rejected ${d}. Restart the OpenClaw Gateway, run agentos doctor, then retry ${d}. ${a}`:`Gateway device access was repaired, but OpenClaw still rejected ${d}. Run agentos doctor, then retry ${d}. ${a}`),f)}}}async function l(a,b){let c=m(a)??await t();if(!c)return null;await b.onStatus?.(p(c.kind,b.operationLabel));try{await (b.repairGatewayAuth??v)(c.kind)}catch(a){throw new i(r(c.kind,b.operationLabel,a),a)}return await b.onStatus?.(q(c.kind,b.operationLabel)),c}function m(a){let b=a.diagnostics,c=b.transport,e=(0,d.aH)(c),f=(0,d.wi)(b.gatewayFallbackDiagnostics??[],c),g=e?b.gatewayFallbackReasons??[]:[],h=e?b.capabilityMatrix?.fallbackDiagnostics??[]:[],i=e?b.capabilityMatrix?.fallbackReasons??[]:[];for(let a of[...e?[c?.lastNativeError,c?.recovery]:[],...b.issues,...g,...f.flatMap(a=>[a.issue,a.recovery]),...b.capabilityMatrix?.diagnostics??[],...i,...h.flatMap(a=>[a.issue,a.recovery])]){let b=s(a);if(b)return b}return null}function n(a){let b=Array.isArray(a?.rpc?.auth?.scopes)?a.rpc.auth.scopes.filter(a=>"string"==typeof a):[];for(let c of[a?.lastError,a?.rpc?.error,a?.rpc?.capability,a?.rpc?.auth?.capability,b.join(" ")]){let a=s("string"==typeof c?c:null);if(a)return a}return a?.rpc?.ok===!0&&a.rpc.auth?.role==="operator"&&b.length>0&&!g.Tv.every(a=>b.includes(a))?{kind:"device-access",detail:"Gateway device access needs operator scope."}:null}function o(a,b){return"gateway-token"===a.kind?`AgentOS cannot continue ${b} because its local Gateway token no longer matches OpenClaw. AgentOS will rotate the token and restart the Gateway automatically; if this repeats, run agentos doctor and retry setup.`:`AgentOS cannot continue ${b} because the local device is missing OpenClaw operator access. Repair device access in Gateway settings, then retry setup.`}function p(a,b){return"gateway-token"===a?`Gateway auth changed during setup. Repairing the local Gateway token before ${b}...`:`Gateway device access needs operator scope. Repairing local device access before ${b}...`}function q(a,b){return"gateway-token"===a?`Gateway token repaired. Retrying ${b}...`:`Gateway device access repaired. Retrying ${b}...`}function r(a,b,c){let d=w(a,c);return"gateway-token"===a?`AgentOS could not repair the local Gateway token before ${b}. Open Gateway settings, run Repair token, then retry ${b}. ${d}`:`AgentOS could not repair local device access before ${b}. Open Gateway settings, run Repair access, then retry ${b}. ${d}`}function s(a){return(0,e.yb)(a)?{kind:"gateway-token",detail:"Gateway token mismatch."}:(0,e.D8)(a)?{kind:"device-access",detail:"Gateway device access needs operator scope."}:null}async function t(){let a=await (0,f.W6)().catch(()=>null);return a?s([a.native.issue,a.recommendation].filter(Boolean).join("\n")):null}async function u(a){let b;return(b=x(a),/Gateway-native operation failed|Timed out|timeout|unreachable|failed to connect|connection closed|gateway starting|retry shortly/i.test(b))?t():null}async function v(a){if("gateway-token"===a){let a=await (0,f.MQ)();if(!a.verified)throw Error(a.verificationIssue||a.restartIssue||"Gateway token was rotated, but the new token did not verify after restarting OpenClaw.");return a}return(0,f.f5)()}function w(a,b){let c=x(b);return"gateway-token"===a||(0,e.yb)(c)?"Gateway reported a token mismatch.":"device-access"===a||(0,e.D8)(c)?"Gateway reported missing operator device access.":(0,h.n3)(b,"Gateway auth repair failed.")}function x(a){return a instanceof Error?a.message:String(a||"")}},37037:(a,b,c)=>{function d(a){let b="clone"===a.sourceMode?{label:"Cloning repository",description:"The repository is being cloned before workspace files are added."}:"existing"===a.sourceMode?{label:"Attaching existing folder",description:"AgentOS is validating the existing directory and preparing it for bootstrap."}:{label:"Preparing workspace folder",description:"A fresh workspace directory is being created inside the configured workspace root."};return{title:"Provisioning workspace",description:"AgentOS is creating the workspace and reporting each real bootstrap step as it finishes.",steps:[{id:"validate",label:"Checking input and target path",description:"Workspace input, agent ids, and the destination directory are being validated."},{id:"source",label:b.label,description:b.description},{id:"scaffold",label:"Scaffolding workspace files",description:"Core docs, local state, starter memory, and shared workspace metadata are being written."},{id:"agents",label:1===a.agentCount?"Creating the first agent":"Creating workspace agents",description:1===a.agentCount?"The primary agent is being provisioned and linked to the workspace.":"Each enabled agent is being provisioned and linked to the workspace."},{id:"kickoff",label:a.kickoffMission?"Running kickoff mission":"Finalizing workspace",description:a.kickoffMission?"The primary agent is inspecting the new workspace and refining the initial setup.":"Workspace bootstrap is wrapping up without a kickoff mission."}]}}function e(a){return{title:"Deploying workspace",description:"The planner is turning the blueprint into a live workspace and streaming each deploy stage.",steps:[{id:"plan",label:"Locking deploy plan",description:"Deploy blockers are being checked and the planner state is being locked for launch."},...d({sourceMode:a.sourceMode,agentCount:a.agentCount,kickoffMission:a.kickoffMission}).steps,{id:"blueprint",label:"Writing planner files",description:"Planner blueprint, company notes, and workflow docs are being written into the workspace."},{id:"channels",label:a.hasChannels?"Provisioning channels":"Checking channels",description:a.hasChannels?"Enabled external channels are being provisioned and connected.":"No external channels are enabled, so this stage will pass quickly."},{id:"automations",label:a.hasAutomations?"Provisioning automations":"Checking automation loops",description:a.hasAutomations?"Enabled recurring loops are being attached to their target agents.":"No recurring automations are enabled, so this stage is mostly validation."},{id:"planner-kickoff",label:a.hasPlannerKickoffs?"Running planner kickoff missions":"Finalizing deploy",description:a.hasPlannerKickoffs?"The first missions are being dispatched so the new workspace starts with clear momentum.":"The workspace is being finalized and the deploy request is wrapping up."}]}}function f({template:a,onProgress:b}){let c={title:a.title,description:a.description,percent:0,steps:a.steps.map(a=>({...a,status:"pending",percent:0,activities:[]}))},d=0,e=a=>{let b=c.steps.find(b=>b.id===a);if(!b)throw Error(`Unknown operation progress step: ${a}`);return b},i=async()=>{c.percent=g(c.steps),await b?.(structuredClone(c))},j=(a,b)=>{let c=e(a);"string"==typeof b.label&&(c.label=b.label),"string"==typeof b.description&&(c.description=b.description),"string"==typeof b.detail&&(c.detail=b.detail),"number"==typeof b.percent&&(c.percent=h(b.percent)),b.status&&(c.status=b.status)};return{snapshot:()=>(c.percent=g(c.steps),structuredClone(c)),async startStep(a,b){j(a,{status:"active",percent:Math.max(e(a).percent,2),detail:b}),await i()},async updateStep(a,b){j(a,b),await i()},async addActivity(a,b,c="active"){let f=e(a),g={id:`${a}-${d}`,message:b,status:c};d+=1,f.activities.push(g),"pending"===f.status&&"active"===c&&(f.status="active"),await i()},async completeStep(a,b){j(a,{status:"done",percent:100,detail:b}),await i()},async failStep(a,b){j(a,{status:"error",percent:100,detail:b}),await i()},async syncStep(a){let b=e(a.id);b.label=a.label,b.description=a.description,b.status=a.status,b.percent=h(a.percent),b.detail=a.detail,b.activities=structuredClone(a.activities),await i()}}}function g(a){return 0===a.length?0:Math.round(a.reduce((a,b)=>a+h(b.percent),0)/a.length)}function h(a){return Number.isFinite(a)?Math.min(100,Math.max(0,Math.round(a))):0}c.d(b,{Bb:()=>e,X6:()=>f,fV:()=>d})},55828:(a,b,c)=>{c.d(b,{Bt:()=>g,d9:()=>i,h6:()=>e,iN:()=>f,l9:()=>h,tP:()=>j});var d=c(96972);function e(a){return a.diagnostics.installed&&a.diagnostics.rpcOk}function f(a){var b;return a.diagnostics.installed&&a.diagnostics.rpcOk&&(b=a).diagnostics.runtime.stateWritable&&b.diagnostics.runtime.sessionStoreWritable}function g(a){var b;return f(a)&&e(b=a)&&(b.diagnostics.modelReadiness.ready||!!n(b))&&"passed"===a.diagnostics.runtime.smokeTest.status}function h(a,b){let c=k(a);if(c)return`${c} Mission dispatch is blocked until OpenClaw system readiness is healthy.`;let d=l(a,b);return d?`${d} Mission dispatch is blocked until a usable model is ready.`:null}function i(a,b){let c=k(a);if(c)return`${c} Workspace creation is blocked before any files are written.`;let d=l(a,b);return d?`${d} Choose a model before creating the first workspace.`:null}function j(a,b){let c=k(a);if(c)return`${c} Agent creation is blocked until OpenClaw is ready.`;let d=l(a,b);return d?`${d} Choose a ready model before creating the agent.`:null}function k(a){let b=a.diagnostics;if(!b.installed)return"OpenClaw CLI is not installed or not on PATH. Install OpenClaw, then run agentos doctor and agentos start --open.";if(!b.rpcOk){let a=b.transport,c=m(a?.recovery),d=m(a?.lastNativeError),e=c||d?` ${c||d}`:"";return a?.gatewayMode==="cli-forced"?`OpenClaw Gateway native transport is disabled by CLI-forced mode.${e||" Unset CLI-forced Gateway mode and restart AgentOS."}`:a?.gatewayMode==="unreachable"?`OpenClaw Gateway is unreachable.${e||" Start or restart the Gateway, then retry."}`:a?.gatewayMode==="fallback-active"||a?.gatewayMode==="degraded"?`OpenClaw Gateway is not fully ready (${a.statusLabel}).${e||" Inspect Gateway diagnostics, repair auth/device access, and retry."}`:b.loaded?"OpenClaw Gateway service is registered, but RPC is not ready. Restart the Gateway and inspect diagnostics if it stays offline.":"OpenClaw Gateway is not running. Start or repair the local Gateway before using write actions."}if(!b.runtime.stateWritable||!b.runtime.sessionStoreWritable){let a=b.runtime.issues.map(d.bS).find(Boolean);return a?`OpenClaw runtime state is not writable. ${a}`:`OpenClaw runtime state is not writable at ${b.runtime.stateRoot}. Check permissions and retry.`}return null}function l(a,b){let c=a.diagnostics.modelReadiness,e=o(b);if(e){var f,g;let b,d=p(a,e);return d?q(d)?null:`OpenClaw model setup is incomplete. Requested model ${e} is not ready.`:c.ready&&(f=a,g=e,[o((b=f.diagnostics.modelReadiness).resolvedDefaultModel),o(b.defaultModel),o(b.recommendedModelId),...f.agents.map(a=>o(a.modelId))].includes(g))?null:`OpenClaw model setup is incomplete. Requested model ${e} is not ready.`}if(c.ready||n(a))return null;let h=c.issues.map(d.bS).find(Boolean);return h?`OpenClaw model setup is incomplete. ${h}`:0===c.totalModelCount?"OpenClaw model setup is incomplete. No models are configured yet.":0===c.availableModelCount?"OpenClaw model setup is incomplete. Models are configured, but none are currently available.":c.defaultModel&&!c.defaultModelReady?`OpenClaw model setup is incomplete. Default model ${c.defaultModel} is not ready.`:"OpenClaw model setup is incomplete. Configure a usable default model in Add Models."}function m(a){return("string"==typeof a?(0,d.bS)(a).trim():"")||null}function n(a){return a.agents.map(a=>o(a.modelId)).find(b=>{let c;return b&&!!(c=p(a,b))&&q(c)})}function o(a){let b=a?.trim();return b&&"unassigned"!==b?b:null}function p(a,b){return a.models.find(a=>a.id===b)}function q(a){return!0!==a.missing&&!1!==a.available}}};