@wular/coder 0.4.5 → 0.4.6

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 (190) hide show
  1. package/dist/{add-DTwoL7vJ.js → add-BIp1t_pT.js} +1 -1
  2. package/dist/{add-cdKdz3K0.js → add-CKENklTr.js} +1 -1
  3. package/dist/{add-Bffwutko.js → add-DrbKvzAF.js} +1 -1
  4. package/dist/{add-Bz8uaOcu.js → add-KkLx1WbE.js} +1 -1
  5. package/dist/{add-json-BIcbE3Nf.js → add-json-GHTfZV_U.js} +1 -1
  6. package/dist/{agent-DQK_S1PE.js → agent-CR8UFMa-.js} +1 -1
  7. package/dist/{agent-BcXXkOmD.js → agent-D0pQ_ewc.js} +1 -1
  8. package/dist/{alias-KQ85bphl.js → alias--pfI-nvH.js} +1 -1
  9. package/dist/{app-DaccLHrx.js → app-C7sw1ZkI.js} +1 -1
  10. package/dist/{approvals-CZt_aPCy.js → approvals-9-G-QxOy.js} +1 -1
  11. package/dist/{approve-DxjyXd66.js → approve-CAk8qPqG.js} +1 -1
  12. package/dist/{apps-eueTmHR5.js → apps-CaHoLNE7.js} +1 -1
  13. package/dist/{archive-C3JazQuo.js → archive-Ylxh0HIl.js} +1 -1
  14. package/dist/{archive-C9yrU4Wg.js → archive-fs5RjYHc.js} +1 -1
  15. package/dist/{archive-sweep-CHbOP-p6.js → archive-sweep-BrqWj4kr.js} +1 -1
  16. package/dist/{ask-DdYrvsTk.js → ask-Dmk0HGtI.js} +1 -1
  17. package/dist/{auth-q8CROpG-.js → auth-CS0cH0gq.js} +1 -1
  18. package/dist/auth-cZ0FrkBv.js +1 -0
  19. package/dist/{cli-msOzZFXW.js → cli-IfrPgeYz.js} +1 -1
  20. package/dist/cli.d.ts +1 -1
  21. package/dist/cli.js +1 -1
  22. package/dist/{config-BllYHi8S.js → config-Duf8jCkd.js} +1 -1
  23. package/dist/{create-BYki3g42.js → create-Ik613gJw.js} +1 -1
  24. package/dist/credentials-Dxpb5jCT.js +1 -0
  25. package/dist/dash/standalone/server/manifest.json +822 -822
  26. package/dist/dash/standalone/server/modules-server-server-react-server/src/server/dash/app/dash/agents/(list)/page.8f85fbaff456c5fe.js +2 -2
  27. package/dist/dash/standalone/server/modules-server-server-react-server/src/server/dash/app/dash/agents/[slug]/(tabs)/layout.d3aec63db0f5230d.js +1 -1
  28. package/dist/dash/standalone/server/modules-server-server-react-server/src/server/dash/app/dash/agents/[slug]/(tabs)/page.7fd1bfcf08e25919.js +2 -2
  29. package/dist/dash/standalone/server/modules-server-server-react-server/src/server/dash/app/dash/agents/[slug]/(tabs)/platforms/page.31687af871d75d39.js +1 -1
  30. package/dist/dash/standalone/server/modules-server-server-react-server/src/server/dash/app/dash/agents/[slug]/(tabs)/settings/page.1ed5379637860fab.js +1 -1
  31. package/dist/dash/standalone/server/modules-server-server-react-server/src/server/dash/app/dash/agents/[slug]/edit/page.1798dbd9cd334e8f.js +1 -1
  32. package/dist/dash/standalone/server/modules-server-server-react-server/src/server/dash/app/dash/agents/new/page.44f60b1a32344f70.js +1 -1
  33. package/dist/dash/standalone/server/modules-server-server-react-server/src/server/dash/app/dash/settings/[tab]/credentials.6423846391b20446.js +2 -2
  34. package/dist/dash/standalone/server/modules-server-server-react-server/src/server/dash/app/dash/settings/[tab]/page.04b07f9c365be073.js +4 -4
  35. package/dist/dash/standalone/server/modules-server-server-react-server/src/server/dash/app/dash/tasks/[id]/page.d1ded90712ca586f.js +1 -1
  36. package/dist/dash/standalone/server/modules-server-server-react-server/src/server/dash/app/dash/tasks/list/tasks-list.9698bdff71c3b3c7.js +1 -1
  37. package/dist/dash/standalone/server/modules-server-server-react-server/src/server/dash/app/dash/tasks/list/tasks-section.c77194f05c3f58fb.js +1 -1
  38. package/dist/dash/standalone/static/assets/chunks/{agent-pills-0163fdf910179991.js → agent-pills-65087e563e7f928c.js} +1 -1
  39. package/dist/dash/standalone/static/assets/chunks/{agent-settings-form-b1fcd9a5236b1fc7.js → agent-settings-form-51f5d16c5b35b0c4.js} +1 -1
  40. package/dist/dash/standalone/static/assets/chunks/{agents-grid-1d8f0ec6cf8c797e.js → agents-grid-8d8fb47aa05c1022.js} +1 -1
  41. package/dist/dash/standalone/static/assets/chunks/{badge-9984d2fd0e7f995d.js → badge-b8e1e1429e8418e8.js} +1 -1
  42. package/dist/dash/standalone/static/assets/chunks/{card-818c7a0d580e2e0d.js → card-abb16544e8e5a5e0.js} +1 -1
  43. package/dist/dash/standalone/static/assets/chunks/{combo-0d55fb62af761ac5.js → combo-0feaff3c2ab55606.js} +1 -1
  44. package/dist/dash/standalone/static/assets/chunks/{composer-8abfcac26339cc99.js → composer-08a1aad17120af8a.js} +1 -1
  45. package/dist/dash/standalone/static/assets/chunks/composer-261cde2206340a07.js +1 -0
  46. package/dist/dash/standalone/static/assets/chunks/{confirm-be929e2de15876a6.js → confirm-d804955ec454f00f.js} +1 -1
  47. package/dist/dash/standalone/static/assets/chunks/{connect-apps-3e8b55a43315f58a.js → connect-apps-c4b8fc9d3a25e545.js} +1 -1
  48. package/dist/dash/standalone/static/assets/chunks/{connect-repositories-8864a63f83ffd411.js → connect-repositories-2cf520006ed18949.js} +1 -1
  49. package/dist/dash/standalone/static/assets/chunks/{credentials-list-518af85578eacf6d.js → credentials-list-a1b81c1b630a8415.js} +1 -1
  50. package/dist/dash/standalone/static/assets/chunks/{custom-range-e8977f0d9699c1e6.js → custom-range-79011164d1e2529c.js} +1 -1
  51. package/dist/dash/standalone/static/assets/chunks/{editor-75d6d2d01f4fc35a.js → editor-b86137d54feb4ba1.js} +1 -1
  52. package/dist/dash/standalone/static/assets/chunks/{engines-list-2f6b8b3f2e873e4d.js → engines-list-0cf0dd6427e45add.js} +1 -1
  53. package/dist/dash/standalone/static/assets/chunks/{field-43fea54c1c287e30.js → field-329f272ef3edae30.js} +1 -1
  54. package/dist/dash/standalone/static/assets/chunks/{filter-55618648fc10c377.js → filter-673d0e6dbc95293c.js} +1 -1
  55. package/dist/dash/standalone/static/assets/chunks/{heads-1326669bdce3da2f.js → heads-bdb3900291e3ba2c.js} +1 -1
  56. package/dist/dash/standalone/static/assets/chunks/{instructions-0b968d5d0a58c716.js → instructions-7f289881a4d96d85.js} +1 -1
  57. package/dist/dash/standalone/static/assets/chunks/instructions-c175184f89172c15.js +1 -0
  58. package/dist/dash/standalone/static/assets/chunks/{list-90a47c07c4dd932e.js → list-074a086ab5e19d77.js} +1 -1
  59. package/dist/dash/standalone/static/assets/chunks/{mcp-list-735e401c60ab51a3.js → mcp-list-c97f883efa3f7d03.js} +1 -1
  60. package/dist/dash/standalone/static/assets/chunks/{models-list-999f54c76ca31379.js → models-list-3f869a70740e4244.js} +1 -1
  61. package/dist/dash/standalone/static/assets/chunks/{platform-actions-4592c82f72b21b1a.js → platform-actions-b317343915219089.js} +1 -1
  62. package/dist/dash/standalone/static/assets/chunks/{runners-list-ab64a5fb01d5eef8.js → runners-list-33a7339bd7cb3e18.js} +1 -1
  63. package/dist/dash/standalone/static/assets/chunks/{segmented-bf5a4c06605249e0.js → segmented-c9d58f98a7d32b4d.js} +1 -1
  64. package/dist/dash/standalone/static/assets/chunks/{select-591ca78b6ae29bd8.js → select-f4ea2f12a2298e4a.js} +1 -1
  65. package/dist/dash/standalone/static/assets/chunks/{sentinel-b4c91a38a5d79219.js → sentinel-9e882d8ad784d4bd.js} +1 -1
  66. package/dist/dash/standalone/static/assets/chunks/shared-init-bee5eaed36ee3dc4.js +5 -0
  67. package/dist/dash/standalone/static/assets/chunks/shared-init-cf66e1c1a2f30ef1.js +2 -0
  68. package/dist/dash/standalone/static/assets/chunks/{tail-74153aeac1f0baec.js → tail-5a5f739bca637202.js} +1 -1
  69. package/dist/dash/standalone/static/assets/chunks/{task-actions-26ad7f7c937f2589.js → task-actions-37ed047ca8c5b129.js} +1 -1
  70. package/dist/dash/standalone/static/assets/chunks/{task-view-0d085ce407e8511e.js → task-view-efe402c64d6a3c9b.js} +3 -3
  71. package/dist/dash/standalone/static/assets/chunks/{tasks-list-e9e914cf5dd959e9.js → tasks-list-eae2a32d61b437c5.js} +1 -1
  72. package/dist/dash/standalone/static/assets/chunks/{toolbar-a99d36b4b6f05bb1.js → toolbar-7aee851cfcc688cc.js} +1 -1
  73. package/dist/dash/standalone/static/assets/chunks/{versions-list-875a9a0ebb3f7d08.js → versions-list-836e397952b5d251.js} +1 -1
  74. package/dist/dash/standalone/static/assets/pnext-client-00c2425020b8564c.js +1 -0
  75. package/dist/dash/standalone/static/assets/pnext-client-091090fd50a6c9cd.js +1 -0
  76. package/dist/dash/standalone/static/assets/pnext-client-0b8b6a688cfb5246.js +1 -0
  77. package/dist/dash/standalone/static/assets/pnext-client-0cc2ff4668470e6f.js +1 -0
  78. package/dist/dash/standalone/static/assets/{pnext-client-4ed05f9a51f559a3.js → pnext-client-11f56cbcfd2a3fca.js} +1 -1
  79. package/dist/dash/standalone/static/assets/pnext-client-146cb2e293fd710e.js +1 -0
  80. package/dist/dash/standalone/static/assets/pnext-client-1cdaef1ffee188d4.js +1 -0
  81. package/dist/dash/standalone/static/assets/pnext-client-3298ffa52f79e244.js +1 -0
  82. package/dist/dash/standalone/static/assets/pnext-client-415baafb72caaf21.js +1 -0
  83. package/dist/dash/standalone/static/assets/pnext-client-50de47aa1f3aed6f.js +1 -0
  84. package/dist/dash/standalone/static/assets/{pnext-client-899f9625435988dd.js → pnext-client-802be87d22e144c4.js} +1 -1
  85. package/dist/dash/standalone/static/assets/pnext-client-9ec55ee4d6315657.js +1 -0
  86. package/dist/dash/standalone/static/assets/pnext-client-9fb279f4c6135368.js +1 -0
  87. package/dist/dash/standalone/static/assets/pnext-client-a543b7bfddcdae35.js +1 -0
  88. package/dist/dash/standalone/static/assets/pnext-client-a9f7e73b9a3252b9.js +1 -0
  89. package/dist/dash/standalone/static/assets/pnext-client-e9f4f42456943129.js +1 -0
  90. package/dist/{default-aLeIO8IR.js → default-BfXXngYf.js} +1 -1
  91. package/dist/{default-fMaQH1wm.js → default-zMKQ15xH.js} +1 -1
  92. package/dist/{delete-Cj16PYaw.js → delete-BbsEN7tF.js} +1 -1
  93. package/dist/{delete-DNj3leWA.js → delete-CZuI4sJi.js} +1 -1
  94. package/dist/{disable-CQg5Vybq.js → disable-B860lJDh.js} +1 -1
  95. package/dist/{discover-bVM8EJEz.js → discover-tM_915iZ.js} +1 -1
  96. package/dist/{docs-CqeYenUp.js → docs-BdmVTydv.js} +1 -1
  97. package/dist/{enable-8m3z7i3i.js → enable-DD4OsTnA.js} +1 -1
  98. package/dist/flow/index.d.ts +1 -1
  99. package/dist/{flow-DeCL3x2p.js → flow-DwhBWoSx.js} +1 -1
  100. package/dist/{index-Xe8n_t2Z.d.ts → index-JcLiq1ac.d.ts} +1 -1
  101. package/dist/{init-BujliQ7q.js → init-Bo3RS_va.js} +1 -1
  102. package/dist/integrations-CstFKLTr.js +1 -0
  103. package/dist/{list-QLTjk5SN.js → list-Bu1S3hPM.js} +1 -1
  104. package/dist/{list-CXu4cr8D.js → list-CLVoliXi.js} +1 -1
  105. package/dist/{list-BdiYneg5.js → list-DWeYdLMU.js} +1 -1
  106. package/dist/{list-DbY1jyj3.js → list-DYzczkQZ.js} +2 -2
  107. package/dist/{list-DhVfqr0A.js → list-DaQ14K1K.js} +1 -1
  108. package/dist/{list-DGoVY-ao.js → list-DhJOorrE.js} +1 -1
  109. package/dist/{list-DyqtSWvn.js → list-Motuarjd.js} +1 -1
  110. package/dist/{list-vKOTwd4G.js → list-P1Zi9bhT.js} +1 -1
  111. package/dist/{login-otJB9SYu.js → login-C-VTh_6i.js} +1 -1
  112. package/dist/{login-BzdlmD_o.js → login-KHrM3MI3.js} +1 -1
  113. package/dist/{logout-DOrRoxDV.js → logout-CqUKg0lc.js} +1 -1
  114. package/dist/{maintenance-Bg_FzXSq.js → maintenance-CVfHIraw.js} +1 -1
  115. package/dist/{mcp-xSvAWiXX.js → mcp-DCydEehH.js} +1 -1
  116. package/dist/{migrate-CN-fdMV9.js → migrate-DPprwsbm.js} +1 -1
  117. package/dist/{model-BJ-Sokha.js → model-_e9f9Oth.js} +1 -1
  118. package/dist/{push-Cg7-XT5h.js → push-HLTHyhsP.js} +1 -1
  119. package/dist/{queue-yo-Z8TaE.js → queue-EvplGOuk.js} +2 -2
  120. package/dist/refresh-ZbMy3Y9T.js +1 -0
  121. package/dist/{remove-DgMg_OOu.js → remove-B6PskfkD.js} +1 -1
  122. package/dist/{remove-BuaShRZ3.js → remove-CC7UyWNI.js} +1 -1
  123. package/dist/{remove-C8Rm8KP-.js → remove-CWd4Qs4F.js} +1 -1
  124. package/dist/{remove-CcMma1x3.js → remove-CZmO4BSd.js} +1 -1
  125. package/dist/{rename-C0vNcl8e.js → rename-ODyRelrw.js} +1 -1
  126. package/dist/{result-C6ovl_Dn.js → result-CRIAetqH.js} +1 -1
  127. package/dist/{result-oQey_hdw.js → result-DtXZusqj.js} +1 -1
  128. package/dist/{resume-T_TXWfqE.js → resume-CI-swBxa.js} +1 -1
  129. package/dist/{review-CCs6XUSO.js → review-IRsckIiU.js} +1 -1
  130. package/dist/{rotate-key-CYimsQR5.js → rotate-key-CmvHXXnp.js} +1 -1
  131. package/dist/{run-BFYg-zZt.js → run-Dd9HdNSL.js} +1 -1
  132. package/dist/{run-D7F7JPV6.js → run-FYA9XIij.js} +1 -1
  133. package/dist/{run-hiPyO7js.js → run-IWXjB5OD.js} +1 -1
  134. package/dist/runner-CbDswgji.js +1 -0
  135. package/dist/sdk.d.ts +2 -2
  136. package/dist/sdk.js +1 -1
  137. package/dist/{serve-C-AD60Wa.js → serve-CML2mkKG.js} +1 -1
  138. package/dist/{serve-BgGXjT_O.js → serve-CY46ohfr.js} +1 -1
  139. package/dist/{serve-GIK3fqKA.js → serve-D_XiZzYd.js} +2 -2
  140. package/dist/{serve-K3BVTcDI.js → serve-t38OrDrk.js} +2 -2
  141. package/dist/{server-DQTGc55C.js → server-83YZ2Kkh.js} +1 -1
  142. package/dist/{setup-host-By8-gv_v.js → setup-host-DRuUX8zg.js} +1 -1
  143. package/dist/{shared-TznJgMFW.js → shared-D64pQ0XU.js} +1 -1
  144. package/dist/{show-C9ojrH5W.js → show-DlKWR0Hy.js} +1 -1
  145. package/dist/{show-o4yXzSWZ.js → show-aCUICSoc.js} +1 -1
  146. package/dist/{status-BBW7Qyde.js → status-C09SKASS.js} +1 -1
  147. package/dist/{steer-D47cuggj.js → steer-BGKYpW4T.js} +1 -1
  148. package/dist/{stop-CD2JW6dI.js → stop-CiAJVnU2.js} +1 -1
  149. package/dist/{stop-7brPdki9.js → stop-svJYkhTt.js} +1 -1
  150. package/dist/{store-BCBTo0rl.js → store-B0RLMUR9.js} +1 -1
  151. package/dist/{store-qp7UE2ES.js → store-Cxc2GYyj.js} +2 -2
  152. package/dist/{task-CyrDqqf8.js → task-DvPkqHCF.js} +1 -1
  153. package/dist/{test-BcFQUHRo.js → test-9FHRw5Jc.js} +1 -1
  154. package/dist/{tools-D20XYPnO.js → tools-DhlrB8xV.js} +1 -1
  155. package/dist/{types-DMGBYB_K.d.ts → types-CdIo1Zbm.d.ts} +2 -2
  156. package/dist/{unalias-G3sM8fVw.js → unalias-D6UESHzK.js} +1 -1
  157. package/dist/{update-JvgB6Xws.js → update-DTYOhoQC.js} +1 -1
  158. package/dist/{upgrade-DN3hXDdo.js → upgrade-BOYs5Vyi.js} +2 -2
  159. package/dist/{usage-C1oN2W9c.js → usage-BlT_poNA.js} +1 -1
  160. package/dist/{usage-DR3wWtYD.js → usage-Bw7fQeFC.js} +1 -1
  161. package/dist/{watch-DDmHonTf.js → watch-BlGYjH88.js} +1 -1
  162. package/dist/{watch-DYkC6Q2q.js → watch-Y82ubvGH.js} +1 -1
  163. package/dist/{worker-CaNTsqcD.js → worker-4TKVAB01.js} +1 -1
  164. package/dist/{workflow-7rqzHHWZ.js → workflow-Mi1OCrOI.js} +1 -1
  165. package/package.json +1 -1
  166. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  167. package/plugins/cursor/.cursor-plugin/plugin.json +1 -1
  168. package/dist/auth-FTKev9__.js +0 -1
  169. package/dist/credentials-DLMuf9OT.js +0 -1
  170. package/dist/dash/standalone/static/assets/chunks/composer-44516934e5619d32.js +0 -1
  171. package/dist/dash/standalone/static/assets/chunks/instructions-f3ecfb5c50f270c2.js +0 -1
  172. package/dist/dash/standalone/static/assets/chunks/shared-init-17c1fd399ac53851.js +0 -5
  173. package/dist/dash/standalone/static/assets/chunks/shared-init-8a34c730aabe942d.js +0 -2
  174. package/dist/dash/standalone/static/assets/pnext-client-1473d0349f242421.js +0 -1
  175. package/dist/dash/standalone/static/assets/pnext-client-195f74ae46e817da.js +0 -1
  176. package/dist/dash/standalone/static/assets/pnext-client-2b5532ce488c9391.js +0 -1
  177. package/dist/dash/standalone/static/assets/pnext-client-2d3ea662f22db27f.js +0 -1
  178. package/dist/dash/standalone/static/assets/pnext-client-43c0166e51dce87f.js +0 -1
  179. package/dist/dash/standalone/static/assets/pnext-client-652affde71fecdf7.js +0 -1
  180. package/dist/dash/standalone/static/assets/pnext-client-82beeebf704714a6.js +0 -1
  181. package/dist/dash/standalone/static/assets/pnext-client-ad1fab64ee1a5b30.js +0 -1
  182. package/dist/dash/standalone/static/assets/pnext-client-b2dccebfff1465f5.js +0 -1
  183. package/dist/dash/standalone/static/assets/pnext-client-c8a42c9bfeded4e4.js +0 -1
  184. package/dist/dash/standalone/static/assets/pnext-client-d04d2ffbb491564c.js +0 -1
  185. package/dist/dash/standalone/static/assets/pnext-client-d060565c4d80b60e.js +0 -1
  186. package/dist/dash/standalone/static/assets/pnext-client-dce6e1b84ee02f09.js +0 -1
  187. package/dist/dash/standalone/static/assets/pnext-client-e753846e298d2403.js +0 -1
  188. package/dist/integrations-6kXL9hRo.js +0 -1
  189. package/dist/refresh-CmBQALAW.js +0 -1
  190. package/dist/runner-D5jaEfhG.js +0 -1
@@ -1 +1 @@
1
- import{i as e}from"./cli-msOzZFXW.js";import{n as t}from"./args-DEMOfLz2.js";import n from"node:process";const r=e({name:`server rotate-key`,globalFlags:{cwd:!1},help:{usage:`coder server rotate-key [--json]`,summary:`Re-seal stored app, installation, engine, and linked user secrets with the current key.`,env:[[`SERVER_ENCRYPTION_KEY`,`the new key`],[`SERVER_ENCRYPTION_KEY_PREVIOUS`,`the old key, still accepted while rotating`]]},options:{json:t},run:async()=>{let{rotateKey:e}=await import(`./maintenance-Bg_FzXSq.js`).then(e=>e.t);return e()},json:({moved:e})=>({ok:!0,moved:e}),print:({moved:e})=>n.stdout.write(`Re-sealed ${e} secret${e===1?``:`s`}.\n`)});export{r as commandServerRotateKey};
1
+ import{i as e}from"./cli-IfrPgeYz.js";import{n as t}from"./args-DEMOfLz2.js";import n from"node:process";const r=e({name:`server rotate-key`,globalFlags:{cwd:!1},help:{usage:`coder server rotate-key [--json]`,summary:`Re-seal stored app, installation, engine, and linked user secrets with the current key.`,env:[[`SERVER_ENCRYPTION_KEY`,`the new key`],[`SERVER_ENCRYPTION_KEY_PREVIOUS`,`the old key, still accepted while rotating`]]},options:{json:t},run:async()=>{let{rotateKey:e}=await import(`./maintenance-CVfHIraw.js`).then(e=>e.t);return e()},json:({moved:e})=>({ok:!0,moved:e}),print:({moved:e})=>n.stdout.write(`Re-sealed ${e} secret${e===1?``:`s`}.\n`)});export{r as commandServerRotateKey};
@@ -1,4 +1,4 @@
1
- import{St as e}from"./dispatch-YW1aqjEg.js";import{i as t}from"./cli-msOzZFXW.js";import{p as n,s as r}from"./output-BKeyLbvt.js";import{n as i,s as a,t as o}from"./args-DEMOfLz2.js";import{FlowStepRenderer as s,printFollow as c,printRunSummary as l}from"./watch-DDmHonTf.js";import u from"node:process";const d={...o,args:a,wait:i,concurrency:a,"max-tasks":a,"dry-run":i};function f(t){let n={};for(let r of t){let t=r.indexOf(`=`);if(t===-1)throw new e(`invalid-option`,`Invalid argument "${r}": expected key=value.`,{hint:`Help: coder flow run --help`});let i=r.slice(0,t),a=r.slice(t+1);try{n[i]=JSON.parse(a)}catch{n[i]=a}}return n}function p(t,n){if(t!==void 0)try{return JSON.parse(t)}catch(t){throw new e(`invalid-option`,`Invalid --args JSON: ${t instanceof Error?t.message:String(t)}`)}return n.length?f(n):{}}const m=e=>e?Number(e):void 0,h=(e,t)=>({cwd:t,dryRun:e[`dry-run`],concurrency:m(e.concurrency),maxTasks:m(e[`max-tasks`]),argv:u.argv.slice(2),wait:e.wait}),g=e=>e[`dry-run`]&&!e.json?v():{},_=t({name:`flow run`,help:{usage:`coder flow run <name|path> [--args '<json>' | key=value...] [--wait] [--concurrency N] [--max-tasks N] [--json] [--dry-run]`,summary:`Run a flow: a TypeScript file that orchestrates many coder tasks with gates,
1
+ import{St as e}from"./dispatch-YW1aqjEg.js";import{i as t}from"./cli-IfrPgeYz.js";import{p as n,s as r}from"./output-BKeyLbvt.js";import{n as i,s as a,t as o}from"./args-DEMOfLz2.js";import{FlowStepRenderer as s,printFollow as c,printRunSummary as l}from"./watch-BlGYjH88.js";import u from"node:process";const d={...o,args:a,wait:i,concurrency:a,"max-tasks":a,"dry-run":i};function f(t){let n={};for(let r of t){let t=r.indexOf(`=`);if(t===-1)throw new e(`invalid-option`,`Invalid argument "${r}": expected key=value.`,{hint:`Help: coder flow run --help`});let i=r.slice(0,t),a=r.slice(t+1);try{n[i]=JSON.parse(a)}catch{n[i]=a}}return n}function p(t,n){if(t!==void 0)try{return JSON.parse(t)}catch(t){throw new e(`invalid-option`,`Invalid --args JSON: ${t instanceof Error?t.message:String(t)}`)}return n.length?f(n):{}}const m=e=>e?Number(e):void 0,h=(e,t)=>({cwd:t,dryRun:e[`dry-run`],concurrency:m(e.concurrency),maxTasks:m(e[`max-tasks`]),argv:u.argv.slice(2),wait:e.wait}),g=e=>e[`dry-run`]&&!e.json?v():{},_=t({name:`flow run`,help:{usage:`coder flow run <name|path> [--args '<json>' | key=value...] [--wait] [--concurrency N] [--max-tasks N] [--json] [--dry-run]`,summary:`Run a flow: a TypeScript file that orchestrates many coder tasks with gates,
2
2
  journaling, and resume. Prints the run id and orchestrates in the background;
3
3
  --wait follows the run in the foreground with live progress (Ctrl-C detaches;
4
4
  it keeps running), and \`coder flow watch\` shows the same lines any time.
@@ -1,2 +1,2 @@
1
- import{p as e}from"./prompt-K7-bKcTC.js";import{i as t,r as n}from"./cli-msOzZFXW.js";import{p as r,s as i}from"./output-BKeyLbvt.js";import{i as a,n as o,s,t as c}from"./args-DEMOfLz2.js";import{i as l}from"./result-oQey_hdw.js";import{printLine as u}from"./watch-DYkC6Q2q.js";import d from"node:process";const f={...c,flow:s,server:a,workspace:s,wait:o,task:s,yes:o},p=t({name:`agent run --task`,options:f,run:async({options:e,cwd:t})=>{let{agents:n}=await import(`./agent-BcXXkOmD.js`).then(e=>e.t);return n.runTask(e.task,{cwd:t})}}),m=t({name:`agent run`,help:{usage:`coder agent run <agent> <file> [--server [url] [--wait]] [--flow <name>] [--json] [--cwd <dir>]`,summary:`Run a recorded platform event (AgentEvent JSON) through an agent. With --server it goes through your Coder server exactly like a webhook: real app, tokens, runner, and the reply is posted. Without it the engine runs here on the agent's prompt and this checkout, platform tools off, and the reply is printed.`,flags:[n,[`--wait`,`with --server: follow the task log here until it finishes, then print the reply`],[`--flow <name>`,`override the matched flow`]],examples:[[`coder agent run helper sample-slack-mention.json`,`offline: print what the agent would reply`],[`coder agent run helper event.json --server`,`for real, through the server`]]},options:f,args:2,run:async({options:e,args:[t,n],cwd:i})=>{let{agents:a}=await import(`./agent-BcXXkOmD.js`).then(e=>e.t);return a.run(t,n,{...e,cwd:i,organization:e.workspace,...e.json?{}:{onLog:e=>u(e,r),onDone:e=>l(e,r)}})},json:e=>Array.isArray(e)&&e.length===1?e[0]:e,print(t,{options:n}){if(!Array.isArray(t)){if(`tasks`in t){if(!t.tasks.length)return void d.stdout.write(`The server accepted the event but no agent matched it.
1
+ import{p as e}from"./prompt-K7-bKcTC.js";import{i as t,r as n}from"./cli-IfrPgeYz.js";import{p as r,s as i}from"./output-BKeyLbvt.js";import{i as a,n as o,s,t as c}from"./args-DEMOfLz2.js";import{i as l}from"./result-DtXZusqj.js";import{printLine as u}from"./watch-Y82ubvGH.js";import d from"node:process";const f={...c,flow:s,server:a,workspace:s,wait:o,task:s,yes:o},p=t({name:`agent run --task`,options:f,run:async({options:e,cwd:t})=>{let{agents:n}=await import(`./agent-D0pQ_ewc.js`).then(e=>e.t);return n.runTask(e.task,{cwd:t})}}),m=t({name:`agent run`,help:{usage:`coder agent run <agent> <file> [--server [url] [--wait]] [--flow <name>] [--json] [--cwd <dir>]`,summary:`Run a recorded platform event (AgentEvent JSON) through an agent. With --server it goes through your Coder server exactly like a webhook: real app, tokens, runner, and the reply is posted. Without it the engine runs here on the agent's prompt and this checkout, platform tools off, and the reply is printed.`,flags:[n,[`--wait`,`with --server: follow the task log here until it finishes, then print the reply`],[`--flow <name>`,`override the matched flow`]],examples:[[`coder agent run helper sample-slack-mention.json`,`offline: print what the agent would reply`],[`coder agent run helper event.json --server`,`for real, through the server`]]},options:f,args:2,run:async({options:e,args:[t,n],cwd:i})=>{let{agents:a}=await import(`./agent-D0pQ_ewc.js`).then(e=>e.t);return a.run(t,n,{...e,cwd:i,organization:e.workspace,...e.json?{}:{onLog:e=>u(e,r),onDone:e=>l(e,r)}})},json:e=>Array.isArray(e)&&e.length===1?e[0]:e,print(t,{options:n}){if(!Array.isArray(t)){if(`tasks`in t){if(!t.tasks.length)return void d.stdout.write(`The server accepted the event but no agent matched it.
2
2
  `);d.stdout.write(`${r.bold(`Queued on the server`)} as task ${t.tasks.join(`, `)}.\n\n${i([`Watch it: coder task watch ${t.tasks[0]} --server ${e(n.server)}`],r)}\n`);return}t.reply===void 0?t.result!==void 0&&d.stdout.write(`${JSON.stringify(t.result,null,2)}\n`):d.stdout.write(`${t.reply.trim()}\n`)}}}),h=Object.assign(e=>(e.some(e=>e===`--task`||e.startsWith(`--task=`))?p:m)(e),{commandName:`agent run`,help:m.help});export{h as commandAgentRun};
@@ -1,2 +1,2 @@
1
- import{d as e,i as t,n,p as r}from"./cli-msOzZFXW.js";import{p as i,r as a,s as o,u as s}from"./output-BKeyLbvt.js";import{c,i as l,n as u,s as d,t as f}from"./args-DEMOfLz2.js";import{i as p,r as m}from"./result-oQey_hdw.js";import{printLine as h}from"./watch-DYkC6Q2q.js";import{TASK_FLAGS as g}from"./task-CyrDqqf8.js";import _ from"node:process";function v(t){let n=e([{usage:`coder task result ${t} --wait`,blurb:`run this in its own background shell, one per task (never wait on several tasks in one call). Returns with the answer or a pending approval.`},{usage:`coder task steer ${t} "<follow-up>"`,blurb:`steer the task with a message (use 'ask' without interrupting main thread)`},{usage:`coder task stop ${t}`,blurb:`stop the task`},{usage:`coder task list`,blurb:`recent tasks`},{usage:`coder task --help`,blurb:`all task commands`}],i,i.blue);return[...r(`Next step`,n.slice(0,1),i),...r(`Related`,n.slice(1),i)].join(`
1
+ import{d as e,i as t,n,p as r}from"./cli-IfrPgeYz.js";import{p as i,r as a,s as o,u as s}from"./output-BKeyLbvt.js";import{c,i as l,n as u,s as d,t as f}from"./args-DEMOfLz2.js";import{i as p,r as m}from"./result-DtXZusqj.js";import{printLine as h}from"./watch-Y82ubvGH.js";import{TASK_FLAGS as g}from"./task-DvPkqHCF.js";import _ from"node:process";function v(t){let n=e([{usage:`coder task result ${t} --wait`,blurb:`run this in its own background shell, one per task (never wait on several tasks in one call). Returns with the answer or a pending approval.`},{usage:`coder task steer ${t} "<follow-up>"`,blurb:`steer the task with a message (use 'ask' without interrupting main thread)`},{usage:`coder task stop ${t}`,blurb:`stop the task`},{usage:`coder task list`,blurb:`recent tasks`},{usage:`coder task --help`,blurb:`all task commands`}],i,i.blue);return[...r(`Next step`,n.slice(0,1),i),...r(`Related`,n.slice(1),i)].join(`
2
2
  `)}function y(e,t){_.stdout.write(`${i.dim(`[coder]`)} task ${i.blue(e)} started in the background (${t}).\n`),_.stdout.write(`${v(e)}\n`)}function b(e){_.stderr.write(`${i.dim(`[coder]`)} Task ${i.cyan(e)} started and is waiting to finish. Press Ctrl-C to detach. It keeps running.\n`),_.stderr.write(`${v(e)}\n`)}function x(e){_.stderr.write(`\n${i.dim(`[coder] Detached. The task is still running.`)}\n\n${o([`Wait in its own background shell, one per task: coder task result ${e} --wait`],a)}\n`)}function S(e){_.stdout.write(`\n${e.finalMessage||(e.error?`${i.red(`error:`)} ${e.error}`:`(no final message)`)}\n\n`);let t=e.tokens?` tokens=${s(e.tokens,e.model)}`:``;_.stderr.write(`${i.dim(`[coder] task=${e.taskId} status=${e.status}${t}`)}\n\n${m(e.taskId,a)}\n`)}const C=t({name:`task run`,help:{usage:`coder task run "<task text>"`,summary:`Dispatch a coding task to the configured engine. Backgrounds by default and\nprints a task id; --wait runs in the foreground and prints the answer.\nShortcut: \`coder run "<text>"\`.\n\nWriting a task: one task per focused goal, independent goals as parallel runs.\nThe worker starts with nothing but the text, so include the goal, file paths,\nconstraints and any context only you have. Delegate rather than doing the work\nyourself first, however small it looks.\n\nWaiting: run \`coder task result <task-id> --wait\` in its own background shell, one\nper task. Never wait on several tasks in one call, or their approvals and answers\nnever reach you one by one.\n\n${n}`,flags:[[`--output-schema <json>`,`JSON Schema for the task answer`],[`--name <name>`,`label the task (shown in list/result)`],[`--agent <id>`,`run as that agent: its system.md, engine settings, MCP servers and flows; flags override them`],[`--system <text>`,`standing instructions prepended to the task (kept out of prompt previews)`],...g,[`--server [url] [--workspace <slug>]`,`run the task on your Coder server and follow it here (--background prints its id)`],[`--repo <owner/name>`,`with --server: check out a repo from the workspace's installs`],[`--runner <name>`,`with --server: where it runs (a runner kind or a registered runner)`]],exitCodes:[[`0`,`The task started, or --wait printed a successful answer.`],[`1`,`Dispatch or the task failed.`],[`3`,`No engine could start; follow fallback.instructions in the JSON payload.`],[`4`,`An approval is pending; answer it, then run result --wait again.`],[`130`,`The foreground wait was detached and the task is still running.`]],examples:[[`coder run "add a /health endpoint"`,`dispatch in the background, print a task id`],[`coder result <task-id> --wait`,`then block until it finishes and print the answer`],[`coder run --wait "fix the failing test"`,`or block on the run itself`],[`coder task run --model luna --system "tests live in test/, don't touch anything outside of it" "rename foo to bar"`,`pick an engine via its model alias; --system adds standing instructions`],[`coder task run --agent reviewer "review the last commit"`,`run a repo agent from .coder/agents/reviewer`],[`coder run --add-dir ../api --add-dir ../shared "update the client for the new endpoint"`,`let the task reach sibling repos too`]]},options:{...f,agent:d,"output-schema":d,engine:d,model:d,effort:d,permissions:d,host:d,name:d,system:d,mcp:d,"add-dir":c,background:u,wait:u,"simulate-approval":u,server:l,workspace:d,yes:u,repo:d,runner:d},args:1/0,async run({options:e,args:t}){let{tasks:n}=await import(`./task-DEp3GHwH.js`).then(e=>e.t),r=e.json,a;return _.on(`SIGINT`,()=>{a&&x(a),_.exit(130)}),n.run(t.join(` `).trim(),{cwd:e.cwd,agent:e.agent,outputSchema:e[`output-schema`]?JSON.parse(e[`output-schema`]):void 0,engine:e.engine,model:e.model,effort:e.effort,permissions:e.permissions,name:e.name,system:e.system,mcp:e.mcp,addDirs:e[`add-dir`],wait:e.server===void 0?e.wait:!e.background,simulateApproval:e[`simulate-approval`],repo:e.repo,runner:e.runner,server:e.server,yes:e.yes,organization:e.workspace,onFallback:({engine:e,detail:t,next:n})=>_.stderr.write(`[coder] ${e} failed to start (${t}); falling back to ${n}.\n`),onNote:e=>_.stderr.write(`[coder] ${e}\n`),onWaiting:e=>{a=e,r||b(e)},onLog:e=>r?_.stdout.write(`${JSON.stringify(e,null,2)}\n`):h(e,i)})},print(e,{options:t}){if(`attempts`in e)return t.background?void _.stdout.write(`${e.task.id}\n`):p(e,i);t.wait?S(e):y(e.taskId,e.status)},exit:(e,{options:t})=>(`attempts`in e?!t.background:t.wait)?e.status===`completed`?0:1:void 0});export{C as commandTask};
@@ -0,0 +1 @@
1
+ import{s as e}from"./cli-IfrPgeYz.js";const t=e(`runner`,{add:async()=>(await import(`./add-KkLx1WbE.js`)).commandRunnerAdd,default:async()=>(await import(`./default-BfXXngYf.js`)).commandRunnerDefault,test:async()=>(await import(`./test-9FHRw5Jc.js`)).commandRunnerTest,serve:async()=>(await import(`./serve-CY46ohfr.js`)).commandRunnerServe,list:async()=>(await import(`./list-DWeYdLMU.js`)).commandRunnerList,rename:async()=>(await import(`./rename-ODyRelrw.js`)).commandRunnerRename,remove:async()=>(await import(`./remove-CZmO4BSd.js`)).commandRunnerRemove},{menu:[{usage:`add <kind>`,blurb:`connect a runner`},{usage:`default <id>`,blurb:`set the default in its scope`},{usage:`test <id>`,blurb:`check a runner connection`},{usage:`serve --url <public url>`,blurb:`run your server's tasks on this machine`},{usage:`list`,blurb:`list your runners and the workspace's`},{usage:`rename <id> <name>`,blurb:`rename a runner`},{usage:`remove <id>`,blurb:`remove a runner`}],description:[`Run your Coder server's tasks on your own machine, reached through any tunnel.`],exampleCommand:`runner serve`});export{t as commandRunner};
package/dist/sdk.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { C as CoderConfig, D as McpConfigEntry, E as McpAddOptions, O as Permission, S as TaskTurn, T as Effort, _ as RunnerPairing, b as RunnerTest, c as TaskStatus$1, d as TokenUsage, f as LocalFolder, g as RunnerKind, h as RunnerInput, l as TurnResult, m as ProbeResult, n as Availability, p as LocalFolders, s as Task, t as Approval, u as TaskLogEntry, v as RunnerRow, w as CustomModelConfig, x as RunnerUpdate, y as RunnerSpec } from "./types-DMGBYB_K.js";
1
+ import { C as CoderConfig, D as McpConfigEntry, E as McpAddOptions, O as Permission, S as TaskTurn, T as Effort, _ as RunnerPairing, b as RunnerTest, c as TaskStatus$1, d as TokenUsage, f as LocalFolder, g as RunnerKind, h as RunnerInput, l as TurnResult, m as ProbeResult, n as Availability, p as LocalFolders, s as Task, t as Approval, u as TaskLogEntry, v as RunnerRow, w as CustomModelConfig, x as RunnerUpdate, y as RunnerSpec } from "./types-CdIo1Zbm.js";
2
2
  import { ReviewArgs, ReviewResult } from "./flow/builtin/review.js";
3
- import { C as FlowStep, a as readTurnResults, b as FlowEvent, c as archiveRuns, d as RunSummary, f as StopSummary, i as readTask, l as deleteRuns, n as flowSdk, o as CoderError, r as TaskResult, s as RunResult$1, u as RunOptions, x as FlowRecord, y as DiscoveredFlow } from "./index-Xe8n_t2Z.js";
3
+ import { C as FlowStep, a as readTurnResults, b as FlowEvent, c as archiveRuns, d as RunSummary, f as StopSummary, i as readTask, l as deleteRuns, n as flowSdk, o as CoderError, r as TaskResult, s as RunResult$1, u as RunOptions, x as FlowRecord, y as DiscoveredFlow } from "./index-JcLiq1ac.js";
4
4
  import "zod/mini";
5
5
  import { Message, SerializedMessage, SerializedThread } from "chat";
6
6
  import "drizzle-orm";
package/dist/sdk.js CHANGED
@@ -1 +1 @@
1
- import{C as e,St as t,X as n,Y as r,at as i,nt as a,ot as o,rt as s,w as c}from"./dispatch-YW1aqjEg.js";import{n as l,r as u,s as ee,t as d}from"./remote-AcWWfKVS.js";import{n as f}from"./executor-HWnIIYUL.js";import{n as p}from"./agent-BcXXkOmD.js";import{t as m}from"./docs-Byrpar10.js";import{a as h,i as g,n as _,o as v,r as y,s as b,t as x}from"./models-DGPrMV51.js";import{n as S}from"./task-DEp3GHwH.js";import C from"./flow/index.js";import{i as w,n as T,o as E,r as D,s as O,t as k}from"./runner-c-2w6Eoj.js";import{t as A}from"./serve-xMihn4g-.js";import{t as j}from"./github-actions-CvLya8ve.js";import{n as M}from"./apps-eueTmHR5.js";import{n as N,r as P}from"./maintenance-Bg_FzXSq.js";import{r as F,t as I}from"./serve-GIK3fqKA.js";import L from"node:path";import R from"node:process";function z(e){return e?L.resolve(e):R.cwd()}const B=S,V={add:(e,t)=>x(z(t.cwd),e,t),update:(e,t)=>b(z(t.cwd),e,t),remove:(e,t={})=>g(z(t.cwd),e,t),list:(e={})=>y(z(e.cwd)),alias:(e,t,n={})=>_(z(n.cwd),e,t,n),unalias:(e,t={})=>v(z(t.cwd),e,t),disable:(e,t={})=>h(z(t.cwd),e,!0,t),enable:(e,t={})=>h(z(t.cwd),e,!1,t)},H={get:(e,t={})=>r(z(t.cwd),e),set:(e,t,r={})=>n(z(r.cwd),e,t,r)},U={add:(e,t)=>a(z(t.cwd),e,t),addJson:(e,t,n={})=>s(z(n.cwd),e,t,n),list:(e={})=>i(z(e.cwd)),remove:(e,t={})=>o(z(t.cwd),e,t)};function W(t=[],n={}){return e(z(n.cwd),{hosts:t})}function G(e={}){return c(e)}function K(e,t={}){return m(e,t)}const q={async run(e={}){let t=await f(`review`,{cwd:e.cwd,args:e});return{...t.result,runId:t.runId}}},J=ee,Y={serve:I,migrate:N,rotateKey:P,workflow:()=>j,app:{create:M},handler:F},X={list:(e={})=>l(e).credentials.list(),add:d,remove:(e,t={})=>l(t).credentials.remove(e,t),default:(e,t={})=>l(t).credentials.setDefault(e,t),login:u},Z={list:(e={})=>l(e).folders.list(),check:(e,t={})=>l(t).folders.check(e)},Q={list:T,add:k,pair:D,update:O,default:(e,t={})=>O(e,{default:!0},t),test:E,rename:(e,t,n={})=>O(e,{name:t},n),remove:w,serve:A},$=p;var te={task:B,flow:C,model:V,config:H,mcp:U,setupHost:W,upgrade:G,docs:K,review:q,auth:J,agent:$,credentials:X,folders:Z,runner:Q,server:Y};export{t as CoderError,$ as agent,J as auth,H as config,X as credentials,te as default,K as docs,C as flow,Z as folders,U as mcp,V as model,q as review,Q as runner,Y as server,W as setupHost,B as task,G as upgrade};
1
+ import{C as e,St as t,X as n,Y as r,at as i,nt as a,ot as o,rt as s,w as c}from"./dispatch-YW1aqjEg.js";import{n as l,r as u,s as ee,t as d}from"./remote-AcWWfKVS.js";import{n as f}from"./executor-HWnIIYUL.js";import{n as p}from"./agent-D0pQ_ewc.js";import{t as m}from"./docs-Byrpar10.js";import{a as h,i as g,n as _,o as v,r as y,s as b,t as x}from"./models-DGPrMV51.js";import{n as S}from"./task-DEp3GHwH.js";import C from"./flow/index.js";import{i as w,n as T,o as E,r as D,s as O,t as k}from"./runner-c-2w6Eoj.js";import{t as A}from"./serve-xMihn4g-.js";import{t as j}from"./github-actions-CvLya8ve.js";import{n as M}from"./apps-CaHoLNE7.js";import{n as N,r as P}from"./maintenance-CVfHIraw.js";import{r as F,t as I}from"./serve-D_XiZzYd.js";import L from"node:path";import R from"node:process";function z(e){return e?L.resolve(e):R.cwd()}const B=S,V={add:(e,t)=>x(z(t.cwd),e,t),update:(e,t)=>b(z(t.cwd),e,t),remove:(e,t={})=>g(z(t.cwd),e,t),list:(e={})=>y(z(e.cwd)),alias:(e,t,n={})=>_(z(n.cwd),e,t,n),unalias:(e,t={})=>v(z(t.cwd),e,t),disable:(e,t={})=>h(z(t.cwd),e,!0,t),enable:(e,t={})=>h(z(t.cwd),e,!1,t)},H={get:(e,t={})=>r(z(t.cwd),e),set:(e,t,r={})=>n(z(r.cwd),e,t,r)},U={add:(e,t)=>a(z(t.cwd),e,t),addJson:(e,t,n={})=>s(z(n.cwd),e,t,n),list:(e={})=>i(z(e.cwd)),remove:(e,t={})=>o(z(t.cwd),e,t)};function W(t=[],n={}){return e(z(n.cwd),{hosts:t})}function G(e={}){return c(e)}function K(e,t={}){return m(e,t)}const q={async run(e={}){let t=await f(`review`,{cwd:e.cwd,args:e});return{...t.result,runId:t.runId}}},J=ee,Y={serve:I,migrate:N,rotateKey:P,workflow:()=>j,app:{create:M},handler:F},X={list:(e={})=>l(e).credentials.list(),add:d,remove:(e,t={})=>l(t).credentials.remove(e,t),default:(e,t={})=>l(t).credentials.setDefault(e,t),login:u},Z={list:(e={})=>l(e).folders.list(),check:(e,t={})=>l(t).folders.check(e)},Q={list:T,add:k,pair:D,update:O,default:(e,t={})=>O(e,{default:!0},t),test:E,rename:(e,t,n={})=>O(e,{name:t},n),remove:w,serve:A},$=p;var te={task:B,flow:C,model:V,config:H,mcp:U,setupHost:W,upgrade:G,docs:K,review:q,auth:J,agent:$,credentials:X,folders:Z,runner:Q,server:Y};export{t as CoderError,$ as agent,J as auth,H as config,X as credentials,te as default,K as docs,C as flow,Z as folders,U as mcp,V as model,q as review,Q as runner,Y as server,W as setupHost,B as task,G as upgrade};
@@ -1,4 +1,4 @@
1
- import{An as e,Et as t,Mn as n,Vt as r,W as i,_ as a,an as o,nn as s,tt as c,v as l,wn as u,y as d}from"./dispatch-YW1aqjEg.js";import{i as f}from"./cli-msOzZFXW.js";import{s as p}from"./args-DEMOfLz2.js";import{n as m}from"./mcp-server-DGzme0YX.js";import h from"node:path";import g from"node:fs";import{spawn as _}from"node:child_process";import{randomUUID as v}from"node:crypto";function y(e){return h.join(e,`sidecar.json`)}function b(t){return e(y(t))??{sessionId:null,declineStreak:0}}async function x(e){let t=h.join(e,`sidecar.lock`),n=Date.now()+12e4;for(;;)try{return g.mkdirSync(t),()=>{try{g.rmdirSync(t)}catch{}}}catch{try{if(Date.now()-g.statSync(t).mtimeMs>9e4){g.rmdirSync(t);continue}}catch{continue}if(Date.now()>n)throw Error(`sidecar lock wait timed out`);await new Promise(e=>setTimeout(e,250))}}function S(e,t,n,r){return[`-p`,r,`--output-format`,`json`,`--model`,`sonnet`,`--effort`,`low`,`--strict-mcp-config`,`--no-chrome`,`--mcp-config`,`{"mcpServers":{}}`,`--settings`,`{"disableClaudeAiConnectors":true}`,n?`--resume`:`--session-id`,t,...i,`--add-dir`,e]}function C(e,t,n,r,i){let a=S(t,n,r,i);return new Promise((t,n)=>{let r=_(`claude`,a,{cwd:e,stdio:[`ignore`,`pipe`,`pipe`]}),i=``,o=``,s=setTimeout(()=>{r.kill(`SIGKILL`),n(Error(`sidecar call timed out`))},12e4);r.stdout.on(`data`,e=>i+=e),r.stderr.on(`data`,e=>o+=e),r.on(`error`,e=>{clearTimeout(s),n(e)}),r.on(`close`,e=>{if(clearTimeout(s),e!==0){n(Error(`sidecar claude exited ${e}: ${o.trim().slice(0,200)}`));return}try{let e=JSON.parse(i);if(e.is_error){n(Error(`sidecar turn errored: ${String(e.result??``).slice(0,200)}`));return}t(String(e.result??``))}catch{n(Error(`sidecar returned unparseable output`))}})})}function w(e){let t=e.match(/\{[^{}]*"decision"[^{}]*\}/);if(!t)return null;try{let e=JSON.parse(t[0]);if(e.decision===`accept`||e.decision===`decline`||e.decision===`escalate`)return{decision:e.decision,reason:String(e.reason??``)}}catch{}return null}async function T(e,t,r){let i=null;try{i=await x(t);let a=b(t);if(a.declineStreak>=3)return{decision:`escalate`,reason:`sidecar decline streak; needs human review`};if(!a.sessionId){let i=v();await C(e,t,i,!1,`You are the approval reviewer for a "coder" background coding task. The task runs inside an OS sandbox; you review only actions that escape it.
1
+ import{An as e,Et as t,Mn as n,Vt as r,W as i,_ as a,an as o,nn as s,tt as c,v as l,wn as u,y as d}from"./dispatch-YW1aqjEg.js";import{i as f}from"./cli-IfrPgeYz.js";import{s as p}from"./args-DEMOfLz2.js";import{n as m}from"./mcp-server-DGzme0YX.js";import h from"node:path";import g from"node:fs";import{spawn as _}from"node:child_process";import{randomUUID as v}from"node:crypto";function y(e){return h.join(e,`sidecar.json`)}function b(t){return e(y(t))??{sessionId:null,declineStreak:0}}async function x(e){let t=h.join(e,`sidecar.lock`),n=Date.now()+12e4;for(;;)try{return g.mkdirSync(t),()=>{try{g.rmdirSync(t)}catch{}}}catch{try{if(Date.now()-g.statSync(t).mtimeMs>9e4){g.rmdirSync(t);continue}}catch{continue}if(Date.now()>n)throw Error(`sidecar lock wait timed out`);await new Promise(e=>setTimeout(e,250))}}function S(e,t,n,r){return[`-p`,r,`--output-format`,`json`,`--model`,`sonnet`,`--effort`,`low`,`--strict-mcp-config`,`--no-chrome`,`--mcp-config`,`{"mcpServers":{}}`,`--settings`,`{"disableClaudeAiConnectors":true}`,n?`--resume`:`--session-id`,t,...i,`--add-dir`,e]}function C(e,t,n,r,i){let a=S(t,n,r,i);return new Promise((t,n)=>{let r=_(`claude`,a,{cwd:e,stdio:[`ignore`,`pipe`,`pipe`]}),i=``,o=``,s=setTimeout(()=>{r.kill(`SIGKILL`),n(Error(`sidecar call timed out`))},12e4);r.stdout.on(`data`,e=>i+=e),r.stderr.on(`data`,e=>o+=e),r.on(`error`,e=>{clearTimeout(s),n(e)}),r.on(`close`,e=>{if(clearTimeout(s),e!==0){n(Error(`sidecar claude exited ${e}: ${o.trim().slice(0,200)}`));return}try{let e=JSON.parse(i);if(e.is_error){n(Error(`sidecar turn errored: ${String(e.result??``).slice(0,200)}`));return}t(String(e.result??``))}catch{n(Error(`sidecar returned unparseable output`))}})})}function w(e){let t=e.match(/\{[^{}]*"decision"[^{}]*\}/);if(!t)return null;try{let e=JSON.parse(t[0]);if(e.decision===`accept`||e.decision===`decline`||e.decision===`escalate`)return{decision:e.decision,reason:String(e.reason??``)}}catch{}return null}async function T(e,t,r){let i=null;try{i=await x(t);let a=b(t);if(a.declineStreak>=3)return{decision:`escalate`,reason:`sidecar decline streak; needs human review`};if(!a.sessionId){let i=v();await C(e,t,i,!1,`You are the approval reviewer for a "coder" background coding task. The task runs inside an OS sandbox; you review only actions that escape it.
2
2
 
3
3
  Rules:
4
4
  - git stays read-only: decline any git write (commit/push/checkout/reset/...).
@@ -1 +1 @@
1
- import{i as e,t}from"./cli-msOzZFXW.js";import{p as n,s as r}from"./output-BKeyLbvt.js";import{n as i,o as a,s as o,t as s}from"./args-DEMOfLz2.js";import c from"node:process";import*as l from"zod/mini";const u=e({name:`runner serve`,help:{usage:`coder runner serve --url <public url> [--token <token>] [--runner-url <url>] [--port <n>] [--name <name>] [--workspace] [--server [url]] [--json]`,summary:`Run tasks on this machine with its own claude and codex logins. Expose the port with any tunnel (cloudflared, ngrok, Tailscale Funnel or a public VS Code port) and pass the tunnel's URL; each start registers the current URL, so a changing tunnel URL is fine. Choose a default with coder runner default. Tasks use their named runner, the agent setting, your default, the workspace default, then the server default.`,flags:[[`--url <public url>`,`the HTTPS address the server reaches this runner at`],[`--token <token>`,`one-use pairing token, --url is the Coder server`],[`--runner-url <url>`,`public tunnel address when pairing, or CODER_RUNNER_URL`],[`--port <n>`,`local port the tunnel forwards to (default 4100)`],[`--name <name>`,`shown in the dashboard (default: this machine's hostname)`],[`--workspace`,`run every member's tasks, not only yours (owners and admins)`],t],examples:[[`cloudflared tunnel --url http://localhost:4100`,`expose the port in one terminal`],[`coder runner serve --url https://abc.trycloudflare.com`,`then serve through it`]]},options:{...s,port:l.optional(l.coerce.number().check(l.int(),l.positive())),url:o,name:o,token:o,"runner-url":o,workspace:i,server:a,yes:i},async run({options:e}){let{serveRunner:t}=await import(`./serve-xMihn4g-.js`).then(e=>e.n),n=await t({...e,runnerUrl:e[`runner-url`]}),r=()=>void n.close().finally(()=>c.exit(0));return c.once(`SIGINT`,r),c.once(`SIGTERM`,r),n},json:({server:e,close:t,...n})=>({ok:!0,...n}),print:e=>c.stdout.write(`Runner ${n.bold(e.name)} serves ${e.server} at ${n.cyan(e.config.url??``)} (${e.scope}), listening on localhost:${e.port}.\n${r([`Tasks run here with this machine's own claude and codex logins`,`Stop with Ctrl-C; the server marks the runner offline`],n,n.cyan)}\n`)});export{u as commandRunnerServe};
1
+ import{i as e,t}from"./cli-IfrPgeYz.js";import{p as n,s as r}from"./output-BKeyLbvt.js";import{n as i,o as a,s as o,t as s}from"./args-DEMOfLz2.js";import c from"node:process";import*as l from"zod/mini";const u=e({name:`runner serve`,help:{usage:`coder runner serve --url <public url> [--token <token>] [--runner-url <url>] [--port <n>] [--name <name>] [--workspace] [--server [url]] [--json]`,summary:`Run tasks on this machine with its own claude and codex logins. Expose the port with any tunnel (cloudflared, ngrok, Tailscale Funnel or a public VS Code port) and pass the tunnel's URL; each start registers the current URL, so a changing tunnel URL is fine. Choose a default with coder runner default. Tasks use their named runner, the agent setting, your default, the workspace default, then the server default.`,flags:[[`--url <public url>`,`the HTTPS address the server reaches this runner at`],[`--token <token>`,`one-use pairing token, --url is the Coder server`],[`--runner-url <url>`,`public tunnel address when pairing, or CODER_RUNNER_URL`],[`--port <n>`,`local port the tunnel forwards to (default 4100)`],[`--name <name>`,`shown in the dashboard (default: this machine's hostname)`],[`--workspace`,`run every member's tasks, not only yours (owners and admins)`],t],examples:[[`cloudflared tunnel --url http://localhost:4100`,`expose the port in one terminal`],[`coder runner serve --url https://abc.trycloudflare.com`,`then serve through it`]]},options:{...s,port:l.optional(l.coerce.number().check(l.int(),l.positive())),url:o,name:o,token:o,"runner-url":o,workspace:i,server:a,yes:i},async run({options:e}){let{serveRunner:t}=await import(`./serve-xMihn4g-.js`).then(e=>e.n),n=await t({...e,runnerUrl:e[`runner-url`]}),r=()=>void n.close().finally(()=>c.exit(0));return c.once(`SIGINT`,r),c.once(`SIGTERM`,r),n},json:({server:e,close:t,...n})=>({ok:!0,...n}),print:e=>c.stdout.write(`Runner ${n.bold(e.name)} serves ${e.server} at ${n.cyan(e.config.url??``)} (${e.scope}), listening on localhost:${e.port}.\n${r([`Tasks run here with this machine's own claude and codex logins`,`Stop with Ctrl-C; the server marks the runner offline`],n,n.cyan)}\n`)});export{u as commandRunnerServe};
@@ -1,8 +1,8 @@
1
- import{t as e}from"./rolldown-runtime-DT7IzrpZ.js";import{$ as t,G as n,H as r,K as i,Mt as a,Q as o,St as s,U as c,Vt as l,_t as u,ct as d,et as f,jt as p,kn as m,nn as h,ut as g,wn as _}from"./dispatch-YW1aqjEg.js";import{i as v,n as y,r as b,u as x}from"./load-DDZfByUe.js";import{c as S,d as C,l as w,n as ee}from"./integrations-B2CavXR1.js";import{c as te}from"./models-DGPrMV51.js";import{o as T}from"./local-B0GiaLV0.js";import{a as E,d as D,f as ne,l as O,n as re,o as ie,p as k,r as ae,s as oe,t as se,u as ce}from"./http-DG54kyx4.js";import{$ as le,$n as A,$t as ue,A as de,An as fe,At as j,B as pe,Bt as me,C as he,Cn as ge,Ct as _e,D as ve,Dn as ye,Dt as M,E as be,En as xe,Et as Se,F as Ce,Fn as we,Ft as Te,G as Ee,Gn as De,Gt as Oe,H as ke,Hn as Ae,Ht as je,I as Me,In as N,It as Ne,J as Pe,Jn as P,Jt as Fe,K as Ie,Kn as Le,Kt as Re,L as ze,Ln as Be,M as Ve,Mn as He,Mt as Ue,N as We,Nn as Ge,Nt as Ke,O as F,On as qe,Ot as Je,P as Ye,Pn as Xe,Pt as Ze,Q as Qe,Qn as I,Qt as $e,R as et,Rn as L,Rt as tt,S as R,Sn as nt,St as rt,T as it,Tn as at,Tt as ot,U as st,Un as ct,Ut as lt,V as ut,Vn as dt,Vt as ft,W as pt,Wn as mt,Wt as ht,X as gt,Xn as _t,Xt as vt,Yn as z,Yt as yt,Z as bt,Zn as xt,Zt as St,_ as Ct,_n as B,_t as wt,an as Tt,at as Et,b as V,bn as H,bt as Dt,c as Ot,cn as kt,ct as At,d as jt,dn as Mt,en as Nt,er as Pt,et as Ft,f as It,g as Lt,gn as Rt,gt as zt,hn as U,ht as Bt,i as Vt,in as Ht,j as Ut,jn as Wt,jt as Gt,k as Kt,kn as qt,kt as Jt,l as Yt,ln as Xt,lt as Zt,m as W,mn as Qt,mt as $t,nn as en,nt as tn,o as nn,on as rn,ot as an,p as G,pt as on,q as sn,qn as cn,qt as ln,r as un,rn as dn,sn as fn,t as pn,tn as mn,tt as hn,un as gn,ut as _n,v as vn,vn as yn,vt as bn,w as xn,wn as Sn,wt as Cn,x as K,xn as wn,xt as Tn,y as En,yn as Dn,yt as On,z as kn,zt as An}from"./store-qp7UE2ES.js";import{n as jn,r as Mn}from"./env-LsVTi18f.js";import{l as Nn}from"./schema-DoNO0dPh.js";import{r as Pn,t as Fn}from"./migrate-DAC6sFgg.js";import{n as In,r as Ln}from"./usage-DR3wWtYD.js";import q from"node:path";import J from"node:process";import*as Y from"zod/mini";import Rn from"node:fs";import{createHash as zn,randomBytes as Bn,randomUUID as Vn}from"node:crypto";import X from"node:fs/promises";import{isDeepStrictEqual as Hn}from"node:util";import Un from"node:http";import{sql as Wn}from"drizzle-orm";async function Gn(e){try{return await X.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function Kn(e){try{return await X.lstat(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function qn(e,t){if(e===t||!await Kn(e))return 0;let n=await Gn(e),r=n.filter(e=>e.isDirectory()).length;if(!await Kn(t))return await m(e,t),r;for(let r of n)await m(q.join(e,r.name),q.join(t,r.name));return await X.rmdir(e),r}async function Jn(e){let t=q.dirname(e),n=q.basename(e);for(let e of await Gn(t)){let r=e.name.startsWith(n)?e.name.slice(n.length):``;if(!e.isFile()||!(r===`.tmp`||/^\.\d+(?:\.[a-f0-9-]{36})?\.tmp$/.test(r)))continue;let i=Number(e.name.slice(n.length+1).split(`.`)[0]);if(Number.isInteger(i)&&i>0)try{process.kill(i,0);continue}catch(e){if(e.code!==`ESRCH`)continue}await X.unlink(q.join(t,e.name)).catch(e=>{if(e.code!==`ENOENT`)throw e})}}async function Yn(e,t){if(await Jn(e),e===t||!await Kn(e))return 0;if(!await Kn(t))return await m(e,t),1;let n=JSON.parse(await X.readFile(e,`utf8`)),r=JSON.parse(await X.readFile(t,`utf8`)),i={...n,...r,...n.rows||r.rows?{rows:{...n.rows,...r.rows}}:{}},a=`${t}.${process.pid}.${Vn()}.tmp`;try{await X.writeFile(a,`${JSON.stringify(i)}\n`,{mode:384,flag:`wx`}),await X.rename(a,t),await X.unlink(e)}finally{await X.rm(a,{force:!0})}return 1}async function Xn(){let e=p(),t=a(`state`),n=p(`archive`),r=p(`flows-archived`),i=p(`usage.json`),o=p(`runner`,`usage.json`),s={from:a(`checkouts`),to:p(`checkouts`)},c={from:a(`update-check.json`),to:p(`update-check.json`)},l={cache:e,tasks:0,flows:0,files:0},u=(await Gn(t)).filter(e=>e.isDirectory()).map(e=>({archive:a(`state`,e.name,`archive`),flows:a(`state`,e.name,`flows-archived`),usage:a(`state`,e.name,`usage.json`),runnerUsage:a(`state`,e.name,`runner`,`usage.json`)}));await Jn(i),await Jn(o);for(let e of u)l.tasks+=await qn(e.archive,n),l.flows+=await qn(e.flows,r),l.files+=await Yn(e.usage,i),l.files+=await Yn(e.runnerUsage,o);return await qn(s.from,s.to),l.files+=await Yn(c.from,c.to),l}async function Zn(e){let t=(e.now??Date.now)(),n=await e.store.list(`runner`);return{online:1+n.filter(({value:e})=>e.lastSeen!==void 0&&t-e.lastSeen<3e5).length,total:1+n.length}}async function Qn(e){let t=(e.now??Date.now)(),n=e.health,{body:r,status:i}=n&&t-n.at<5e3?n:await $n(e);e.health=i===200?{at:n&&t-n.at<5e3?n.at:t,body:r,status:i}:void 0;let a=Math.max(0,t-(e.limits?.startedAt??t))/1e3;return E({...r,uptime:a},i,{"cache-control":`no-store`})}async function $n(e){let t=e.config.store===`postgres`?`down`:`none`,n={online:0,total:0},r=!0;try{if(e.config.store===`postgres`){if(!e.databaseHealth)throw Error(`Database health probe is unavailable`);await e.databaseHealth(),t=`ok`}n=e.healthRunners?await e.healthRunners():await Zn(e)}catch{r=!1,e.config.store===`postgres`&&(t=`down`)}return{body:{ok:r,version:_(),db:t,runners:n},status:r?200:503}}async function er(e){let t=(e.now??Date.now)();if(e.queue.metrics&&!e.local)return{...await e.queue.metrics(e.organizationId,t-864e5),runnersOnline:(await Zn(e)).online,requests:e.limits?.requests??0,rateLimitRejections:e.limits?.rejections??0};let n=await e.queue.list(e.organizationId),r=e.local?[...W(e.local.cwd,!1),...W(e.local.cwd,!0)]:[],i=new Map([...r,...n.map(e=>e.status===`queued`?e:r.find(t=>t.task.id===e.task.id)??e)].map(e=>[e.task.id,e])),a={queued:0,running:0,waiting:0,completed:0,failed:0,cancelled:0},o=0;for(let e of i.values())e.createdAt>=t-864e5&&a[e.status]++,e.status===`queued`&&o++;return{tasks:a,queueDepth:o,runnersOnline:(await Zn(e)).online,requests:e.limits?.requests??0,rateLimitRejections:e.limits?.rejections??0}}async function tr(e,t,n,r){if(!t.auth)return E({mode:tt(t),organization:{id:t.organizationId},server:nr(t)});let i=t.session;return E({mode:tt(t),user:i.user,organization:i.organizations.find(e=>e.id===i.organizationId)??null,organizations:i.organizations,manageMembersUrl:`${t.auth.issuer}/auth/onboarding`,server:nr(t)})}function nr(e){return{name:e.config.name??`Coder`,store:e.config.store,...e.config.publicUrl?{url:e.config.publicUrl}:{},subscriptions:{claude:!!e.config.subscriptions?.claude,codex:!!e.config.subscriptions?.codex}}}async function rr(e,t,n,r){let i=e.headers.get(`content-type`)??``,a=i.includes(`application/json`)?await e.json().catch(()=>void 0):await e.formData().then(e=>Object.fromEntries(e.entries()),()=>void 0);if(!a||typeof a!=`object`)return E({error:`Send the workspace as a form or JSON body.`},400);let o=typeof a.organization==`string`?a.organization:``,s=o?await t.auth.setOrganization(e.headers,o):void 0;if(!s)return E({error:`You are not a member of that workspace.`},403);let{cookies:c,...l}=s,u=i.includes(`application/json`)?E({organization:l}):k(`/dash`,303);for(let e of c)u.headers.append(`set-cookie`,e);return u}async function ir(e,t,n,r){let i=t.session.user.id;n.id;let a=(await e.json().catch(()=>({}))).engine??``;if(!lr.has(a)||!t.config.subscriptions?.[a])return E({error:`Sign in with ${a||`that engine`} is off on this server.`},403);let o=t.runners[t.config.runner];if(!o||o.kind===`github-actions`)return E({error:`Sign-in cannot run on the ${t.config.runner} runner.`},409);let s=`login-${Bn(12).toString(`base64url`)}`,c=Ae(s,t.organizationId,0),l={owner:i,engine:a,state:`starting`,tokenHash:c.hash,runner:o.kind,createdAt:ur(t),expiresAt:ur(t)+cr};await dr(t,s,l);let u;try{let e=await o.start({id:s},{CODER_SERVER:t.config.publicUrl??``,CODER_TASK_TOKEN:c.token,CODER_LOGIN:a}),n=await t.store.patchLogin(s,{handle:e},{tokenHash:l.tokenHash});if(!n)return await o.stop(e).catch(()=>{}),E({error:`This sign-in is gone. Start again.`},409);u=n}catch(e){return await t.store.delete(`login`,s),E({error:e instanceof Error?e.message:String(e)},502)}return E(fr(s,u),201)}async function ar(e,t,n,r){t.session.user.id;let i=n.id??``,a=i&&!i.includes(`/`)?await pr(t,i):void 0;return a?E(fr(i,a)):E({error:`This sign-in is gone. Start again.`},404)}async function or(e,t,n,r){t.session.user.id;let i=n.id??``,a=i&&!i.includes(`/`)?await pr(t,i):void 0;if(!a)return E({error:`This sign-in is gone. Start again.`},404);let o=await e.json().catch(()=>({})),s=typeof o.code==`string`?o.code.trim():``;return a.engine!==`claude`||a.state!==`open`||!s||!await t.store.patchLogin(i,{state:`verifying`,input:L(t.config,s)},{state:`open`,tokenHash:a.tokenHash})?E({error:`This sign-in is not waiting for a code.`},409):E({ok:!0})}async function sr(e,t,n,r){t.session.user.id;let i=n.id??``,a=i&&!i.includes(`/`)?await pr(t,i):void 0;return a?(await t.store.delete(`login`,i),a.handle&&await t.runners[a.runner]?.stop(a.handle).catch(()=>{}),E({ok:!0})):E({error:`This sign-in is gone. Start again.`},404)}const cr=6e5,lr=new Set([`claude`,`codex`]),ur=e=>(e.now??Date.now)();function dr(e,t,n){return e.store.put(`login`,t,n,{ttlMs:Math.max(1,n.expiresAt-ur(e))})}function fr(e,t){return{id:e,engine:t.engine,state:t.state,expiresAt:t.expiresAt,...t.url?{url:t.url}:{},...t.code?{code:t.code}:{},...t.error?{error:t.error}:{},...t.label?{label:t.label}:{}}}async function pr(e,t){let n=await e.store.get(`login`,t);return n&&n.owner===e.session?.user.id?n:void 0}async function mr(e,t,n,r){let i=n.id,a=t.callbackLogin,o=Date.now()+25e3;for(;!a.input&&Date.now()<o&&!e.signal.aborted;){await new Promise(e=>setTimeout(e,250));let e=await t.store.get(`login`,i);if(!e)return new Response(`Unauthorized`,{status:401});a=e}if(!a.input)return E({});let s=await t.store.patchLogin(i,{input:null},{input:a.input,tokenHash:a.tokenHash});return E(s?{code:N(t.config,a.input)}:{})}async function hr(e,t,n,r){n.id;let i=t.callbackLogin;return E({engine:i.engine})}async function gr(e,t,n,r){let i=n.id,a=t.callbackLogin,o=await e.json().catch(()=>({}));if(a.state===`done`||a.state===`failed`)return E({ok:!0});let s={state:[`starting`,`open`,`verifying`],tokenHash:a.tokenHash};if(typeof o.error==`string`)return await t.store.patchLogin(i,{state:`failed`,error:o.error.slice(0,500)},s),E({ok:!0});let c=o.result?.env;if(c){let e=a.engine===`claude`?`CLAUDE_CODE_OAUTH_TOKEN`:`CODEX_AUTH_JSON`;if(Object.keys(c).join()!==e||typeof c[e]!=`string`)return E({error:`Invalid sign-in result`},400);let n=`${a.engine}-subscription`,r=o.result?.account;return await t.store.completeLogin(i,a.tokenHash,n,{...Be(t.config,{env:c}),engine:a.engine,createdAt:(t.now??Date.now)(),...r?.email||r?.plan?{account:{...typeof r.email==`string`?{email:r.email}:{},...typeof r.plan==`string`?{plan:r.plan}:{}}}:{}})?E({ok:!0}):E({error:`This sign-in changed. Try again.`},409)}let l={...typeof o.url==`string`&&/^https:\/\//.test(o.url)?{url:o.url}:{},...typeof o.code==`string`?{code:o.code.slice(0,64)}:{}};return(a.state===`starting`?await t.store.patchLogin(i,{...l,state:`open`},{state:`starting`,tokenHash:a.tokenHash})??await t.store.patchLogin(i,l,{...s,state:[`open`,`verifying`]}):await t.store.patchLogin(i,l,s))?E({ok:!0}):E({error:`This sign-in changed. Try again.`},409)}async function _r(e,t,n,r){let i=n.id,a=t.operatorApp??!1;if(!/^[a-z0-9_-]+$/.test(r.pathname.split(`/`)[2]))return;let o=a?`*`:t.session?.user.id??`anonymous`,s=t.integrations[i];if(!s)return P(`Unknown integration "${i}"; run coder agent integrations list to see them`,404);let c=t.config.publicUrl;if(!c)return P(`PUBLIC_URL is not set on this server; set it to the address platforms should call and restart`,400);t.fetch,t.now?.();let l=z(r.searchParams);if(!l)return P(`Setup link is missing or malformed; start again from the agent's Platforms tab`,400);if(!l.definition.integrations[i])return P(`This agent declares no ${i} integration in its agent.json`,400);if(l.state.public&&!a)return P(`Only the server operator creates public apps`,403);let u=De(i,l.state),d=l.state.tx?await I(t,l.state.tx,`create`,o)===u?l.state.tx:void 0:await A(t,`create`,o,u);if(!d)return P(`This app creation link is invalid, expired, or already used`,403);let f={...l.state,tx:d};return s.app.createPage({publicUrl:c,state:f,definition:l.definition,encodedState:T(f)})}async function vr(e,t,n,r){let i=n.id,a=t.operatorApp??!1;if(!/^[a-z0-9_-]+$/.test(r.pathname.split(`/`)[2]))return;let o=a?`*`:t.session?.user.id??`anonymous`,s=t.integrations[i];if(!s)return P(`Unknown integration "${i}"; run coder agent integrations list to see them`,404);let c=t.config.publicUrl;if(!c)return P(`PUBLIC_URL is not set on this server; set it to the address platforms should call and restart`,400);let l=t.fetch??fetch,u=t.now?.()??Date.now(),d=ae(r.searchParams.get(`state`)),f=z(r.searchParams)??(d&&z(new URLSearchParams(Object.entries(d).filter(([,e])=>e!==void 0))))??void 0;if(!f)return P(`Setup state was lost between the platform and this server; start again`,400);if(!f.state.tx||!await xt(t,f.state.tx,`create`,o,De(i,f.state)))return P(`This app creation link is invalid, expired, or already used`,403);let p=await s.app.createCallback(e,{publicUrl:c,...f,fetch:l}).catch(e=>P(`Creating the ${i} app failed: ${e instanceof Error?e.message:e}`,400));if(p instanceof Response)return p;let m={id:`${i}:${p.platformAppId}`,integration:i,agent:f.state.agent,name:p.name,...f.state.repo?{agentsRepo:f.state.repo}:{},...f.state.repo?{branch:f.state.branch??`main`}:{},...a?{builtin:!0}:{},credentials:L(t.config,p.credentials),createdAt:u};if(await t.store.put(`app`,m.id,m),a)return P(`Created ${p.name}. Every workspace on this server can now connect it from its dashboard.`);let h=await A(t,`install`,o,m.id),g=`/dash/agents/${encodeURIComponent(m.agent)}/platforms`;return k(`${c}/install/${i}?app=${encodeURIComponent(m.id)}&state=${T({tx:h,back:g})}`)}async function yr(e,t,n,r){let i=n.id,a=t.operatorApp??!1;if(!/^[a-z0-9_-]+$/.test(r.pathname.split(`/`)[2]))return;let o=a?`*`:t.session?.user.id??`anonymous`,s=t.integrations[i];if(!s)return P(`Unknown integration "${i}"; run coder agent integrations list to see them`,404);let c=t.config.publicUrl;if(!c)return P(`PUBLIC_URL is not set on this server; set it to the address platforms should call and restart`,400);let l=t.fetch??fetch,u=t.now?.()??Date.now(),d=new URLSearchParams(await e.clone().text()),f=ae(r.searchParams.get(`state`)),p=z(r.searchParams)??(f&&z(new URLSearchParams(Object.entries(f).filter(([,e])=>e!==void 0))))??(d&&z(d));if(!p)return P(`Setup state was lost between the platform and this server; start again`,400);if(!p.state.tx||!await xt(t,p.state.tx,`create`,o,De(i,p.state)))return P(`This app creation link is invalid, expired, or already used`,403);let m=await s.app.createCallback(e,{publicUrl:c,...p,fetch:l}).catch(e=>P(`Creating the ${i} app failed: ${e instanceof Error?e.message:e}`,400));if(m instanceof Response)return m;let h={id:`${i}:${m.platformAppId}`,integration:i,agent:p.state.agent,name:m.name,...p.state.repo?{agentsRepo:p.state.repo}:{},...p.state.repo?{branch:p.state.branch??`main`}:{},...a?{builtin:!0}:{},credentials:L(t.config,m.credentials),createdAt:u};if(await t.store.put(`app`,h.id,h),a)return P(`Created ${m.name}. Every workspace on this server can now connect it from its dashboard.`);let g=await A(t,`install`,o,h.id),_=`/dash/agents/${encodeURIComponent(h.agent)}/platforms`;return k(`${c}/install/${i}?app=${encodeURIComponent(h.id)}&state=${T({tx:g,back:_})}`)}async function br(e,t,n,r){let i=n.id,a=t.operatorApp??!1;if(!/^[a-z0-9_-]+$/.test(r.pathname.split(`/`)[2]))return;let o=a?`*`:t.session?.user.id??`anonymous`,s=t.integrations[i];if(!s)return P(`Unknown integration "${i}"; run coder agent integrations list to see them`,404);let c=t.config.publicUrl;if(!c)return P(`PUBLIC_URL is not set on this server; set it to the address platforms should call and restart`,400);t.fetch,t.now?.();let l=ae(r.searchParams.get(`state`)),u=r.searchParams.get(`app`),d=l?.tx?await I(t,l.tx,`install`,o):void 0;if(!d||u&&u!==d)return P(`This installation link is invalid, expired, or already used`,403);let f=await t.store.get(`app`,u??d);if(!f)return P(`This app is not known to this server; create it first`,400);let p=N(t.config,f.credentials);return k(s.app.installUrl(f,p,{publicUrl:c,state:r.searchParams.get(`state`)??T({})}))}async function xr(e,t,n,r){let i=n.id,a=t.operatorApp??!1;if(!/^[a-z0-9_-]+$/.test(r.pathname.split(`/`)[2]))return;let o=a?`*`:t.session?.user.id??`anonymous`,s=t.integrations[i];if(!s)return P(`Unknown integration "${i}"; run coder agent integrations list to see them`,404);let c=t.config.publicUrl;if(!c)return P(`PUBLIC_URL is not set on this server; set it to the address platforms should call and restart`,400);let l=t.fetch??fetch,u=t.now?.()??Date.now(),d=ae(r.searchParams.get(`state`)),f=r.searchParams.get(`app`),p=d?.tx?await I(t,d.tx,`install`,o):void 0;if(!p||f&&f!==p||!await xt(t,d.tx,`install`,o,p))return P(`This installation link is invalid, expired, or already used`,403);let m=await t.store.get(`app`,f??p),h=d?.link?await t.store.get(`installation`,d.link):void 0,g=m??(h&&await cn(t,h,i));if(!g)return d&&!d.link?P(`Connected.`):P(`This install does not match any app on this server; create the app first`,400);let _=N(t.config,g.credentials),v=await s.app.installCallback(e,{app:g,credentials:_,publicUrl:c,fetch:l,connect:mt(t,g,c)}).catch(e=>P(e instanceof Error?e.message:String(e),400));if(v instanceof Response)return v;let y=`${g.id}:${v.platformInstallId}`,b=t.session;v.user&&b&&t.auth&&await t.auth.link(b.user,i,v.user.id,{organizations:b.organizations.map(e=>e.id),...v.user.token?{token:L(t.config,v.user.token)}:{}});let x=await t.store.get(`installation`,y),S={...x,id:y,app:g.id,integration:i,account:v.account??x?.account??h?.account??{login:`unknown`},...v.token?{token:L(t.config,v.token)}:{},...v.installer?{installer:v.installer}:{},createdAt:x?.createdAt??u};delete S.deletedAt;let C=h&&!h.deletedAt?h:void 0;C&&(S=Le(S,C.integration,C.id));try{await t.store.put(`installation`,y,S)}catch{return P(`This ${i} installation is already connected to another workspace; disconnect it there first`,409)}if(C&&await t.store.put(`installation`,C.id,Le(C,i,y)),s.renew){let e=await(await import(`./store-qp7UE2ES.js`).then(e=>e.Y)).renewInstallation({...t,fetch:l},g,v.platformInstallId).then(()=>void 0,e=>e instanceof Error?e.message:String(e));if(e)return P(`Connected, but ${i} did not start sending events yet. ${e}. Coder tries again within the hour.`,502)}let w=ct(d?.back);return w?k(`${c.replace(/\/$/,``)}${w}`):v.response}const Z=(e,t=200)=>w(`<title>Coder</title><p>${S(e)}</p>`,t);function Sr(e,t,n){return n&&t.organizations.some(e=>e.id===n)?{...dt(e,n),session:t}:void 0}async function Cr(e,t){let n=await e.store.get(`installation`,t);return n&&!n.deletedAt?e.store.get(`app`,n.app):void 0}async function wr(e,t,n,r){let i=t.linkContext,a=i.session,o=e=>{let t=Pt(i,e);return t&&a.organizations.some(e=>e.id===t)?{...dt(i,t),session:a}:i},s=r.searchParams.get(`token`)??``,c=o(s);if(await I(c,s,`link`,a.user.id))return await gn(e,void 0,t.dashboardHosts)??new Response(`UI is not built`,{status:503});let l=await _t(c,s,`link-start`,a.user.id);if(!l)return new Response(`This link is invalid or has expired.`,{status:400});let u=await A(c,`link`,a.user.id,l,3e5);return k(`/connect?token=${encodeURIComponent(u)}`)}async function Tr(e,t,n,r){let i=t.linkContext,a=i.session,o=e=>{let t=Pt(i,e);return t&&a.organizations.some(e=>e.id===t)?{...dt(i,t),session:a}:i},s=await e.json().catch(()=>({})),c=typeof s.token==`string`?await _t(o(s.token),s.token,`link`,a.user.id):void 0;if(!c)return E({error:`This link is invalid or has expired.`},400);let l=JSON.parse(c);return await t.auth.link(a.user,l.platform,l.platformUserId,{organizations:a.organizations.map(e=>e.id)})===`taken`?E({error:`That platform account is connected to someone else.`},409):E({ok:!0,...l})}async function Er(e,t,n,r){let i=t.integrations[n.integration].auth.user,a=t.config.publicUrl,o=t.linkContext.session,s=r.searchParams.get(`installation`)??``,c=Sr(t,o,s?await t.installationOrganization?.(s):void 0);if(!c)return Z(`Only members of the workspace this agent works for can link here.`,403);let l=await Cr(c,s);if(!l)return Z(`This installation is no longer connected.`,404);let u=await A(c,`link-oauth`,o.user.id,s);return k(i.authorizeUrl(N(t.config,l.credentials),{publicUrl:a,state:u}))}async function Dr(e,t,n,r){let i=t.integrations[n.integration],a=i.auth.user,o=t.config.publicUrl,s=t.linkContext.session,c=r.searchParams.get(`state`)??``,l=Sr(t,s,Pt(t,c)),u=l&&await _t(l,c,`link-oauth`,s.user.id),d=l&&u?await Cr(l,u):void 0;if(!l||!d)return Z(`This link is invalid or has expired.`,400);let f=await a.exchange(e,N(t.config,d.credentials),{publicUrl:o,fetch:t.fetch??fetch}).catch(e=>e instanceof Error?e:Error(String(e)));return f instanceof Error?Z(f.message,400):await t.auth.link(s.user,i.id,f.id,{organizations:s.organizations.map(e=>e.id),...f.token?{token:L(t.config,f.token)}:{}})===`taken`?Z(`That ${i.id} account is connected to someone else.`,409):Z(`Linked ${f.login??f.id} on ${i.id} to your Coder account. Mention the agent again to start.`)}const Or=Y.object({installation:Y.string().check(Y.minLength(1)),integration:Y.string().check(Y.minLength(1)),token:Y.string().check(Y.minLength(1)),account:Y.optional(Y.string())});async function kr(e,t){let n;try{n=await e.json()}catch{return new Response(`Invalid JSON`,{status:400})}let r=Or.safeParse(n);if(!r.success)return new Response(`Invalid connection`,{status:400});let{installation:i,integration:a,token:o,account:s}=r.data,c=await t.store.get(`installation`,i);if(!c||c.deletedAt)return new Response(`Unknown installation`,{status:404});let l={kind:`oauth`,token:L(t.config,o),...s?{account:s}:{}};return await Vt(t.store,`installation`,i,{connections:{...c.connections,[a]:l}}),E({ok:!0})}async function Ar(e,t,n,r){let i=await t.store.get(`app`,n);if(!i)return E({error:`Unknown app`},404);let a=t.config.publicUrl;if(!a)return E({error:`PUBLIC_URL is not set on this server`},400);let o=await A(t,`install`,t.session?.user.id??`anonymous`,i.id),s=T({tx:o,...r?{back:r}:{}});return E({url:`${a.replace(/\/$/,``)}/install/${i.integration}?app=${encodeURIComponent(i.id)}&state=${s}`})}async function jr(e,t,n,r){let i=r.searchParams.get(`agent`),a=t.serverOrganizationId,[o,s]=await Promise.all([t.store.list(`app`),a!==void 0&&a!==t.organizationId&&t.scope?t.scope(a).store.list(`app`).then(e=>e.map(({id:e,value:t})=>({id:e,value:{...t,builtin:!0}}))):[]]),c=[...o,...s];return E(c.filter(({value:e})=>!i||e.agent===i).map(({id:e,value:t})=>{let{credentials:n,...r}=t;return{id:e,value:r}}))}async function Mr(e,t,n,r){let i=r.searchParams.get(`agent`),[a,o]=await Promise.all([t.store.list(`installation`),i?t.store.list(`app`):[]]),s=new Set(o.filter(({value:e})=>e.agent===i).map(({id:e})=>e));return E(a.filter(({value:e})=>!i||s.has(e.app)).map(({id:e,value:t})=>{let{token:n,connections:r,...i}=t;return{id:e,value:i}}))}function Nr(e){return E(Object.values(e.integrations).map(e=>({id:e.id,name:e.name,brand:e.brand,description:e.description,installLabel:e.installLabel??`Connect ${e.id}`,organizationApps:e.organizationApps===!0,events:Object.fromEntries(Object.entries(e.events).map(([e,{description:t,noisy:n,addressed:r}])=>[e,{description:t,...n?{noisy:n}:{},...r?{addressed:r}:{}}])),presets:e.tools.presets,repositories:!!e.repos})))}async function Pr(e){let t=new Map;for(let{value:n}of await e.store.list(`installation`)){let r=e.integrations[n.integration];if(n.deletedAt||!r?.repos)continue;let i=await e.store.get(`app`,n.app);if(i)try{let a=await r.auth.token(n.token?{...n,token:N(e.config,n.token)}:n,N(e.config,i.credentials));for(let e of await r.repos.list(n,a))t.has(e)||t.set(e,{repo:e,integration:r.id})}catch{}}return E([...t.values()].sort((e,t)=>e.repo.localeCompare(t.repo)))}async function Fr(e,t){let n=(await e.store.list(`installation`)).filter(({value:t})=>!t.deletedAt&&e.integrations[t.integration]?.repos),r=new Map((await un(e.store,n.map(({value:e})=>e.app))).map(({id:e,value:t})=>[e,t]));for(let{value:i}of n){let n=e.integrations[i.integration];if(i.deletedAt||!n?.repos)continue;let a=r.get(i.app);if(!(!a||a.integration!==n.id))try{let r=i.token?{...i,token:N(e.config,i.token)}:i,o=await n.auth.token(r,N(e.config,a.credentials));if((await n.repos.list(r,o)).includes(t))return{contents:n,token:o,app:a,installation:i}}catch{}}}async function Ir(e,t,n){let r=await Fr(e,t);if(!r)return E({error:`No installed app can read ${t}`},400);let i=await r.contents.repos.listDir(t,Ee,r.token,n).catch(()=>[]),a=await Promise.all(i.map(async i=>{let a=await r.contents.repos.readFile(t,`${Ee}/${i}/agent.json`,r.token,n).catch(()=>void 0);if(a===void 0)return;let o={};try{o=JSON.parse(a)}catch{}let s=await H(e.store,i),c=s?.source===`repo`&&s.repo===t,l=c?await wn(e.store,i):void 0;return{id:i,name:typeof o.name==`string`?o.name:i,...typeof o.description==`string`?{description:o.description}:{},...c?{version:s.currentVersion,...l?.source?{commit:l.source.commit}:{}}:{},...s&&!c?{taken:!0}:{}}}));return E({repo:t,agents:a.filter(Boolean)})}async function Lr(e,t,n,r){let i=r.searchParams.get(`repo`);return i?Ir(t,i,r.searchParams.get(`ref`)||`HEAD`):E({error:`repo is required`},400)}async function Rr(e,t,n,r){let i=await e.json().catch(()=>void 0),a=i?.agents;if(typeof i?.repo!=`string`||i.ref!==void 0&&typeof i.ref!=`string`||a!==void 0&&!(Array.isArray(a)&&a.every(e=>typeof e==`string`)))return E({error:`repo is required, ref must be a string and agents a list of ids`},400);try{let e=await Fr(t,i.repo);if(!e)return E({error:`No installed app can read ${i.repo}`},400);let n=i.ref??`HEAD`,r=a??await e.contents.repos.listDir(i.repo,`.coder/agents`,e.token,n);for(let e of r){let n=await H(t.store,e);if(n&&(n.source!==`repo`||n.repo!==i.repo))return E({error:`Agent id "${e}" is already taken`},409)}let o=await Ie(t.store,e.contents,i.repo,n,e.token,(t.now??Date.now)(),{slugs:r});return await Pe(t,o),E({imported:o.map(e=>e.agent)})}catch(e){return E({error:e instanceof Error?e.message:String(e)},400)}}async function zr(e,t,n,r){if(t.source!==`repo`||!t.repo)return;let i=(await(r??e.store.list(`app`))).find(({value:e})=>e.agent===t.id&&e.agentsRepo===t.repo)?.value;return((i&&e.integrations[i.integration])??Object.values(e.integrations).find(e=>e.repos))?.repos?.url(t.repo,t.path,i?.branch??n?.commit)}async function Br(e,t,n){let r=await yn(e.store,t);return await ge(e.store,n,t,r)?yn(e.store,t):r}async function Q(e,t){let n=(e.now??Date.now)(),r=e.local?await hn(e.store,e.local.cwd,e.integrations,t).catch(()=>void 0):void 0;return{now:n,local:r,loadCurrent:()=>r?Promise.resolve(r.find(({record:e})=>e.id===t)??{}):Br(e,t,n)}}async function Vr(e,t,n,r){let i=n.slug;if(n.version&&Number(n.version),n.version&&!/^\d+$/.test(r.pathname.split(`/`).at(-1)))return O();let{now:a,local:o,loadCurrent:s}=await Q(t,i);if(!o&&t.store.listAgentSummaries&&(await Sn(t.store,a),ne(r)))return E(await Kr(t,r));let c=o??(t.store.listAgentSummaries?await t.store.listAgentSummaries():await Dn(t.store));if(!o&&!t.store.listAgentSummaries&&await Sn(t.store,a,c)&&(c=await Dn(t.store)),ne(r))return E(await Kr(t,r,c));let l;return E(await Promise.all(c.map(async({record:e,version:n})=>{e.source===`repo`&&e.repo&&(l??=t.store.list(`app`));let r=await zr(t,e,n,l);return{...e,definition:n?.definition,...r?{sourceUrl:r}:{}}})))}async function Hr(e,t,n,r){let i=n.slug;if(n.version&&Number(n.version),n.version&&!/^\d+$/.test(r.pathname.split(`/`).at(-1)))return O();let{now:a,local:o,loadCurrent:s}=await Q(t,i),c=D(r,10,50),l=re(r),[u,d]=await Promise.all([o?s().then(e=>e.record):H(t.store,i),o?Promise.resolve(o.flatMap(({version:e})=>e?[{value:e}]:[])):t.store.listVersions?.(i,c+1,l)]);return u?E(await qr(t,u,c,l??u.currentVersion+1,d)):E({error:`No agent named "${i}"`},404)}async function Ur(e,t,n,r){let i=n.slug,a=n.version?Number(n.version):void 0;if(n.version&&!/^\d+$/.test(r.pathname.split(`/`).at(-1)))return O();let{now:o,local:s,loadCurrent:c}=await Q(t,i),l=s?s.find(({version:e})=>e?.version===a)?.version:await wn(t.store,i,a);return l?E(l):E({error:`No version ${a} for agent "${i}"`},404)}async function Wr(e,t,n,r){let i=n.slug;if(n.version&&Number(n.version),n.version&&!/^\d+$/.test(r.pathname.split(`/`).at(-1)))return O();let{now:a,local:o,loadCurrent:s}=await Q(t,i),c=r.searchParams.get(`versions`)!==`0`,l=r.searchParams.get(`content`)!==`0`,[{record:u,version:d},f]=await Promise.all([!l&&!o&&t.store.listAgentSummaries&&!v()[i]?t.store.listAgentSummaries({slug:i}).then(e=>e[0]??{}):s(),c?o?o.flatMap(({version:e})=>e?[{value:e}]:[]):t.store.listVersions?t.store.listVersions(i):t.store.list(`agentversion`,{prefix:`${i}:`}):[]]);if(!u)return E({error:`No agent named "${i}"`},404);let p=f.map(({value:e})=>{let{systemPrompt:t,files:n,...r}=e;return r}),m=await zr(t,u,d);return E({...u,...d?{definition:d.definition,...l&&`systemPrompt`in d?{systemPrompt:d.systemPrompt,...d.files?{files:d.files}:{}}:{}}:{},...m?{sourceUrl:m}:{},...c?{versions:p}:{}})}const Gr={builtin:`builtin`,dashboard:`upload`,repository:`repo`};async function Kr(e,t,n){let r=D(t,24,100),i=re(t),a=t.searchParams.get(`q`)?.trim().toLowerCase(),o=Gr[t.searchParams.get(`type`)??``],s=t.searchParams.get(`platform`),c=t.searchParams.get(`connect`)===`1`,l=e.serverOrganizationId,u=e.store.list(`app`),[d,f,p,m]=await Promise.all([u,e.store.list(`installation`),c&&l!==void 0&&l!==e.organizationId&&e.scope?e.scope(l).store.list(`app`):[],n?n.filter(({record:e})=>(!i||e.id>i)&&(!o||e.source===o)&&(!a||[e.id,e.name,e.description,e.repo].some(e=>e?.toLowerCase().includes(a)))):e.store.listAgentSummaries({after:i,source:o,q:a,platform:s??void 0,limit:r+1})]),h=new Set(f.filter(({value:e})=>!e.deletedAt).map(({value:e})=>e.app)),g=(e,t)=>{let n=d.filter(({value:n})=>n.agent===e&&n.integration===t);return n.length?n.some(({value:e})=>h.has(e.id))?`installed`:`created`:`none`},_=[];for(let{record:e,version:t}of m){let n=Object.keys(t?.definition?.integrations??{}).sort();if(!(s&&!n.includes(s))&&(_.push({record:e,version:t,ids:n}),_.length>r))break}let v=ce(_,r,e=>e.record.id);return{...v,...c?{connectable:[...d,...p.map(e=>({...e,value:{...e.value,builtin:!0}}))].filter(({value:e})=>e.builtin&&!h.has(e.id)).map(({value:e})=>({id:e.id,integration:e.integration}))}:{},items:await Promise.all(v.items.map(async({record:t,version:n,ids:r})=>{let i=await zr(e,t,n,u);return{...t,definition:n?.definition,...i?{sourceUrl:i}:{},platforms:r.map(e=>({id:e,state:g(t.id,e)}))}}))}}async function qr(e,t,n,r,i){let a=r-n-2,o=(i??await e.store.list(`agentversion`,{prefix:`${t.id}:`,...a>0?{after:ye(t.id,a)}:{},limit:n+1})).map(({value:e})=>{let{systemPrompt:t,files:n,definition:r,...i}=e;return i}).filter(e=>e.version<r).reverse();return ce(o,n,e=>e.version)}function Jr(e){if(!e||Array.isArray(e)||typeof e!=`object`)return!1;let t=Object.entries(e);if(t.length>100)return!1;let n=0;for(let[e,r]of t){if(typeof r!=`string`||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)||e.split(`/`).includes(`..`)||e===`agent.json`||e===`system.md`)return!1;n+=Buffer.byteLength(e)+Buffer.byteLength(r)}return n<=262144}async function Yr(e,t,n,r){let i=n.slug;if(n.version&&Number(n.version),n.version&&!/^\d+$/.test(r.pathname.split(`/`).at(-1)))return O();let{now:a,local:o,loadCurrent:s}=await Q(t,i),c=await e.json().catch(()=>void 0);try{let e=x({[i]:c})[i];if(!e||typeof e!=`object`)throw Error(`settings must be an object`);let{record:n,version:r}=await s();if(!n||!r)throw Error(`No agent named "${i}".`);return xe({...n,settings:void 0},r,e,t.integrations),t.local?(await ve(t,t=>{t.agents={...t.agents,[i]:e}}),await hn(t.store,t.local.cwd,t.integrations),E(await H(t.store,i))):E(await at(t.store,i,e,(t.now??Date.now)()))}catch(e){return E({error:e instanceof Error?e.message:String(e)},400)}}async function Xr(e,t,n,r){let i=n.slug;if(n.version&&Number(n.version),n.version&&!/^\d+$/.test(r.pathname.split(`/`).at(-1)))return O();let{now:a,local:o,loadCurrent:s}=await Q(t,i),{record:c}=await s();if(!c)return E({error:`No agent named "${i}"`},404);if(c.source===`builtin`)return E({error:`Built-in agents cannot be deleted.`},400);if(t.local&&!await Ft(t.local.cwd,t.integrations,i))return E({error:`Delete .coder/agents/${i} in the repo`},409);for(let{id:e}of await t.store.list(`agentversion`,{prefix:`${i}:`}))await t.store.delete(`agentversion`,e);return await t.store.delete(`agent`,i),E({ok:!0})}async function Zr(e,t,n,r){let i=n.slug;if(n.version&&Number(n.version),n.version&&!/^\d+$/.test(r.pathname.split(`/`).at(-1)))return O();let{now:a,local:o,loadCurrent:s}=await Q(t,i),c=await e.json().catch(()=>void 0);if(!c||typeof c.systemPrompt!=`string`||c.files!==void 0&&!Jr(c.files)||c.name!==void 0&&typeof c.name!=`string`||c.description!==void 0&&typeof c.description!=`string`)return E({error:`definition and systemPrompt are required; files must contain strings`},400);try{b([i]);let[e]=y({definitions:{[i]:{json:c.definition,builtin:!1}},usage:void 0},t.integrations);if(!e)throw Error(`No agent named "${i}".`);let n=t.local?await H(t.store,i):void 0,r=t.local&&n?await wn(t.store,i):void 0,a=c.files;t.local&&(await tn(t.local.cwd,t.integrations,i,{definition:{...c.definition,...c.name===void 0?{}:{name:c.name},...c.description===void 0?{}:{description:c.description}},systemPrompt:c.systemPrompt,...a?{files:a}:{}}),await hn(t.store,t.local.cwd,t.integrations));let o=t.local?void 0:await nt(t.store,{id:i,name:c.name??e.name,description:c.description??e.definition.description,source:`upload`,definition:e.definition,systemPrompt:c.systemPrompt,files:a,importedFrom:`upload`},(t.now??Date.now)()),s=o?.version??await wn(t.store,i),l=o?.unchanged??Hn(r&&{...r,createdAt:0},{...s,createdAt:0});await Pe(t,[s]);let u=o?.record??await H(t.store,i);return E({...u,definition:s.definition,version:s.version,unchanged:l})}catch(e){return E({error:e instanceof Error?e.message:String(e)},400)}}async function Qr(e,t,n,r){let i=n.id,a=Number(r.searchParams.get(`after`)??-1),o=Number.isFinite(a)?a:-1;r.searchParams.has(`limit`)&&D(r,500,2e3);let s=await t.store.get(`task`,i);if(!s||t.local&&s.handle?.startsWith(`cli:`)&&s.task.flow==="default"){let n=s?.task.cwd??t.local?.cwd;if(!n||!G(n,i,!1))return E({error:`No task "${i}"`},404);{let r=Number(e.headers.get(`last-event-id`)??o);return oi(e,t,`cli:${n}:${i}`,Number.isFinite(r)?r:o,async e=>{let t=G(n,i);if(t)return{status:t,lines:It(n,i,e,500),pendingResult:$r(n,t,!t.result)}})}}let c=Number(e.headers.get(`last-event-id`)??o),l=t.statementTimeout??((e,t)=>t());return oi(e,t,i,Number.isFinite(c)?c:o,e=>l(ii,async()=>{let n=await t.store.get(`task`,i);if(!n)return;let r=n.task.runner===`github-actions`&&n.handle,a=r&&F.has(n.status)?(await(await Xe(t,n.task))?.status(n.handle).catch(()=>void 0))?.state===`running`:!1;return{status:n,lines:([`running`,`waiting`].includes(n.status)||r)&&n.handle?await yt(t,n,e,500).catch(()=>vt(t.store,i,e,500)):await vt(t.store,i,e,500),pendingLogs:a}}))}function $r(e,t,n=!1){if(!F.has(t.status)||t.error||t.status===`cancelled`)return!1;let r=l(e,t.task.id),i=Math.max(t.finishedAt??0,Date.parse(r?.resumedAt??r?.createdAt??``)||0);return n||(Rn.statSync(q.join(h(e,t.task.id),`result.json`),{throwIfNoEntry:!1})?.mtimeMs??0)<i}const ei=1e3,$=3e4;function ti(e,t,n,r){let i=[...new Set((r.searchParams.get(`tasks`)??``).split(`,`).filter(Boolean))].slice(0,100),a=Date.now(),o=t.taskWatcher??new ri,s=o.tag(t),[c,l]=(e.headers.get(`last-event-id`)??``).split(`-`),u=Number(c),d=u>0&&`-${l}`===s,f=d?Math.min(Math.max(u,a-29e4),a):a,p=u>0&&(!d||u<f)?`event: reset
1
+ import{t as e}from"./rolldown-runtime-DT7IzrpZ.js";import{$ as t,G as n,H as r,K as i,Mt as a,Q as o,St as s,U as c,Vt as l,_t as u,ct as d,et as f,jt as p,kn as m,nn as h,ut as g,wn as _}from"./dispatch-YW1aqjEg.js";import{i as v,n as y,r as b,u as x}from"./load-DDZfByUe.js";import{c as S,d as C,l as w,n as ee}from"./integrations-B2CavXR1.js";import{c as te}from"./models-DGPrMV51.js";import{o as T}from"./local-B0GiaLV0.js";import{a as E,d as D,f as ne,l as O,n as re,o as ie,p as k,r as ae,s as oe,t as se,u as ce}from"./http-DG54kyx4.js";import{$ as le,$n as A,$t as ue,A as de,An as fe,At as j,B as pe,Bt as me,C as he,Cn as ge,Ct as _e,D as ve,Dn as ye,Dt as M,E as be,En as xe,Et as Se,F as Ce,Fn as we,Ft as Te,G as Ee,Gn as De,Gt as Oe,H as ke,Hn as Ae,Ht as je,I as Me,In as N,It as Ne,J as Pe,Jn as P,Jt as Fe,K as Ie,Kn as Le,Kt as Re,L as ze,Ln as Be,M as Ve,Mn as He,Mt as Ue,N as We,Nn as Ge,Nt as Ke,O as F,On as qe,Ot as Je,P as Ye,Pn as Xe,Pt as Ze,Q as Qe,Qn as I,Qt as $e,R as et,Rn as L,Rt as tt,S as R,Sn as nt,St as rt,T as it,Tn as at,Tt as ot,U as st,Un as ct,Ut as lt,V as ut,Vn as dt,Vt as ft,W as pt,Wn as mt,Wt as ht,X as gt,Xn as _t,Xt as vt,Yn as z,Yt as yt,Z as bt,Zn as xt,Zt as St,_ as Ct,_n as B,_t as wt,an as Tt,at as Et,b as V,bn as H,bt as Dt,c as Ot,cn as kt,ct as At,d as jt,dn as Mt,en as Nt,er as Pt,et as Ft,f as It,g as Lt,gn as Rt,gt as zt,hn as U,ht as Bt,i as Vt,in as Ht,j as Ut,jn as Wt,jt as Gt,k as Kt,kn as qt,kt as Jt,l as Yt,ln as Xt,lt as Zt,m as W,mn as Qt,mt as $t,nn as en,nt as tn,o as nn,on as rn,ot as an,p as G,pt as on,q as sn,qn as cn,qt as ln,r as un,rn as dn,sn as fn,t as pn,tn as mn,tt as hn,un as gn,ut as _n,v as vn,vn as yn,vt as bn,w as xn,wn as Sn,wt as Cn,x as K,xn as wn,xt as Tn,y as En,yn as Dn,yt as On,z as kn,zt as An}from"./store-Cxc2GYyj.js";import{n as jn,r as Mn}from"./env-LsVTi18f.js";import{l as Nn}from"./schema-DoNO0dPh.js";import{r as Pn,t as Fn}from"./migrate-DAC6sFgg.js";import{n as In,r as Ln}from"./usage-Bw7fQeFC.js";import q from"node:path";import J from"node:process";import*as Y from"zod/mini";import Rn from"node:fs";import{createHash as zn,randomBytes as Bn,randomUUID as Vn}from"node:crypto";import X from"node:fs/promises";import{isDeepStrictEqual as Hn}from"node:util";import Un from"node:http";import{sql as Wn}from"drizzle-orm";async function Gn(e){try{return await X.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function Kn(e){try{return await X.lstat(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function qn(e,t){if(e===t||!await Kn(e))return 0;let n=await Gn(e),r=n.filter(e=>e.isDirectory()).length;if(!await Kn(t))return await m(e,t),r;for(let r of n)await m(q.join(e,r.name),q.join(t,r.name));return await X.rmdir(e),r}async function Jn(e){let t=q.dirname(e),n=q.basename(e);for(let e of await Gn(t)){let r=e.name.startsWith(n)?e.name.slice(n.length):``;if(!e.isFile()||!(r===`.tmp`||/^\.\d+(?:\.[a-f0-9-]{36})?\.tmp$/.test(r)))continue;let i=Number(e.name.slice(n.length+1).split(`.`)[0]);if(Number.isInteger(i)&&i>0)try{process.kill(i,0);continue}catch(e){if(e.code!==`ESRCH`)continue}await X.unlink(q.join(t,e.name)).catch(e=>{if(e.code!==`ENOENT`)throw e})}}async function Yn(e,t){if(await Jn(e),e===t||!await Kn(e))return 0;if(!await Kn(t))return await m(e,t),1;let n=JSON.parse(await X.readFile(e,`utf8`)),r=JSON.parse(await X.readFile(t,`utf8`)),i={...n,...r,...n.rows||r.rows?{rows:{...n.rows,...r.rows}}:{}},a=`${t}.${process.pid}.${Vn()}.tmp`;try{await X.writeFile(a,`${JSON.stringify(i)}\n`,{mode:384,flag:`wx`}),await X.rename(a,t),await X.unlink(e)}finally{await X.rm(a,{force:!0})}return 1}async function Xn(){let e=p(),t=a(`state`),n=p(`archive`),r=p(`flows-archived`),i=p(`usage.json`),o=p(`runner`,`usage.json`),s={from:a(`checkouts`),to:p(`checkouts`)},c={from:a(`update-check.json`),to:p(`update-check.json`)},l={cache:e,tasks:0,flows:0,files:0},u=(await Gn(t)).filter(e=>e.isDirectory()).map(e=>({archive:a(`state`,e.name,`archive`),flows:a(`state`,e.name,`flows-archived`),usage:a(`state`,e.name,`usage.json`),runnerUsage:a(`state`,e.name,`runner`,`usage.json`)}));await Jn(i),await Jn(o);for(let e of u)l.tasks+=await qn(e.archive,n),l.flows+=await qn(e.flows,r),l.files+=await Yn(e.usage,i),l.files+=await Yn(e.runnerUsage,o);return await qn(s.from,s.to),l.files+=await Yn(c.from,c.to),l}async function Zn(e){let t=(e.now??Date.now)(),n=await e.store.list(`runner`);return{online:1+n.filter(({value:e})=>e.lastSeen!==void 0&&t-e.lastSeen<3e5).length,total:1+n.length}}async function Qn(e){let t=(e.now??Date.now)(),n=e.health,{body:r,status:i}=n&&t-n.at<5e3?n:await $n(e);e.health=i===200?{at:n&&t-n.at<5e3?n.at:t,body:r,status:i}:void 0;let a=Math.max(0,t-(e.limits?.startedAt??t))/1e3;return E({...r,uptime:a},i,{"cache-control":`no-store`})}async function $n(e){let t=e.config.store===`postgres`?`down`:`none`,n={online:0,total:0},r=!0;try{if(e.config.store===`postgres`){if(!e.databaseHealth)throw Error(`Database health probe is unavailable`);await e.databaseHealth(),t=`ok`}n=e.healthRunners?await e.healthRunners():await Zn(e)}catch{r=!1,e.config.store===`postgres`&&(t=`down`)}return{body:{ok:r,version:_(),db:t,runners:n},status:r?200:503}}async function er(e){let t=(e.now??Date.now)();if(e.queue.metrics&&!e.local)return{...await e.queue.metrics(e.organizationId,t-864e5),runnersOnline:(await Zn(e)).online,requests:e.limits?.requests??0,rateLimitRejections:e.limits?.rejections??0};let n=await e.queue.list(e.organizationId),r=e.local?[...W(e.local.cwd,!1),...W(e.local.cwd,!0)]:[],i=new Map([...r,...n.map(e=>e.status===`queued`?e:r.find(t=>t.task.id===e.task.id)??e)].map(e=>[e.task.id,e])),a={queued:0,running:0,waiting:0,completed:0,failed:0,cancelled:0},o=0;for(let e of i.values())e.createdAt>=t-864e5&&a[e.status]++,e.status===`queued`&&o++;return{tasks:a,queueDepth:o,runnersOnline:(await Zn(e)).online,requests:e.limits?.requests??0,rateLimitRejections:e.limits?.rejections??0}}async function tr(e,t,n,r){if(!t.auth)return E({mode:tt(t),organization:{id:t.organizationId},server:nr(t)});let i=t.session;return E({mode:tt(t),user:i.user,organization:i.organizations.find(e=>e.id===i.organizationId)??null,organizations:i.organizations,manageMembersUrl:`${t.auth.issuer}/auth/onboarding`,server:nr(t)})}function nr(e){return{name:e.config.name??`Coder`,store:e.config.store,...e.config.publicUrl?{url:e.config.publicUrl}:{},subscriptions:{claude:!!e.config.subscriptions?.claude,codex:!!e.config.subscriptions?.codex}}}async function rr(e,t,n,r){let i=e.headers.get(`content-type`)??``,a=i.includes(`application/json`)?await e.json().catch(()=>void 0):await e.formData().then(e=>Object.fromEntries(e.entries()),()=>void 0);if(!a||typeof a!=`object`)return E({error:`Send the workspace as a form or JSON body.`},400);let o=typeof a.organization==`string`?a.organization:``,s=o?await t.auth.setOrganization(e.headers,o):void 0;if(!s)return E({error:`You are not a member of that workspace.`},403);let{cookies:c,...l}=s,u=i.includes(`application/json`)?E({organization:l}):k(`/dash`,303);for(let e of c)u.headers.append(`set-cookie`,e);return u}async function ir(e,t,n,r){let i=t.session.user.id;n.id;let a=(await e.json().catch(()=>({}))).engine??``;if(!lr.has(a)||!t.config.subscriptions?.[a])return E({error:`Sign in with ${a||`that engine`} is off on this server.`},403);let o=t.runners[t.config.runner];if(!o||o.kind===`github-actions`)return E({error:`Sign-in cannot run on the ${t.config.runner} runner.`},409);let s=`login-${Bn(12).toString(`base64url`)}`,c=Ae(s,t.organizationId,0),l={owner:i,engine:a,state:`starting`,tokenHash:c.hash,runner:o.kind,createdAt:ur(t),expiresAt:ur(t)+cr};await dr(t,s,l);let u;try{let e=await o.start({id:s},{CODER_SERVER:t.config.publicUrl??``,CODER_TASK_TOKEN:c.token,CODER_LOGIN:a}),n=await t.store.patchLogin(s,{handle:e},{tokenHash:l.tokenHash});if(!n)return await o.stop(e).catch(()=>{}),E({error:`This sign-in is gone. Start again.`},409);u=n}catch(e){return await t.store.delete(`login`,s),E({error:e instanceof Error?e.message:String(e)},502)}return E(fr(s,u),201)}async function ar(e,t,n,r){t.session.user.id;let i=n.id??``,a=i&&!i.includes(`/`)?await pr(t,i):void 0;return a?E(fr(i,a)):E({error:`This sign-in is gone. Start again.`},404)}async function or(e,t,n,r){t.session.user.id;let i=n.id??``,a=i&&!i.includes(`/`)?await pr(t,i):void 0;if(!a)return E({error:`This sign-in is gone. Start again.`},404);let o=await e.json().catch(()=>({})),s=typeof o.code==`string`?o.code.trim():``;return a.engine!==`claude`||a.state!==`open`||!s||!await t.store.patchLogin(i,{state:`verifying`,input:L(t.config,s)},{state:`open`,tokenHash:a.tokenHash})?E({error:`This sign-in is not waiting for a code.`},409):E({ok:!0})}async function sr(e,t,n,r){t.session.user.id;let i=n.id??``,a=i&&!i.includes(`/`)?await pr(t,i):void 0;return a?(await t.store.delete(`login`,i),a.handle&&await t.runners[a.runner]?.stop(a.handle).catch(()=>{}),E({ok:!0})):E({error:`This sign-in is gone. Start again.`},404)}const cr=6e5,lr=new Set([`claude`,`codex`]),ur=e=>(e.now??Date.now)();function dr(e,t,n){return e.store.put(`login`,t,n,{ttlMs:Math.max(1,n.expiresAt-ur(e))})}function fr(e,t){return{id:e,engine:t.engine,state:t.state,expiresAt:t.expiresAt,...t.url?{url:t.url}:{},...t.code?{code:t.code}:{},...t.error?{error:t.error}:{},...t.label?{label:t.label}:{}}}async function pr(e,t){let n=await e.store.get(`login`,t);return n&&n.owner===e.session?.user.id?n:void 0}async function mr(e,t,n,r){let i=n.id,a=t.callbackLogin,o=Date.now()+25e3;for(;!a.input&&Date.now()<o&&!e.signal.aborted;){await new Promise(e=>setTimeout(e,250));let e=await t.store.get(`login`,i);if(!e)return new Response(`Unauthorized`,{status:401});a=e}if(!a.input)return E({});let s=await t.store.patchLogin(i,{input:null},{input:a.input,tokenHash:a.tokenHash});return E(s?{code:N(t.config,a.input)}:{})}async function hr(e,t,n,r){n.id;let i=t.callbackLogin;return E({engine:i.engine})}async function gr(e,t,n,r){let i=n.id,a=t.callbackLogin,o=await e.json().catch(()=>({}));if(a.state===`done`||a.state===`failed`)return E({ok:!0});let s={state:[`starting`,`open`,`verifying`],tokenHash:a.tokenHash};if(typeof o.error==`string`)return await t.store.patchLogin(i,{state:`failed`,error:o.error.slice(0,500)},s),E({ok:!0});let c=o.result?.env;if(c){let e=a.engine===`claude`?`CLAUDE_CODE_OAUTH_TOKEN`:`CODEX_AUTH_JSON`;if(Object.keys(c).join()!==e||typeof c[e]!=`string`)return E({error:`Invalid sign-in result`},400);let n=`${a.engine}-subscription`,r=o.result?.account;return await t.store.completeLogin(i,a.tokenHash,n,{...Be(t.config,{env:c}),engine:a.engine,createdAt:(t.now??Date.now)(),...r?.email||r?.plan?{account:{...typeof r.email==`string`?{email:r.email}:{},...typeof r.plan==`string`?{plan:r.plan}:{}}}:{}})?E({ok:!0}):E({error:`This sign-in changed. Try again.`},409)}let l={...typeof o.url==`string`&&/^https:\/\//.test(o.url)?{url:o.url}:{},...typeof o.code==`string`?{code:o.code.slice(0,64)}:{}};return(a.state===`starting`?await t.store.patchLogin(i,{...l,state:`open`},{state:`starting`,tokenHash:a.tokenHash})??await t.store.patchLogin(i,l,{...s,state:[`open`,`verifying`]}):await t.store.patchLogin(i,l,s))?E({ok:!0}):E({error:`This sign-in changed. Try again.`},409)}async function _r(e,t,n,r){let i=n.id,a=t.operatorApp??!1;if(!/^[a-z0-9_-]+$/.test(r.pathname.split(`/`)[2]))return;let o=a?`*`:t.session?.user.id??`anonymous`,s=t.integrations[i];if(!s)return P(`Unknown integration "${i}"; run coder agent integrations list to see them`,404);let c=t.config.publicUrl;if(!c)return P(`PUBLIC_URL is not set on this server; set it to the address platforms should call and restart`,400);t.fetch,t.now?.();let l=z(r.searchParams);if(!l)return P(`Setup link is missing or malformed; start again from the agent's Platforms tab`,400);if(!l.definition.integrations[i])return P(`This agent declares no ${i} integration in its agent.json`,400);if(l.state.public&&!a)return P(`Only the server operator creates public apps`,403);let u=De(i,l.state),d=l.state.tx?await I(t,l.state.tx,`create`,o)===u?l.state.tx:void 0:await A(t,`create`,o,u);if(!d)return P(`This app creation link is invalid, expired, or already used`,403);let f={...l.state,tx:d};return s.app.createPage({publicUrl:c,state:f,definition:l.definition,encodedState:T(f)})}async function vr(e,t,n,r){let i=n.id,a=t.operatorApp??!1;if(!/^[a-z0-9_-]+$/.test(r.pathname.split(`/`)[2]))return;let o=a?`*`:t.session?.user.id??`anonymous`,s=t.integrations[i];if(!s)return P(`Unknown integration "${i}"; run coder agent integrations list to see them`,404);let c=t.config.publicUrl;if(!c)return P(`PUBLIC_URL is not set on this server; set it to the address platforms should call and restart`,400);let l=t.fetch??fetch,u=t.now?.()??Date.now(),d=ae(r.searchParams.get(`state`)),f=z(r.searchParams)??(d&&z(new URLSearchParams(Object.entries(d).filter(([,e])=>e!==void 0))))??void 0;if(!f)return P(`Setup state was lost between the platform and this server; start again`,400);if(!f.state.tx||!await xt(t,f.state.tx,`create`,o,De(i,f.state)))return P(`This app creation link is invalid, expired, or already used`,403);let p=await s.app.createCallback(e,{publicUrl:c,...f,fetch:l}).catch(e=>P(`Creating the ${i} app failed: ${e instanceof Error?e.message:e}`,400));if(p instanceof Response)return p;let m={id:`${i}:${p.platformAppId}`,integration:i,agent:f.state.agent,name:p.name,...f.state.repo?{agentsRepo:f.state.repo}:{},...f.state.repo?{branch:f.state.branch??`main`}:{},...a?{builtin:!0}:{},credentials:L(t.config,p.credentials),createdAt:u};if(await t.store.put(`app`,m.id,m),a)return P(`Created ${p.name}. Every workspace on this server can now connect it from its dashboard.`);let h=await A(t,`install`,o,m.id),g=`/dash/agents/${encodeURIComponent(m.agent)}/platforms`;return k(`${c}/install/${i}?app=${encodeURIComponent(m.id)}&state=${T({tx:h,back:g})}`)}async function yr(e,t,n,r){let i=n.id,a=t.operatorApp??!1;if(!/^[a-z0-9_-]+$/.test(r.pathname.split(`/`)[2]))return;let o=a?`*`:t.session?.user.id??`anonymous`,s=t.integrations[i];if(!s)return P(`Unknown integration "${i}"; run coder agent integrations list to see them`,404);let c=t.config.publicUrl;if(!c)return P(`PUBLIC_URL is not set on this server; set it to the address platforms should call and restart`,400);let l=t.fetch??fetch,u=t.now?.()??Date.now(),d=new URLSearchParams(await e.clone().text()),f=ae(r.searchParams.get(`state`)),p=z(r.searchParams)??(f&&z(new URLSearchParams(Object.entries(f).filter(([,e])=>e!==void 0))))??(d&&z(d));if(!p)return P(`Setup state was lost between the platform and this server; start again`,400);if(!p.state.tx||!await xt(t,p.state.tx,`create`,o,De(i,p.state)))return P(`This app creation link is invalid, expired, or already used`,403);let m=await s.app.createCallback(e,{publicUrl:c,...p,fetch:l}).catch(e=>P(`Creating the ${i} app failed: ${e instanceof Error?e.message:e}`,400));if(m instanceof Response)return m;let h={id:`${i}:${m.platformAppId}`,integration:i,agent:p.state.agent,name:m.name,...p.state.repo?{agentsRepo:p.state.repo}:{},...p.state.repo?{branch:p.state.branch??`main`}:{},...a?{builtin:!0}:{},credentials:L(t.config,m.credentials),createdAt:u};if(await t.store.put(`app`,h.id,h),a)return P(`Created ${m.name}. Every workspace on this server can now connect it from its dashboard.`);let g=await A(t,`install`,o,h.id),_=`/dash/agents/${encodeURIComponent(h.agent)}/platforms`;return k(`${c}/install/${i}?app=${encodeURIComponent(h.id)}&state=${T({tx:g,back:_})}`)}async function br(e,t,n,r){let i=n.id,a=t.operatorApp??!1;if(!/^[a-z0-9_-]+$/.test(r.pathname.split(`/`)[2]))return;let o=a?`*`:t.session?.user.id??`anonymous`,s=t.integrations[i];if(!s)return P(`Unknown integration "${i}"; run coder agent integrations list to see them`,404);let c=t.config.publicUrl;if(!c)return P(`PUBLIC_URL is not set on this server; set it to the address platforms should call and restart`,400);t.fetch,t.now?.();let l=ae(r.searchParams.get(`state`)),u=r.searchParams.get(`app`),d=l?.tx?await I(t,l.tx,`install`,o):void 0;if(!d||u&&u!==d)return P(`This installation link is invalid, expired, or already used`,403);let f=await t.store.get(`app`,u??d);if(!f)return P(`This app is not known to this server; create it first`,400);let p=N(t.config,f.credentials);return k(s.app.installUrl(f,p,{publicUrl:c,state:r.searchParams.get(`state`)??T({})}))}async function xr(e,t,n,r){let i=n.id,a=t.operatorApp??!1;if(!/^[a-z0-9_-]+$/.test(r.pathname.split(`/`)[2]))return;let o=a?`*`:t.session?.user.id??`anonymous`,s=t.integrations[i];if(!s)return P(`Unknown integration "${i}"; run coder agent integrations list to see them`,404);let c=t.config.publicUrl;if(!c)return P(`PUBLIC_URL is not set on this server; set it to the address platforms should call and restart`,400);let l=t.fetch??fetch,u=t.now?.()??Date.now(),d=ae(r.searchParams.get(`state`)),f=r.searchParams.get(`app`),p=d?.tx?await I(t,d.tx,`install`,o):void 0;if(!p||f&&f!==p||!await xt(t,d.tx,`install`,o,p))return P(`This installation link is invalid, expired, or already used`,403);let m=await t.store.get(`app`,f??p),h=d?.link?await t.store.get(`installation`,d.link):void 0,g=m??(h&&await cn(t,h,i));if(!g)return d&&!d.link?P(`Connected.`):P(`This install does not match any app on this server; create the app first`,400);let _=N(t.config,g.credentials),v=await s.app.installCallback(e,{app:g,credentials:_,publicUrl:c,fetch:l,connect:mt(t,g,c)}).catch(e=>P(e instanceof Error?e.message:String(e),400));if(v instanceof Response)return v;let y=`${g.id}:${v.platformInstallId}`,b=t.session;v.user&&b&&t.auth&&await t.auth.link(b.user,i,v.user.id,{organizations:b.organizations.map(e=>e.id),...v.user.token?{token:L(t.config,v.user.token)}:{}});let x=await t.store.get(`installation`,y),S={...x,id:y,app:g.id,integration:i,account:v.account??x?.account??h?.account??{login:`unknown`},...v.token?{token:L(t.config,v.token)}:{},...v.installer?{installer:v.installer}:{},createdAt:x?.createdAt??u};delete S.deletedAt;let C=h&&!h.deletedAt?h:void 0;C&&(S=Le(S,C.integration,C.id));try{await t.store.put(`installation`,y,S)}catch{return P(`This ${i} installation is already connected to another workspace; disconnect it there first`,409)}if(C&&await t.store.put(`installation`,C.id,Le(C,i,y)),s.renew){let e=await(await import(`./store-Cxc2GYyj.js`).then(e=>e.Y)).renewInstallation({...t,fetch:l},g,v.platformInstallId).then(()=>void 0,e=>e instanceof Error?e.message:String(e));if(e)return P(`Connected, but ${i} did not start sending events yet. ${e}. Coder tries again within the hour.`,502)}let w=ct(d?.back);return w?k(`${c.replace(/\/$/,``)}${w}`):v.response}const Z=(e,t=200)=>w(`<title>Coder</title><p>${S(e)}</p>`,t);function Sr(e,t,n){return n&&t.organizations.some(e=>e.id===n)?{...dt(e,n),session:t}:void 0}async function Cr(e,t){let n=await e.store.get(`installation`,t);return n&&!n.deletedAt?e.store.get(`app`,n.app):void 0}async function wr(e,t,n,r){let i=t.linkContext,a=i.session,o=e=>{let t=Pt(i,e);return t&&a.organizations.some(e=>e.id===t)?{...dt(i,t),session:a}:i},s=r.searchParams.get(`token`)??``,c=o(s);if(await I(c,s,`link`,a.user.id))return await gn(e,void 0,t.dashboardHosts)??new Response(`UI is not built`,{status:503});let l=await _t(c,s,`link-start`,a.user.id);if(!l)return new Response(`This link is invalid or has expired.`,{status:400});let u=await A(c,`link`,a.user.id,l,3e5);return k(`/connect?token=${encodeURIComponent(u)}`)}async function Tr(e,t,n,r){let i=t.linkContext,a=i.session,o=e=>{let t=Pt(i,e);return t&&a.organizations.some(e=>e.id===t)?{...dt(i,t),session:a}:i},s=await e.json().catch(()=>({})),c=typeof s.token==`string`?await _t(o(s.token),s.token,`link`,a.user.id):void 0;if(!c)return E({error:`This link is invalid or has expired.`},400);let l=JSON.parse(c);return await t.auth.link(a.user,l.platform,l.platformUserId,{organizations:a.organizations.map(e=>e.id)})===`taken`?E({error:`That platform account is connected to someone else.`},409):E({ok:!0,...l})}async function Er(e,t,n,r){let i=t.integrations[n.integration].auth.user,a=t.config.publicUrl,o=t.linkContext.session,s=r.searchParams.get(`installation`)??``,c=Sr(t,o,s?await t.installationOrganization?.(s):void 0);if(!c)return Z(`Only members of the workspace this agent works for can link here.`,403);let l=await Cr(c,s);if(!l)return Z(`This installation is no longer connected.`,404);let u=await A(c,`link-oauth`,o.user.id,s);return k(i.authorizeUrl(N(t.config,l.credentials),{publicUrl:a,state:u}))}async function Dr(e,t,n,r){let i=t.integrations[n.integration],a=i.auth.user,o=t.config.publicUrl,s=t.linkContext.session,c=r.searchParams.get(`state`)??``,l=Sr(t,s,Pt(t,c)),u=l&&await _t(l,c,`link-oauth`,s.user.id),d=l&&u?await Cr(l,u):void 0;if(!l||!d)return Z(`This link is invalid or has expired.`,400);let f=await a.exchange(e,N(t.config,d.credentials),{publicUrl:o,fetch:t.fetch??fetch}).catch(e=>e instanceof Error?e:Error(String(e)));return f instanceof Error?Z(f.message,400):await t.auth.link(s.user,i.id,f.id,{organizations:s.organizations.map(e=>e.id),...f.token?{token:L(t.config,f.token)}:{}})===`taken`?Z(`That ${i.id} account is connected to someone else.`,409):Z(`Linked ${f.login??f.id} on ${i.id} to your Coder account. Mention the agent again to start.`)}const Or=Y.object({installation:Y.string().check(Y.minLength(1)),integration:Y.string().check(Y.minLength(1)),token:Y.string().check(Y.minLength(1)),account:Y.optional(Y.string())});async function kr(e,t){let n;try{n=await e.json()}catch{return new Response(`Invalid JSON`,{status:400})}let r=Or.safeParse(n);if(!r.success)return new Response(`Invalid connection`,{status:400});let{installation:i,integration:a,token:o,account:s}=r.data,c=await t.store.get(`installation`,i);if(!c||c.deletedAt)return new Response(`Unknown installation`,{status:404});let l={kind:`oauth`,token:L(t.config,o),...s?{account:s}:{}};return await Vt(t.store,`installation`,i,{connections:{...c.connections,[a]:l}}),E({ok:!0})}async function Ar(e,t,n,r){let i=await t.store.get(`app`,n);if(!i)return E({error:`Unknown app`},404);let a=t.config.publicUrl;if(!a)return E({error:`PUBLIC_URL is not set on this server`},400);let o=await A(t,`install`,t.session?.user.id??`anonymous`,i.id),s=T({tx:o,...r?{back:r}:{}});return E({url:`${a.replace(/\/$/,``)}/install/${i.integration}?app=${encodeURIComponent(i.id)}&state=${s}`})}async function jr(e,t,n,r){let i=r.searchParams.get(`agent`),a=t.serverOrganizationId,[o,s]=await Promise.all([t.store.list(`app`),a!==void 0&&a!==t.organizationId&&t.scope?t.scope(a).store.list(`app`).then(e=>e.map(({id:e,value:t})=>({id:e,value:{...t,builtin:!0}}))):[]]),c=[...o,...s];return E(c.filter(({value:e})=>!i||e.agent===i).map(({id:e,value:t})=>{let{credentials:n,...r}=t;return{id:e,value:r}}))}async function Mr(e,t,n,r){let i=r.searchParams.get(`agent`),[a,o]=await Promise.all([t.store.list(`installation`),i?t.store.list(`app`):[]]),s=new Set(o.filter(({value:e})=>e.agent===i).map(({id:e})=>e));return E(a.filter(({value:e})=>!i||s.has(e.app)).map(({id:e,value:t})=>{let{token:n,connections:r,...i}=t;return{id:e,value:i}}))}function Nr(e){return E(Object.values(e.integrations).map(e=>({id:e.id,name:e.name,brand:e.brand,description:e.description,installLabel:e.installLabel??`Connect ${e.id}`,organizationApps:e.organizationApps===!0,events:Object.fromEntries(Object.entries(e.events).map(([e,{description:t,noisy:n,addressed:r}])=>[e,{description:t,...n?{noisy:n}:{},...r?{addressed:r}:{}}])),presets:e.tools.presets,repositories:!!e.repos})))}async function Pr(e){let t=new Map;for(let{value:n}of await e.store.list(`installation`)){let r=e.integrations[n.integration];if(n.deletedAt||!r?.repos)continue;let i=await e.store.get(`app`,n.app);if(i)try{let a=await r.auth.token(n.token?{...n,token:N(e.config,n.token)}:n,N(e.config,i.credentials));for(let e of await r.repos.list(n,a))t.has(e)||t.set(e,{repo:e,integration:r.id})}catch{}}return E([...t.values()].sort((e,t)=>e.repo.localeCompare(t.repo)))}async function Fr(e,t){let n=(await e.store.list(`installation`)).filter(({value:t})=>!t.deletedAt&&e.integrations[t.integration]?.repos),r=new Map((await un(e.store,n.map(({value:e})=>e.app))).map(({id:e,value:t})=>[e,t]));for(let{value:i}of n){let n=e.integrations[i.integration];if(i.deletedAt||!n?.repos)continue;let a=r.get(i.app);if(!(!a||a.integration!==n.id))try{let r=i.token?{...i,token:N(e.config,i.token)}:i,o=await n.auth.token(r,N(e.config,a.credentials));if((await n.repos.list(r,o)).includes(t))return{contents:n,token:o,app:a,installation:i}}catch{}}}async function Ir(e,t,n){let r=await Fr(e,t);if(!r)return E({error:`No installed app can read ${t}`},400);let i=await r.contents.repos.listDir(t,Ee,r.token,n).catch(()=>[]),a=await Promise.all(i.map(async i=>{let a=await r.contents.repos.readFile(t,`${Ee}/${i}/agent.json`,r.token,n).catch(()=>void 0);if(a===void 0)return;let o={};try{o=JSON.parse(a)}catch{}let s=await H(e.store,i),c=s?.source===`repo`&&s.repo===t,l=c?await wn(e.store,i):void 0;return{id:i,name:typeof o.name==`string`?o.name:i,...typeof o.description==`string`?{description:o.description}:{},...c?{version:s.currentVersion,...l?.source?{commit:l.source.commit}:{}}:{},...s&&!c?{taken:!0}:{}}}));return E({repo:t,agents:a.filter(Boolean)})}async function Lr(e,t,n,r){let i=r.searchParams.get(`repo`);return i?Ir(t,i,r.searchParams.get(`ref`)||`HEAD`):E({error:`repo is required`},400)}async function Rr(e,t,n,r){let i=await e.json().catch(()=>void 0),a=i?.agents;if(typeof i?.repo!=`string`||i.ref!==void 0&&typeof i.ref!=`string`||a!==void 0&&!(Array.isArray(a)&&a.every(e=>typeof e==`string`)))return E({error:`repo is required, ref must be a string and agents a list of ids`},400);try{let e=await Fr(t,i.repo);if(!e)return E({error:`No installed app can read ${i.repo}`},400);let n=i.ref??`HEAD`,r=a??await e.contents.repos.listDir(i.repo,`.coder/agents`,e.token,n);for(let e of r){let n=await H(t.store,e);if(n&&(n.source!==`repo`||n.repo!==i.repo))return E({error:`Agent id "${e}" is already taken`},409)}let o=await Ie(t.store,e.contents,i.repo,n,e.token,(t.now??Date.now)(),{slugs:r});return await Pe(t,o),E({imported:o.map(e=>e.agent)})}catch(e){return E({error:e instanceof Error?e.message:String(e)},400)}}async function zr(e,t,n,r){if(t.source!==`repo`||!t.repo)return;let i=(await(r??e.store.list(`app`))).find(({value:e})=>e.agent===t.id&&e.agentsRepo===t.repo)?.value;return((i&&e.integrations[i.integration])??Object.values(e.integrations).find(e=>e.repos))?.repos?.url(t.repo,t.path,i?.branch??n?.commit)}async function Br(e,t,n){let r=await yn(e.store,t);return await ge(e.store,n,t,r)?yn(e.store,t):r}async function Q(e,t){let n=(e.now??Date.now)(),r=e.local?await hn(e.store,e.local.cwd,e.integrations,t).catch(()=>void 0):void 0;return{now:n,local:r,loadCurrent:()=>r?Promise.resolve(r.find(({record:e})=>e.id===t)??{}):Br(e,t,n)}}async function Vr(e,t,n,r){let i=n.slug;if(n.version&&Number(n.version),n.version&&!/^\d+$/.test(r.pathname.split(`/`).at(-1)))return O();let{now:a,local:o,loadCurrent:s}=await Q(t,i);if(!o&&t.store.listAgentSummaries&&(await Sn(t.store,a),ne(r)))return E(await Kr(t,r));let c=o??(t.store.listAgentSummaries?await t.store.listAgentSummaries():await Dn(t.store));if(!o&&!t.store.listAgentSummaries&&await Sn(t.store,a,c)&&(c=await Dn(t.store)),ne(r))return E(await Kr(t,r,c));let l;return E(await Promise.all(c.map(async({record:e,version:n})=>{e.source===`repo`&&e.repo&&(l??=t.store.list(`app`));let r=await zr(t,e,n,l);return{...e,definition:n?.definition,...r?{sourceUrl:r}:{}}})))}async function Hr(e,t,n,r){let i=n.slug;if(n.version&&Number(n.version),n.version&&!/^\d+$/.test(r.pathname.split(`/`).at(-1)))return O();let{now:a,local:o,loadCurrent:s}=await Q(t,i),c=D(r,10,50),l=re(r),[u,d]=await Promise.all([o?s().then(e=>e.record):H(t.store,i),o?Promise.resolve(o.flatMap(({version:e})=>e?[{value:e}]:[])):t.store.listVersions?.(i,c+1,l)]);return u?E(await qr(t,u,c,l??u.currentVersion+1,d)):E({error:`No agent named "${i}"`},404)}async function Ur(e,t,n,r){let i=n.slug,a=n.version?Number(n.version):void 0;if(n.version&&!/^\d+$/.test(r.pathname.split(`/`).at(-1)))return O();let{now:o,local:s,loadCurrent:c}=await Q(t,i),l=s?s.find(({version:e})=>e?.version===a)?.version:await wn(t.store,i,a);return l?E(l):E({error:`No version ${a} for agent "${i}"`},404)}async function Wr(e,t,n,r){let i=n.slug;if(n.version&&Number(n.version),n.version&&!/^\d+$/.test(r.pathname.split(`/`).at(-1)))return O();let{now:a,local:o,loadCurrent:s}=await Q(t,i),c=r.searchParams.get(`versions`)!==`0`,l=r.searchParams.get(`content`)!==`0`,[{record:u,version:d},f]=await Promise.all([!l&&!o&&t.store.listAgentSummaries&&!v()[i]?t.store.listAgentSummaries({slug:i}).then(e=>e[0]??{}):s(),c?o?o.flatMap(({version:e})=>e?[{value:e}]:[]):t.store.listVersions?t.store.listVersions(i):t.store.list(`agentversion`,{prefix:`${i}:`}):[]]);if(!u)return E({error:`No agent named "${i}"`},404);let p=f.map(({value:e})=>{let{systemPrompt:t,files:n,...r}=e;return r}),m=await zr(t,u,d);return E({...u,...d?{definition:d.definition,...l&&`systemPrompt`in d?{systemPrompt:d.systemPrompt,...d.files?{files:d.files}:{}}:{}}:{},...m?{sourceUrl:m}:{},...c?{versions:p}:{}})}const Gr={builtin:`builtin`,dashboard:`upload`,repository:`repo`};async function Kr(e,t,n){let r=D(t,24,100),i=re(t),a=t.searchParams.get(`q`)?.trim().toLowerCase(),o=Gr[t.searchParams.get(`type`)??``],s=t.searchParams.get(`platform`),c=t.searchParams.get(`connect`)===`1`,l=e.serverOrganizationId,u=e.store.list(`app`),[d,f,p,m]=await Promise.all([u,e.store.list(`installation`),c&&l!==void 0&&l!==e.organizationId&&e.scope?e.scope(l).store.list(`app`):[],n?n.filter(({record:e})=>(!i||e.id>i)&&(!o||e.source===o)&&(!a||[e.id,e.name,e.description,e.repo].some(e=>e?.toLowerCase().includes(a)))):e.store.listAgentSummaries({after:i,source:o,q:a,platform:s??void 0,limit:r+1})]),h=new Set(f.filter(({value:e})=>!e.deletedAt).map(({value:e})=>e.app)),g=(e,t)=>{let n=d.filter(({value:n})=>n.agent===e&&n.integration===t);return n.length?n.some(({value:e})=>h.has(e.id))?`installed`:`created`:`none`},_=[];for(let{record:e,version:t}of m){let n=Object.keys(t?.definition?.integrations??{}).sort();if(!(s&&!n.includes(s))&&(_.push({record:e,version:t,ids:n}),_.length>r))break}let v=ce(_,r,e=>e.record.id);return{...v,...c?{connectable:[...d,...p.map(e=>({...e,value:{...e.value,builtin:!0}}))].filter(({value:e})=>e.builtin&&!h.has(e.id)).map(({value:e})=>({id:e.id,integration:e.integration}))}:{},items:await Promise.all(v.items.map(async({record:t,version:n,ids:r})=>{let i=await zr(e,t,n,u);return{...t,definition:n?.definition,...i?{sourceUrl:i}:{},platforms:r.map(e=>({id:e,state:g(t.id,e)}))}}))}}async function qr(e,t,n,r,i){let a=r-n-2,o=(i??await e.store.list(`agentversion`,{prefix:`${t.id}:`,...a>0?{after:ye(t.id,a)}:{},limit:n+1})).map(({value:e})=>{let{systemPrompt:t,files:n,definition:r,...i}=e;return i}).filter(e=>e.version<r).reverse();return ce(o,n,e=>e.version)}function Jr(e){if(!e||Array.isArray(e)||typeof e!=`object`)return!1;let t=Object.entries(e);if(t.length>100)return!1;let n=0;for(let[e,r]of t){if(typeof r!=`string`||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)||e.split(`/`).includes(`..`)||e===`agent.json`||e===`system.md`)return!1;n+=Buffer.byteLength(e)+Buffer.byteLength(r)}return n<=262144}async function Yr(e,t,n,r){let i=n.slug;if(n.version&&Number(n.version),n.version&&!/^\d+$/.test(r.pathname.split(`/`).at(-1)))return O();let{now:a,local:o,loadCurrent:s}=await Q(t,i),c=await e.json().catch(()=>void 0);try{let e=x({[i]:c})[i];if(!e||typeof e!=`object`)throw Error(`settings must be an object`);let{record:n,version:r}=await s();if(!n||!r)throw Error(`No agent named "${i}".`);return xe({...n,settings:void 0},r,e,t.integrations),t.local?(await ve(t,t=>{t.agents={...t.agents,[i]:e}}),await hn(t.store,t.local.cwd,t.integrations),E(await H(t.store,i))):E(await at(t.store,i,e,(t.now??Date.now)()))}catch(e){return E({error:e instanceof Error?e.message:String(e)},400)}}async function Xr(e,t,n,r){let i=n.slug;if(n.version&&Number(n.version),n.version&&!/^\d+$/.test(r.pathname.split(`/`).at(-1)))return O();let{now:a,local:o,loadCurrent:s}=await Q(t,i),{record:c}=await s();if(!c)return E({error:`No agent named "${i}"`},404);if(c.source===`builtin`)return E({error:`Built-in agents cannot be deleted.`},400);if(t.local&&!await Ft(t.local.cwd,t.integrations,i))return E({error:`Delete .coder/agents/${i} in the repo`},409);for(let{id:e}of await t.store.list(`agentversion`,{prefix:`${i}:`}))await t.store.delete(`agentversion`,e);return await t.store.delete(`agent`,i),E({ok:!0})}async function Zr(e,t,n,r){let i=n.slug;if(n.version&&Number(n.version),n.version&&!/^\d+$/.test(r.pathname.split(`/`).at(-1)))return O();let{now:a,local:o,loadCurrent:s}=await Q(t,i),c=await e.json().catch(()=>void 0);if(!c||typeof c.systemPrompt!=`string`||c.files!==void 0&&!Jr(c.files)||c.name!==void 0&&typeof c.name!=`string`||c.description!==void 0&&typeof c.description!=`string`)return E({error:`definition and systemPrompt are required; files must contain strings`},400);try{b([i]);let[e]=y({definitions:{[i]:{json:c.definition,builtin:!1}},usage:void 0},t.integrations);if(!e)throw Error(`No agent named "${i}".`);let n=t.local?await H(t.store,i):void 0,r=t.local&&n?await wn(t.store,i):void 0,a=c.files;t.local&&(await tn(t.local.cwd,t.integrations,i,{definition:{...c.definition,...c.name===void 0?{}:{name:c.name},...c.description===void 0?{}:{description:c.description}},systemPrompt:c.systemPrompt,...a?{files:a}:{}}),await hn(t.store,t.local.cwd,t.integrations));let o=t.local?void 0:await nt(t.store,{id:i,name:c.name??e.name,description:c.description??e.definition.description,source:`upload`,definition:e.definition,systemPrompt:c.systemPrompt,files:a,importedFrom:`upload`},(t.now??Date.now)()),s=o?.version??await wn(t.store,i),l=o?.unchanged??Hn(r&&{...r,createdAt:0},{...s,createdAt:0});await Pe(t,[s]);let u=o?.record??await H(t.store,i);return E({...u,definition:s.definition,version:s.version,unchanged:l})}catch(e){return E({error:e instanceof Error?e.message:String(e)},400)}}async function Qr(e,t,n,r){let i=n.id,a=Number(r.searchParams.get(`after`)??-1),o=Number.isFinite(a)?a:-1;r.searchParams.has(`limit`)&&D(r,500,2e3);let s=await t.store.get(`task`,i);if(!s||t.local&&s.handle?.startsWith(`cli:`)&&s.task.flow==="default"){let n=s?.task.cwd??t.local?.cwd;if(!n||!G(n,i,!1))return E({error:`No task "${i}"`},404);{let r=Number(e.headers.get(`last-event-id`)??o);return oi(e,t,`cli:${n}:${i}`,Number.isFinite(r)?r:o,async e=>{let t=G(n,i);if(t)return{status:t,lines:It(n,i,e,500),pendingResult:$r(n,t,!t.result)}})}}let c=Number(e.headers.get(`last-event-id`)??o),l=t.statementTimeout??((e,t)=>t());return oi(e,t,i,Number.isFinite(c)?c:o,e=>l(ii,async()=>{let n=await t.store.get(`task`,i);if(!n)return;let r=n.task.runner===`github-actions`&&n.handle,a=r&&F.has(n.status)?(await(await Xe(t,n.task))?.status(n.handle).catch(()=>void 0))?.state===`running`:!1;return{status:n,lines:([`running`,`waiting`].includes(n.status)||r)&&n.handle?await yt(t,n,e,500).catch(()=>vt(t.store,i,e,500)):await vt(t.store,i,e,500),pendingLogs:a}}))}function $r(e,t,n=!1){if(!F.has(t.status)||t.error||t.status===`cancelled`)return!1;let r=l(e,t.task.id),i=Math.max(t.finishedAt??0,Date.parse(r?.resumedAt??r?.createdAt??``)||0);return n||(Rn.statSync(q.join(h(e,t.task.id),`result.json`),{throwIfNoEntry:!1})?.mtimeMs??0)<i}const ei=1e3,$=3e4;function ti(e,t,n,r){let i=[...new Set((r.searchParams.get(`tasks`)??``).split(`,`).filter(Boolean))].slice(0,100),a=Date.now(),o=t.taskWatcher??new ri,s=o.tag(t),[c,l]=(e.headers.get(`last-event-id`)??``).split(`-`),u=Number(c),d=u>0&&`-${l}`===s,f=d?Math.min(Math.max(u,a-29e4),a):a,p=u>0&&(!d||u<f)?`event: reset
2
2
  data: {}
3
3
 
4
4
  `:``,m=new TextEncoder,h=()=>{},g=new ReadableStream({start(n){n.enqueue(m.encode(`retry: ${ei}\nid: ${f}${s}\n\n${p}`)),h=o.watch(t,i,f,e=>n.enqueue(m.encode(e)),()=>n.close());let r=()=>{h();try{n.close()}catch{}};e.signal.aborted?r():e.signal.addEventListener(`abort`,r)},cancel(){h()}});return new Response(g,{headers:{"content-type":`text/event-stream; charset=utf-8`,"cache-control":`no-cache, no-transform`}})}function ni(e,t){let{task:n,approval:r,archivedAt:i,createdAt:a,startedAt:o,finishedAt:s}=e;return{id:n.id,agent:n.agent,status:e.status,approval:r??null,archivedAt:e.autoArchived&&!t?void 0:i,createdAt:a,startedAt:o,finishedAt:s,...t?{result:e.result??null,error:e.error??null,answer:e.answer??null}:{}}}var ri=class{options;watches=new Set;timer;reading=!1;closed=!1;last=Date.now();scans=new Map;left=new Map;archived=new Map;reads=0;generation=Vn().slice(0,8);constructor(e={}){this.options=e}watch(e,t,n,r,i){if(this.closed)return queueMicrotask(i),()=>{};let a=Date.now();this.watches.size||(this.last=a);let o={ctx:e,ids:new Set(t),sent:new Map,gone:new Set,from:n,fresh:!0,tag:this.tag(e),beat:a,marked:a,until:a+(this.options.lifeMs??29e4),send:r,close:i};return this.watches.add(o),this.timer||(this.timer=setInterval(()=>this.tick(),this.options.pollMs??1e3),this.timer.unref?.()),this.tick(),()=>this.drop(o)}tag(e){return`-${zn(`sha256`).update(e.organizationId).digest(`hex`).slice(0,8)}${e.queue instanceof nn?`.${this.generation}`:``}`}close(){this.closed=!0;for(let e of[...this.watches]){this.drop(e);try{e.close()}catch{}}}drop(e){this.watches.delete(e)&&(this.watches.size||(clearInterval(this.timer),this.timer=void 0))}tick(){let e=Date.now();for(let t of[...this.watches])if(e>=t.until){this.drop(t);try{t.close()}catch{}}else e-t.beat>=(this.options.heartbeatMs??2e4)&&(t.beat=e,this.send(t,`: ping
5
5
 
6
6
  `));this.reading||!this.watches.size||(this.reading=!0,this.read(e).finally(()=>this.reading=!1))}send(e,t){try{e.send(t)}catch{this.drop(e)}}async read(e){let t=[...this.watches],n=new Map;for(let e of t){let t=n.get(e.ctx.organizationId)??{ctx:e.ctx,ids:new Set};for(let n of e.ids)t.ids.add(n);n.set(e.ctx.organizationId,t)}let r=Math.min(this.last,...t.flatMap(e=>e.fresh?[e.from]:[]));this.reads++;let i=await this.changes(n,r-$,e).catch(()=>void 0);if(i){this.last=e;for(let n of t){if(!this.watches.has(n))continue;let t=[];try{t=this.news(n,i,e)}catch{}!t.length&&e-n.marked>=(this.options.heartbeatMs??2e4)&&t.push(`id: ${e}${n.tag}\n\n`),t.length&&(n.marked=e,this.send(n,t.join(``)))}}}async changes(e,t,n){let r=await[...e.values()][0].ctx.queue.changes([...e].map(([e,t])=>({organizationId:e,ids:[...t.ids]})),t),i=new Map;for(let{organizationId:e,status:t}of r.rows){let n=i.get(e)??new Map;i.set(e,n.set(t.task.id,t))}let a=new Map;for(let{organizationId:e,id:t,at:n}of r.deleted){let r=a.get(e)??new Map;a.set(e,r.set(t,n))}for(let[t,{ctx:r}]of e){if(!r.local)continue;let e=[...i.get(t)?.values()??[]],a=this.scans.get(r.local.cwd);if(!a||n-a.at>=4e3||e.some(e=>e.updatedAt>a.at)){let e=!a||n-a.archivedAt>=15e3;await vn(r,r.local.cwd);let t=e?W(r.local.cwd,!0):a.archived,i=W(r.local.cwd,!1),o=new Set(i.map(e=>e.task.id)),s=[...i,...t.filter(e=>!o.has(e.task.id))],c=new Set(s.map(e=>e.task.id)),u=this.left.get(r.local.cwd)??new Map;for(let e of a?.rows??[])c.has(e.task.id)||u.set(e.task.id,a.at);for(let[e,t]of u)(t<n-6e5||c.has(e))&&u.delete(e);let d=this.archived.get(r.local.cwd)??new Set;for(let e of d)c.has(e)?d.delete(e):l(r.local.cwd,e)||(u.set(e,a?.at??n),d.delete(e));this.left.set(r.local.cwd,u),this.scans.set(r.local.cwd,a={at:n,rows:s,archived:t,archivedAt:e?n:a.archivedAt})}i.set(t,new Map(Ce(r.local.cwd,a.rows,e).map(e=>[e.task.id,e])))}return{rows:i,deleted:a}}news(e,{rows:t,deleted:n},r){let{ctx:i}=e,a=t.get(i.organizationId)??new Map,o=[],s=(t,n)=>{let i=JSON.stringify(n);e.sent.get(t)!==i&&(e.sent.set(t,i),o.push(`id: ${r}${e.tag}\nevent: task\ndata: ${i}\n\n`))},c=e=>({id:e,deleted:!0}),l=t=>{let n=i.local&&G(i.local.cwd,t,e.ids.has(t));if(s(t,n?ni(n,e.ids.has(t)):c(t)),e.gone.add(t),n&&i.local){let e=this.archived.get(i.local.cwd)??new Set;this.archived.set(i.local.cwd,e.add(t))}};for(let[t,n]of a){let a=e.ids.has(t);e.gone.delete(t);let o=ni(a&&i.local&&n.local&&F.has(n.status)?G(i.local.cwd,t)??n:n,a);if(i.local&&n.local&&e.sent.get(t)!==JSON.stringify(o)&&r-(n.finishedAt??0)<$&&$r(i.local.cwd,n)){e.sent.has(t)||e.sent.set(t,``);continue}a||i.local&&!e.fresh||n.updatedAt>e.from-$?s(t,o):e.fresh&&e.sent.set(t,JSON.stringify(o))}for(let t of e.ids)a.has(t)||l(t);for(let[t,r]of n.get(i.organizationId)??[])r>e.from-$&&s(t,c(t));if(i.local){for(let t of e.sent.keys())!a.has(t)&&!e.ids.has(t)&&!e.gone.has(t)&&l(t);for(let[t,n]of this.left.get(i.local.cwd)??[])n>e.from-$&&!a.has(t)&&e.sent.get(t)!==JSON.stringify(c(t))&&l(t)}return e.fresh=!1,e.from=r,o}};const ii=1e4;var ai=class{options;feeds=new Map;closed=!1;reads=0;constructor(e={}){this.options=e}watch(e,t,n,r,i){if(this.closed)return queueMicrotask(i),()=>{};let a=this.feeds.get(e),o=a?.reading!==void 0&&Date.now()-a.reading>=(this.options.stallMs??1e4);if(!a||o){let t={key:e,read:n,watches:new Set,head:1/0};if(a){clearTimeout(a.timer);for(let e of a.watches)t.watches.add(Object.assign(e,{feed:t}));a.watches.clear()}this.feeds.set(e,a=t)}let s={cursor:t,feed:a,timers:[],send:r,close:i};s.timers=[setTimeout(()=>this.end(s),this.options.lifeMs??5e4),setInterval(()=>this.send(s,`: ping
7
7
 
8
- `),this.options.heartbeatMs??2e4)];for(let e of s.timers)e.unref?.();return a.watches.add(s),a.reading===void 0&&t<a.head&&(clearTimeout(a.timer),this.read(a)),()=>this.drop(s)}close(){this.closed=!0;for(let e of[...this.feeds.values()])for(let t of[...e.watches])this.end(t)}drop(e){let{feed:t}=e;for(let t of e.timers)clearTimeout(t);!t.watches.delete(e)||t.watches.size||(clearTimeout(t.timer),this.feeds.get(t.key)===t&&this.feeds.delete(t.key))}end(e,t=``){try{t&&e.send(t),e.close()}catch{}this.drop(e)}send(e,t){try{e.send(t)}catch{this.drop(e)}}async read(e){if(e.timer=void 0,this.feeds.get(e.key)!==e||!e.watches.size)return;let t=[...e.watches],n=Math.min(...t.map(e=>e.cursor));e.reading=Date.now(),this.reads++;let r=await e.read(n).catch(()=>null);if(e.reading=void 0,this.feeds.get(e.key)!==e)return;let i=t.filter(t=>e.watches.has(t)),a=i.length<e.watches.size?0:this.options.pollMs??1e3;if(r===void 0)for(let e of i)this.end(e);else if(r){let{status:t,lines:o,pendingLogs:s,pendingResult:c}=r,l=o.length===500,u=F.has(t.status)&&!l&&!s&&!c,d=o.map(e=>[e.seq,`id: ${e.seq}\nevent: log\ndata: ${JSON.stringify(e)}\n\n`]);e.head=Math.max(n,o.at(-1)?.seq??n),l&&(a=0);for(let e of i){let t=d.flatMap(([t,n])=>t>e.cursor?[n]:[]).join(``);e.cursor=Math.max(e.cursor,o.at(-1)?.seq??-1),u?this.end(e,`${t}event: end\ndata: {}\n\n`):t&&this.send(e,t)}}this.feeds.get(e.key)===e&&(e.timer=setTimeout(()=>void this.read(e),a),e.timer.unref?.())}};function oi(e,t,n,r,i){let a=t.logWatcher??new ai,o=new TextEncoder,s=()=>{},c=new ReadableStream({start(c){c.enqueue(o.encode(`retry: ${ei}\n\n`)),s=a.watch(`${t.organizationId}:${n}`,r,i,e=>c.enqueue(o.encode(e)),()=>c.close());let l=()=>{s();try{c.close()}catch{}};e.signal.aborted?l():e.signal.addEventListener(`abort`,l)},cancel(){s()}});return new Response(c,{headers:{"content-type":`text/event-stream; charset=utf-8`,"cache-control":`no-cache, no-transform`}})}var si=class{options;entries=new Map;pending=new Map;constructor(e={ttlMs:6e5,max:100}){this.options=e}get size(){return this.entries.size}get inFlight(){return this.pending.size}has(e){return this.entries.has(e)}keys(){return this.entries.keys()}async get(e,t){let n=this.options.now??Date.now,r=n(),i=this.entries.get(e);if(i&&r-i.at<this.options.ttlMs)return i.value;for(let[t,n]of this.entries)t!==e&&r-n.at>=this.options.ttlMs&&this.entries.delete(t);let a=this.pending.get(e);return a||(a=Promise.resolve().then(t).then(t=>{if(t===void 0)return i?.value;if(this.options.accept&&!this.options.accept(t))return i?.value??t;this.entries.set(e,{value:t,at:n()});let r=this.entries.keys().next().value;return this.entries.size>this.options.max&&r!==void 0&&this.entries.delete(r),t}).catch(()=>i?.value).finally(()=>this.pending.delete(e)),this.pending.set(e,a)),a}};const ci=/^[a-z0-9][a-z0-9-]*$/,li=new Set([`openrouter.ai`,`ai-gateway.vercel.sh`,`api.groq.com`,`api.together.xyz`]);function ui(e){return{builtin:{codex:i,claude:c},models:e.models??{}}}async function di(e,t){let{baseUrl:n,envKey:r,key:i}=await K(e);if(!n||!/^https?:\/\//.test(n)||!URL.canParse(n))return E({error:`An http or https base URL is required`},400);let a=!i&&r&&await fi(t,n,r)?await an(t,r):void 0,o=i||a,s=t.settings??={},c=s.probes??=new si({ttlMs:6e5,max:100,now:t.now,accept:e=>e.reachable}),l=`${new URL(n).host}|${r??``}|${C(String(o??``))}`;return E(await c.get(l,()=>te({baseUrl:n},{key:o,fetch:t.fetch})))}async function fi(e,t,n){let r=new URL(t).host;if(li.has(r))return!0;let i=(await be(e)).models??{};return Object.values(i).some(e=>`baseUrl`in e&&e.envKey===n&&new URL(e.baseUrl).host===r)}async function pi(e,t,n,r){return E(ui(await be(t)))}async function mi(e,n,r,i){let{name:a=``,...o}=await K(e);return!ci.test(a)||t(a)?E({error:`Invalid model name "${a}"`},400):R(n,e=>{if(e.models?.[a])throw new V(`"${a}" already exists`);e.models={...e.models,[a]:o}})}async function hi(e,t,n,r){let i=n.name;return R(t,e=>{if(!e.models?.[i])throw new V(`No model "${i}"`);g(e,i)})}async function gi(e,t,a,o){let s=a.name,{spec:l}=await K(e);return R(t,e=>{if(!ci.test(s))throw new V(`Invalid alias name "${s}"`);let t=e.models?.[s];if(t&&f(t))throw new V(`"${s}" is a custom model name`);let a=d(l,u(e));if(!a?.model||a.engine===`custom`)throw new V(`"${l}" does not name a codex or claude model`);let o=a.engine===`claude`?c:i,p=l.split(`:`).some(e=>n.has(e)||r.has(e));e.models={...e.models,[s]:{provider:a.engine,model:o[a.model]??a.model,...p&&a.effort?{effort:a.effort}:{}}}})}async function _i(e,t,n,r){let i=n.name;return R(t,e=>{let t=e.models??={},n=t[i];n&&(f(n)||o(n))?n.disabled=!0:t[i]={disabled:!0}})}async function vi(e,t,n,r){let i=n.name;return R(t,e=>{let t=e.models??={},n=t[i];n&&(f(n)||o(n))?delete n.disabled:delete t[i]})}const yi=/^[a-z0-9][a-z0-9_-]*$/i;async function bi(e,t,n,r){return E((await be(t)).mcp??{})}async function xi(e,t,n,r){let{name:i=``,...a}=await K(e);return yi.test(i)?R(t,e=>{e.mcp={...e.mcp,[i]:a}}):E({error:`Invalid server name "${i}"`},400)}async function Si(e,t,n,r){let i=n.name;return R(t,e=>{if(!e.mcp?.[i])throw new V(`No MCP server "${i}"`);delete e.mcp[i]})}const Ci={npm:[`npx`,`-y`],pypi:[`uvx`],oci:[`docker`,`run`,`-i`,`--rm`]},wi=(e=[])=>e.map(({name:e,description:t,isRequired:n,isSecret:r,value:i,default:a})=>({name:e,...t?{description:t}:{},...i??a?{placeholder:i??a}:{},required:n===!0,secret:r===!0}));function Ti(e=[],t,n){return e.flatMap((e,r)=>{let i=`${t}:${r}`,a=Object.entries(e.variables??{}),o=e.value??e.default,s=(e,t,r)=>{let[i]=wi([{...r,name:e}]);return n.push({...i,label:t}),`{${e}}`};if(a.length)for(let[e,t]of a)o=o?.replaceAll(`{${e}}`,s(`${i}:${e}`,e,t));else o===void 0&&(e.valueHint||e.isRequired)&&(o=s(i,e.valueHint??e.name??i,e));return[...e.type===`named`&&e.name?[e.name]:[],...o===void 0?[]:[o]]})}function Ei(e){let t=e.remotes?.find(e=>e.type===`streamable-http`||e.type===`sse`);if(t)return{type:t.type===`sse`?`sse`:`http`,url:t.url,env:[],headers:wi(t.headers)};let n=e.packages?.find(e=>Ci[e.registryType]&&(e.transport?.type??`stdio`)===`stdio`);if(!n)return;let[r,...i]=Ci[n.registryType],a=[],o=Ti(n.runtimeArguments,`runtime`,a),s=Ti(n.packageArguments,`package`,a);return{type:`stdio`,command:n.runtimeHint??r,args:[...!n.runtimeHint||n.runtimeHint===r?i:[],...o,n.identifier,...s],...a.length?{argumentInputs:a}:{},env:wi(n.environmentVariables),headers:[]}}async function Di(e,t,n){let r=n.searchParams.get(`q`)?.trim()??``,i=t.settings??={},a=await(i.registry??=new si({ttlMs:6e5,max:100,now:t.now})).get(r,()=>Oi(t,r));return a?E(a):E({error:`The MCP registry did not answer. Try again.`},502)}async function Oi(e,t){let n=new URLSearchParams({version:`latest`,limit:`30`});t&&n.set(`search`,t);try{let t=await(e.fetch??fetch)(`https://registry.modelcontextprotocol.io/v0.1/servers?${n}`,{headers:{accept:`application/json`},signal:AbortSignal.timeout(2e4)});if(!t.ok)return;let{servers:r=[]}=await t.json();return r.flatMap(({server:e})=>{let t=Ei(e);return t?[{name:e.name,title:e.title??e.name.split(`/`).pop()??e.name,description:e.description??``,...t}]:[]})}catch{return}}const ki=`/api/auth/callback`,Ai=`/.well-known/oauth-client.json`,ji=`/.well-known/oauth-cli-client.json`,Mi=`openid profile email offline_access organizations:read`;function Ni(e,t){return{client_id:`${e}${Ai}`,client_name:`Coder at ${new URL(e).host}`,redirect_uris:[`${e}${ki}`],post_logout_redirect_uris:[`${e}/?signed_out=1`],grant_types:[`authorization_code`,`refresh_token`],response_types:[`code`],token_endpoint_auth_method:`private_key_jwt`,token_endpoint_auth_signing_alg:`ES256`,jwks:t,scope:Mi}}function Pi(e){return{client_id:`${e}${ji}`,client_name:`Coder CLI for ${new URL(e).host}`,redirect_uris:[`http://127.0.0.1/callback`],grant_types:[`authorization_code`,`refresh_token`,`urn:ietf:params:oauth:grant-type:device_code`],response_types:[`code`],token_endpoint_auth_method:`none`,scope:Mi}}function Fi(e,t){return{resource:new URL(e).origin,authorization_servers:[t],bearer_methods_supported:[`header`],scopes_supported:Mi.split(` `)}}function Ii(e){let t=E(e);return t.headers.set(`cache-control`,`public, max-age=3600`),t}function Li(e,t,n,r){return t.config.publicUrl&&t.auth?Ii(Ni(t.config.publicUrl,t.auth.jwks)):void 0}function Ri(e,t,n,r){return t.config.publicUrl&&t.auth?Ii(Pi(t.config.publicUrl)):void 0}function zi(e,t,n,r){return t.config.publicUrl&&t.auth?Ii(Fi(t.config.publicUrl,t.auth.issuer)):void 0}const Bi=[B(`GET`,Ai,Li,Ue),B(`GET`,ji,Ri,Ue),B(`GET`,`/.well-known/oauth-protected-resource`,zi,Ue),B(`GET`,`/health`,(e,t)=>Qn(t)),B(`GET`,`/`,fn,Te),B(`GET`,`/login`,Mt,An),...Rt(`/login`,kt,An).filter(e=>e.method!==`GET`),B(`POST`,`/dash/token`,rn,Cn),...Rt(`/dash`,Tt,_e)],Vi=[B(`GET`,`/api/auth/capabilities`,(e,t)=>E({wular:t.auth?.issuer??null})),...Rt(`/api/auth`,(e,t)=>t.auth.handler(e),On),B(`GET`,`/me`,tr,zt),B(`POST`,`/me/organization`,rr,Ze)],Hi=[...U(`/tasks`,[B(`GET`,`/:id/messages`,Re,Se),B(`POST`,`/:id/ack`,lt,Se),B(`POST`,`/:id/heartbeat`,ht,Se),B(`POST`,`/:id/result`,Fe,Dt),B(`POST`,`/:id/credential`,ln,Dt),B(`GET`,`/:id`,Oe,ft)]),...U(`/logins`,[B(`GET`,`/:id/input`,mr,Gt),B(`GET`,`/:id`,hr,Gt),B(`POST`,`/:id`,gr,Gt)]),...U(`/runners`,[B(`POST`,`/register`,en)])],Ui=[...U(`/create`,[B(`GET`,`/:id`,_r,Tn),B(`POST`,`/:id`,_r,Tn),B(`GET`,`/:id/callback`,vr,Tn),B(`POST`,`/:id/callback`,yr,Tn)]),...U(`/install`,[B(`GET`,`/:id`,br,M),B(`POST`,`/:id`,br,M),B(`GET`,`/:id/callback`,xr,M),B(`POST`,`/:id/callback`,xr,M)])],Wi=U(`/connect`,[B(`GET`,``,wr,je),B(`POST`,``,Tr,je),B(`GET`,`/:integration`,Er,Ke),B(`GET`,`/:integration/callback`,Dr,Ke)]),Gi=[...U(`/hooks`,[B(`POST`,`/*`,(e,t,n)=>pe(e,t,n[`*`]),(e,t,n)=>t.integrations[n[`*`]]?t:O())]),...Ui,...Wi],Ki=[B(`GET`,`/metrics`,async(e,t)=>E(await er(t),200,{"cache-control":`no-store`}),bn),B(`GET`,`/usage`,In),B(`GET`,`/usage/totals`,Ln)],qi=U(``,[B(`GET`,`/folders`,(e,t)=>E(fe(t.local.cwd))),B(`POST`,`/folders/check`,async(e,t)=>{let n=await e.json().catch(()=>void 0);return E(qe(n?.path))}),B(`POST`,`/folders/clone`,async(e,t)=>{let n=await e.json().catch(()=>void 0);return E(await qt(n?.url))}),B(`POST`,`/folders/pick`,async(e,t)=>E(await Wt()))],Jt),Ji=U(``,[B(`GET`,`/engines/status`,async(e,t)=>E(await jt())),B(`POST`,`/engines/:engine/login`,on),B(`POST`,`/engines/:engine/logout`,$t)],ot),Yi=[B(`POST`,`/apps/:id/install`,(e,t,n,r)=>Ar(e,t,n.id,r.searchParams.get(`back`))),B(`GET`,`/apps`,jr),B(`GET`,`/installations`,Mr),B(`POST`,`/connections`,(e,t)=>kr(e,t)),B(`GET`,`/integrations`,(e,t)=>Nr(t)),B(`GET`,`/repositories`,(e,t)=>Pr(t))],Xi=[B(`GET`,`/agents/import`,Lr),B(`POST`,`/agents/import`,Rr),B(`GET`,`/agents`,Vr),B(`PATCH`,`/agents/:slug/settings`,Yr),B(`GET`,`/agents/:slug/versions`,Hr),B(`GET`,`/agents/:slug/versions/:version`,Ur),B(`GET`,`/agents/:slug`,Wr),B(`DELETE`,`/agents/:slug`,Xr,(e,t)=>Ne(t,`Only an owner or admin can delete an agent.`)),B(`PUT`,`/agents/:slug`,Zr)],Zi=[B(`GET`,`/credentials`,_n),B(`POST`,`/credentials`,Et,rt),B(`POST`,`/credentials/:label/default`,At),B(`DELETE`,`/credentials/:label`,Zt),B(`POST`,`/logins`,ir,j),B(`GET`,`/logins/:id`,ar,j),B(`POST`,`/logins/:id`,or,j),B(`DELETE`,`/logins/:id`,sr,j)],Qi=[B(`GET`,`/runners`,Nt),B(`POST`,`/runners`,$e),B(`POST`,`/runners/pair`,mn),B(`POST`,`/runners/:id/test`,St),B(`PATCH`,`/runners/:id`,dn),B(`DELETE`,`/runners/:id`,ue)],$i=[B(`GET`,`/tasks`,Ye),B(`POST`,`/tasks`,Kt),B(`GET`,`/tasks/:id`,Me),B(`DELETE`,`/tasks/:id`,ze),B(`GET`,`/tasks/:id/logs`,kn),B(`GET`,`/tasks/:id/stream`,Qr),B(`POST`,`/tasks/:id/steer`,et),B(`POST`,`/tasks/:id/ask`,Ve),B(`POST`,`/tasks/:id/approve`,de),B(`POST`,`/tasks/:id/cancel`,We),B(`POST`,`/tasks/:id/archive`,Ut),B(`GET`,`/events`,ti)],ea=[B(`GET`,`/config`,xn),B(`PATCH`,`/config`,he),B(`PUT`,`/config`,it)],ta=[B(`POST`,`/models/probe`,(e,t)=>di(e,t)),B(`GET`,`/models`,pi),B(`POST`,`/models`,mi),B(`DELETE`,`/models/:name`,hi),B(`POST`,`/models/:name/alias`,gi),B(`POST`,`/models/:name/disable`,_i),B(`POST`,`/models/:name/enable`,vi)],na=[B(`GET`,`/mcp`,bi),B(`POST`,`/mcp`,xi),B(`DELETE`,`/mcp/:name`,Si),B(`GET`,`/mcp-registry`,(e,t,n,r)=>Di(e,t,r))],ra=[B(`GET`,`/flows`,ut),B(`GET`,`/pulls`,ke),B(`POST`,`/flows/:name/run`,pt),B(`POST`,`/review`,st)],ia=U(`/admin`,[...Ki,...qi,...Ji,...Yi,...Xi,...Zi,...Qi,...$i,...ea,...ta,...na,...ra]).map(e=>({...e,guard:wt(e.guard)})),aa=[...Hi,...ia,...Vi,...Gi,...Bi];async function oa(e,t,n){if(!Je(e,t))return O();let r=new URL(e.url);return n.scope instanceof Response?n.scope:(t=n.scope??t,await Qt(aa,e,t,r)??Xt(e,t,r))}const sa=`x-coder-request-scope`;function ca(e,{sessions:t,cookies:n}){let r=e.auth;return r?{...e,auth:{...r,session(e,i){let a=JSON.stringify([...[`cookie`,`authorization`,`x-coder-organization`].map(t=>e.get(t)),!!i]),o=t.get(a);return o||(o=r.session(e,i,n),t.set(a,o)),o}}}:e}function la(e,t,n){let r=t.requestScopes??=new Map,i=e.headers.get(sa),a=n&&i?r.get(i):void 0;if(a)return{req:e,ctx:ca(t,a),end(){}};let o=new Headers(e.headers);if(o.delete(sa),!t.auth)return{req:i?new Request(e,{headers:o}):e,ctx:t,end(){}};let s=Vn(),c={sessions:new Map,cookies:[]};return r.set(s,c),o.set(sa,s),{req:new Request(e,{headers:o}),ctx:ca(t,c),cookies:c.cookies,end:()=>r.delete(s)}}async function ua(e,t,n={}){t.limits??=new Qe((t.now??Date.now)()),t.limits.requests++,t.settings??={},t.taskWatcher??=new ri,t.logWatcher??=new ai,t.dashboardHosts??=new Ht;let r=()=>da(e,t,n);return t.dbProfile?t.dbProfile.request(n.inProcess===!0,r):r()}async function da(e,t,n){let r=await ie(e,se(new URL(e.url).pathname));if(r instanceof Response)return r;let i=la(r,t,n.inProcess===!0),a=!1;try{let r=n.clientIp??`unknown`,o=await le(i.req,i.ctx,r),s=fa(o instanceof Response?o:await oa(i.req,i.ctx,o),i.cookies),c=new URL(e.url).pathname.split(`/`),l=c[1]===`tasks`,u=c[1]===`admin`&&c[2]===`tasks`;return e.method!==`GET`&&s.ok&&![`hooks`,`tasks`,`logins`].includes(c[1])&&Yt(t),e.method!==`GET`&&s.ok&&!(l&&c.length===4&&c[2]&&c[3]===`heartbeat`)&&!(u&&c.length===5&&c[3]&&[`steer`,`ask`,`approve`,`archive`].includes(c[4]))&&(l||u||c[1]===`admin`&&c[2]===`review`||c[1]===`admin`&&c[2]===`flows`&&c.length===5&&c[3]&&c[4]===`run`)&&bt(t,u&&c.length===3&&e.method===`POST`),a=!!s.body&&(s.headers.get(`content-type`)??``).includes(`text/html`),a?pa(s,i.end):s}finally{a||i.end()}}function fa(e,t=[]){if(!t.length)return e;let n=new Headers(e.headers);for(let e of t)n.append(`set-cookie`,e);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}function pa(e,t){let n=e.body.getReader(),r=new ReadableStream({async pull(e){try{let{done:r,value:i}=await n.read();r?(t(),e.close()):e.enqueue(i)}catch(n){t(),e.error(n)}},cancel(e){return t(),n.cancel(e)}});return new Response(r,e)}async function ma(e={}){let t=e.env??J.env,n=jn(t,e.host??`node`),r=e.runner??n.runner;if((e.host===`vercel`||t.VERCEL)&&(r===`local`||r===`local-docker`))throw new s(`invalid-option`,`The ${r} runner cannot run on Vercel.`,{hint:`Leave RUNNER unset to use vercel-sandbox.`});if(n.store===`memory`&&r!==`local`&&r!==`local-docker`)throw new s(`invalid-option`,`The ${r} runner needs a database.`,{hint:`Set DATABASE_URL, or use RUNNER=local for a memory server.`});if(!n.publicUrl)throw new s(`invalid-option`,`PUBLIC_URL is required to start a Coder server.`,{hint:`Set PUBLIC_URL to the address platforms and browsers use.`});let i=[];if(n.store===`memory`&&!e.local&&i.push(`test server, not for production: everything is in memory, nothing survives a restart, no sign-in; set DATABASE_URL for a real deployment`),!t.SERVER_ENCRYPTION_KEY&&!e.local&&i.push(`secrets are stored unencrypted; set SERVER_ENCRYPTION_KEY (openssl rand -base64 32)`),n.store===`postgres`&&!n.encryptionKey)throw new s(`invalid-option`,`SERVER_ENCRYPTION_KEY is required for a Postgres server.`,{hint:`Set SERVER_ENCRYPTION_KEY (openssl rand -base64 32); sign-in keys derive from it.`});let a=ee(n.integrations),o=n.store===`memory`&&!n.adminToken?Bn(18).toString(`base64url`):void 0;n.store===`postgres`&&n.adminToken&&i.push(`ADMIN_TOKEN is ignored with Postgres; owners and admins sign in with coder auth login`);let c={...n,...n.store===`postgres`?{adminToken:void 0}:{},...o?{adminToken:o}:{},...e.runner?{runner:e.runner}:{}},l=await pn(c,{local:!!e.local});if(l.connection)try{let e=await Pn(l.connection.db);if(!e.applied)throw new s(`server`,`The database is not set up yet.`,{hint:`Create the tables: coder server migrate`});e.pending&&i.push(`database is ${e.pending} migration${e.pending===1?``:`s`} behind; run coder server migrate`)}catch(e){throw await l.close(),e}try{c.store===`memory`&&await Sn(l.store(l.defaultOrganizationId),Date.now());let n=l.connection&&c.auth?await(await import(`./auth-q8CROpG-.js`)).createAuth(l.connection.db,c):void 0,r=e.cwd??J.cwd(),u=l.store(l.defaultOrganizationId),d=Ge({kind:c.runner,workDir:c.workDir,config:c.runnerConfig,local:!(e.host===`vercel`||t.VERCEL),sandbox:{region:we(c.databaseUrl),snapshots:{get:e=>u.get(`snapshot`,e),put:(e,t)=>u.put(`snapshot`,e,t)}}});if(!d[c.runner])throw await l.close(),new s(`invalid-option`,`Runner ${c.runner} is not configured.`,{hint:`Set RUNNER_CONFIG to JSON containing url and secret.`});let f=new Ht,p=new Qe,m=new Map,h=new Map,g=new ri,_=new ai,v=t=>{let i=m.get(t);if(i)return i;let o=l.store(t),s={limits:p,...l.connection?{databaseHealth:async()=>{await l.connection.db.execute(Wn`select 1`)},statementTimeout:l.connection.statementTimeout,healthRunners:async()=>{let[e]=await l.connection.db.select({total:Wn`count(*)::int`,online:Wn`count(*) filter (where ${Nn.lastSeen} > clock_timestamp() - interval '5 minutes')::int`}).from(Nn);return e??{online:0,total:0}}}:{},config:c,settings:{},organizationId:t,integrations:a,runners:d,store:o,queue:l.queue,requestScopes:h,taskWatcher:g,logWatcher:_,dashboardHosts:f,dbProfile:l.connection?.profile,chatState:l.chatState,loadAgent:sn(a,{cwd:r,config:c,store:o}),...n?{auth:n}:{},scope:v,webhookTarget:(e,t)=>l.webhookTarget(e,t),appRecord:e=>l.appRecord(e),installationOrganization:e=>l.installationOrganization(e),installations:e=>l.installations(e),serverOrganizationId:l.defaultOrganizationId,taskOrganization:(e,t)=>l.taskOrganization(e,t),...e.local?{local:e.local}:{}};return m.set(t,s),s};globalThis.__coder={handle:e=>ua(e,v(l.defaultOrganizationId),{inProcess:!0})};let y=v(l.defaultOrganizationId),b;return e.local&&(await Lt(y),b=setImmediate(()=>{En(y).catch(()=>void 0)})),{config:c,context:v,defaultContext:y,warnings:i,...o?{mintedToken:o}:{},sweep:l.sweep,close:async()=>{g.close(),_.close(),b&&clearImmediate(b),await y.local?.usageSync?.catch(()=>void 0),await Ct(y),await l.close()}}}catch(e){throw await l.close(),e}}var ha=e({serve:()=>ya,serverHandler:()=>_a});function ga(e){try{let t=new URL(e);return Bt.has(t.hostname)?Number(t.port||(t.protocol===`https:`?443:80)):void 0}catch{return}}function _a(e=J.env,t=e.VERCEL?`vercel`:`node`){Mn();let n,r=()=>n??=ma({env:e,host:t}).catch(e=>{throw n=void 0,e});return Object.assign(async(t,n)=>{let i=await r(),a=n?e=>n(e):e=>void e.catch(()=>{}),o=e=>({...i.context(e),waitUntil:a,scope:o});return ua(t,o(i.defaultContext.organizationId),{clientIp:e.VERCEL?t.headers.get(`x-forwarded-for`)?.split(`,`,1)[0]?.trim():void 0})},{scheduled:async()=>{let e=await r();await Promise.all([e.sweep(),import(`./store-qp7UE2ES.js`).then(e=>e.Y).then(t=>t.renewInstallations(e.defaultContext)),gt(e.defaultContext,!1,!0),Ot(e.defaultContext)])},close:async()=>{let e=n;n=void 0,await(await e)?.close()}})}async function va(e={}){Mn();let t=e.env??J.env;if(e.runner&&!He.includes(e.runner))throw new s(`invalid-option`,`Invalid --runner value: use ${He.join(`, `)}`);if(e.port!==void 0&&(!Number.isInteger(e.port)||e.port<1||e.port>65535))throw new s(`invalid-option`,`Invalid port: use 1 through 65535.`);let n=t.PORT&&/^\d+$/.test(t.PORT)?Number(t.PORT):void 0,r=ga(t.PUBLIC_URL),i=e.port??n??r??8787;if(!Number.isInteger(i)||i<1||i>65535)throw new s(`invalid-option`,`Invalid PORT: use 1 through 65535.`);let a=t.PUBLIC_URL?t:{...t,PUBLIC_URL:`http://localhost:${i}`},o=!!(t.DATABASE_URL||t.POSTGRES_URL);if(o&&e.memory)throw new s(`invalid-option`,`A memory server cannot use DATABASE_URL.`,{hint:`Unset DATABASE_URL, or drop --memory.`});let c=(e.host??t.HOST??(o?void 0:`127.0.0.1`))?.replace(/^\[(.*)\]$/,`$1`),l=!o&&!e.memory;if(l&&!Bt.has(c))throw new s(`invalid-option`,`A local server listens on loopback only.`,{hint:`Reach it through a tunnel or a proxy on this machine; set DATABASE_URL for a deployment, or use --memory for a test server.`});if(e.memory&&t.VERCEL)throw new s(`invalid-option`,`A memory server cannot run on Vercel.`,{hint:`Set DATABASE_URL for a real deployment.`});let u,d,f=l?new Promise((e,t)=>{d=t,u=()=>{Xn().then(e,t)}}):void 0,p=f?.then(()=>void 0).catch(()=>void 0),m=l?{cwd:e.cwd??J.cwd(),port:i,cacheMaintenance:p}:void 0,h=await ma({cwd:e.cwd,env:a,runner:e.runner,...m?{local:m}:{}}),g=h.defaultContext,_=()=>{h.sweep().catch(()=>{}),import(`./store-qp7UE2ES.js`).then(e=>e.Y).then(e=>e.renewInstallations(g)).catch(()=>{})};_();let v=setInterval(_,36e5);v.unref();let y=setInterval(()=>{gt(g,!1,!0).catch(()=>{}),Ot(g).catch(()=>{}),t.PUBLIC_URL||import(`./store-qp7UE2ES.js`).then(e=>e.Y).then(e=>e.renewInstallations(g,`sync`)).catch(()=>{})},6e4);y.unref();let b=Un.createServer(oe((e,t)=>ua(e,g,{clientIp:t}),{limit:se,admit:e=>o||me(e.socket.remoteAddress,e.url??`/`)})),x=h.config.publicUrl;r!==void 0&&r!==i&&h.warnings.push(`PUBLIC_URL points at port ${r} but the server listens on ${i}`),await new Promise((e,t)=>{b.once(`error`,t),b.listen(i,c,e)}).catch(async e=>{throw d?.(e),clearInterval(y),clearInterval(v),await h.close(),e});let S=u?setTimeout(u,0):void 0,C=!1,w=async()=>{C||(C=!0,clearInterval(y),clearInterval(v),g.taskWatcher?.close(),g.logWatcher?.close(),await new Promise((e,t)=>b.close(n=>n?t(n):e())),await p,S&&clearTimeout(S),await h.close())},ee=g.auth?`Wular Auth (${g.auth.issuer})`:void 0,te=`http://localhost:${i}`,T=tt(g),E=T===`local`?te:x,D=h.config.store===`memory`?h.mintedToken??t.ADMIN_TOKEN:void 0;return{address:te,publicUrl:x,warnings:h.warnings,close:w,runner:h.config.runner,store:h.config.store,mode:T,...f?{cacheMigration:f}:{},maxTasks:h.config.maxTasks??h.config.limits?.concurrentTasks??10,...ee?{signIn:ee}:{},...h.mintedToken?{mintedToken:h.mintedToken}:{},...h.config.store===`postgres`&&t.DATABASE_URL?{database:Fn(t.DATABASE_URL)}:{},...Bt.has(new URL(E).hostname)?{dashboard:`${E}/dash${D?`#token=${encodeURIComponent(D)}`:``}`}:{}}}async function ya(e={}){try{return await va(e)}catch(e){if(e instanceof s)throw e;let t=e instanceof Error&&e.cause instanceof Error?`: ${e.cause.message}`:``;throw new s(`server`,`${e instanceof Error?e.message:String(e)}${t}`)}}export{Mi as a,ki as i,ha as n,Ai as o,_a as r,ya as t};
8
+ `),this.options.heartbeatMs??2e4)];for(let e of s.timers)e.unref?.();return a.watches.add(s),a.reading===void 0&&t<a.head&&(clearTimeout(a.timer),this.read(a)),()=>this.drop(s)}close(){this.closed=!0;for(let e of[...this.feeds.values()])for(let t of[...e.watches])this.end(t)}drop(e){let{feed:t}=e;for(let t of e.timers)clearTimeout(t);!t.watches.delete(e)||t.watches.size||(clearTimeout(t.timer),this.feeds.get(t.key)===t&&this.feeds.delete(t.key))}end(e,t=``){try{t&&e.send(t),e.close()}catch{}this.drop(e)}send(e,t){try{e.send(t)}catch{this.drop(e)}}async read(e){if(e.timer=void 0,this.feeds.get(e.key)!==e||!e.watches.size)return;let t=[...e.watches],n=Math.min(...t.map(e=>e.cursor));e.reading=Date.now(),this.reads++;let r=await e.read(n).catch(()=>null);if(e.reading=void 0,this.feeds.get(e.key)!==e)return;let i=t.filter(t=>e.watches.has(t)),a=i.length<e.watches.size?0:this.options.pollMs??1e3;if(r===void 0)for(let e of i)this.end(e);else if(r){let{status:t,lines:o,pendingLogs:s,pendingResult:c}=r,l=o.length===500,u=F.has(t.status)&&!l&&!s&&!c,d=o.map(e=>[e.seq,`id: ${e.seq}\nevent: log\ndata: ${JSON.stringify(e)}\n\n`]);e.head=Math.max(n,o.at(-1)?.seq??n),l&&(a=0);for(let e of i){let t=d.flatMap(([t,n])=>t>e.cursor?[n]:[]).join(``);e.cursor=Math.max(e.cursor,o.at(-1)?.seq??-1),u?this.end(e,`${t}event: end\ndata: {}\n\n`):t&&this.send(e,t)}}this.feeds.get(e.key)===e&&(e.timer=setTimeout(()=>void this.read(e),a),e.timer.unref?.())}};function oi(e,t,n,r,i){let a=t.logWatcher??new ai,o=new TextEncoder,s=()=>{},c=new ReadableStream({start(c){c.enqueue(o.encode(`retry: ${ei}\n\n`)),s=a.watch(`${t.organizationId}:${n}`,r,i,e=>c.enqueue(o.encode(e)),()=>c.close());let l=()=>{s();try{c.close()}catch{}};e.signal.aborted?l():e.signal.addEventListener(`abort`,l)},cancel(){s()}});return new Response(c,{headers:{"content-type":`text/event-stream; charset=utf-8`,"cache-control":`no-cache, no-transform`}})}var si=class{options;entries=new Map;pending=new Map;constructor(e={ttlMs:6e5,max:100}){this.options=e}get size(){return this.entries.size}get inFlight(){return this.pending.size}has(e){return this.entries.has(e)}keys(){return this.entries.keys()}async get(e,t){let n=this.options.now??Date.now,r=n(),i=this.entries.get(e);if(i&&r-i.at<this.options.ttlMs)return i.value;for(let[t,n]of this.entries)t!==e&&r-n.at>=this.options.ttlMs&&this.entries.delete(t);let a=this.pending.get(e);return a||(a=Promise.resolve().then(t).then(t=>{if(t===void 0)return i?.value;if(this.options.accept&&!this.options.accept(t))return i?.value??t;this.entries.set(e,{value:t,at:n()});let r=this.entries.keys().next().value;return this.entries.size>this.options.max&&r!==void 0&&this.entries.delete(r),t}).catch(()=>i?.value).finally(()=>this.pending.delete(e)),this.pending.set(e,a)),a}};const ci=/^[a-z0-9][a-z0-9-]*$/,li=new Set([`openrouter.ai`,`ai-gateway.vercel.sh`,`api.groq.com`,`api.together.xyz`]);function ui(e){return{builtin:{codex:i,claude:c},models:e.models??{}}}async function di(e,t){let{baseUrl:n,envKey:r,key:i}=await K(e);if(!n||!/^https?:\/\//.test(n)||!URL.canParse(n))return E({error:`An http or https base URL is required`},400);let a=!i&&r&&await fi(t,n,r)?await an(t,r):void 0,o=i||a,s=t.settings??={},c=s.probes??=new si({ttlMs:6e5,max:100,now:t.now,accept:e=>e.reachable}),l=`${new URL(n).host}|${r??``}|${C(String(o??``))}`;return E(await c.get(l,()=>te({baseUrl:n},{key:o,fetch:t.fetch})))}async function fi(e,t,n){let r=new URL(t).host;if(li.has(r))return!0;let i=(await be(e)).models??{};return Object.values(i).some(e=>`baseUrl`in e&&e.envKey===n&&new URL(e.baseUrl).host===r)}async function pi(e,t,n,r){return E(ui(await be(t)))}async function mi(e,n,r,i){let{name:a=``,...o}=await K(e);return!ci.test(a)||t(a)?E({error:`Invalid model name "${a}"`},400):R(n,e=>{if(e.models?.[a])throw new V(`"${a}" already exists`);e.models={...e.models,[a]:o}})}async function hi(e,t,n,r){let i=n.name;return R(t,e=>{if(!e.models?.[i])throw new V(`No model "${i}"`);g(e,i)})}async function gi(e,t,a,o){let s=a.name,{spec:l}=await K(e);return R(t,e=>{if(!ci.test(s))throw new V(`Invalid alias name "${s}"`);let t=e.models?.[s];if(t&&f(t))throw new V(`"${s}" is a custom model name`);let a=d(l,u(e));if(!a?.model||a.engine===`custom`)throw new V(`"${l}" does not name a codex or claude model`);let o=a.engine===`claude`?c:i,p=l.split(`:`).some(e=>n.has(e)||r.has(e));e.models={...e.models,[s]:{provider:a.engine,model:o[a.model]??a.model,...p&&a.effort?{effort:a.effort}:{}}}})}async function _i(e,t,n,r){let i=n.name;return R(t,e=>{let t=e.models??={},n=t[i];n&&(f(n)||o(n))?n.disabled=!0:t[i]={disabled:!0}})}async function vi(e,t,n,r){let i=n.name;return R(t,e=>{let t=e.models??={},n=t[i];n&&(f(n)||o(n))?delete n.disabled:delete t[i]})}const yi=/^[a-z0-9][a-z0-9_-]*$/i;async function bi(e,t,n,r){return E((await be(t)).mcp??{})}async function xi(e,t,n,r){let{name:i=``,...a}=await K(e);return yi.test(i)?R(t,e=>{e.mcp={...e.mcp,[i]:a}}):E({error:`Invalid server name "${i}"`},400)}async function Si(e,t,n,r){let i=n.name;return R(t,e=>{if(!e.mcp?.[i])throw new V(`No MCP server "${i}"`);delete e.mcp[i]})}const Ci={npm:[`npx`,`-y`],pypi:[`uvx`],oci:[`docker`,`run`,`-i`,`--rm`]},wi=(e=[])=>e.map(({name:e,description:t,isRequired:n,isSecret:r,value:i,default:a})=>({name:e,...t?{description:t}:{},...i??a?{placeholder:i??a}:{},required:n===!0,secret:r===!0}));function Ti(e=[],t,n){return e.flatMap((e,r)=>{let i=`${t}:${r}`,a=Object.entries(e.variables??{}),o=e.value??e.default,s=(e,t,r)=>{let[i]=wi([{...r,name:e}]);return n.push({...i,label:t}),`{${e}}`};if(a.length)for(let[e,t]of a)o=o?.replaceAll(`{${e}}`,s(`${i}:${e}`,e,t));else o===void 0&&(e.valueHint||e.isRequired)&&(o=s(i,e.valueHint??e.name??i,e));return[...e.type===`named`&&e.name?[e.name]:[],...o===void 0?[]:[o]]})}function Ei(e){let t=e.remotes?.find(e=>e.type===`streamable-http`||e.type===`sse`);if(t)return{type:t.type===`sse`?`sse`:`http`,url:t.url,env:[],headers:wi(t.headers)};let n=e.packages?.find(e=>Ci[e.registryType]&&(e.transport?.type??`stdio`)===`stdio`);if(!n)return;let[r,...i]=Ci[n.registryType],a=[],o=Ti(n.runtimeArguments,`runtime`,a),s=Ti(n.packageArguments,`package`,a);return{type:`stdio`,command:n.runtimeHint??r,args:[...!n.runtimeHint||n.runtimeHint===r?i:[],...o,n.identifier,...s],...a.length?{argumentInputs:a}:{},env:wi(n.environmentVariables),headers:[]}}async function Di(e,t,n){let r=n.searchParams.get(`q`)?.trim()??``,i=t.settings??={},a=await(i.registry??=new si({ttlMs:6e5,max:100,now:t.now})).get(r,()=>Oi(t,r));return a?E(a):E({error:`The MCP registry did not answer. Try again.`},502)}async function Oi(e,t){let n=new URLSearchParams({version:`latest`,limit:`30`});t&&n.set(`search`,t);try{let t=await(e.fetch??fetch)(`https://registry.modelcontextprotocol.io/v0.1/servers?${n}`,{headers:{accept:`application/json`},signal:AbortSignal.timeout(2e4)});if(!t.ok)return;let{servers:r=[]}=await t.json();return r.flatMap(({server:e})=>{let t=Ei(e);return t?[{name:e.name,title:e.title??e.name.split(`/`).pop()??e.name,description:e.description??``,...t}]:[]})}catch{return}}const ki=`/api/auth/callback`,Ai=`/.well-known/oauth-client.json`,ji=`/.well-known/oauth-cli-client.json`,Mi=`openid profile email offline_access organizations:read`;function Ni(e,t){return{client_id:`${e}${Ai}`,client_name:`Coder at ${new URL(e).host}`,redirect_uris:[`${e}${ki}`],post_logout_redirect_uris:[`${e}/?signed_out=1`],grant_types:[`authorization_code`,`refresh_token`],response_types:[`code`],token_endpoint_auth_method:`private_key_jwt`,token_endpoint_auth_signing_alg:`ES256`,jwks:t,scope:Mi}}function Pi(e){return{client_id:`${e}${ji}`,client_name:`Coder CLI for ${new URL(e).host}`,redirect_uris:[`http://127.0.0.1/callback`],grant_types:[`authorization_code`,`refresh_token`,`urn:ietf:params:oauth:grant-type:device_code`],response_types:[`code`],token_endpoint_auth_method:`none`,scope:Mi}}function Fi(e,t){return{resource:new URL(e).origin,authorization_servers:[t],bearer_methods_supported:[`header`],scopes_supported:Mi.split(` `)}}function Ii(e){let t=E(e);return t.headers.set(`cache-control`,`public, max-age=3600`),t}function Li(e,t,n,r){return t.config.publicUrl&&t.auth?Ii(Ni(t.config.publicUrl,t.auth.jwks)):void 0}function Ri(e,t,n,r){return t.config.publicUrl&&t.auth?Ii(Pi(t.config.publicUrl)):void 0}function zi(e,t,n,r){return t.config.publicUrl&&t.auth?Ii(Fi(t.config.publicUrl,t.auth.issuer)):void 0}const Bi=[B(`GET`,Ai,Li,Ue),B(`GET`,ji,Ri,Ue),B(`GET`,`/.well-known/oauth-protected-resource`,zi,Ue),B(`GET`,`/health`,(e,t)=>Qn(t)),B(`GET`,`/`,fn,Te),B(`GET`,`/login`,Mt,An),...Rt(`/login`,kt,An).filter(e=>e.method!==`GET`),B(`POST`,`/dash/token`,rn,Cn),...Rt(`/dash`,Tt,_e)],Vi=[B(`GET`,`/api/auth/capabilities`,(e,t)=>E({wular:t.auth?.issuer??null})),...Rt(`/api/auth`,(e,t)=>t.auth.handler(e),On),B(`GET`,`/me`,tr,zt),B(`POST`,`/me/organization`,rr,Ze)],Hi=[...U(`/tasks`,[B(`GET`,`/:id/messages`,Re,Se),B(`POST`,`/:id/ack`,lt,Se),B(`POST`,`/:id/heartbeat`,ht,Se),B(`POST`,`/:id/result`,Fe,Dt),B(`POST`,`/:id/credential`,ln,Dt),B(`GET`,`/:id`,Oe,ft)]),...U(`/logins`,[B(`GET`,`/:id/input`,mr,Gt),B(`GET`,`/:id`,hr,Gt),B(`POST`,`/:id`,gr,Gt)]),...U(`/runners`,[B(`POST`,`/register`,en)])],Ui=[...U(`/create`,[B(`GET`,`/:id`,_r,Tn),B(`POST`,`/:id`,_r,Tn),B(`GET`,`/:id/callback`,vr,Tn),B(`POST`,`/:id/callback`,yr,Tn)]),...U(`/install`,[B(`GET`,`/:id`,br,M),B(`POST`,`/:id`,br,M),B(`GET`,`/:id/callback`,xr,M),B(`POST`,`/:id/callback`,xr,M)])],Wi=U(`/connect`,[B(`GET`,``,wr,je),B(`POST`,``,Tr,je),B(`GET`,`/:integration`,Er,Ke),B(`GET`,`/:integration/callback`,Dr,Ke)]),Gi=[...U(`/hooks`,[B(`POST`,`/*`,(e,t,n)=>pe(e,t,n[`*`]),(e,t,n)=>t.integrations[n[`*`]]?t:O())]),...Ui,...Wi],Ki=[B(`GET`,`/metrics`,async(e,t)=>E(await er(t),200,{"cache-control":`no-store`}),bn),B(`GET`,`/usage`,In),B(`GET`,`/usage/totals`,Ln)],qi=U(``,[B(`GET`,`/folders`,(e,t)=>E(fe(t.local.cwd))),B(`POST`,`/folders/check`,async(e,t)=>{let n=await e.json().catch(()=>void 0);return E(qe(n?.path))}),B(`POST`,`/folders/clone`,async(e,t)=>{let n=await e.json().catch(()=>void 0);return E(await qt(n?.url))}),B(`POST`,`/folders/pick`,async(e,t)=>E(await Wt()))],Jt),Ji=U(``,[B(`GET`,`/engines/status`,async(e,t)=>E(await jt())),B(`POST`,`/engines/:engine/login`,on),B(`POST`,`/engines/:engine/logout`,$t)],ot),Yi=[B(`POST`,`/apps/:id/install`,(e,t,n,r)=>Ar(e,t,n.id,r.searchParams.get(`back`))),B(`GET`,`/apps`,jr),B(`GET`,`/installations`,Mr),B(`POST`,`/connections`,(e,t)=>kr(e,t)),B(`GET`,`/integrations`,(e,t)=>Nr(t)),B(`GET`,`/repositories`,(e,t)=>Pr(t))],Xi=[B(`GET`,`/agents/import`,Lr),B(`POST`,`/agents/import`,Rr),B(`GET`,`/agents`,Vr),B(`PATCH`,`/agents/:slug/settings`,Yr),B(`GET`,`/agents/:slug/versions`,Hr),B(`GET`,`/agents/:slug/versions/:version`,Ur),B(`GET`,`/agents/:slug`,Wr),B(`DELETE`,`/agents/:slug`,Xr,(e,t)=>Ne(t,`Only an owner or admin can delete an agent.`)),B(`PUT`,`/agents/:slug`,Zr)],Zi=[B(`GET`,`/credentials`,_n),B(`POST`,`/credentials`,Et,rt),B(`POST`,`/credentials/:label/default`,At),B(`DELETE`,`/credentials/:label`,Zt),B(`POST`,`/logins`,ir,j),B(`GET`,`/logins/:id`,ar,j),B(`POST`,`/logins/:id`,or,j),B(`DELETE`,`/logins/:id`,sr,j)],Qi=[B(`GET`,`/runners`,Nt),B(`POST`,`/runners`,$e),B(`POST`,`/runners/pair`,mn),B(`POST`,`/runners/:id/test`,St),B(`PATCH`,`/runners/:id`,dn),B(`DELETE`,`/runners/:id`,ue)],$i=[B(`GET`,`/tasks`,Ye),B(`POST`,`/tasks`,Kt),B(`GET`,`/tasks/:id`,Me),B(`DELETE`,`/tasks/:id`,ze),B(`GET`,`/tasks/:id/logs`,kn),B(`GET`,`/tasks/:id/stream`,Qr),B(`POST`,`/tasks/:id/steer`,et),B(`POST`,`/tasks/:id/ask`,Ve),B(`POST`,`/tasks/:id/approve`,de),B(`POST`,`/tasks/:id/cancel`,We),B(`POST`,`/tasks/:id/archive`,Ut),B(`GET`,`/events`,ti)],ea=[B(`GET`,`/config`,xn),B(`PATCH`,`/config`,he),B(`PUT`,`/config`,it)],ta=[B(`POST`,`/models/probe`,(e,t)=>di(e,t)),B(`GET`,`/models`,pi),B(`POST`,`/models`,mi),B(`DELETE`,`/models/:name`,hi),B(`POST`,`/models/:name/alias`,gi),B(`POST`,`/models/:name/disable`,_i),B(`POST`,`/models/:name/enable`,vi)],na=[B(`GET`,`/mcp`,bi),B(`POST`,`/mcp`,xi),B(`DELETE`,`/mcp/:name`,Si),B(`GET`,`/mcp-registry`,(e,t,n,r)=>Di(e,t,r))],ra=[B(`GET`,`/flows`,ut),B(`GET`,`/pulls`,ke),B(`POST`,`/flows/:name/run`,pt),B(`POST`,`/review`,st)],ia=U(`/admin`,[...Ki,...qi,...Ji,...Yi,...Xi,...Zi,...Qi,...$i,...ea,...ta,...na,...ra]).map(e=>({...e,guard:wt(e.guard)})),aa=[...Hi,...ia,...Vi,...Gi,...Bi];async function oa(e,t,n){if(!Je(e,t))return O();let r=new URL(e.url);return n.scope instanceof Response?n.scope:(t=n.scope??t,await Qt(aa,e,t,r)??Xt(e,t,r))}const sa=`x-coder-request-scope`;function ca(e,{sessions:t,cookies:n}){let r=e.auth;return r?{...e,auth:{...r,session(e,i){let a=JSON.stringify([...[`cookie`,`authorization`,`x-coder-organization`].map(t=>e.get(t)),!!i]),o=t.get(a);return o||(o=r.session(e,i,n),t.set(a,o)),o}}}:e}function la(e,t,n){let r=t.requestScopes??=new Map,i=e.headers.get(sa),a=n&&i?r.get(i):void 0;if(a)return{req:e,ctx:ca(t,a),end(){}};let o=new Headers(e.headers);if(o.delete(sa),!t.auth)return{req:i?new Request(e,{headers:o}):e,ctx:t,end(){}};let s=Vn(),c={sessions:new Map,cookies:[]};return r.set(s,c),o.set(sa,s),{req:new Request(e,{headers:o}),ctx:ca(t,c),cookies:c.cookies,end:()=>r.delete(s)}}async function ua(e,t,n={}){t.limits??=new Qe((t.now??Date.now)()),t.limits.requests++,t.settings??={},t.taskWatcher??=new ri,t.logWatcher??=new ai,t.dashboardHosts??=new Ht;let r=()=>da(e,t,n);return t.dbProfile?t.dbProfile.request(n.inProcess===!0,r):r()}async function da(e,t,n){let r=await ie(e,se(new URL(e.url).pathname));if(r instanceof Response)return r;let i=la(r,t,n.inProcess===!0),a=!1;try{let r=n.clientIp??`unknown`,o=await le(i.req,i.ctx,r),s=fa(o instanceof Response?o:await oa(i.req,i.ctx,o),i.cookies),c=new URL(e.url).pathname.split(`/`),l=c[1]===`tasks`,u=c[1]===`admin`&&c[2]===`tasks`;return e.method!==`GET`&&s.ok&&![`hooks`,`tasks`,`logins`].includes(c[1])&&Yt(t),e.method!==`GET`&&s.ok&&!(l&&c.length===4&&c[2]&&c[3]===`heartbeat`)&&!(u&&c.length===5&&c[3]&&[`steer`,`ask`,`approve`,`archive`].includes(c[4]))&&(l||u||c[1]===`admin`&&c[2]===`review`||c[1]===`admin`&&c[2]===`flows`&&c.length===5&&c[3]&&c[4]===`run`)&&bt(t,u&&c.length===3&&e.method===`POST`),a=!!s.body&&(s.headers.get(`content-type`)??``).includes(`text/html`),a?pa(s,i.end):s}finally{a||i.end()}}function fa(e,t=[]){if(!t.length)return e;let n=new Headers(e.headers);for(let e of t)n.append(`set-cookie`,e);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}function pa(e,t){let n=e.body.getReader(),r=new ReadableStream({async pull(e){try{let{done:r,value:i}=await n.read();r?(t(),e.close()):e.enqueue(i)}catch(n){t(),e.error(n)}},cancel(e){return t(),n.cancel(e)}});return new Response(r,e)}async function ma(e={}){let t=e.env??J.env,n=jn(t,e.host??`node`),r=e.runner??n.runner;if((e.host===`vercel`||t.VERCEL)&&(r===`local`||r===`local-docker`))throw new s(`invalid-option`,`The ${r} runner cannot run on Vercel.`,{hint:`Leave RUNNER unset to use vercel-sandbox.`});if(n.store===`memory`&&r!==`local`&&r!==`local-docker`)throw new s(`invalid-option`,`The ${r} runner needs a database.`,{hint:`Set DATABASE_URL, or use RUNNER=local for a memory server.`});if(!n.publicUrl)throw new s(`invalid-option`,`PUBLIC_URL is required to start a Coder server.`,{hint:`Set PUBLIC_URL to the address platforms and browsers use.`});let i=[];if(n.store===`memory`&&!e.local&&i.push(`test server, not for production: everything is in memory, nothing survives a restart, no sign-in; set DATABASE_URL for a real deployment`),!t.SERVER_ENCRYPTION_KEY&&!e.local&&i.push(`secrets are stored unencrypted; set SERVER_ENCRYPTION_KEY (openssl rand -base64 32)`),n.store===`postgres`&&!n.encryptionKey)throw new s(`invalid-option`,`SERVER_ENCRYPTION_KEY is required for a Postgres server.`,{hint:`Set SERVER_ENCRYPTION_KEY (openssl rand -base64 32); sign-in keys derive from it.`});let a=ee(n.integrations),o=n.store===`memory`&&!n.adminToken?Bn(18).toString(`base64url`):void 0;n.store===`postgres`&&n.adminToken&&i.push(`ADMIN_TOKEN is ignored with Postgres; owners and admins sign in with coder auth login`);let c={...n,...n.store===`postgres`?{adminToken:void 0}:{},...o?{adminToken:o}:{},...e.runner?{runner:e.runner}:{}},l=await pn(c,{local:!!e.local});if(l.connection)try{let e=await Pn(l.connection.db);if(!e.applied)throw new s(`server`,`The database is not set up yet.`,{hint:`Create the tables: coder server migrate`});e.pending&&i.push(`database is ${e.pending} migration${e.pending===1?``:`s`} behind; run coder server migrate`)}catch(e){throw await l.close(),e}try{c.store===`memory`&&await Sn(l.store(l.defaultOrganizationId),Date.now());let n=l.connection&&c.auth?await(await import(`./auth-CS0cH0gq.js`)).createAuth(l.connection.db,c):void 0,r=e.cwd??J.cwd(),u=l.store(l.defaultOrganizationId),d=Ge({kind:c.runner,workDir:c.workDir,config:c.runnerConfig,local:!(e.host===`vercel`||t.VERCEL),sandbox:{region:we(c.databaseUrl),snapshots:{get:e=>u.get(`snapshot`,e),put:(e,t)=>u.put(`snapshot`,e,t)}}});if(!d[c.runner])throw await l.close(),new s(`invalid-option`,`Runner ${c.runner} is not configured.`,{hint:`Set RUNNER_CONFIG to JSON containing url and secret.`});let f=new Ht,p=new Qe,m=new Map,h=new Map,g=new ri,_=new ai,v=t=>{let i=m.get(t);if(i)return i;let o=l.store(t),s={limits:p,...l.connection?{databaseHealth:async()=>{await l.connection.db.execute(Wn`select 1`)},statementTimeout:l.connection.statementTimeout,healthRunners:async()=>{let[e]=await l.connection.db.select({total:Wn`count(*)::int`,online:Wn`count(*) filter (where ${Nn.lastSeen} > clock_timestamp() - interval '5 minutes')::int`}).from(Nn);return e??{online:0,total:0}}}:{},config:c,settings:{},organizationId:t,integrations:a,runners:d,store:o,queue:l.queue,requestScopes:h,taskWatcher:g,logWatcher:_,dashboardHosts:f,dbProfile:l.connection?.profile,chatState:l.chatState,loadAgent:sn(a,{cwd:r,config:c,store:o}),...n?{auth:n}:{},scope:v,webhookTarget:(e,t)=>l.webhookTarget(e,t),appRecord:e=>l.appRecord(e),installationOrganization:e=>l.installationOrganization(e),installations:e=>l.installations(e),serverOrganizationId:l.defaultOrganizationId,taskOrganization:(e,t)=>l.taskOrganization(e,t),...e.local?{local:e.local}:{}};return m.set(t,s),s};globalThis.__coder={handle:e=>ua(e,v(l.defaultOrganizationId),{inProcess:!0})};let y=v(l.defaultOrganizationId),b;return e.local&&(await Lt(y),b=setImmediate(()=>{En(y).catch(()=>void 0)})),{config:c,context:v,defaultContext:y,warnings:i,...o?{mintedToken:o}:{},sweep:l.sweep,close:async()=>{g.close(),_.close(),b&&clearImmediate(b),await y.local?.usageSync?.catch(()=>void 0),await Ct(y),await l.close()}}}catch(e){throw await l.close(),e}}var ha=e({serve:()=>ya,serverHandler:()=>_a});function ga(e){try{let t=new URL(e);return Bt.has(t.hostname)?Number(t.port||(t.protocol===`https:`?443:80)):void 0}catch{return}}function _a(e=J.env,t=e.VERCEL?`vercel`:`node`){Mn();let n,r=()=>n??=ma({env:e,host:t}).catch(e=>{throw n=void 0,e});return Object.assign(async(t,n)=>{let i=await r(),a=n?e=>n(e):e=>void e.catch(()=>{}),o=e=>({...i.context(e),waitUntil:a,scope:o});return ua(t,o(i.defaultContext.organizationId),{clientIp:e.VERCEL?t.headers.get(`x-forwarded-for`)?.split(`,`,1)[0]?.trim():void 0})},{scheduled:async()=>{let e=await r();await Promise.all([e.sweep(),import(`./store-Cxc2GYyj.js`).then(e=>e.Y).then(t=>t.renewInstallations(e.defaultContext)),gt(e.defaultContext,!1,!0),Ot(e.defaultContext)])},close:async()=>{let e=n;n=void 0,await(await e)?.close()}})}async function va(e={}){Mn();let t=e.env??J.env;if(e.runner&&!He.includes(e.runner))throw new s(`invalid-option`,`Invalid --runner value: use ${He.join(`, `)}`);if(e.port!==void 0&&(!Number.isInteger(e.port)||e.port<1||e.port>65535))throw new s(`invalid-option`,`Invalid port: use 1 through 65535.`);let n=t.PORT&&/^\d+$/.test(t.PORT)?Number(t.PORT):void 0,r=ga(t.PUBLIC_URL),i=e.port??n??r??8787;if(!Number.isInteger(i)||i<1||i>65535)throw new s(`invalid-option`,`Invalid PORT: use 1 through 65535.`);let a=t.PUBLIC_URL?t:{...t,PUBLIC_URL:`http://localhost:${i}`},o=!!(t.DATABASE_URL||t.POSTGRES_URL);if(o&&e.memory)throw new s(`invalid-option`,`A memory server cannot use DATABASE_URL.`,{hint:`Unset DATABASE_URL, or drop --memory.`});let c=(e.host??t.HOST??(o?void 0:`127.0.0.1`))?.replace(/^\[(.*)\]$/,`$1`),l=!o&&!e.memory;if(l&&!Bt.has(c))throw new s(`invalid-option`,`A local server listens on loopback only.`,{hint:`Reach it through a tunnel or a proxy on this machine; set DATABASE_URL for a deployment, or use --memory for a test server.`});if(e.memory&&t.VERCEL)throw new s(`invalid-option`,`A memory server cannot run on Vercel.`,{hint:`Set DATABASE_URL for a real deployment.`});let u,d,f=l?new Promise((e,t)=>{d=t,u=()=>{Xn().then(e,t)}}):void 0,p=f?.then(()=>void 0).catch(()=>void 0),m=l?{cwd:e.cwd??J.cwd(),port:i,cacheMaintenance:p}:void 0,h=await ma({cwd:e.cwd,env:a,runner:e.runner,...m?{local:m}:{}}),g=h.defaultContext,_=()=>{h.sweep().catch(()=>{}),import(`./store-Cxc2GYyj.js`).then(e=>e.Y).then(e=>e.renewInstallations(g)).catch(()=>{})};_();let v=setInterval(_,36e5);v.unref();let y=setInterval(()=>{gt(g,!1,!0).catch(()=>{}),Ot(g).catch(()=>{}),t.PUBLIC_URL||import(`./store-Cxc2GYyj.js`).then(e=>e.Y).then(e=>e.renewInstallations(g,`sync`)).catch(()=>{})},6e4);y.unref();let b=Un.createServer(oe((e,t)=>ua(e,g,{clientIp:t}),{limit:se,admit:e=>o||me(e.socket.remoteAddress,e.url??`/`)})),x=h.config.publicUrl;r!==void 0&&r!==i&&h.warnings.push(`PUBLIC_URL points at port ${r} but the server listens on ${i}`),await new Promise((e,t)=>{b.once(`error`,t),b.listen(i,c,e)}).catch(async e=>{throw d?.(e),clearInterval(y),clearInterval(v),await h.close(),e});let S=u?setTimeout(u,0):void 0,C=!1,w=async()=>{C||(C=!0,clearInterval(y),clearInterval(v),g.taskWatcher?.close(),g.logWatcher?.close(),await new Promise((e,t)=>b.close(n=>n?t(n):e())),await p,S&&clearTimeout(S),await h.close())},ee=g.auth?`Wular Auth (${g.auth.issuer})`:void 0,te=`http://localhost:${i}`,T=tt(g),E=T===`local`?te:x,D=h.config.store===`memory`?h.mintedToken??t.ADMIN_TOKEN:void 0;return{address:te,publicUrl:x,warnings:h.warnings,close:w,runner:h.config.runner,store:h.config.store,mode:T,...f?{cacheMigration:f}:{},maxTasks:h.config.maxTasks??h.config.limits?.concurrentTasks??10,...ee?{signIn:ee}:{},...h.mintedToken?{mintedToken:h.mintedToken}:{},...h.config.store===`postgres`&&t.DATABASE_URL?{database:Fn(t.DATABASE_URL)}:{},...Bt.has(new URL(E).hostname)?{dashboard:`${E}/dash${D?`#token=${encodeURIComponent(D)}`:``}`}:{}}}async function ya(e={}){try{return await va(e)}catch(e){if(e instanceof s)throw e;let t=e instanceof Error&&e.cause instanceof Error?`: ${e.cause.message}`:``;throw new s(`server`,`${e instanceof Error?e.message:String(e)}${t}`)}}export{Mi as a,ki as i,ha as n,Ai as o,_a as r,ya as t};
@@ -1,2 +1,2 @@
1
- import{St as e,Zt as t}from"./dispatch-YW1aqjEg.js";import{i as n}from"./prompt-K7-bKcTC.js";import{i as r}from"./cli-msOzZFXW.js";import{p as i,s as a}from"./output-BKeyLbvt.js";import{n as o,s,t as c}from"./args-DEMOfLz2.js";import l from"node:process";import*as u from"zod/mini";function d(e){let r=i,o=[...e.publicUrl===e.address?[]:[[`public`,e.publicUrl]],[`store`,e.database??(e.mode===`local`?t():e.store)],[`runner`,e.runner],...e.signIn?[[`sign-in`,e.signIn]]:[],...e.mintedToken?[[`token`,e.mintedToken]]:[]],s=Math.max(...o.map(([e])=>e.length))+2;l.stdout.write(`${r.bold({local:`Coder local server`,memory:`Coder test server`,cloud:`Coder server`}[e.mode])} ${r.dim(`listening on ${e.address}`)}\n`);for(let[e,t]of o)l.stdout.write(` ${r.light(e.padEnd(s))}${t}\n`);e.warnings.length&&l.stdout.write(`
2
- `);for(let t of e.warnings)l.stdout.write(` ${r.yellow(`!`)} ${t}\n`);if(e.cacheMigration?.then(e=>{(e.tasks||e.flows||e.files)&&l.stdout.write(`\n moved ${e.tasks.toLocaleString(`en-US`)} archived tasks to ${e.cache}\n`)}).catch(e=>l.stderr.write(`\n Cache migration failed: ${e instanceof Error?e.message:String(e)}\n`)),e.mode===`memory`&&l.stdout.write(`\n${a([`the CLI reaches this server with its token in ADMIN_TOKEN: coder task list --server ${e.publicUrl}`],r)}\n`),e.dashboard){let t=l.stdout.isTTY&&n(e.dashboard);l.stdout.write(t?`\nOpening the dashboard in your browser. If it doesn't open, go to:\n ${e.dashboard}\n`:`\n ${r.light(`dashboard`)} ${e.dashboard}\n`)}}const f=r({name:`server serve`,help:{usage:`coder server serve [--port <n>] [--host <address>] [--memory] [--runner <name>] [--json] [--cwd <dir>]`,summary:`Run the Coder server on Bun: the address platforms deliver events to, the dashboard, and the worker that runs tasks. With DATABASE_URL it is a full server with sign-in and workspaces. Without one it is the dashboard for this machine's CLI: its config, agents, tasks and engine logins, on loopback only. --memory makes a throwaway test server that keeps everything in memory. Configured through the environment; every variable is in coder docs self-host. It never migrates the database itself: coder server migrate does.`,flags:[[`--port <n>`,`listen port (default: PORT, else the port in a localhost PUBLIC_URL, else 8787)`],[`--host <address>`,`listen address (default: HOST, else 127.0.0.1 without a database, else every interface)`],[`--memory`,`a throwaway test server: everything in memory, no sign-in, admin token only`],[`--runner <name>`,`local, local-docker, vercel-sandbox, github-actions, or http`]],env:[[`PUBLIC_URL`,`the address platforms and browsers reach the server at (default http://localhost:<port>)`],[`PORT`,`listen port, as hosts set it (default 8787)`],[`HOST`,`listen address, as --host`],[`DATABASE_URL`,`Postgres, set up by coder server migrate; turns on sign-in and workspaces`],[`AUTH_WULAR_URL`,`the Wular Auth issuer people sign in with (default https://auth.wular.ai)`],[`SERVER_ENCRYPTION_KEY`,`encrypts stored secrets and derives the sign-in keys; required with DATABASE_URL (openssl rand -base64 32)`],[`RUNNER`,`where tasks run: local (default), local-docker, vercel-sandbox, github-actions, http`],[`MAX_TASKS, TASK_TIMEOUT, TASK_STALL, TASK_ATTEMPTS`,`runner capacity and lifecycle limits`],[`ADMIN_TOKEN`,`local and memory servers: the dashboard and CLI key; minted and shown when unset`],[`CODER_CACHE_HOME`,`archived tasks, flows and usage (default OS cache directory/wular-coder)`],[`WORK_DIR`,`where tasks check out repositories`],[`SERVER_NAME`,`what the dashboard calls this server (default Coder)`]],examples:[[`PUBLIC_URL=https://abc.ngrok.app coder server serve`,`receive GitHub and Slack events through a tunnel; the tunnel serves only their webhooks and callbacks`],[`PUBLIC_URL=https://agents.example.com DATABASE_URL=postgres://... coder server serve`,`on your own host, backed by Postgres`]]},options:{...c,port:u.optional(u.coerce.number().check(u.int(),u.positive())),host:s,runner:s,memory:o},async run({options:t,cwd:n}){let{rerunUnderBun:r}=await import(`./env-LsVTi18f.js`).then(e=>e.t);if(await r(),t.memory&&!l.env.ADMIN_TOKEN&&!l.stdout.isTTY)throw new e(`invalid-option`,`Memory server needs an admin token: set ADMIN_TOKEN, or run in a terminal to get a printed one.`);let{serve:i}=await import(`./serve-GIK3fqKA.js`).then(e=>e.n),a=await i({cwd:n,port:t.port,...t.host?{host:t.host}:{},...t.runner?{runner:t.runner}:{},...t.memory?{memory:!0}:{}}),o=()=>void a.close().finally(()=>l.exit(0));return l.once(`SIGINT`,o),l.once(`SIGTERM`,o),a},json:e=>({ok:!0,address:e.address,publicUrl:e.publicUrl,runner:e.runner,store:e.store,mode:e.mode,maxTasks:e.maxTasks,...e.signIn?{signIn:e.signIn}:{},...e.mintedToken?{adminToken:e.mintedToken}:{},warnings:e.warnings}),print:d});export{f as commandServerServe};
1
+ import{St as e,Zt as t}from"./dispatch-YW1aqjEg.js";import{i as n}from"./prompt-K7-bKcTC.js";import{i as r}from"./cli-IfrPgeYz.js";import{p as i,s as a}from"./output-BKeyLbvt.js";import{n as o,s,t as c}from"./args-DEMOfLz2.js";import l from"node:process";import*as u from"zod/mini";function d(e){let r=i,o=[...e.publicUrl===e.address?[]:[[`public`,e.publicUrl]],[`store`,e.database??(e.mode===`local`?t():e.store)],[`runner`,e.runner],...e.signIn?[[`sign-in`,e.signIn]]:[],...e.mintedToken?[[`token`,e.mintedToken]]:[]],s=Math.max(...o.map(([e])=>e.length))+2;l.stdout.write(`${r.bold({local:`Coder local server`,memory:`Coder test server`,cloud:`Coder server`}[e.mode])} ${r.dim(`listening on ${e.address}`)}\n`);for(let[e,t]of o)l.stdout.write(` ${r.light(e.padEnd(s))}${t}\n`);e.warnings.length&&l.stdout.write(`
2
+ `);for(let t of e.warnings)l.stdout.write(` ${r.yellow(`!`)} ${t}\n`);if(e.cacheMigration?.then(e=>{(e.tasks||e.flows||e.files)&&l.stdout.write(`\n moved ${e.tasks.toLocaleString(`en-US`)} archived tasks to ${e.cache}\n`)}).catch(e=>l.stderr.write(`\n Cache migration failed: ${e instanceof Error?e.message:String(e)}\n`)),e.mode===`memory`&&l.stdout.write(`\n${a([`the CLI reaches this server with its token in ADMIN_TOKEN: coder task list --server ${e.publicUrl}`],r)}\n`),e.dashboard){let t=l.stdout.isTTY&&n(e.dashboard);l.stdout.write(t?`\nOpening the dashboard in your browser. If it doesn't open, go to:\n ${e.dashboard}\n`:`\n ${r.light(`dashboard`)} ${e.dashboard}\n`)}}const f=r({name:`server serve`,help:{usage:`coder server serve [--port <n>] [--host <address>] [--memory] [--runner <name>] [--json] [--cwd <dir>]`,summary:`Run the Coder server on Bun: the address platforms deliver events to, the dashboard, and the worker that runs tasks. With DATABASE_URL it is a full server with sign-in and workspaces. Without one it is the dashboard for this machine's CLI: its config, agents, tasks and engine logins, on loopback only. --memory makes a throwaway test server that keeps everything in memory. Configured through the environment; every variable is in coder docs self-host. It never migrates the database itself: coder server migrate does.`,flags:[[`--port <n>`,`listen port (default: PORT, else the port in a localhost PUBLIC_URL, else 8787)`],[`--host <address>`,`listen address (default: HOST, else 127.0.0.1 without a database, else every interface)`],[`--memory`,`a throwaway test server: everything in memory, no sign-in, admin token only`],[`--runner <name>`,`local, local-docker, vercel-sandbox, github-actions, or http`]],env:[[`PUBLIC_URL`,`the address platforms and browsers reach the server at (default http://localhost:<port>)`],[`PORT`,`listen port, as hosts set it (default 8787)`],[`HOST`,`listen address, as --host`],[`DATABASE_URL`,`Postgres, set up by coder server migrate; turns on sign-in and workspaces`],[`AUTH_WULAR_URL`,`the Wular Auth issuer people sign in with (default https://auth.wular.ai)`],[`SERVER_ENCRYPTION_KEY`,`encrypts stored secrets and derives the sign-in keys; required with DATABASE_URL (openssl rand -base64 32)`],[`RUNNER`,`where tasks run: local (default), local-docker, vercel-sandbox, github-actions, http`],[`MAX_TASKS, TASK_TIMEOUT, TASK_STALL, TASK_ATTEMPTS`,`runner capacity and lifecycle limits`],[`ADMIN_TOKEN`,`local and memory servers: the dashboard and CLI key; minted and shown when unset`],[`CODER_CACHE_HOME`,`archived tasks, flows and usage (default OS cache directory/wular-coder)`],[`WORK_DIR`,`where tasks check out repositories`],[`SERVER_NAME`,`what the dashboard calls this server (default Coder)`]],examples:[[`PUBLIC_URL=https://abc.ngrok.app coder server serve`,`receive GitHub and Slack events through a tunnel; the tunnel serves only their webhooks and callbacks`],[`PUBLIC_URL=https://agents.example.com DATABASE_URL=postgres://... coder server serve`,`on your own host, backed by Postgres`]]},options:{...c,port:u.optional(u.coerce.number().check(u.int(),u.positive())),host:s,runner:s,memory:o},async run({options:t,cwd:n}){let{rerunUnderBun:r}=await import(`./env-LsVTi18f.js`).then(e=>e.t);if(await r(),t.memory&&!l.env.ADMIN_TOKEN&&!l.stdout.isTTY)throw new e(`invalid-option`,`Memory server needs an admin token: set ADMIN_TOKEN, or run in a terminal to get a printed one.`);let{serve:i}=await import(`./serve-D_XiZzYd.js`).then(e=>e.n),a=await i({cwd:n,port:t.port,...t.host?{host:t.host}:{},...t.runner?{runner:t.runner}:{},...t.memory?{memory:!0}:{}}),o=()=>void a.close().finally(()=>l.exit(0));return l.once(`SIGINT`,o),l.once(`SIGTERM`,o),a},json:e=>({ok:!0,address:e.address,publicUrl:e.publicUrl,runner:e.runner,store:e.store,mode:e.mode,maxTasks:e.maxTasks,...e.signIn?{signIn:e.signIn}:{},...e.mintedToken?{adminToken:e.mintedToken}:{},warnings:e.warnings}),print:d});export{f as commandServerServe};
@@ -1 +1 @@
1
- import{s as e}from"./cli-msOzZFXW.js";const t=e(`server`,{serve:async()=>(await import(`./serve-K3BVTcDI.js`)).commandServerServe,migrate:async()=>(await import(`./migrate-CN-fdMV9.js`)).commandServerMigrate,"rotate-key":async()=>(await import(`./rotate-key-CYimsQR5.js`)).commandServerRotateKey,app:async()=>(await import(`./app-DaccLHrx.js`)).commandServerApp,workflow:async()=>(await import(`./workflow-7rqzHHWZ.js`)).commandServerWorkflow},{menu:[{usage:`serve [--port <n>]`,blurb:`run the server`},{usage:`migrate`,blurb:`apply pending database migrations`},{usage:`rotate-key`,blurb:`re-seal secrets with SERVER_ENCRYPTION_KEY`},{usage:`app create <integration>`,blurb:`create the built-in agent's public app`},{usage:`workflow`,blurb:`print the GitHub Actions workflow for RUNNER=github-actions`}],description:[`Self-host Coder: the server your agents and platform apps talk to, with a dashboard and sign-in. We run one as the hosted service; you can run your own.`],exampleCommand:`server serve`},{nested:[`app`]});export{t as commandServer};
1
+ import{s as e}from"./cli-IfrPgeYz.js";const t=e(`server`,{serve:async()=>(await import(`./serve-t38OrDrk.js`)).commandServerServe,migrate:async()=>(await import(`./migrate-DPprwsbm.js`)).commandServerMigrate,"rotate-key":async()=>(await import(`./rotate-key-CmvHXXnp.js`)).commandServerRotateKey,app:async()=>(await import(`./app-C7sw1ZkI.js`)).commandServerApp,workflow:async()=>(await import(`./workflow-Mi1OCrOI.js`)).commandServerWorkflow},{menu:[{usage:`serve [--port <n>]`,blurb:`run the server`},{usage:`migrate`,blurb:`apply pending database migrations`},{usage:`rotate-key`,blurb:`re-seal secrets with SERVER_ENCRYPTION_KEY`},{usage:`app create <integration>`,blurb:`create the built-in agent's public app`},{usage:`workflow`,blurb:`print the GitHub Actions workflow for RUNNER=github-actions`}],description:[`Self-host Coder: the server your agents and platform apps talk to, with a dashboard and sign-in. We run one as the hosted service; you can run your own.`],exampleCommand:`server serve`},{nested:[`app`]});export{t as commandServer};
@@ -1,4 +1,4 @@
1
- import{C as e}from"./dispatch-YW1aqjEg.js";import{i as t}from"./cli-msOzZFXW.js";import{f as n,p as r,t as i}from"./output-BKeyLbvt.js";import{n as a,t as o}from"./args-DEMOfLz2.js";import s from"node:process";const c=t({name:`setup-host`,help:{usage:`coder setup-host [claude] [codex] [agents] [--json]`,summary:`Set up coder in your host: check engines and auth, seed the config, and
1
+ import{C as e}from"./dispatch-YW1aqjEg.js";import{i as t}from"./cli-IfrPgeYz.js";import{f as n,p as r,t as i}from"./output-BKeyLbvt.js";import{n as a,t as o}from"./args-DEMOfLz2.js";import s from"node:process";const c=t({name:`setup-host`,help:{usage:`coder setup-host [claude] [codex] [agents] [--json]`,summary:`Set up coder in your host: check engines and auth, seed the config, and
2
2
  install the host plugin/skill for the named host(s). Claude Code gets its
3
3
  marketplace plugin; "agents" installs a skill into ~/.agents/skills for
4
4
  every host that reads the Agent Skills standard dir (Codex, Pi, OpenCode,
@@ -1 +1 @@
1
- import{t as e}from"./rolldown-runtime-DT7IzrpZ.js";import{Bn as t}from"./store-qp7UE2ES.js";import{d as n,n as r,o as i,p as a,s as o,t as s}from"./schema-DoNO0dPh.js";import{and as c,eq as l,or as u}from"drizzle-orm";var d=e({UNSCOPED_ORGANIZATION:()=>``,addSecret:()=>N,agentRowId:()=>O,agentValue:()=>S,app:()=>m,appRowId:()=>D,date:()=>_,defined:()=>y,escapeLike:()=>v,install:()=>h,installationRowId:()=>k,ms:()=>g,opaque:()=>M,rows:()=>L,setSecret:()=>P,splitKey:()=>p,stateKey:()=>I,statePrefix:()=>F,taskRecord:()=>E,taskRowId:()=>A,versionColumns:()=>w,versionSummary:()=>T,versionValue:()=>C});const f=``;function p(e){let t=e.lastIndexOf(`:`),n=e.slice(t+1);return t>0&&/^\d+$/.test(n)?[e.slice(0,t),Number(n)]:void 0}const m=i,h=o,g=e=>e.getTime(),_=e=>new Date(e),v=e=>e.replace(/[\\%_]/g,`\\$&`),y=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>e!=null)),b=e=>e?g(e):void 0,x=(e,t)=>{let n=/^repo:([^@]+)@(.+)$/.exec(e);return n&&t?{repo:n[1],ref:n[2],commit:t}:void 0},S=e=>y({id:e.slug,name:e.name,description:e.description,source:e.source,repo:e.repo,path:e.path,currentVersion:e.currentVersion,settings:e.settings,createdAt:g(e.createdAt),updatedAt:g(e.updatedAt)}),C=(e,t)=>y({agent:t,version:e.version,definition:e.definition,systemPrompt:e.systemPrompt,files:e.files,commit:e.commit,source:x(e.importedFrom,e.commit),importedFrom:e.importedFrom,createdAt:g(e.createdAt)}),w={id:r.id,agentId:r.agentId,version:r.version,definition:r.definition,commit:r.commit,importedFrom:r.importedFrom,createdAt:r.createdAt},T=(e,t)=>{let{systemPrompt:n,files:r,...i}=C({...e,systemPrompt:``,files:null},t);return i};function E(e){return y({task:y({id:e.publicId,source:e.source,agent:e.agent,flow:e.flow,runner:e.runner,permissions:e.permissions,event:e.event,prompt:e.prompt,args:e.args,mcp:e.mcp,author:e.author,definition:e.definition,credential:e.credential,requester:e.requester,runnerId:e.runnerId,usage:e.usage,tools:e.tools,toolScopes:e.toolScopes,context:e.context,files:e.files}),status:e.status,attempts:e.attempts,generation:e.generation,inboxSeq:e.inboxSeq,inboxAck:e.inboxAck<0?void 0:{generation:e.generation,seq:e.inboxAck},result:e.result,error:e.error,tokens:e.tokens,handle:e.handle,tokenHash:e.tokenHash,lastSeenAt:b(e.lastSeenAt),logCursor:e.logCursor??void 0,logSeq:e.logSeq??void 0,logBytes:e.logBytes??void 0,archivedAt:b(e.archivedAt),approval:e.approval,answer:Array.isArray(e.answer)?e.answer:void 0,createdAt:g(e.createdAt),startedAt:b(e.startedAt),finishedAt:b(e.finishedAt),cancelRequestedAt:b(e.cancelRequestedAt),updatedAt:g(e.updatedAt)})}async function D(e,t){let[n]=await e.db.select({id:m.id}).from(m).where(c(u(e.mine(m.organizationId),l(m.organizationId,``)),l(m.key,t)));if(!n)throw Error(`Unknown app "${t}".`);return n.id}async function O(e,t){let[n]=await e.db.select({id:s.id}).from(s).where(c(e.mine(s.organizationId),l(s.slug,t)));if(!n)throw Error(`Unknown agent "${t}".`);return n.id}async function k(e,t){let[n]=await e.db.select({id:h.id}).from(h).where(c(e.mine(h.organizationId),l(h.key,t)));if(!n)throw Error(`Unknown installation "${t}".`);return n.id}async function A(e,t){let[n]=await e.db.select({id:a.id}).from(a).where(c(e.mine(a.organizationId),l(a.publicId,t)));if(!n)throw Error(`Unknown task "${t}".`);return n.id}function j(e,n){if(n.startsWith(`plain.`))return{iv:`plain`,tag:``,ciphertext:n.slice(6),keyVersion:0};let[r,i,a]=n.split(`.`);if(!r||!i||!a)throw Error(`Invalid encrypted secret`);return{iv:r,tag:i,ciphertext:a,keyVersion:t(e.encryption,n)}}function M(e){return e.iv===`plain`?`plain.${e.ciphertext}`:`${e.iv}.${e.tag}.${e.ciphertext}`}async function N(e,t,r){let[i]=await e.db.insert(n).values({organizationId:e.organizationId,kind:t,...j(e,r)}).returning({id:n.id});return i.id}async function P(e,t,r){await e.db.update(n).set({...j(e,r),updatedAt:e.at()}).where(c(e.mine(n.organizationId),l(n.id,t)))}const F=(e,t)=>`o:${JSON.stringify([e,t])}:`,I=(e,t,n)=>F(e,t)+n;async function L(e,t){let n=await e.execute(t);return Array.isArray(n)?n:n.rows}export{T as C,w as S,p as _,m as a,E as b,y as c,k as d,g as f,d as g,P as h,S as i,v as l,L as m,N as n,D as o,M as p,O as r,_ as s,f as t,h as u,I as v,C as w,A as x,F as y};
1
+ import{t as e}from"./rolldown-runtime-DT7IzrpZ.js";import{Bn as t}from"./store-Cxc2GYyj.js";import{d as n,n as r,o as i,p as a,s as o,t as s}from"./schema-DoNO0dPh.js";import{and as c,eq as l,or as u}from"drizzle-orm";var d=e({UNSCOPED_ORGANIZATION:()=>``,addSecret:()=>N,agentRowId:()=>O,agentValue:()=>S,app:()=>m,appRowId:()=>D,date:()=>_,defined:()=>y,escapeLike:()=>v,install:()=>h,installationRowId:()=>k,ms:()=>g,opaque:()=>M,rows:()=>L,setSecret:()=>P,splitKey:()=>p,stateKey:()=>I,statePrefix:()=>F,taskRecord:()=>E,taskRowId:()=>A,versionColumns:()=>w,versionSummary:()=>T,versionValue:()=>C});const f=``;function p(e){let t=e.lastIndexOf(`:`),n=e.slice(t+1);return t>0&&/^\d+$/.test(n)?[e.slice(0,t),Number(n)]:void 0}const m=i,h=o,g=e=>e.getTime(),_=e=>new Date(e),v=e=>e.replace(/[\\%_]/g,`\\$&`),y=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>e!=null)),b=e=>e?g(e):void 0,x=(e,t)=>{let n=/^repo:([^@]+)@(.+)$/.exec(e);return n&&t?{repo:n[1],ref:n[2],commit:t}:void 0},S=e=>y({id:e.slug,name:e.name,description:e.description,source:e.source,repo:e.repo,path:e.path,currentVersion:e.currentVersion,settings:e.settings,createdAt:g(e.createdAt),updatedAt:g(e.updatedAt)}),C=(e,t)=>y({agent:t,version:e.version,definition:e.definition,systemPrompt:e.systemPrompt,files:e.files,commit:e.commit,source:x(e.importedFrom,e.commit),importedFrom:e.importedFrom,createdAt:g(e.createdAt)}),w={id:r.id,agentId:r.agentId,version:r.version,definition:r.definition,commit:r.commit,importedFrom:r.importedFrom,createdAt:r.createdAt},T=(e,t)=>{let{systemPrompt:n,files:r,...i}=C({...e,systemPrompt:``,files:null},t);return i};function E(e){return y({task:y({id:e.publicId,source:e.source,agent:e.agent,flow:e.flow,runner:e.runner,permissions:e.permissions,event:e.event,prompt:e.prompt,args:e.args,mcp:e.mcp,author:e.author,definition:e.definition,credential:e.credential,requester:e.requester,runnerId:e.runnerId,usage:e.usage,tools:e.tools,toolScopes:e.toolScopes,context:e.context,files:e.files}),status:e.status,attempts:e.attempts,generation:e.generation,inboxSeq:e.inboxSeq,inboxAck:e.inboxAck<0?void 0:{generation:e.generation,seq:e.inboxAck},result:e.result,error:e.error,tokens:e.tokens,handle:e.handle,tokenHash:e.tokenHash,lastSeenAt:b(e.lastSeenAt),logCursor:e.logCursor??void 0,logSeq:e.logSeq??void 0,logBytes:e.logBytes??void 0,archivedAt:b(e.archivedAt),approval:e.approval,answer:Array.isArray(e.answer)?e.answer:void 0,createdAt:g(e.createdAt),startedAt:b(e.startedAt),finishedAt:b(e.finishedAt),cancelRequestedAt:b(e.cancelRequestedAt),updatedAt:g(e.updatedAt)})}async function D(e,t){let[n]=await e.db.select({id:m.id}).from(m).where(c(u(e.mine(m.organizationId),l(m.organizationId,``)),l(m.key,t)));if(!n)throw Error(`Unknown app "${t}".`);return n.id}async function O(e,t){let[n]=await e.db.select({id:s.id}).from(s).where(c(e.mine(s.organizationId),l(s.slug,t)));if(!n)throw Error(`Unknown agent "${t}".`);return n.id}async function k(e,t){let[n]=await e.db.select({id:h.id}).from(h).where(c(e.mine(h.organizationId),l(h.key,t)));if(!n)throw Error(`Unknown installation "${t}".`);return n.id}async function A(e,t){let[n]=await e.db.select({id:a.id}).from(a).where(c(e.mine(a.organizationId),l(a.publicId,t)));if(!n)throw Error(`Unknown task "${t}".`);return n.id}function j(e,n){if(n.startsWith(`plain.`))return{iv:`plain`,tag:``,ciphertext:n.slice(6),keyVersion:0};let[r,i,a]=n.split(`.`);if(!r||!i||!a)throw Error(`Invalid encrypted secret`);return{iv:r,tag:i,ciphertext:a,keyVersion:t(e.encryption,n)}}function M(e){return e.iv===`plain`?`plain.${e.ciphertext}`:`${e.iv}.${e.tag}.${e.ciphertext}`}async function N(e,t,r){let[i]=await e.db.insert(n).values({organizationId:e.organizationId,kind:t,...j(e,r)}).returning({id:n.id});return i.id}async function P(e,t,r){await e.db.update(n).set({...j(e,r),updatedAt:e.at()}).where(c(e.mine(n.organizationId),l(n.id,t)))}const F=(e,t)=>`o:${JSON.stringify([e,t])}:`,I=(e,t,n)=>F(e,t)+n;async function L(e,t){let n=await e.execute(t);return Array.isArray(n)?n:n.rows}export{T as C,w as S,p as _,m as a,E as b,y as c,k as d,g as f,d as g,P as h,S as i,v as l,L as m,N as n,D as o,M as p,O as r,_ as s,f as t,h as u,I as v,C as w,A as x,F as y};
@@ -1 +1 @@
1
- import{i as e}from"./cli-msOzZFXW.js";import{g as t,p as n}from"./output-BKeyLbvt.js";import{n as r}from"./args-DEMOfLz2.js";import i from"node:process";function a(e){let r=n,a=[...Object.entries(e.events).map(([e,t])=>({kind:`event`,name:e,does:t})),...Object.entries(e.tools).map(([e,t])=>({kind:`tools`,name:e,does:t.join(`, `)}))];i.stdout.write(t([{header:`kind`,value:e=>e.kind,paint:e=>r.light(e)},{header:`name`,value:e=>e.name},{header:`does`,value:e=>e.does}],a,r))}const o=e({name:`agent integrations show`,globalFlags:{cwd:!1},help:{usage:`coder agent integrations show <id> [--json]`,summary:`Describe one integration: each event with what triggers it, and the tools each preset (observe, comment, write) allows.`,examples:[[`coder agent integrations show github`,`the GitHub integration in full`]]},options:{json:r},args:1,run:async({args:[e]})=>{let{agents:t}=await import(`./agent-BcXXkOmD.js`).then(e=>e.t);return t.integrations.show(e)},print:a});export{o as commandIntegrationsShow};
1
+ import{i as e}from"./cli-IfrPgeYz.js";import{g as t,p as n}from"./output-BKeyLbvt.js";import{n as r}from"./args-DEMOfLz2.js";import i from"node:process";function a(e){let r=n,a=[...Object.entries(e.events).map(([e,t])=>({kind:`event`,name:e,does:t})),...Object.entries(e.tools).map(([e,t])=>({kind:`tools`,name:e,does:t.join(`, `)}))];i.stdout.write(t([{header:`kind`,value:e=>e.kind,paint:e=>r.light(e)},{header:`name`,value:e=>e.name},{header:`does`,value:e=>e.does}],a,r))}const o=e({name:`agent integrations show`,globalFlags:{cwd:!1},help:{usage:`coder agent integrations show <id> [--json]`,summary:`Describe one integration: each event with what triggers it, and the tools each preset (observe, comment, write) allows.`,examples:[[`coder agent integrations show github`,`the GitHub integration in full`]]},options:{json:r},args:1,run:async({args:[e]})=>{let{agents:t}=await import(`./agent-D0pQ_ewc.js`).then(e=>e.t);return t.integrations.show(e)},print:a});export{o as commandIntegrationsShow};
@@ -1 +1 @@
1
- import{i as e,r as t}from"./cli-msOzZFXW.js";import{g as n,p as r}from"./output-BKeyLbvt.js";import{i,n as a,s as o,t as s}from"./args-DEMOfLz2.js";import{isLocal as c}from"./list-DbY1jyj3.js";import l from"node:path";import u from"node:process";const d={server:i,workspace:o,yes:a};function f(e,t){return c(e)?{id:e.id,name:e.name,source:e.builtin?`builtin`:`repo`,...e.dir&&!e.builtin?{dir:l.relative(t,e.dir)}:{},definition:e.definition,...e.usage?{usage:e.usage}:{}}:{id:e.id,name:e.name,source:e.source,definition:e.definition,...e.settings?{usage:e.settings}:{}}}function p(e){let t=r,{definition:i,usage:a}=e,o=`dir`in e?e.dir:void 0,s=[[`name`,e.name],[`source`,o?`${e.source} (${o})`:e.source],[`description`,i.description],[`permissions`,a?.permissions??i.permissions],[`engine`,a?.engine??i.engine],[`model`,a?.model??i.model],[`effort`,a?.effort??i.effort]],c=Math.max(...s.map(([e])=>e.length))+2;for(let[e,n]of s)n&&u.stdout.write(`${t.dim(e.padEnd(c))}${n}\n`);let l=Object.entries(i.integrations).map(([e,t])=>{let n=a?.integrations?.[e],r=Array.isArray(t.triggers)?t.triggers:Object.keys(t.triggers??{}),i=n?.allowedEvents?r.filter(e=>n.allowedEvents.includes(e)):r,o=n?.allowedTools??t.tools;return{id:e,events:i.join(`, `)||`-`,tools:Array.isArray(o)?o.join(`, `):o??`-`}});u.stdout.write(`\n${n([{header:`integration`,value:e=>e.id,paint:e=>t.cyan(e)},{header:`events`,value:e=>e.events},{header:`tools`,value:e=>e.tools}],l,{style:t,border:!0})}`)}const m=e({name:`agent show`,help:{usage:`coder agent show <id> [--server [url]] [--json] [--cwd <dir>]`,summary:`Describe one agent as it will run here, or its active version on a server: its settings and per-integration triggers and tools.`,flags:[t],examples:[[`coder agent show coder`,`what the built-in agent listens to and may do`]]},options:{...s,...d},args:1,run:async({options:e,args:[t],cwd:n})=>{let{agents:r}=await import(`./agent-BcXXkOmD.js`).then(e=>e.t);return r.show(t,{...e,cwd:n,organization:e.workspace})},json:(e,{cwd:t})=>f(e,t),print:(e,{cwd:t})=>p(f(e,t))});export{m as commandAgentShow};
1
+ import{i as e,r as t}from"./cli-IfrPgeYz.js";import{g as n,p as r}from"./output-BKeyLbvt.js";import{i,n as a,s as o,t as s}from"./args-DEMOfLz2.js";import{isLocal as c}from"./list-DYzczkQZ.js";import l from"node:path";import u from"node:process";const d={server:i,workspace:o,yes:a};function f(e,t){return c(e)?{id:e.id,name:e.name,source:e.builtin?`builtin`:`repo`,...e.dir&&!e.builtin?{dir:l.relative(t,e.dir)}:{},definition:e.definition,...e.usage?{usage:e.usage}:{}}:{id:e.id,name:e.name,source:e.source,definition:e.definition,...e.settings?{usage:e.settings}:{}}}function p(e){let t=r,{definition:i,usage:a}=e,o=`dir`in e?e.dir:void 0,s=[[`name`,e.name],[`source`,o?`${e.source} (${o})`:e.source],[`description`,i.description],[`permissions`,a?.permissions??i.permissions],[`engine`,a?.engine??i.engine],[`model`,a?.model??i.model],[`effort`,a?.effort??i.effort]],c=Math.max(...s.map(([e])=>e.length))+2;for(let[e,n]of s)n&&u.stdout.write(`${t.dim(e.padEnd(c))}${n}\n`);let l=Object.entries(i.integrations).map(([e,t])=>{let n=a?.integrations?.[e],r=Array.isArray(t.triggers)?t.triggers:Object.keys(t.triggers??{}),i=n?.allowedEvents?r.filter(e=>n.allowedEvents.includes(e)):r,o=n?.allowedTools??t.tools;return{id:e,events:i.join(`, `)||`-`,tools:Array.isArray(o)?o.join(`, `):o??`-`}});u.stdout.write(`\n${n([{header:`integration`,value:e=>e.id,paint:e=>t.cyan(e)},{header:`events`,value:e=>e.events},{header:`tools`,value:e=>e.tools}],l,{style:t,border:!0})}`)}const m=e({name:`agent show`,help:{usage:`coder agent show <id> [--server [url]] [--json] [--cwd <dir>]`,summary:`Describe one agent as it will run here, or its active version on a server: its settings and per-integration triggers and tools.`,flags:[t],examples:[[`coder agent show coder`,`what the built-in agent listens to and may do`]]},options:{...s,...d},args:1,run:async({options:e,args:[t],cwd:n})=>{let{agents:r}=await import(`./agent-D0pQ_ewc.js`).then(e=>e.t);return r.show(t,{...e,cwd:n,organization:e.workspace})},json:(e,{cwd:t})=>f(e,t),print:(e,{cwd:t})=>p(f(e,t))});export{m as commandAgentShow};
@@ -1 +1 @@
1
- import{i as e}from"./cli-msOzZFXW.js";import{g as t,p as n,s as r}from"./output-BKeyLbvt.js";import{n as i}from"./args-DEMOfLz2.js";import a from"node:process";const o=e({name:`auth status`,globalFlags:{cwd:!1},help:{usage:`coder auth status [--json]`,summary:`List saved sessions with their server, user, and workspace.`,env:[[`CODER_SERVER`,`the server to use instead of https://coder.wular.ai`]]},options:{json:i},run:async()=>{let{sessions:e}=await import(`./remote-AcWWfKVS.js`).then(e=>e.c);return e.status()},print:e=>{let i=n,o=Object.entries(e);if(!o.length)return void a.stdout.write(`${i.dim(`Not signed in`)}\n\n${r([`Sign in: coder auth login`],i)}\n`);a.stdout.write(`${t([{header:`server`,value:([e])=>e,paint:e=>i.cyan(e)},{header:`user`,value:([,e])=>e.user.email},{header:`workspace`,value:([,e])=>e.organization?`${e.organization.name} (${e.organization.slug})`:`-`}],o,i)}\n`)}});export{o as commandStatus};
1
+ import{i as e}from"./cli-IfrPgeYz.js";import{g as t,p as n,s as r}from"./output-BKeyLbvt.js";import{n as i}from"./args-DEMOfLz2.js";import a from"node:process";const o=e({name:`auth status`,globalFlags:{cwd:!1},help:{usage:`coder auth status [--json]`,summary:`List saved sessions with their server, user, and workspace.`,env:[[`CODER_SERVER`,`the server to use instead of https://coder.wular.ai`]]},options:{json:i},run:async()=>{let{sessions:e}=await import(`./remote-AcWWfKVS.js`).then(e=>e.c);return e.status()},print:e=>{let i=n,o=Object.entries(e);if(!o.length)return void a.stdout.write(`${i.dim(`Not signed in`)}\n\n${r([`Sign in: coder auth login`],i)}\n`);a.stdout.write(`${t([{header:`server`,value:([e])=>e,paint:e=>i.cyan(e)},{header:`user`,value:([,e])=>e.user.email},{header:`workspace`,value:([,e])=>e.organization?`${e.organization.name} (${e.organization.slug})`:`-`}],o,i)}\n`)}});export{o as commandStatus};
@@ -1,4 +1,4 @@
1
- import{St as e}from"./dispatch-YW1aqjEg.js";import{i as t,r as n}from"./cli-msOzZFXW.js";import{p as r,r as i,s as a}from"./output-BKeyLbvt.js";import{i as o,n as s,s as c,t as l}from"./args-DEMOfLz2.js";import{i as u,r as d}from"./result-oQey_hdw.js";import f from"node:process";const p={server:o,workspace:c,yes:s};function m(t,n,r){let[i,...a]=t,o=a.join(` `).trim();if(!i||!o)throw new e(`invalid-option`,n,{hint:r});return{id:i,text:o}}function h(e,t=!1){let{taskId:n,steered:o}=e;if(o===`queued`){f.stdout.write(`${r.dim(`[coder]`)} follow-up queued for task ${r.cyan(n)}; it runs when the current turn finishes.\n`),t&&f.stdout.write(`\n${r.dim(`[coder] --wait is not available for a queued follow-up.`)}\n\n${a([`Wait in its own background shell, one per task: coder task result ${n} --wait`],r)}\n`);return}if(!t){f.stdout.write(o===`live`?`${r.dim(`[coder]`)} steered follow-up into running task ${r.cyan(n)}.\n`:`${r.dim(`[coder]`)} resumed task ${r.cyan(n)} with the follow-up (same thread, same id).\n`),f.stdout.write(`\n${a([`Wait in its own background shell, one per task: coder task result ${n} --wait`],r)}\n`);return}f.stdout.write(`\n${e.finalMessage||`(no final message)`}\n\n`),f.stderr.write(`${r.dim(`[coder] task=${n} status=${e.status??`unknown`}`)}\n\n${d(n,i)}\n`)}const g=t({name:`task steer`,help:{usage:`coder task steer <task-id> "<follow-up instructions>" [--wait] [--server [url]]`,summary:`Continue a task's thread with new instructions. They are injected into a live Codex or
1
+ import{St as e}from"./dispatch-YW1aqjEg.js";import{i as t,r as n}from"./cli-IfrPgeYz.js";import{p as r,r as i,s as a}from"./output-BKeyLbvt.js";import{i as o,n as s,s as c,t as l}from"./args-DEMOfLz2.js";import{i as u,r as d}from"./result-DtXZusqj.js";import f from"node:process";const p={server:o,workspace:c,yes:s};function m(t,n,r){let[i,...a]=t,o=a.join(` `).trim();if(!i||!o)throw new e(`invalid-option`,n,{hint:r});return{id:i,text:o}}function h(e,t=!1){let{taskId:n,steered:o}=e;if(o===`queued`){f.stdout.write(`${r.dim(`[coder]`)} follow-up queued for task ${r.cyan(n)}; it runs when the current turn finishes.\n`),t&&f.stdout.write(`\n${r.dim(`[coder] --wait is not available for a queued follow-up.`)}\n\n${a([`Wait in its own background shell, one per task: coder task result ${n} --wait`],r)}\n`);return}if(!t){f.stdout.write(o===`live`?`${r.dim(`[coder]`)} steered follow-up into running task ${r.cyan(n)}.\n`:`${r.dim(`[coder]`)} resumed task ${r.cyan(n)} with the follow-up (same thread, same id).\n`),f.stdout.write(`\n${a([`Wait in its own background shell, one per task: coder task result ${n} --wait`],r)}\n`);return}f.stdout.write(`\n${e.finalMessage||`(no final message)`}\n\n`),f.stderr.write(`${r.dim(`[coder] task=${n} status=${e.status??`unknown`}`)}\n\n${d(n,i)}\n`)}const g=t({name:`task steer`,help:{usage:`coder task steer <task-id> "<follow-up instructions>" [--wait] [--server [url]]`,summary:`Continue a task's thread with new instructions. They are injected into a live Codex or
2
2
  Claude turn at its next tool boundary and queued across a startup or completion race.
3
3
  A stopped, finished, or archived task resumes on the same task id. It reuses the
4
4
  task's engine, model, and permissions unless overridden.`,flags:[[`--wait`,`run in the foreground and block until the answer is ready`],[`--model <alias|slug>`,`override the task's model for this follow-up`],[`--effort <low|medium|high>`,`override the task's reasoning effort`],[`--permissions <mode>`,`read-only · workspace-write · auto`],n],examples:[[`coder task steer task-abc "now add tests"`,`continue that task with a follow-up`]]},options:{...l,model:c,effort:c,permissions:c,wait:s,...p},args:1/0,async run({options:e,args:t}){let{tasks:n}=await import(`./task-DEp3GHwH.js`).then(e=>e.t),{id:r,text:i}=m(t,`Missing task id or follow-up text.`,[`Usage: coder task steer <task-id> "<follow-up>" [--wait]`,`Help: coder task steer --help`]);return n.steer(r,i,{...e,organization:e.workspace})},json(e,{options:t}){let n=e;return t.server!==void 0||!t.wait||n.steered===`queued`?e:{taskId:n.taskId,status:n.status??null,finalMessage:n.finalMessage??null}},print(e,{options:t,args:[n]}){if(t.server===void 0)return h(e,t.wait);if(t.wait)return u(e,r);f.stdout.write(`Steered server task ${r.cyan(n)}.\n`)},exit(e,{options:t}){let n=e;if(t.wait&&(t.server!==void 0||n.steered!==`queued`))return n.status===`completed`?0:1}});export{g as commandSteer,m as idAndText};
@@ -1,3 +1,3 @@
1
- import{i as e}from"./cli-msOzZFXW.js";import{m as t,p as n,s as r}from"./output-BKeyLbvt.js";import{n as i,t as a}from"./args-DEMOfLz2.js";import o from"node:process";const s=e({name:`flow stop`,help:{usage:`coder flow stop [run-id] [--keep-tasks] [--json]`,summary:`Stop a running flow: signal the orchestrator so it stops dispatching, stamp the
1
+ import{i as e}from"./cli-IfrPgeYz.js";import{m as t,p as n,s as r}from"./output-BKeyLbvt.js";import{n as i,t as a}from"./args-DEMOfLz2.js";import o from"node:process";const s=e({name:`flow stop`,help:{usage:`coder flow stop [run-id] [--keep-tasks] [--json]`,summary:`Stop a running flow: signal the orchestrator so it stops dispatching, stamp the
2
2
  run stopped, and stop its still-running tasks. Defaults to the most recent run;
3
3
  the journal stays ready for \`coder flow resume\`.`,flags:[[`--keep-tasks`,`leave the run's still-running tasks running`]]},options:{...a,"keep-tasks":i},args:1,run:async({options:e,args:[t]})=>{let{stopRun:n}=await import(`./executor-HWnIIYUL.js`).then(e=>e.t);return n(t,{keepTasks:e[`keep-tasks`]})},print:c});function c(e){let i=n;e.status===`failed`?o.stdout.write(`${i.dim(`[flow]`)} Run ${i.cyan(e.runId)} orchestrator died. Marked ${t(`failed`)}.\n`):o.stdout.write(`${i.dim(`[flow]`)} run ${i.cyan(e.runId)} ${t(e.status)}.\n`),e.stoppedTasks.length&&o.stdout.write(`${i.dim(`[flow]`)} stopped tasks: ${e.stoppedTasks.join(`, `)}\n`),e.keptTasks.length&&o.stdout.write(`${i.dim(`[flow]`)} left running: ${e.keptTasks.join(`, `)}\n`),o.stdout.write(`\n${r([`Resume: coder flow resume ${e.runId}`],i)}\n`)}export{s as commandStop};
@@ -1 +1 @@
1
- import{i as e,r as t}from"./cli-msOzZFXW.js";import{p as n}from"./output-BKeyLbvt.js";import{i as r,n as i,s as a,t as o}from"./args-DEMOfLz2.js";import s from"node:process";const c={server:r,workspace:a,yes:i},l=e({name:`task stop`,help:{usage:`coder task stop <task-id> [--server [url]]`,summary:`Interrupt a running task and mark it cancelled.`,flags:[t]},options:{...o,...c},args:1,run:async({options:e,args:[t]})=>{let{tasks:n}=await import(`./task-DEp3GHwH.js`).then(e=>e.t);return n.stop(t,{...e,organization:e.workspace})},print:(e,{options:t,args:[r]})=>s.stdout.write(t.server===void 0?`Stopped task ${n.cyan(e.taskId)} ${n.dim(`(${e.interrupt})`)}\n`:`Stopped server task ${n.cyan(r)}.\n`)});export{l as commandStop};
1
+ import{i as e,r as t}from"./cli-IfrPgeYz.js";import{p as n}from"./output-BKeyLbvt.js";import{i as r,n as i,s as a,t as o}from"./args-DEMOfLz2.js";import s from"node:process";const c={server:r,workspace:a,yes:i},l=e({name:`task stop`,help:{usage:`coder task stop <task-id> [--server [url]]`,summary:`Interrupt a running task and mark it cancelled.`,flags:[t]},options:{...o,...c},args:1,run:async({options:e,args:[t]})=>{let{tasks:n}=await import(`./task-DEp3GHwH.js`).then(e=>e.t);return n.stop(t,{...e,organization:e.workspace})},print:(e,{options:t,args:[r]})=>s.stdout.write(t.server===void 0?`Stopped task ${n.cyan(e.taskId)} ${n.dim(`(${e.interrupt})`)}\n`:`Stopped server task ${n.cyan(r)}.\n`)});export{l as commandStop};
@@ -1,4 +1,4 @@
1
- import{dt as e,it as t,rt as n,st as r}from"./store-qp7UE2ES.js";import{_ as i,a,d as o,h as s,i as c,l,m as u,n as d,p as f,r as p,t as m}from"./schema-DoNO0dPh.js";import{i as h}from"./client-31YzOj-i.js";import{C as g,S as _,_ as v,a as y,b as ee,c as b,d as x,f as S,h as C,i as w,l as T,n as E,o as D,p as O,r as k,s as A,u as j,v as M,w as N,x as P,y as te}from"./shared-TznJgMFW.js";import{i as ne,t as re}from"./usage-DR3wWtYD.js";import{isDeepStrictEqual as F}from"node:util";import{and as I,asc as L,desc as ie,eq as R,gt as z,gte as B,ilike as V,inArray as H,isNull as U,lt as W,lte as G,or as K,sql as q}from"drizzle-orm";import{alias as J}from"drizzle-orm/pg-core";function ae(e,t,n){return e.db.transaction(async r=>{let[i]=await r.insert(m).values({organizationId:e.organizationId,slug:t.id,name:t.name,description:t.description??null,source:t.source,repo:t.repo??null,path:t.path??null,currentVersion:0,createdAt:A(t.createdAt),updatedAt:A(t.updatedAt)}).onConflictDoUpdate({target:[m.organizationId,m.slug],set:{slug:t.id}}).returning(),a=w(i),[o]=a.currentVersion?await r.select().from(d).where(I(R(d.agentId,i.id),R(d.version,a.currentVersion))):[],s=o&&N(o,t.id),c=!!(s&&F(s.definition,n.definition)&&s.systemPrompt===n.systemPrompt&&F(s.files,n.files)),l=c?s:{...n,version:a.currentVersion+1},u={...t,currentVersion:l.version,createdAt:a.createdAt,...a.settings?{settings:a.settings}:{},updatedAt:a.updatedAt};if(c&&F(u,a))return{record:a,version:l,unchanged:c};u={...u,updatedAt:t.updatedAt};let f=c?q``:q`with published as (
1
+ import{dt as e,it as t,rt as n,st as r}from"./store-Cxc2GYyj.js";import{_ as i,a,d as o,h as s,i as c,l,m as u,n as d,p as f,r as p,t as m}from"./schema-DoNO0dPh.js";import{i as h}from"./client-31YzOj-i.js";import{C as g,S as _,_ as v,a as y,b as ee,c as b,d as x,f as S,h as C,i as w,l as T,n as E,o as D,p as O,r as k,s as A,u as j,v as M,w as N,x as P,y as te}from"./shared-D64pQ0XU.js";import{i as ne,t as re}from"./usage-Bw7fQeFC.js";import{isDeepStrictEqual as F}from"node:util";import{and as I,asc as L,desc as ie,eq as R,gt as z,gte as B,ilike as V,inArray as H,isNull as U,lt as W,lte as G,or as K,sql as q}from"drizzle-orm";import{alias as J}from"drizzle-orm/pg-core";function ae(e,t,n){return e.db.transaction(async r=>{let[i]=await r.insert(m).values({organizationId:e.organizationId,slug:t.id,name:t.name,description:t.description??null,source:t.source,repo:t.repo??null,path:t.path??null,currentVersion:0,createdAt:A(t.createdAt),updatedAt:A(t.updatedAt)}).onConflictDoUpdate({target:[m.organizationId,m.slug],set:{slug:t.id}}).returning(),a=w(i),[o]=a.currentVersion?await r.select().from(d).where(I(R(d.agentId,i.id),R(d.version,a.currentVersion))):[],s=o&&N(o,t.id),c=!!(s&&F(s.definition,n.definition)&&s.systemPrompt===n.systemPrompt&&F(s.files,n.files)),l=c?s:{...n,version:a.currentVersion+1},u={...t,currentVersion:l.version,createdAt:a.createdAt,...a.settings?{settings:a.settings}:{},updatedAt:a.updatedAt};if(c&&F(u,a))return{record:a,version:l,unchanged:c};u={...u,updatedAt:t.updatedAt};let f=c?q``:q`with published as (
2
2
  insert into ${d} (agent_id, version, definition, system_prompt, files, commit, imported_from, created_at)
3
3
  values (${i.id}, ${l.version}, ${JSON.stringify(l.definition)}::jsonb, ${l.systemPrompt},
4
4
  ${l.files?JSON.stringify(l.files):null}::jsonb, ${l.commit??null}, ${l.importedFrom}, ${A(l.createdAt).toISOString()}::timestamptz)