superfactory 0.0.0-stage → 0.4.30

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 (308) hide show
  1. package/README.md +34 -2
  2. package/THIRD-PARTY-NOTICES.md +27604 -0
  3. package/bin/superfactory.js +57 -0
  4. package/cli/agent-rf446fr1.js +2 -0
  5. package/cli/agent-state-wv62c1td.js +2 -0
  6. package/cli/bin-0cvfmkhh.js +33 -0
  7. package/cli/bin-0t68hf99.js +3 -0
  8. package/cli/bin-19vpzq7g.js +4 -0
  9. package/cli/bin-37w316c6.js +3 -0
  10. package/cli/bin-3dsqxzbz.js +3 -0
  11. package/cli/bin-4j0jjd8g.js +3 -0
  12. package/cli/bin-4tdqjbbd.js +229 -0
  13. package/cli/bin-4zvje4sn.js +502 -0
  14. package/cli/bin-674kd343.js +7 -0
  15. package/cli/bin-8jdkg4ke.js +3 -0
  16. package/cli/bin-d99yte0j.js +5 -0
  17. package/cli/bin-fgvkq9cq.js +867 -0
  18. package/cli/bin-fkp3j5f3.js +3 -0
  19. package/cli/bin-fypan1f6.js +951 -0
  20. package/cli/bin-gg19acwr.js +4 -0
  21. package/cli/bin-ghp5x0x5.js +139 -0
  22. package/cli/bin-gk00mnmn.js +5 -0
  23. package/cli/bin-gne2w036.js +29 -0
  24. package/cli/bin-grxzwpe8.js +3 -0
  25. package/cli/bin-h57gajkz.js +8 -0
  26. package/cli/bin-mbpvzx2b.js +8 -0
  27. package/cli/bin-nnq8kd9z.js +4 -0
  28. package/cli/bin-ven2efjq.js +3 -0
  29. package/cli/bin-yqb1d1mw.js +22 -0
  30. package/cli/bin-z5b3tt05.js +20 -0
  31. package/cli/bin-za1by1n5.js +3 -0
  32. package/cli/bin-zpfe0pxz.js +1 -0
  33. package/cli/bin.js +3 -0
  34. package/cli/child-agent-qgeqvs03.js +4 -0
  35. package/cli/connect-chn8pxyf.js +2 -0
  36. package/cli/container-j6zr9gww.js +4 -0
  37. package/cli/dev-gsaehf19.js +7 -0
  38. package/cli/health-nqzge5kh.js +2 -0
  39. package/cli/home-lock-5seng0k3.js +2 -0
  40. package/cli/host-7dfjhf0z.js +1507 -0
  41. package/cli/index-1wseh1tm.js +2 -0
  42. package/cli/index-axfe8zef.js +2 -0
  43. package/cli/index-s9pw90xe.js +2 -0
  44. package/cli/install-17r8t45e.js +2 -0
  45. package/cli/join-551zg7yr.js +31 -0
  46. package/cli/local-server-2smsafvg.js +2 -0
  47. package/cli/machine-zfjmpw7h.js +2 -0
  48. package/cli/main-0mxhd968.js +33 -0
  49. package/cli/main-53qmhxmd.js +303 -0
  50. package/cli/move-to-xrr2b135.js +2 -0
  51. package/cli/npm-package.json +1 -0
  52. package/cli/pair-phone-070c9ztt.js +5 -0
  53. package/cli/prompt-psc4drtd.js +2 -0
  54. package/cli/reached-vwzx2cdg.js +2 -0
  55. package/cli/sessions-bm4mk37y.js +3 -0
  56. package/cli/sf-cli-s42gkp0b.js +2 -0
  57. package/cli/sf-db-r8f1a20b.js +23 -0
  58. package/cli/sf-deploy-wqaa4fdm.js +21 -0
  59. package/cli/sf-pr-rg3q3tn6.js +13 -0
  60. package/cli/sf-test-pff158qc.js +10 -0
  61. package/cli/tart-isolation-wr3xwfmw.js +3 -0
  62. package/cli/tray-4rr0y1dv.png +0 -0
  63. package/cli/tray-mac-offline-89dva0gs.png +0 -0
  64. package/cli/tray-mac-paused-hq3a1cxv.png +0 -0
  65. package/cli/tray-mac-tvtavf0g.png +0 -0
  66. package/cli/tray-offline-xj6b5ta4.png +0 -0
  67. package/cli/tray-paused-6pzdv5ze.png +0 -0
  68. package/cli/vm-keeper-p0ggcw3z.js +3 -0
  69. package/package.json +50 -4
  70. package/plugins/sf-video-review/.claude-plugin/plugin.json +17 -0
  71. package/plugins/sf-video-review/.mcp.json +9 -0
  72. package/plugins/sf-video-review/dist/video-review.mjs +135 -0
  73. package/plugins/sf-video-review/skills/video-review/SKILL.md +65 -0
  74. package/plugins/sf-video-studio/.claude-plugin/plugin.json +17 -0
  75. package/plugins/sf-video-studio/.mcp.json +19 -0
  76. package/plugins/sf-video-studio/dist/demo-video.mjs +139 -0
  77. package/plugins/sf-video-studio/dist/narration-voice.mjs +134 -0
  78. package/plugins/sf-video-studio/dist/video-generation.mjs +131 -0
  79. package/plugins/sf-video-studio/fonts/DejaVuSansMono-Bold.ttf +0 -0
  80. package/plugins/sf-video-studio/fonts/DejaVuSansMono.ttf +0 -0
  81. package/plugins/sf-video-studio/fonts/LICENSE-DejaVu +187 -0
  82. package/plugins/sf-video-studio/hooks/hooks.json +17 -0
  83. package/plugins/sf-video-studio/hooks/no-robot-voice.sh +77 -0
  84. package/plugins/sf-video-studio/kokoro/package-lock.json +1137 -0
  85. package/plugins/sf-video-studio/kokoro/package.json +11 -0
  86. package/plugins/sf-video-studio/skills/demo-video/SKILL.md +101 -0
  87. package/plugins/sf-video-studio/skills/narration-voice/SKILL.md +49 -0
  88. package/plugins/sf-video-studio/skills/video-generation/SKILL.md +30 -0
  89. package/server/dist/account.js +3 -0
  90. package/server/dist/backup-process.js +2 -0
  91. package/server/dist/backup.js +3 -0
  92. package/server/dist/chunk-0tbq288f.js +3055 -0
  93. package/server/dist/chunk-18n7tr66.js +3 -0
  94. package/server/dist/chunk-1kgfrgmv.js +3 -0
  95. package/server/dist/chunk-1rnmxaav.js +209 -0
  96. package/server/dist/chunk-26zhqbyn.js +25 -0
  97. package/server/dist/chunk-34mn2zj2.js +2 -0
  98. package/server/dist/chunk-3psgsw9t.js +2 -0
  99. package/server/dist/chunk-8zbwppny.js +391 -0
  100. package/server/dist/chunk-9pn7q001.js +3 -0
  101. package/server/dist/chunk-9y7a9gkf.js +2 -0
  102. package/server/dist/chunk-bhm6jzch.js +8 -0
  103. package/server/dist/chunk-dbzjsqvb.js +17 -0
  104. package/server/dist/chunk-fxn504n0.js +2 -0
  105. package/server/dist/chunk-g6pwaap3.js +2 -0
  106. package/server/dist/chunk-gefgv8rg.js +7 -0
  107. package/server/dist/chunk-jg8b833v.js +2 -0
  108. package/server/dist/chunk-jy148bhn.js +3 -0
  109. package/server/dist/chunk-ky4nz39j.js +7 -0
  110. package/server/dist/chunk-mbd1y9qk.js +2 -0
  111. package/server/dist/chunk-neyhk32g.js +13 -0
  112. package/server/dist/chunk-nrz953bx.js +2 -0
  113. package/server/dist/chunk-padvv31s.js +2 -0
  114. package/server/dist/chunk-q1s2ez77.js +3 -0
  115. package/server/dist/chunk-q403h2bh.js +10 -0
  116. package/server/dist/chunk-t64r6enn.js +4 -0
  117. package/server/dist/chunk-vccappg7.js +59 -0
  118. package/server/dist/chunk-vj60fbhw.js +2 -0
  119. package/server/dist/chunk-xj26rwda.js +3 -0
  120. package/server/dist/chunk-xyw98jst.js +5 -0
  121. package/server/dist/main.js +43 -0
  122. package/server/dist/move.js +3 -0
  123. package/server/drizzle/pg/0000_baseline.sql +632 -0
  124. package/server/drizzle/pg/0001_transcripts_packed.sql +2 -0
  125. package/server/drizzle/pg/0002_vm_server_origin.sql +1 -0
  126. package/server/drizzle/pg/0003_reached_machines.sql +1 -0
  127. package/server/drizzle/pg/0004_link_records.sql +2 -0
  128. package/server/drizzle/pg/0005_task_columns.sql +7 -0
  129. package/server/drizzle/pg/0006_task_bundle.sql +3 -0
  130. package/server/drizzle/pg/0007_server_log.sql +9 -0
  131. package/server/drizzle/pg/0008_notification_pauses.sql +6 -0
  132. package/server/drizzle/pg/0009_vm_replaces.sql +1 -0
  133. package/server/drizzle/pg/0010_question_told_once.sql +10 -0
  134. package/server/drizzle/pg/0011_node_next_key.sql +3 -0
  135. package/server/drizzle/pg/0012_task_work.sql +8 -0
  136. package/server/drizzle/pg/0013_task_secret_grants.sql +9 -0
  137. package/server/drizzle/pg/0014_node_paused.sql +2 -0
  138. package/server/drizzle/pg/0015_ssh_machines.sql +19 -0
  139. package/server/drizzle/pg/0016_node_wake.sql +1 -0
  140. package/server/drizzle/pg/0017_node_uninstall_key.sql +1 -0
  141. package/server/drizzle/pg/0018_release_starts.sql +6 -0
  142. package/server/drizzle/pg/0019_session_memory.sql +7 -0
  143. package/server/drizzle/pg/meta/_journal.json +146 -0
  144. package/server/drizzle/sqlite/0000_pre_drizzle_schema.sql +351 -0
  145. package/server/drizzle/sqlite/0001_cluster.sql +36 -0
  146. package/server/drizzle/sqlite/0002_task_records.sql +22 -0
  147. package/server/drizzle/sqlite/0003_indexes.sql +12 -0
  148. package/server/drizzle/sqlite/0004_project_machines.sql +19 -0
  149. package/server/drizzle/sqlite/0005_session_events.sql +7 -0
  150. package/server/drizzle/sqlite/0006_task_platforms.sql +8 -0
  151. package/server/drizzle/sqlite/0007_session_event_tags.sql +7 -0
  152. package/server/drizzle/sqlite/0008_sprints.sql +7 -0
  153. package/server/drizzle/sqlite/0009_project_vms.sql +19 -0
  154. package/server/drizzle/sqlite/0010_server_repairs.sql +4 -0
  155. package/server/drizzle/sqlite/0011_drop_todos.sql +2 -0
  156. package/server/drizzle/sqlite/0012_hypervisors.sql +14 -0
  157. package/server/drizzle/sqlite/0013_manager_leads.sql +2 -0
  158. package/server/drizzle/sqlite/0014_session_text.sql +35 -0
  159. package/server/drizzle/sqlite/0015_vm_resize_machine_instructions_access.sql +22 -0
  160. package/server/drizzle/sqlite/0016_tunnel.sql +23 -0
  161. package/server/drizzle/sqlite/0017_session_secret_grants.sql +7 -0
  162. package/server/drizzle/sqlite/0018_https.sql +18 -0
  163. package/server/drizzle/sqlite/0019_secret_grant_runs.sql +1 -0
  164. package/server/drizzle/sqlite/0020_session_transcripts.sql +16 -0
  165. package/server/drizzle/sqlite/0021_claude_signed_out.sql +2 -0
  166. package/server/drizzle/sqlite/0022_machine_disabled.sql +1 -0
  167. package/server/drizzle/sqlite/0023_machine_access_granted_by.sql +1 -0
  168. package/server/drizzle/sqlite/0024_machine_vms.sql +27 -0
  169. package/server/drizzle/sqlite/0025_machine_tunnel_fallback.sql +1 -0
  170. package/server/drizzle/sqlite/0026_tunnel_peer_linked.sql +3 -0
  171. package/server/drizzle/sqlite/0027_tunnel_upgrade_grace.sql +2 -0
  172. package/server/drizzle/sqlite/0028_dialed_machines.sql +2 -0
  173. package/server/drizzle/sqlite/0029_node_link.sql +3 -0
  174. package/server/drizzle/sqlite/0030_sprint_calendar.sql +1 -0
  175. package/server/drizzle/sqlite/0031_transcripts_packed.sql +2 -0
  176. package/server/drizzle/sqlite/0032_vm_server_origin.sql +1 -0
  177. package/server/drizzle/sqlite/meta/_journal.json +237 -0
  178. package/server/src/account.ts +2 -0
  179. package/server/src/backup.ts +2 -0
  180. package/server/src/features/backups/backup-process.ts +2 -0
  181. package/server/src/main.ts +2 -0
  182. package/server/src/move.ts +2 -0
  183. package/ui/dist/_expo/static/css/global-d378e211074d97e633bc15418ccf57d4.css +2 -0
  184. package/ui/dist/_expo/static/css/xterm-8a7c4e0dca731c11dbe6bdff98fb667c.css +1 -0
  185. package/ui/dist/_expo/static/js/web/Network-f300a5960620f5029c91c06cae29dba5.js +3 -0
  186. package/ui/dist/_expo/static/js/web/[...rest]-9e454d985f211f5c983f42bec15b6ad9.js +1 -0
  187. package/ui/dist/_expo/static/js/web/[managerId]-2580b90e8d862ad66197eecb1dc04a12.js +1 -0
  188. package/ui/dist/_expo/static/js/web/[managerId]-39308153b42eed025c0abb9242ae6c71.js +1 -0
  189. package/ui/dist/_expo/static/js/web/[managerId]-8b7a94ec818e50a371b6b2750b73df6a.js +1 -0
  190. package/ui/dist/_expo/static/js/web/[managerId]-ac3a14c7607e4576d7e6c39c1014bcaf.js +1 -0
  191. package/ui/dist/_expo/static/js/web/[managerId]-e8549b2313a119437c373e30207518c0.js +1 -0
  192. package/ui/dist/_expo/static/js/web/[ref]-9b46f1ec4348f980e9838b68d47c34bf.js +2 -0
  193. package/ui/dist/_expo/static/js/web/[sessionId]-09e376674fb8b3edc4ae8aa9b3a189d7.js +1 -0
  194. package/ui/dist/_expo/static/js/web/[sessionId]-0e5fdba25c9f78220cea4cb66227743d.js +1 -0
  195. package/ui/dist/_expo/static/js/web/[sessionId]-104af3c3885009e6a8d204b6fd6e2c3a.js +1 -0
  196. package/ui/dist/_expo/static/js/web/[sessionId]-863a34ca3835b469134ddbc4ebc6fafc.js +1 -0
  197. package/ui/dist/_expo/static/js/web/[taskId]-1218e1dd3ecf175ffb7701fc886d62c9.js +1 -0
  198. package/ui/dist/_expo/static/js/web/[taskId]-31a48c7017dbd096f8ece9dc102a9762.js +1 -0
  199. package/ui/dist/_expo/static/js/web/[taskId]-a56cf85bcfd14f2d6b5d4180ea17e8d7.js +1 -0
  200. package/ui/dist/_expo/static/js/web/[taskId]-f2a157b3cb676b3c5d04c8eadfe90cdd.js +1 -0
  201. package/ui/dist/_expo/static/js/web/__common-1ad58e53e08528a67b99f53a1690b669.js +2078 -0
  202. package/ui/dist/_expo/static/js/web/__expo-metro-runtime-1f8f5d3ca6b7f58204d51e14506d73fb.js +5 -0
  203. package/ui/dist/_expo/static/js/web/_layout-057457e97e0af20433ed41b39cb5e809.js +1 -0
  204. package/ui/dist/_expo/static/js/web/_layout-2a7d73d5356823e1f7d2dab23e440d09.js +7 -0
  205. package/ui/dist/_expo/static/js/web/_layout-42e6a6b7855655d456015ce41aefdd39.js +1 -0
  206. package/ui/dist/_expo/static/js/web/_layout-a5e5a5b2fb3bfbfcc2914131976679e7.js +1 -0
  207. package/ui/dist/_expo/static/js/web/_layout-b2cbba92506f66815a5d744fd7cd5d8c.js +1 -0
  208. package/ui/dist/_expo/static/js/web/_layout-b4d13dc52bbcb65b18b4e52813d53883.js +198 -0
  209. package/ui/dist/_expo/static/js/web/_layout-fb0f75b354800de2e1582dc963f5c148.js +1 -0
  210. package/ui/dist/_expo/static/js/web/index-41299a961569cc8e5410ec53ba2b87c4.js +4 -0
  211. package/ui/dist/_expo/static/js/web/index-6c2bb0d3b6d00c5c007a663e9f4ce108.js +1 -0
  212. package/ui/dist/_expo/static/js/web/index-70484f7d2769d9ae01dac1fdb22aef1d.js +14 -0
  213. package/ui/dist/_expo/static/js/web/index-7d764cb7cefe0a217728c24d44990057.js +14 -0
  214. package/ui/dist/_expo/static/js/web/index-a5eb3d0c6aa4c483674beb5de428634c.js +12 -0
  215. package/ui/dist/_expo/static/js/web/index-b1c2543003cba86eeb3abfa4d21fd8da.js +14 -0
  216. package/ui/dist/_expo/static/js/web/index-d200aded5448966e5e05d9ccb77b56a4.js +5 -0
  217. package/ui/dist/_expo/static/js/web/index-ea43f51ceec4a981c942fc6dce9cedc4.js +2378 -0
  218. package/ui/dist/_expo/static/js/web/index-efa68d817a7febbf8c0163303bf4cd49.js +29 -0
  219. package/ui/dist/_expo/static/js/web/licenses-30f8c0555f7f4d434a68ee4706fa433d.js +1 -0
  220. package/ui/dist/_expo/static/js/web/pair-3f6f72208023894f43f4f07db5116cca.js +1 -0
  221. package/ui/dist/_expo/static/js/web/rich-markdown-editor-dea9c0f7c0306da4146e54ee44cce173.js +228 -0
  222. package/ui/dist/_expo/static/js/web/sign-in-67d2a0c00232e0e6f40efade1a83dc4b.js +4 -0
  223. package/ui/dist/_expo/static/js/web/terminal-view-32db8e6f8a21dd073f6a310862d36db8.js +90 -0
  224. package/ui/dist/apple-touch-icon.png +0 -0
  225. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/100Thin/GeistMono_100Thin.95eed4519d8c395e41b3b837ca97edea.ttf +0 -0
  226. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/100Thin_Italic/GeistMono_100Thin_Italic.2e50fb9a43d70ceb4925a2c54502097c.ttf +0 -0
  227. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/200ExtraLight/GeistMono_200ExtraLight.0714ea94ac265d76bc16698dd1808599.ttf +0 -0
  228. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/200ExtraLight_Italic/GeistMono_200ExtraLight_Italic.107f2670e94507223548f1d38eb14087.ttf +0 -0
  229. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/300Light/GeistMono_300Light.d6a3533adfd5834dd9f68ee37faa1e2d.ttf +0 -0
  230. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/300Light_Italic/GeistMono_300Light_Italic.09420cdceda8d1f1612daceae1e4890e.ttf +0 -0
  231. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/400Regular/GeistMono_400Regular.3656dcb247d3a6cd141f7601c2101125.ttf +0 -0
  232. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/400Regular_Italic/GeistMono_400Regular_Italic.88343c321b266476ad3bc56735cc6ac7.ttf +0 -0
  233. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/500Medium/GeistMono_500Medium.a298cd61aebdb709299e2a7deb73ed93.ttf +0 -0
  234. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/500Medium_Italic/GeistMono_500Medium_Italic.e149441dd9360bd7dbffeb1de9aa1685.ttf +0 -0
  235. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/600SemiBold/GeistMono_600SemiBold.cae945cb3b6156e396a1008b6252af21.ttf +0 -0
  236. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/600SemiBold_Italic/GeistMono_600SemiBold_Italic.e939ba436795ee2f0a379e7271bb957d.ttf +0 -0
  237. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/700Bold/GeistMono_700Bold.7fcc8478bc1dcadc865d97626ba3206b.ttf +0 -0
  238. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/700Bold_Italic/GeistMono_700Bold_Italic.8cc57ff1f3c45e7ed84e74853c141e06.ttf +0 -0
  239. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/800ExtraBold/GeistMono_800ExtraBold.b09b5457204e06ea7bacff03f0880065.ttf +0 -0
  240. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/800ExtraBold_Italic/GeistMono_800ExtraBold_Italic.0b4dd8c1b0e6d8791ea34c8f1417edfd.ttf +0 -0
  241. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/900Black/GeistMono_900Black.9ec025adf049c8a476588eeac81a36e4.ttf +0 -0
  242. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/900Black_Italic/GeistMono_900Black_Italic.8dfe24b2fef43fb3d535316e2412be7d.ttf +0 -0
  243. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/100Thin/HankenGrotesk_100Thin.2d9c9415d97b66fb3bbca06b538f11d8.ttf +0 -0
  244. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/100Thin_Italic/HankenGrotesk_100Thin_Italic.5ad53da9f1ff702f55cf870763a159ff.ttf +0 -0
  245. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/200ExtraLight/HankenGrotesk_200ExtraLight.2cae1a1078b5af081aff084011b07522.ttf +0 -0
  246. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/200ExtraLight_Italic/HankenGrotesk_200ExtraLight_Italic.5d4eff887cdb33164b4fba2066c687e3.ttf +0 -0
  247. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/300Light/HankenGrotesk_300Light.2be9fd730ff95b91631e3f99bc449709.ttf +0 -0
  248. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/300Light_Italic/HankenGrotesk_300Light_Italic.4ae6910889ffdf69093da607b369b0a8.ttf +0 -0
  249. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/400Regular/HankenGrotesk_400Regular.2e544d6119b4e635f6cc5a47800523bb.ttf +0 -0
  250. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/400Regular_Italic/HankenGrotesk_400Regular_Italic.ed9d322cffe9e614205ce9512f144834.ttf +0 -0
  251. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/500Medium/HankenGrotesk_500Medium.a822d33614b51eb05478e0e29cf757f3.ttf +0 -0
  252. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/500Medium_Italic/HankenGrotesk_500Medium_Italic.bc71c45237e12974e52335b615fab7da.ttf +0 -0
  253. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/600SemiBold/HankenGrotesk_600SemiBold.b016ff502f15ce9b59c453304c74fb48.ttf +0 -0
  254. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/600SemiBold_Italic/HankenGrotesk_600SemiBold_Italic.94428d43b74e372dc47910fd4fc6b552.ttf +0 -0
  255. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/700Bold/HankenGrotesk_700Bold.14d2af6df606492d846389d2108dae50.ttf +0 -0
  256. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/700Bold_Italic/HankenGrotesk_700Bold_Italic.d075966aaf26126d8aaac0802735e310.ttf +0 -0
  257. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/800ExtraBold/HankenGrotesk_800ExtraBold.b419489745bc870b4e4288e969945f31.ttf +0 -0
  258. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/800ExtraBold_Italic/HankenGrotesk_800ExtraBold_Italic.ea7ac4778026e067a5d637f4a494b2d2.ttf +0 -0
  259. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/900Black/HankenGrotesk_900Black.55e860e6549b53fa530d9eda7c7518a2.ttf +0 -0
  260. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/900Black_Italic/HankenGrotesk_900Black_Italic.dcad6f722a66aae93f70a72604112754.ttf +0 -0
  261. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/200ExtraLight/Newsreader_200ExtraLight.1ee07dc260606863f8bf8101308d85f2.ttf +0 -0
  262. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/200ExtraLight_Italic/Newsreader_200ExtraLight_Italic.52c51abab458715d1205b8732b55735f.ttf +0 -0
  263. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/300Light/Newsreader_300Light.bf0dfa126654b01f65e1c53a4507ec12.ttf +0 -0
  264. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/300Light_Italic/Newsreader_300Light_Italic.03190fe46aa9b7083610981ac13b10f3.ttf +0 -0
  265. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/400Regular/Newsreader_400Regular.b1d919187d5645f84124ef065868ba9e.ttf +0 -0
  266. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/400Regular_Italic/Newsreader_400Regular_Italic.f7b81d92eb42d85de96b6dc1c72d2c36.ttf +0 -0
  267. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/500Medium/Newsreader_500Medium.df89e83cfd4e37176dda53076a01b3b7.ttf +0 -0
  268. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/500Medium_Italic/Newsreader_500Medium_Italic.fb45099c4fb3c395e8f12e181475230c.ttf +0 -0
  269. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/600SemiBold/Newsreader_600SemiBold.20bce29dc5180892ce1fbf4a563737a0.ttf +0 -0
  270. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/600SemiBold_Italic/Newsreader_600SemiBold_Italic.93e2816e201fa363d3289e741f757ff0.ttf +0 -0
  271. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/700Bold/Newsreader_700Bold.bf7c54edbd2afe9b289d5da777f489e9.ttf +0 -0
  272. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/700Bold_Italic/Newsreader_700Bold_Italic.e2f5e5260513d7d4f9f3edbdcbc9f43f.ttf +0 -0
  273. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/800ExtraBold/Newsreader_800ExtraBold.702211ca77927e4c276b28169dc3694c.ttf +0 -0
  274. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/800ExtraBold_Italic/Newsreader_800ExtraBold_Italic.9b9eacc7d72e5152e692cb144ef7a9fd.ttf +0 -0
  275. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png +0 -0
  276. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png +0 -0
  277. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png +0 -0
  278. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png +0 -0
  279. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png +0 -0
  280. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/drawer/toggle-drawer-icon.ae74bb20586a731af545e6b00fe14a09.png +0 -0
  281. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png +0 -0
  282. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png +0 -0
  283. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png +0 -0
  284. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png +0 -0
  285. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png +0 -0
  286. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png +0 -0
  287. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png +0 -0
  288. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png +0 -0
  289. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png +0 -0
  290. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png +0 -0
  291. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png +0 -0
  292. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png +0 -0
  293. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png +0 -0
  294. package/ui/dist/favicon.ico +0 -0
  295. package/ui/dist/favicon.svg +10 -0
  296. package/ui/dist/icon-192.png +0 -0
  297. package/ui/dist/icon-512.png +0 -0
  298. package/ui/dist/index.html +45 -0
  299. package/ui/dist/legal/privacy-policy.md +174 -0
  300. package/ui/dist/legal/terms-of-use.md +76 -0
  301. package/ui/dist/load-again.js +42 -0
  302. package/ui/dist/manifest.webmanifest +12 -0
  303. package/ui/dist/metadata.json +1 -0
  304. package/ui/dist/sounds/bell.wav +0 -0
  305. package/ui/dist/sounds/chime.wav +0 -0
  306. package/ui/dist/sounds/knock.wav +0 -0
  307. package/ui/dist/sounds/pop.wav +0 -0
  308. package/ui/dist/sw.js +121 -0
@@ -0,0 +1,867 @@
1
+ // @bun
2
+ import{St,md,gd,wd,yd,Ue,ye,_s,Rd,A,Od,Qt,En,Js,jt,se,rt,Dd,qo,Xt,Ud,Fd,Hd,zd,Gd,oe,qd,vr,Vd,Kd,Vo,Sr,Jd,Zd,$r,Xd,eu,Is,Es,Ke,su,Z,iu,ot,R,An,Ko,Yo,yu,bu,ku,vu,Pr,l,ts,Ye,r,Xs,g,Ua,Ap,T,ve,_,Rp,it,xu,Ba}from"./bin-h57gajkz.js";import{e,b,n,t,ht,me,Zl,qc,ep,Bh,Hh,zh,Gh,ga,Co,Jt,Uo,td,up,De}from"./bin-4tdqjbbd.js";import{mt,ua,nr,Te,ko}from"./bin-z5b3tt05.js";import{Pe,z,de,Fm,Bm,U,m}from"./bin-nnq8kd9z.js";import{Gt,Ze}from"./bin-0t68hf99.js";import{fo,Qe,Ds,c,a,ho,ge}from"./bin-gne2w036.js";import{yo,Lc}from"./bin-za1by1n5.js";import{Ji}from"./bin-4j0jjd8g.js";import{k}from"./bin-37w316c6.js";import{O,s}from"./bin-gg19acwr.js";import{hostname as e0}from"os";var ba={name:"@superfactory/agent",version:"0.4.30",private:!0,description:"Node agent: drives claude, git, gh and sandboxes on one machine",type:"module",exports:{".":"./src/index.ts","./main":"./src/main.ts","./state":"./src/state/agent-state.ts","./endpoints":"./src/features/link/endpoints.ts","./machine-tools":"./src/features/machine/tools.ts"},bin:{"superfactory-agent":"./src/main.ts"},scripts:{typecheck:"tsc --noEmit",start:"bun src/main.ts run",build:"bun build --compile src/main.ts --outfile dist/superfactory-agent","build:linux":"bun build --compile --target=bun-linux-x64 src/main.ts --outfile dist/superfactory-agent-linux-x64 && bun build --compile --target=bun-linux-arm64 src/main.ts --outfile dist/superfactory-agent-linux-arm64",e2e:"bun test --preload ../../tools/e2e/heavy-suite.ts --timeout 300000 --parallel=4 --timings=e2e/timings.json"},dependencies:{"@superfactory/claude-driver":"workspace:*","@superfactory/contracts":"workspace:*","@superfactory/runners":"workspace:*","@superfactory/safe-exec":"workspace:*","@superfactory/task-format":"workspace:*","@superfactory/task-ops":"workspace:*",zod:"catalog:"},devDependencies:{"@types/bun":"catalog:",typescript:"catalog:"}};import{readFile as vp,stat as Pp}from"fs/promises";import{homedir as Sa}from"os";import{join as Ir}from"path";import{existsSync as cp}from"fs";import{mkdir as dp,rename as lp,rm as fp,writeFile as $a}from"fs/promises";import{basename as pp,dirname as mp,join as jn}from"path";var hp=0;async function Ce(i,o){let d=jn(mp(i),".tmp");await dp(d,{recursive:!0});let u=jn(d,".gitignore");if(!cp(u))await $a(u,`*
3
+ `);let f=jn(d,`${pp(i)}.${process.pid}.${++hp}.tmp`);try{await $a(f,o),await gp(f,i)}catch(p){throw await fp(f,{force:!0}),p}}async function gp(i,o){for(let d=0;;d++)try{return await lp(i,o)}catch(u){let f=u.code;if(process.platform!=="win32"||f!=="EPERM"&&f!=="EBUSY"||d>=10)throw u;await new Promise((p)=>setTimeout(p,20*(d+1)))}}import{mkdtemp as wp,rm as yp}from"fs/promises";import{tmpdir as bp}from"os";import{join as $p}from"path";var Sp=120000;async function ac(i){if(i)O(i);let o=await wp($p(bp(),"sf-claude-ping-"));try{let d=await g(r(St).programPath(process.env.SUPERFACTORY_CLAUDE_BIN).flag("-p").flag("--model","haiku").flag("--output-format","stream-json").flag("--verbose").flag("--setting-sources","project").flag("--strict-mcp-config").endOptions().arg("Reply with the single word OK.").in(o).secretEnv(i?{CLAUDE_CODE_OAUTH_TOKEN:i}:{}).timeoutMs(Sp).by("claude-keep-started").build()),u=d.stdout.split(`
4
+ `).flatMap((P)=>{try{return[JSON.parse(P)]}catch{return[]}}),f=u.filter((P)=>P.type==="rate_limit_event").map((P)=>ua(P)).filter((P)=>P!==void 0),p=f.find((P)=>!P.window||P.window==="five_hour")??f[0],h=f.find((P)=>P.status==="rejected"),w=u.some((P)=>P.type==="result"&&!P.is_error),y=Object.assign({},...f.map((P)=>P.usage)),S=new nr,v=u.flatMap((P)=>S.push(P)).find((P)=>P.type==="login_failed");return{ok:d.exitCode===0&&w,windowEndsAt:p?.resetsAt,limitedUntil:h?.resetsAt,...Object.keys(y).length>0&&{usage:y},...v?.type==="login_failed"&&{signedOut:v.reason}}}finally{await yp(o,{recursive:!0,force:!0})}}var kp=()=>k("SUPERFACTORY_OWN_LOGIN_CHECK_MS",1800000),xp=()=>k("SUPERFACTORY_OWN_LOGIN_LOOK_MS",60000);class va{deps;state;loaded;lastPing=0;timer;changed=[];back=[];constructor(i){this.deps=i}onChange(i){this.changed.push(i)}onSignedIn(i){this.back.push(i)}get signedOutNow(){return this.state&&{since:this.state.since,reason:this.state.reason}}load(){return this.loaded??=(async()=>{let i=await vp(this.deps.file,"utf8").catch(()=>{return});try{let o=i?JSON.parse(i):void 0;if(o?.since&&o.reason&&typeof o.fingerprint==="string")this.state={since:o.since,reason:o.reason,fingerprint:o.fingerprint}}catch{}if(this.state)this.watch()})(),this.loaded}async refused(i){if(await this.load(),this.state)return;this.state={since:new Date(this.now()).toISOString(),reason:i.slice(0,300),fingerprint:await this.fingerprint()},this.lastPing=this.now(),s.warn(`claude: this machine's own login is signed out (${this.state.reason}): nothing runs on it until it is signed in again`),await this.save(),this.watch();for(let o of this.changed)o()}async worked(){if(await this.load(),!this.state)return;this.state=void 0,s.info("claude: this machine's own login works again"),this.stopWatching(),await this.save();for(let i of[...this.changed,...this.back])i()}async signedOut(){if(await this.load(),!this.state)return!1;if(await this.fingerprint()===this.state.fingerprint)return!0;return s.info("claude: this machine's own Claude credentials changed: its login is tried again"),await this.worked(),!1}async check(){if(!await this.signedOut())return;if(this.now()-this.lastPing<kp())return;if(this.lastPing=this.now(),(await this.deps.ping().catch(()=>{return}))?.ok)await this.worked()}stop(){this.stopWatching()}watch(){if(this.timer)return;this.timer=setInterval(()=>{this.check().catch((i)=>s.warn("claude: checking this machine's own login failed",i))},xp()),this.timer.unref?.()}stopWatching(){if(this.timer)clearInterval(this.timer);this.timer=void 0}now(){return this.deps.now?.()??Date.now()}async fingerprint(){return(await Promise.all(this.deps.credentials().map(async(o)=>{let d=await Pp(o).catch(()=>{return});return d?`${o}:${d.mtimeMs}:${d.size}`:`${o}:none`}))).join("|")}async save(){await Ce(this.deps.file,`${JSON.stringify(this.state??{})}
5
+ `).catch((i)=>s.warn("claude: couldn't keep the state of this machine's own login",i))}}function Ep(i=process.env){if(i.SUPERFACTORY_CLAUDE_CREDENTIALS)return[i.SUPERFACTORY_CLAUDE_CREDENTIALS];return[...new Set([i.CLAUDE_CONFIG_DIR||Ir(Sa(),".claude"),Ir(Sa(),".claude")])].map((d)=>Ir(d,".credentials.json"))}var Hn;function Qf(){return Hn??=new va({file:Ir(m().home,"own-claude-login.json"),credentials:()=>Ep(),ping:()=>ac()}),Hn}var zn=()=>Hn?.signedOutNow;import{existsSync as Rh}from"fs";import{lstat as Jr,mkdir as Oh,readdir as Nc,readFile as _h,rm as Uc,rmdir as Ih,symlink as Th,writeFile as Ch}from"fs/promises";import{homedir as Dc}from"os";import{join as ze}from"path";import{homedir as xh}from"os";import{join as Eh}from"path";import{mkdir as Mp,readdir as Np,rm as Up,stat as ka}from"fs/promises";import{isAbsolute as Dp,join as xa,resolve as Lp}from"path";import{constants as Op}from"os";class L extends Error{name="RunnerError"}var _p=124,Ip=300,Tp=604800000;async function ee(i,o={}){return pe(i,o)}async function G(i,o={}){let d=await ee(i,o);if(d.exitCode!==0)throw new L(`${[i.program,...i.argv.slice(0,2)].join(" ")} failed (${d.exitCode}): ${d.stderr.trim()}`);return d.stdout}function Tr(i){return Bun.which(i)!==null}async function pe(i,o={}){let d=Date.now();if(o.background)return _(i,{stdin:"ignore",stdout:"ignore",stderr:"ignore"}).unref(),{stdout:"",stderr:"",exitCode:0,durationMs:Date.now()-d};let u=await g({...i,timeoutMs:o.timeout??Tp},{input:o.stdin,onStdout:o.onStdout,onStderr:o.onStderr,detached:!0});return{stdout:u.stdout,stderr:u.stderr,exitCode:u.timedOut?_p:u.exitCode,durationMs:Date.now()-d}}function ft(i,o,d){let u=_(i,{stdin:o.stdin?"pipe":"ignore"}),f={status:"running",exitCode:null,signal:null,stdout:"",stderr:""},p=Date.now(),h=(v)=>new Promise((P)=>v?v.once("close",()=>P()):P());u.stdout.on("data",(v)=>{let P=v.toString("utf8");f.stdout+=P,o.onStdout?.(P)}),u.stderr.on("data",(v)=>{let P=v.toString("utf8");f.stderr+=P,o.onStderr?.(P)});let w=Promise.all([h(u.stdout),h(u.stderr)]),y=new Promise((v)=>{u.once("exit",async(P,x)=>{await Promise.race([w,Bun.sleep(Ip)]),Object.assign(f,{status:"exited",exitCode:P,signal:x??null}),o.onExit?.({exitCode:P,signal:f.signal}),v()})}),S=()=>{if(!o.stdin||!u.stdin)throw new L("This process was started without stdin.");return u.stdin};return{pid:u.pid??null,jobId:crypto.randomUUID(),write:async(v)=>{await new Promise((P,x)=>S().write(v,(E)=>E?x(E):P()))},closeStdin:async()=>{S().end()},status:async()=>({...f}),wait:async({timeout:v}={})=>{let P=y.then(()=>!0);if(!(v?await Promise.race([P,Bun.sleep(v).then(()=>!1)]):await P))throw new L(`Process still running after ${v} ms.`);return{stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode??Cp(f.signal),durationMs:Date.now()-p,signal:f.signal}},kill:(v="SIGTERM")=>d(v.replace(/^SIG/,""))}}function Cp(i){let o=i?Op.signals[i]:void 0;return o===void 0?-1:128+o}function he(i,...o){let d=r(Z).script("-c",i);if(o.length)d.arg("sh").argsOf(o);return d.build()}function Pa(i,o,d){return r(Z).script("-c",d).in(i).secretEnv(o).build()}function Ve(i){return{text:i,__script:!0}}function q(i,o,d){return i.runCommand(o.text,d)}function es(i,o,d){return i.startProcess(o.text,d)}function rs(){let i=new Map,o={name:"host",check:async()=>({ready:!0}),sandbox:{create:async(d={})=>{if(!d.directory)throw new L("The host runner needs `directory`: the task's worktree.");let u=d.name??crypto.randomUUID(),f={id:u,directory:d.directory,env:d.envs??{},createdAt:new Date},p=new Ea(f,o,()=>i.delete(u));return i.set(u,p),p},getById:async(d)=>i.get(d)??null,list:async()=>[...i.values()],destroy:async(d)=>{i.delete(d)}}};return o}class Ea{instance;owner;forget;provider="host";sandboxId;filesystem;constructor(i,o,d){this.instance=i;this.owner=o;this.forget=d;this.sandboxId=i.id,this.filesystem=Bp((u)=>Dp(u)?u:xa(i.directory,u))}runCommand(i,o={}){return pe(this.inFolder(i,o),o)}async startProcess(i,o={}){let d=ft(this.inFolder(i,o),o,async(u)=>{let f=d.pid;if(!f||f<=0)return;let p=`SIG${u}`;if(process.platform==="win32"){ve({pid:f,kill:(h)=>process.kill(f,h)},p);return}for(let h of await Fp(f))try{process.kill(h,p)}catch{}});return d}async getInfo(){return{id:this.sandboxId,provider:this.provider,status:"running",createdAt:this.instance.createdAt,timeout:0,metadata:{directory:this.instance.directory}}}async getUrl({port:i,protocol:o="http"}){return`${o}://127.0.0.1:${i}`}async destroy(){this.forget()}getProvider(){return this.owner}getInstance(){return this.instance}inFolder(i,o){let d=o.cwd?Lp(this.instance.directory,o.cwd):this.instance.directory;return{...Pa(d,{...this.instance.env,...o.env},Ve(i)),lowPriority:!0}}}async function Fp(i){let o=await g(r(oe).flag("-axww").flag("-o","pid=,ppid=").build()),d=new Map;for(let f of o.stdout.split(`
6
+ `)){let[p,h]=f.trim().split(/\s+/).map(Number);if(p&&h!==void 0)d.set(h,[...d.get(h)??[],p])}let u=[i];for(let f=0;f<u.length;f++)u.push(...d.get(u[f]??-1)??[]);return u}function Bp(i){return{readFile:(o)=>Bun.file(i(o)).text(),writeFile:async(o,d)=>{await Bun.write(i(o),d)},mkdir:async(o)=>{await Mp(i(o),{recursive:!0})},readdir:async(o)=>{let d=await Np(i(o),{withFileTypes:!0});return Promise.all(d.map(async(u)=>{let f=await ka(xa(i(o),u.name));return{name:u.name,type:u.isDirectory()?"directory":"file",size:f.size,modified:f.mtime}}))},exists:(o)=>ka(i(o)).then(()=>!0,()=>!1),remove:async(o)=>{await Up(i(o),{recursive:!0,force:!0})}}}import{createHash as Hp}from"crypto";import{mkdir as Wp,writeFile as Vp}from"fs/promises";import{join as us}from"path";var Oa=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.168.0.0/16","224.0.0.0/4","240.0.0.0/4"],_a=["fc00::/7","fe80::/10","ff00::/8","::ffff:0:0/96"],be="sf";function Ia(i){return l`set -e
7
+ user=${be}
8
+ command -v setpriv >/dev/null || { echo "The sandbox image needs setpriv (util-linux)." >&2; exit 1; }
9
+ id "$user" >/dev/null 2>&1 || useradd --create-home "$user" 2>/dev/null || adduser -D "$user"
10
+ # The container's first process isn't under no-new-privs, and the user may run it: nothing it could
11
+ # start gives rights either (our image has none; a custom one may). A file that goes while find looks
12
+ # (a temp file of what starts with the sandbox, like Xvfb's /tmp/server-99.xkm) is no failure: find
13
+ # still looks at every other one, and one that's gone can't give rights.
14
+ if ! errors=$(find / -xdev -type f -perm /6000 -exec chmod ug-s {} + 2>&1 >/dev/null); then
15
+ if printf '%s\\n' "$errors" | grep -qv 'No such file or directory'; then echo "$errors" >&2; exit 1; fi
16
+ fi
17
+ if command -v getcap >/dev/null && command -v setcap >/dev/null; then
18
+ getcap -r /usr /bin /sbin /opt 2>/dev/null | while read -r file _; do setcap -r "$file"; done
19
+ fi
20
+ for dir in ${i}; do
21
+ # Root goes through no link: the image (a project's setup, as the work user) may have made any part of
22
+ # the path one, to hand root's own files to that user.
23
+ path=""
24
+ for part in $(printf '%s' "$dir" | tr / ' '); do
25
+ path="$path/$part"
26
+ [ ! -L "$path" ] || { echo "$path is a link: the sandbox's image is refused" >&2; exit 1; }
27
+ done
28
+ mkdir -p "$dir"
29
+ [ "$(stat -c %U "$dir")" = "$user" ] || chown -hR "$user:" "$dir" 2>/dev/null || true
30
+ # Made here under the user's home, its parents were made too, as root.
31
+ parent=$(dirname "$dir")
32
+ while [ "\${parent#/home/$user}" != "$parent" ]; do chown -h "$user:" "$parent"; parent=$(dirname "$parent"); done
33
+ done`}function ns(i){return l`set -e
34
+ for t in iptables ip6tables; do
35
+ $t -F OUTPUT
36
+ $t -A OUTPUT -o lo -j ACCEPT
37
+ $t -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
38
+ done
39
+ for ns in $(awk '/^nameserver/ {print $2}' /etc/resolv.conf); do
40
+ case "$ns" in *:*) t=ip6tables ;; *) t=iptables ;; esac
41
+ $t -A OUTPUT -d "$ns" -p udp --dport 53 -j ACCEPT
42
+ $t -A OUTPUT -d "$ns" -p tcp --dport 53 -j ACCEPT
43
+ done
44
+ for entry in ${i}; do
45
+ case "$entry" in
46
+ *:*) iptables -A OUTPUT -d "\${entry%:*}" -p tcp --dport "\${entry##*:}" -j ACCEPT ;;
47
+ *) iptables -A OUTPUT -d "$entry" -j ACCEPT ;;
48
+ esac
49
+ done
50
+ for range in ${Oa}; do iptables -A OUTPUT -d "$range" -j REJECT; done
51
+ for range in ${_a}; do ip6tables -A OUTPUT -d "$range" -j REJECT; done`}var Cr="/etc/pf.superfactory.conf",Ra="/Library/LaunchDaemons/com.superfactory.egress.plist";function Ta(i,o=void 0){return l`set -e
52
+ export PATH=/usr/bin:/bin:/usr/sbin:/sbin
53
+ v4=; for range in ${Oa}; do v4="$v4 $range"; done
54
+ v6=; for range in ${_a}; do v6="$v6 $range"; done
55
+ {
56
+ echo 'set skip on lo0'
57
+ echo 'scrub-anchor "com.apple/*"'
58
+ echo 'nat-anchor "com.apple/*"'
59
+ echo 'rdr-anchor "com.apple/*"'
60
+ echo 'dummynet-anchor "com.apple/*"'
61
+ echo 'anchor "com.apple/*"'
62
+ echo 'load anchor "com.apple" from "/etc/pf.anchors/com.apple"'
63
+ ${o?l`echo "pass in quick inet proto tcp from ${o.screenFrom} to any port ${o.screenPort}"
64
+ echo "block return in quick proto tcp to any port ${o.screenPort}"`:l`:`}
65
+ echo 'pass in all'
66
+ echo 'pass out quick inet proto udp to any port 67'
67
+ echo 'pass out quick inet6 proto icmp6 all'
68
+ for ns in $(awk '/^nameserver/ {print $2}' /etc/resolv.conf); do
69
+ echo "pass out quick proto { tcp udp } to \${ns%%%*} port 53"
70
+ done
71
+ for entry in ${i}; do
72
+ case "$entry" in
73
+ *:*) echo "pass out quick inet proto tcp to \${entry%:*} port \${entry##*:}" ;;
74
+ *) echo "pass out quick inet to $entry" ;;
75
+ esac
76
+ done
77
+ echo "block return out quick inet to {$v4 }"
78
+ echo "block return out quick inet6 to {$v6 }"
79
+ } > ${Cr}
80
+ pfctl -q -nf ${Cr}
81
+ pfctl -q -E -f ${Cr} 2>/dev/null
82
+ cat > ${Ra} <<PLIST
83
+ <?xml version="1.0" encoding="UTF-8"?>
84
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
85
+ <plist version="1.0"><dict>
86
+ <key>Label</key><string>com.superfactory.egress</string>
87
+ <key>ProgramArguments</key><array><string>/sbin/pfctl</string><string>-E</string><string>-f</string><string>${Cr}</string></array>
88
+ <key>RunAtLoad</key><true/>
89
+ </dict></plist>
90
+ PLIST
91
+ chmod 644 ${Ra}
92
+ printf 'Defaults env_reset, secure_path="/usr/bin:/bin:/usr/sbin:/sbin", timestamp_timeout=0\\nroot ALL = (ALL) ALL\\n${o?l`%s ALL = (ALL) ALL\\n`:l``}' ${o?o.sudoWithPassword:[]} > /etc/sudoers.superfactory
93
+ chmod 440 /etc/sudoers.superfactory
94
+ visudo -q -cf /etc/sudoers.superfactory
95
+ mv /etc/sudoers.superfactory /etc/sudoers
96
+ rm -f /etc/sudoers.d/*
97
+ dseditgroup -o edit -a admin -t user _developer 2>/dev/null || true
98
+ dseditgroup -o edit -d admin -t user admin 2>/dev/null || true`}import{basename as jp}from"path";function Ar(i,o){let d=async(f,p)=>{let h=await i(f,{stdin:p});if(h.exitCode!==0)throw new L(h.stderr.trim()||`${f.text} failed`);return h.stdout},u=(f)=>o==="gnu"?l`find ${f} -mindepth 1 -maxdepth 1 -printf '%y\\t%s\\t%T@\\t%p\\n'`:l`find ${f} -mindepth 1 -maxdepth 1 -exec stat -f '%HT%t%z%t%m%t%N' {} +`;return{readFile:(f)=>d(l`cat -- ${f}`),writeFile:async(f,p)=>{await d(l`f=${f}; mkdir -p "$(dirname "$f")" && cat > "$f"`,p)},mkdir:async(f)=>{await d(l`mkdir -p -- ${f}`)},readdir:async(f)=>(await d(u(f))).split(`
99
+ `).filter(Boolean).map((p)=>{let[h="",w,y,...S]=p.split("\t");return{name:jp(S.join("\t")),type:h==="d"||h==="Directory"?"directory":"file",size:Number(w),modified:new Date(Number(y)*1000)}}),exists:async(f)=>(await i(l`test -e ${f}`)).exitCode===0,remove:async(f)=>{await d(l`rm -rf -- ${f}`)}}}import{connect as Gp}from"net";function as(i,o="127.0.0.1"){return new Promise((d)=>{let u=Gp({port:i,host:o,timeout:1000}),f=(p)=>{u.destroy(),d(p)};u.once("connect",()=>f(!0)),u.once("error",()=>f(!1)),u.once("timeout",()=>f(!1))})}var Na=us(import.meta.dir,"..","..","image"),ss=new Map,Ie="/workspace",Yp=`${Ie}-tasks`,Gn=6080,cc=[3000,5173,8080,8081,19006],je="superfactory.sandbox",Ca="superfactory.user",qp=30000,Aa=/^[a-z0-9][a-z0-9-]{0,63}$/,pt=`/home/${be}`;function Jp(i,o){return[`FROM ${i}`,`COPY --chown=${be}:${be} files /tmp/sf-setup`,`COPY --chown=${be}:${be} run /tmp/sf-setup-run`,`USER ${o?"root":be}`,"WORKDIR /tmp/sf-setup",'RUN ["bash", "/tmp/sf-setup-run/setup.sh"]',`USER ${be}`,'RUN ["bash", "/tmp/sf-setup-run/done.sh"]',"USER root",'RUN ["rm", "-rf", "/tmp/sf-setup", "/tmp/sf-setup-run"]',`USER ${be}`,`WORKDIR ${Ie}`,""].join(`
100
+ `)}var is="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",Kp={bun:`${pt}/.bun/install/cache`,npm:`${pt}/.npm`,pnpm:`${pt}/.local/share/pnpm/store`,cargo:`${pt}/.cargo/registry`,sccache:`${pt}/.cache/sccache`},Ma=(i)=>Kp[i]??`${pt}/.cache/${i}`;function zp(i){if(i.name==="apple-container")return()=>r(md);return()=>{let o=r(Ue);return i.sshTarget?o.env({DOCKER_HOST:i.sshTarget}):o}}function Mr(i){let o=new Map,d=zp(i),u=i.name==="docker"?"docker":"container",f=i.name==="docker"?"volume rm":"volume delete",p=i.name==="docker"?"network rm":"network delete",h=(M)=>{let F=Hp("sha256").update(M).digest("hex").slice(0,8);return`sf-net-${M.toLowerCase().replace(/[^a-z0-9-]+/g,"-").slice(0,46)}-${F}`},w=async(M)=>{let F=os(M),D=await ee(d().sub("inspect").arg(F).build());if(D.exitCode!==0)return null;let[V]=JSON.parse(D.stdout);if(!V)return null;if(i.name==="docker")return{id:M,container:F,labels:V.Config?.Labels??{},ip:V.NetworkSettings?.Networks?.[h(M)]?.IPAddress||void 0};let J=V.status?.networks?.[0]?.ipv4Address;return{id:M,container:F,labels:V.configuration?.labels??{},ip:J?.split("/")[0]}},y=async()=>{if(!Tr(u))return{ready:!1,reason:`${u} is not installed.`,fix:i.installFix};let M=i.name==="docker"?d().sub("info").flag("--format","{{.ServerVersion}}"):d().sub("system status"),F=await ee(M.build());if(F.exitCode!==0)return{ready:!1,reason:F.stderr.trim()||"Not running.",fix:i.serviceFix};return{ready:!0}},S=async(M,{waitForBuild:F=!1}={})=>{if((await ee(d().sub("image inspect").arg(M).build())).exitCode===0)return;if(M!==i.image)return;let D=`${i.name} ${i.sshTarget??"local"} ${M}`,V=ss.get(D);if(V&&!F){let Lt=Math.round((Date.now()-V.since)/60000);throw new L(`Preparing the sandbox image (its first build on this machine, a few minutes; ${Lt?`${Lt} min in`:"just started"}). Start the session again once it's ready.`)}if(V)return V.done;let J=G(d().sub("build").flag("--tag",M).arg(Na).timeoutMs(3600000).build()).then(()=>{return}).finally(()=>ss.delete(D));return ss.set(D,{since:Date.now(),done:J}),J},v=async(M,F)=>{let D=d().sub("volume create");if(process.env.SF_E2E_RUN)D.flag("--label",`superfactory.e2e-run=${process.env.SF_E2E_RUN}`).flag("--label",`superfactory.created=${new Date().toISOString()}`);return await ee(D.arg(M).build()),`type=volume,source=${M},target=${F}`},P=(M)=>{let F=d().sub("rm").flag("--force");if(i.name==="docker")F.flag("--volumes");return F.arg(M).build()},x=async(M={},{keepWorkspace:F=!1}={})=>{let D=M.name??`sf-${crypto.randomUUID().slice(0,8)}`;if(!/^[A-Za-z0-9_-]{1,64}$/.test(D))throw new L(`Bad sandbox name: ${D}`);let V=await y();if(!V.ready)throw new L(`${V.reason} ${V.fix??""}`.trim());let J=M.metadata??{},Lt=M.image??i.image;await S(Lt);let Bn=os(D),ne=d().sub("run").flag("-d").flag("--name",Bn).flag("--label",`${je}=${D}`).flag("--label",`${Ca}=${be}`).flag("--label",`superfactory.created=${new Date().toISOString()}`);if(J.projectId)ne.flag("--label",`superfactory.project=${J.projectId}`);if(J.node)ne.flag("--label",`superfactory.node=${J.node}`);if(J.taskId)ne.flag("--label",`superfactory.task=${J.taskId}`);if(process.env.SF_E2E_RUN)ne.flag("--label",`superfactory.e2e-run=${process.env.SF_E2E_RUN}`);if(J.vnc)ne.flag("--label","superfactory.vnc=1");let pa=i.cpus??(process.env.SF_E2E_RUN?2:void 0);if(pa)ne.flag("--cpus",pa);if(i.name==="apple-container")ne.flag("--cap-add","CAP_NET_ADMIN");if(i.memoryGb)ne.flag("--memory",`${i.memoryGb}g`);if(!F)await ee(d().sub(f).arg(`sf-ws-${D}`).build());ne.flag("--mount",await v(`sf-ws-${D}`,Ie));let Or=J.projectId??"shared";if(!Aa.test(Or))throw new L(`Bad project id for caches: ${Or}`);for(let _e of i.caches){if(!Aa.test(_e))throw new L(`Bad cache name: ${_e}`);let _r=Ma(_e);if(i.cacheDir){let ya=us(i.cacheDir,Or,_e);await Wp(ya,{recursive:!0,mode:448}),ne.flag("-v",`${ya}:${_r}`)}else ne.flag("--mount",await v(`sf-cache-${Or}-${_e}`,_r))}await C(D);let ma=d().sub("network create").flag("--label",`${je}=${D}`);if(process.env.SF_E2E_RUN)ma.flag("--label",`superfactory.e2e-run=${process.env.SF_E2E_RUN}`).flag("--label",`superfactory.created=${new Date().toISOString()}`);if(await G(ma.arg(h(D)).build()),i.sibling)await G(d().sub("network connect").arg(h(D)).arg(i.sibling).build());ne.flag("--network",h(D));let ha={...M.envs,...J.vnc?{SF_VNC:"1",SF_VNC_PASSWORD:Zp()}:{}};if(ne.flags("-e",Object.keys(ha)).secretEnv(ha),!i.reachesSandboxIp){let _e=Qp(J);ne.flag("--label",`superfactory.ports=${_e.join(",")}`),ne.flags("-p",_e.map((_r)=>`127.0.0.1::${_r}`))}ne.flag("-w",Ie).arg(Lt).wrap(r(Dd).arg("infinity").build()),await G(ne.build());let wa=await w(D);if(!wa)throw new L(`Sandbox ${D} didn't start.`);return await E(Bn).catch(async(_e)=>{throw await ee(P(Bn)),_e}),Fn(wa)},E=async(M)=>{if(i.name==="docker")await I(M);let F=d().sub("exec").flag("--user","root").flag("-e",`PATH=${is}`),D=[Ie,Yp,...i.caches.map(Ma)],V=ts([l`export PATH=${is}`,...i.name==="docker"?[]:[ns(i.allowNetwork)],Ia(D)]),J=await ee(F.arg(M).wrap(he(V)).build());if(J.exitCode!==0)throw new L(`Sandbox lock-down failed: ${J.stderr.trim()||J.stdout.trim()}`)},I=async(M)=>{await S(i.image);let F=d().sub("run").flag("--rm").flag("--network",`container:${M}`).flag("--user","root").flag("--cap-add","NET_ADMIN").flag("--cap-add","NET_RAW").flag("-e",`PATH=${is}`).arg(i.image).wrap(he(ns(i.allowNetwork))),D=await ee(F.build());if(D.exitCode!==0)throw new L(`Sandbox lock-down failed: ${D.stderr.trim()||D.stdout.trim()}`)},N=async(M)=>{await ee(P(M.container));let F=(M.labels["superfactory.ports"]??"").split(",").filter(Boolean).map(Number),D={projectId:M.labels["superfactory.project"],vnc:M.labels["superfactory.vnc"]==="1",...F.length?{ports:F.filter((V)=>V!==Gn)}:{}};return x({name:M.id,metadata:D},{keepWorkspace:!0})},W=async(M)=>{for(let D of o.get(M)??[])D.close();o.delete(M);let F=os(M);await re(P(F),d().sub("inspect").arg(F).build()),await ee(d().sub(f).arg(`sf-ws-${M}`).build()),await C(M)},re=async(M,F)=>{for(let D=Date.now()+qp;;await Bun.sleep(500))if(await ee(M),(await ee(F)).exitCode!==0||Date.now()>D)return},C=async(M)=>{if(i.sibling)await ee(d().sub("network disconnect").flag("--force").arg(h(M)).arg(i.sibling).build());await re(d().sub(p).arg(h(M)).build(),d().sub("network inspect").arg(h(M)).build())},B=async()=>{if(i.name==="docker"){let D=d().sub("ps").flag("--all").flag("--filter",`label=${je}`).flag("--format",`{{.Label "${je}"}}`);return(await G(D.build())).split(`
101
+ `).filter(Boolean)}let M=d().sub("ls").flag("--all").flag("--format","json");return JSON.parse(await G(M.build())).map((D)=>D.configuration?.labels?.[je]??"").filter(Boolean)},fe=async()=>{if(i.name==="docker"){let D=d().sub("network ls").flag("--filter",`label=${je}`).flag("--format",`{{.Name}} {{.Label "${je}"}}`);return(await G(D.build())).split(`
102
+ `).map((V)=>V.split("\t")).flatMap(([V,J])=>V&&J?[{name:V,sandbox:J}]:[])}let M=d().sub("network ls").flag("--format","json");return JSON.parse(await G(M.build())).flatMap((D)=>{let V=D.configuration?.labels?.[je];return V?[{name:D.id,sandbox:V}]:[]})},Dt=async(M)=>{let F=new Set(await B()),D=(await fe()).filter((J)=>J.sandbox.startsWith(M)&&!F.has(J.sandbox)),V=[];for(let{name:J}of D)if((await ee(d().sub(p).arg(J).build())).exitCode===0)V.push(J);return V},Fn=(M)=>new Da(M,i,fa,d,(F)=>{o.set(M.id,[...o.get(M.id)??[],F])}),fa={name:i.name,check:y,prepareImage:()=>S(i.image,{waitForBuild:!0}),setupImage:{has:async(M)=>(await ee(d().sub("image inspect").arg(M).build())).exitCode===0,build:async(M,F,{root:D,onOutput:V})=>(await S(i.image,{waitForBuild:!0}),await Vp(us(M,"Dockerfile"),Jp(i.image,D)),pe(d().sub("build").flag("--tag",F).flag("--label",`superfactory.setup=${F}`).arg(M).timeoutMs(3600000).build(),{onStdout:V,onStderr:V}))},pruneNetworks:Dt,sandbox:{create:x,getById:async(M)=>{let F=await w(M);if(!F)return null;return F.labels[Ca]?Fn(F):N(F)},list:async()=>(await Promise.all((await B()).map(w))).filter((F)=>F!==null).map(Fn),destroy:W}};return fa}class Da{instance;engine;owner;cli;keepForward;sandboxId;provider;filesystem;constructor(i,o,d,u,f){this.instance=i;this.engine=o;this.owner=d;this.cli=u;this.keepForward=f;this.sandboxId=i.id,this.provider=o.name,this.filesystem=Ar((p,h)=>q(this,p,h),"gnu")}runCommand(i,o={}){let d=this.exec(he(Ve(i)),o,{detach:o.background,stdin:o.stdin!==void 0}),{timeout:u,onStdout:f,onStderr:p,stdin:h}=o;return pe(d,{timeout:u,onStdout:f,onStderr:p,stdin:h})}async startProcess(i,o={}){let d=`/tmp/sf-${crypto.randomUUID()}.pid`,u=l`echo $$ > ${d}; exec sh -c ${i}`,f=this.exec(he(u),o,{stdin:o.stdin===!0}),p={...o,cwd:void 0};return ft(f,p,async(h)=>{let w=he(l`kill -s "$1" -- "-$(cat "$2")"`,h,d);await ee(this.exec(w,{},{}))})}async getInfo(){let i=this.instance.labels,o=await ee(this.cli().sub("inspect").arg(this.instance.container).build());return{id:this.sandboxId,provider:this.provider,status:Xp(o.exitCode===0?o.stdout:"[]"),createdAt:new Date(i["superfactory.created"]??Date.now()),timeout:0,metadata:{projectId:i["superfactory.project"],vnc:i["superfactory.vnc"]==="1",workdir:Ie,e2eRun:i["superfactory.e2e-run"]}}}async getUrl({port:i,protocol:o="http"}){if(this.engine.reachesSandboxIp){if(!this.instance.ip)throw new L(`Sandbox ${this.sandboxId} has no IP address.`);return`${o}://${this.instance.ip}:${i}`}if(!(this.instance.labels["superfactory.ports"]??"").split(",").map(Number).includes(i))throw new L(`Port ${i} wasn't published; add it to metadata.ports.`);let u=this.cli().sub("port").arg(this.instance.container),f=(await G(u.arg(i).build())).split(`
103
+ `)[0]??"",p=Number(f.slice(f.lastIndexOf(":")+1));if(!this.engine.sshTarget)return`${o}://127.0.0.1:${p}`;return`${o}://127.0.0.1:${await this.forwardOverSsh(this.engine.sshTarget,p)}`}destroy(){return this.owner.sandbox.destroy(this.sandboxId)}getProvider(){return this.owner}getInstance(){return this.instance}ownership(){return{node:this.instance.labels["superfactory.node"],task:this.instance.labels["superfactory.task"]}}exec(i,o,d){let u=this.cli().sub("exec").flag("--user",be);if(d.detach)u.flag("-d");if(d.stdin)u.flag("-i");let f=o.env??{};return u.flag("-w",o.cwd??Ie).flags("-e",Object.keys(f)).secretEnv(f).arg(this.instance.container).wrap(r(qo).flag("--no-new-privs").wrap(i).build()).build()}async forwardOverSsh(i,o){let d=new URL(i);if(d.hostname.startsWith("-")||d.username.startsWith("-"))throw new L(`Bad docker host: ${i}`);let u=Um(),f=r(iu).flag("-N").flag("-o","ExitOnForwardFailure=yes").flag("-L",`127.0.0.1:${u}:127.0.0.1:${o}`);if(d.port)f.flag("-p",d.port);f.arg(d.username?`${d.username}@${d.hostname}`:d.hostname);let p=_(f.build(),{stdin:"ignore",stdout:"ignore",stderr:"ignore"});this.keepForward({close:()=>p.kill()});let h=!1;p.once("exit",()=>{h=!0});for(let w=0;w<50&&!h;w++){if(await as(u))return u;await Bun.sleep(200)}throw new L(`ssh port forward to ${o} didn't start.`)}}function Xp(i){let[o]=JSON.parse(i);return(o?.State?.Status??o?.status?.state)==="running"?"running":"stopped"}function os(i){return`sf-${i}`}function Qp(i){let o=i.ports??cc;return i.vnc?[...o,Gn]:o}function Zp(){return Buffer.from(crypto.getRandomValues(new Uint8Array(6))).toString("base64url")}function Um(){let i=Bun.listen({hostname:"127.0.0.1",port:0,socket:{data(){}}}),{port:o}=i;return i.stop(!0),o}import{mkdir as nc,readdir as hh,rm as sc}from"fs/promises";import{homedir as gh}from"os";import{join as xs}from"path";import{lookup as Dm}from"dns/promises";var La={npm:(i)=>({npm_config_registry:i.href,BUN_CONFIG_REGISTRY:i.href,YARN_NPM_REGISTRY_SERVER:i.href,YARN_REGISTRY:i.href,...i.protocol==="http:"?{YARN_UNSAFE_HTTP_WHITELIST:i.hostname}:{}}),python:(i)=>({PIP_INDEX_URL:i.href,UV_DEFAULT_INDEX:i.href,UV_INDEX_URL:i.href,...i.protocol==="http:"?{PIP_TRUSTED_HOST:i.hostname}:{}}),go:(i)=>({GOPROXY:`${i.href}|https://proxy.golang.org|direct`}),cargo:()=>({CARGO_REGISTRIES_CRATES_IO_PROTOCOL:"sparse"}),cocoapods:()=>({})};function ls(i=process.env){let o=(d)=>{let u=ht.safeParse(i[`SUPERFACTORY_${d}_MIRROR`]);return u.success?u.data:void 0};return{npm:o("NPM"),python:o("PYTHON"),go:o("GO"),cargo:o("CARGO"),cocoapods:o("COCOAPODS")}}var Gm={npm:"-/ping",python:"pip/",cargo:"config.json",cocoapods:"CocoaPods-version.yml"};function Nr(i){let o=new URL(i);return o.username="",o.password="",o.href}async function fs(i,o,d=1e4){let u=Gm[i];if(!u)return;let f=new URL(u,o.endsWith("/")?o:`${o}/`).href,p=Nr(f);try{let h=await fetch(f,{signal:AbortSignal.timeout(d)});return await h.body?.cancel(),h.ok?void 0:`${p} answered ${h.status}`}catch(h){let w=h instanceof Error?h.message:String(h);return`${p}: ${w.replaceAll(f,p)}`}}function ps(i){let o=Object.entries(i);return Object.assign({},...o.map(([d,u])=>u?La[d](new URL(u)):{}))}async function Fa(i){let o=[],d=[],u={};for(let[f,p]of Object.entries(i)){if(!p)continue;let h=new URL(p),w=await Dm(h.hostname.replace(/^\[|\]$/g,""),{all:!0,family:4}).catch(()=>[]);if(!w.length)continue;let y=h.port||(h.protocol==="https:"?"443":"80");for(let{address:S}of w)d.push(`${S}:${y}`);for(let[S,v]of Object.entries(La[f](h)))o.push({name:S,value:v});u[f]=p}return{env:o,allow:d,reachable:u}}function Ft(i){let o=`sparse+${i.endsWith("/")?i:`${i}/`}`;return`[source.crates-io]
104
+ replace-with = "cache"
105
+
106
+ [source.cache]
107
+ registry = ${JSON.stringify(o)}
108
+ `}import{chmod as nh,mkdir as sh,rm as Ya}from"fs/promises";import{homedir as ih}from"os";import{join as Gr}from"path";var gs=2,Ht=[],Ur=new Map,ms=new Set;async function Dr(i,o={},d){let u={...o,vm:i,since:new Date().toISOString(),booting:!0};Ht.push(u),hs();try{for(;;){let f=Ht.indexOf(u);if(f<gs-await Hm())return Ur.set(i,u),{booted:()=>{u.booting=!1}};d?.(f+1),await Bun.sleep(2000)}}finally{Ht.splice(Ht.indexOf(u),1),hs()}}function gt(i){if(Ur.delete(i))hs()}function dc(){let i=({vm:o,booting:d,...u})=>u;return{max:gs,running:[...Ur.values()].map(i),waiting:Ht.map(i)}}function al(i){return ms.add(i),()=>ms.delete(i)}function hs(){let i=dc();for(let o of ms)o(i)}async function Hm(){let i=JSON.parse(await G(r(R).sub("list").flag("--format","json").build())),o=new Set(i.filter((u)=>u.State==="running").map((u)=>u.Name)),d=[...Ur.values()].filter((u)=>u.booting&&!o.has(u.vm)).length;return o.size+d}function Ii(i){return l`set +e
109
+ SYS="/Library/Application Support/com.apple.TCC/TCC.db"
110
+ USR="$HOME/Library/Application Support/com.apple.TCC/TCC.db"
111
+ # One client a line: a path may have spaces.
112
+ clients=""
113
+ for p in ${i} /usr/local/bin/tart-guest-agent /opt/homebrew/bin/tart-guest-agent /opt/homebrew/bin/bun /opt/homebrew/bin/node /usr/local/bin/bun /usr/local/bin/node "$HOME/.bun/bin/bun" "$HOME/.local/bin/claude" /opt/homebrew/bin/claude /usr/bin/osascript /bin/bash /bin/zsh /bin/sh; do
114
+ [ -e "$p" ] && clients="$clients
115
+ $p"
116
+ done
117
+ shown=$(printf %s "$clients" | tr '\n' ' ')
118
+ IFS='
119
+ '
120
+ row() { printf "('%s', '%s', %s, '%s'),\n" "$1" "$(printf %s "$2" | sed "s/'/''/g")" "$3" "$4"; }
121
+ system_rows() {
122
+ for c in $clients; do
123
+ for s in kTCCServiceScreenCapture kTCCServiceAccessibility kTCCServicePostEvent kTCCServiceListenEvent kTCCServiceSystemPolicyAllFiles; do row $s "$c" 1 UNUSED; done
124
+ done
125
+ for s in kTCCServiceScreenCapture kTCCServiceAccessibility kTCCServiceSystemPolicyAllFiles; do row $s com.apple.Terminal 0 UNUSED; done
126
+ }
127
+ user_rows() {
128
+ for c in $clients com.apple.Terminal; do
129
+ t=1; [ "$c" = com.apple.Terminal ] && t=0
130
+ for app in com.apple.systemevents com.apple.finder com.apple.Terminal; do row kTCCServiceAppleEvents "$c" $t $app; done
131
+ for s in kTCCServiceSystemPolicyDesktopFolder kTCCServiceSystemPolicyDocumentsFolder kTCCServiceSystemPolicyDownloadsFolder kTCCServiceAudioCapture kTCCServiceMicrophone; do row $s "$c" $t UNUSED; done
132
+ done
133
+ }
134
+ # The rows wanted, those already granted (unpinned, as these are) left alone; prints how many it wrote.
135
+ grant_sql() {
136
+ echo ".timeout 10000"
137
+ echo "CREATE TEMP TABLE want (service TEXT, client TEXT, client_type INTEGER, object TEXT);"
138
+ echo "INSERT INTO want VALUES"; "$1" | sed '$ s/,$/;/'
139
+ echo "BEGIN IMMEDIATE;"
140
+ echo "INSERT OR REPLACE INTO access (service, client, client_type, auth_value, auth_reason, auth_version, csreq, indirect_object_identifier, flags) SELECT service, client, client_type, 2, 4, 1, NULL, object, 0 FROM want w WHERE NOT EXISTS (SELECT 1 FROM access a WHERE a.service = w.service AND a.client = w.client AND a.client_type = w.client_type AND a.indirect_object_identifier = w.object AND a.auth_value = 2 AND a.csreq IS NULL);"
141
+ echo "SELECT changes();"
142
+ echo "COMMIT;"
143
+ }
144
+ if n=$(grant_sql system_rows | sudo -n sqlite3 "$SYS" 2>/tmp/sf-tcc.err); then
145
+ if [ "$n" -gt 0 ] 2>/dev/null; then
146
+ sudo -n launchctl kickstart -k system/com.apple.tccd.system >/dev/null 2>&1
147
+ echo "TCC: Screen Recording, Accessibility, input and Full Disk Access for$shown ($n granted now; tccd restarted)"
148
+ else echo "TCC: Screen Recording, Accessibility, input and Full Disk Access for$shown (already granted)"; fi
149
+ else echo "TCC: the system's grants didn't go in ($(head -c 200 /tmp/sf-tcc.err)): SIP keeps them, and the agent approves what asks"; fi
150
+ if n=$(grant_sql user_rows | sqlite3 "$USR" 2>/tmp/sf-tcc.err); then
151
+ if [ "$n" -gt 0 ] 2>/dev/null; then
152
+ launchctl kickstart -k "gui/$(id -u)/com.apple.tccd" >/dev/null 2>&1
153
+ echo "TCC: Automation, the user folders, system audio and the microphone for$shown ($n granted now; tccd restarted)"
154
+ else echo "TCC: Automation, the user folders, system audio and the microphone for$shown (already granted)"; fi
155
+ else echo "TCC: the admin's grants didn't go in ($(head -c 200 /tmp/sf-tcc.err))"; fi
156
+ fw=/usr/libexec/ApplicationFirewall/socketfilterfw
157
+ sudo -n $fw --setallowsigned on >/dev/null 2>&1
158
+ sudo -n $fw --setallowsignedapp on >/dev/null 2>&1
159
+ for c in $clients; do sudo -n $fw --add "$c" >/dev/null 2>&1; sudo -n $fw --unblockapp "$c" >/dev/null 2>&1; done
160
+ echo "Firewall: incoming connections for$shown"
161
+ rm -f /tmp/sf-tcc.err
162
+ exit 0`}import{createCipheriv as Wm,createDecipheriv as Vm,hkdfSync as Ym,randomBytes as Wt}from"crypto";import{chmod as qm,mkdir as Jm,readFile as ws,rename as Km,rm as zm,writeFile as Xm}from"fs/promises";import{dirname as Qm,join as ys}from"path";function an(){return{adminPassword:Wt(18).toString("base64url"),screenPassword:Wt(6).toString("base64url")}}function to(i,o){let d=(p)=>ys(i,`${p}.vault`),u,f=()=>(u??=(o!==void 0?Promise.resolve(o):Zm(i)).then(ja),u);return{async get(p){let h=await ws(d(p)).catch(()=>{return});if(!h)return;try{return JSON.parse(Ha(h,await f(),p))}catch{}let w=o!==void 0&&await ws(ys(i,"vault.key"),"utf8").catch(()=>"");if(w)try{let y=JSON.parse(Ha(h,ja(w.trim()),p));return await bs(d(p),Ga(JSON.stringify(y),await f(),p)),y}catch{}return},async put(p,h){let w=Ga(JSON.stringify(h),await f(),p);await bs(d(p),w)},async remove(p){await zm(d(p),{force:!0})}}}var ja=(i)=>Buffer.from(Ym("sha256",i,"superfactory","tart vm passwords",32));async function Zm(i){let o=ys(i,"vault.key"),d=await ws(o,"utf8").catch(()=>{return});if(d)return d.trim();let u=Wt(32).toString("base64url");return await bs(o,u),u}function Ga(i,o,d){let u=Wt(12),f=Wm("aes-256-gcm",o,u).setAAD(Buffer.from(`tart-vm|${d}`)),p=Buffer.concat([f.update(i,"utf8"),f.final()]);return Buffer.concat([Buffer.from([1]),u,f.getAuthTag(),p])}function Ha(i,o,d){if(i[0]!==1)throw Error("unknown vault format");let u=Vm("aes-256-gcm",o,i.subarray(1,13)).setAAD(Buffer.from(`tart-vm|${d}`));return u.setAuthTag(i.subarray(13,29)),Buffer.concat([u.update(i.subarray(29)),u.final()]).toString("utf8")}async function bs(i,o){await Jm(Qm(i),{recursive:!0,mode:448});let d=`${i}.${process.pid}.${Wt(4).toString("hex")}.tmp`;await Xm(d,o,{mode:384}),await qm(d,384),await Km(d,i)}var uc=".superfactory/macos-setup.sh";async function Ei(i){let o=i.stateDir??Ns,d=so(o),u=`${i.name}-building`,f=Date.now();await qe(u,5),await ee(r(R).sub("delete").arg(u).build()),i.onStage?.("waiting");let p=await Dr(u,{projectId:i.projectId});i.onStage?.("building");let h=0,w=0;try{await G(r(R).sub("clone").arg(i.base).arg(u).build()),h=Date.now(),await Fr(u,{vnc:!1,logDir:o}),w=Date.now(),p.booted()}catch(P){throw await qe(u,5),gt(u),P}let y=async(P,x)=>{let E=await Wa(u,P,x,i.onLog);if(E.exitCode!==0)throw new L(`In ${u}: ${E.stderr.trim()||P.text}`)},S=0,v=an();try{if(i.setupScript){let x=await Bun.file(i.setupScript).text();await y(l`cat > /Users/admin/sf-setup.sh && chmod +x /Users/admin/sf-setup.sh`,x),await y(l`cd /Users/admin && ./sf-setup.sh && rm sf-setup.sh`)}S=Date.now(),await y(eh),await y(Ii([])),await y(th);let P=(await d.get(i.base).catch(()=>{return}))?.adminPassword??"admin";await y(l`sudo -n /bin/sh -c ${Wn(!0).text}`,`${P}
163
+ ${v.adminPassword}
164
+ ${v.screenPassword}
165
+ `),await Wa(u,l`sudo shutdown -h now`),await rh(u)}finally{await qe(u,60),gt(u)}return await ee(r(R).sub("delete").arg(i.name).build()),await G(r(R).sub("rename").arg(u).arg(i.name).build()),await d.put(i.name,v),{name:i.name,seconds:{clone:Lr(f,h),boot:Lr(h,w),setup:Lr(w,S),total:Lr(f,Date.now())}}}var eh=ts([l`printf '[install]\nlinker = "isolated"\n' > ~/.bunfig.toml`,l`mkdir -p ~/Library/Preferences/pnpm && printf 'enable-global-virtual-store=true\n' >> ~/Library/Preferences/pnpm/rc`]);async function cl(i,o,d){let u=new Bun.CryptoHasher("sha256").update(d).digest("hex"),f=`${o}.setup-sha256`;if((await q(i,l`cat ${f} 2>/dev/null`)).stdout.trim()===u)return"unchanged";let h=`${o}.setup.sh`,w=await q(i,l`cat > ${h} && chmod +x ${h}`,{stdin:d});if(w.exitCode!==0)throw new L(`The macOS setup didn't go in: ${w.stderr.trim()}`);let y=await q(i,l`cd ${o} && ${h}`);if(y.exitCode!==0)throw new L(`The project's ${uc} failed: ${(y.stderr.trim()||y.stdout.trim()).slice(-2000)}`);return await q(i,l`printf %s ${u} > ${f} && rm -f ${h}`),"ran"}var th=ts([l`sudo launchctl disable system/com.openssh.sshd`,l`sudo launchctl disable system/com.apple.screensharing`,l`sudo launchctl bootout system/com.openssh.sshd 2>/dev/null || true`,l`sudo launchctl bootout system/com.apple.screensharing 2>/dev/null || true`,l`sync`]);async function rh(i){for(let o=0;o<120;o++){if(await Re(i)!=="running")return;await Bun.sleep(1000)}}function Lr(i,o){return Math.round((o-i)/100)/10}function Wa(i,o,d,u){let f=r(R).sub("exec");if(d!==void 0)f.flag("-i");return pe(f.arg(i).wrap(he(o)).build(),{stdin:d,onStdout:u,onStderr:u})}var cs="superfactory-macos",Ai="superfactory-macos-golden",qa=5900,oh="/Users/admin",Ns=Gr(ih(),".superfactory","tart"),Je=(i)=>to(i);function dl(i){Je=i}function so(i){return Je(i)}var Br=new Map;function Ja(i){let o=i.vm??cs;return Ka(o,()=>ah(o,i))}function Ka(i,o){let u=(Br.get(i)??Promise.resolve()).catch(()=>{return}).then(o),f=u.then(()=>{return});return Br.set(i,f),f.catch(()=>Br.get(i)===f&&Br.delete(i)),u}var Vt=(i,o)=>Gr(i,`${o}.vm.json`);async function za(i,o){let d=Bun.file(Vt(i,o));return await d.exists()?await d.json():void 0}async function Xa(i,o,d){let u=Gr(o,`${i}.secrets.json`),f=Bun.file(u);if(!await f.exists())return;let{adminPassword:p,screenPassword:h,allow:w}=await f.json();await d.put(i,{adminPassword:p,screenPassword:h}),await $s(Vt(o,i),{allow:w,autoLogin:!0}),await Ya(u,{force:!0})}async function ah(i,o){let{stateDir:d}=o,u=Je(d);await Xa(i,d,u);let f=await za(d,i),p=await Re(i),h=p?await u.get(i):void 0,w=o.image??Ai;if(!p){if(f=void 0,h=void 0,!await Re(w)){if(!o.base)throw new L(`No ${w}, and no base image to build it from.`);await Ei({base:o.base,name:w,stateDir:d})}await G(r(R).sub("clone").arg(w).arg(i).build());let v=r(R).sub("set").arg(i);if(o.cpus)v.flag("--cpu",o.cpus);if(o.memoryGb)v.flag("--memory",o.memoryGb*1024);if(o.diskGb)v.flag("--disk-size",o.diskGb);await G(v.build())}if(p!=="running"){let v=await Dr(i,{},o.onQueued);try{await Fr(i,{vnc:!1,logDir:d,window:o.window}),v.booted()}catch(P){throw await qe(i,5),gt(i),P}}let y=[...new Set([...f?.allow??[],...o.allowNetwork??[]])].sort(),S=o.autoLogin??!0;if(!h){let v=an(),P=(await u.get(w).catch(()=>{return}))?.adminPassword??"admin";await u.put(i,v);try{let x=await Va(i);await jr(i,void 0,uh(y,x,S),`${P}
166
+ ${v.adminPassword}
167
+ ${v.screenPassword}
168
+ `)}catch(x){throw await ch(i,d),x}await $s(Vt(d,i),{allow:y,autoLogin:S});return}if(!f||y.join()!==f.allow.join())await jr(i,h.adminPassword,ec(y,await Va(i)));if(f&&f.autoLogin!==S)await jr(i,h.adminPassword,Za(S),`${h.adminPassword}
169
+ `);if(!f||y.join()!==f.allow.join()||f.autoLogin!==S)await $s(Vt(d,i),{allow:y,autoLogin:S})}function ul(i,o){return Ka(i,async()=>{if(await Re(i)!=="running")throw new L(`${i} isn't running: start it first.`);let d=Je(o),u=await d.get(i);if(!u)throw new L(`${i} has no passwords kept: it's made again with its next task.`);let f=an(),p=(await za(o,i))?.autoLogin??!0;await jr(i,u.adminPassword,l`${Wn(p)}
170
+ /bin/launchctl kickstart -k system/com.apple.screensharing`,`${u.adminPassword}
171
+ ${f.adminPassword}
172
+ ${f.screenPassword}
173
+ `),await d.put(i,f)})}async function ch(i,o){await Qa(i),await pe(r(R).sub("delete").arg(i).build()),await Ss(i,o)}async function Ss(i,o){await Je(o).remove(i),await Ya(Vt(o,i),{force:!0})}async function Qa(i=cs){if(await Re(i)==="running")await qe(i,60);gt(i)}async function vs(i,o){await Xa(i,o,Je(o));let d=await Je(o).get(i);if(!d)throw new L("The macOS VM has no screen yet.");return{url:`vnc://${await Ps(i)}:${qa}`,password:d.screenPassword}}async function Ps(i){return(await G(r(R).sub("ip").arg(i).flag("--wait",60).build())).trim()}async function $s(i,o){await sh(Gr(i,".."),{recursive:!0,mode:448}),await Bun.write(i,JSON.stringify(o)),await nh(i,384)}async function Va(i){let o=await G(r(R).sub("exec").arg(i).wrap(he(l`/sbin/route -n get default`)).build()),d=o.match(/gateway: (\d+\.\d+\.\d+\.\d+)/)?.[1];if(!d)throw new L(`${i} has no default route: ${o.trim()}`);return d}var dh="/usr/bin:/bin:/usr/sbin:/sbin";async function jr(i,o,d,u=""){let f=l`export PATH=${dh}
174
+ ${d}`,p=o===void 0?l`/usr/bin/sudo -n /bin/sh -c ${f.text}`:l`/usr/bin/sudo -S -k -p '' /bin/sh -c ${f.text}`,h=await pe(r(R).sub("exec").flag("-i").arg(i).wrap(he(p)).build(),{stdin:o===void 0?u:`${o}
175
+ ${u}`});if(h.exitCode!==0)throw new L(`In ${i}, as root: ${(h.stderr.trim()||h.stdout.trim()).slice(-2000)}`)}function uh(i,o,d){return l`set -eu
176
+ launchctl disable system/com.openssh.sshd
177
+ launchctl bootout system/com.openssh.sshd 2>/dev/null || true
178
+ ${Wn(d)}
179
+ defaults write /Library/Preferences/com.apple.RemoteManagement VNCLegacyConnectionsEnabled -bool YES
180
+ launchctl enable system/com.apple.screensharing
181
+ launchctl bootstrap system /System/Library/LaunchDaemons/com.apple.screensharing.plist 2>/dev/null || true
182
+ launchctl kickstart -k system/com.apple.screensharing
183
+ ${ec(i,o)}`}function Wn(i){return l`IFS= read -r old
184
+ IFS= read -r password
185
+ IFS= read -r screen
186
+ /usr/sbin/sysadminctl -adminUser admin -adminPassword "$old" -resetPasswordFor admin -newPassword "$password" >/dev/null 2>&1
187
+ printf '%s\n%s\n' "$old" "$password" | /usr/bin/sudo -u admin /usr/bin/python3 -c ${ph} ${`${oh}/Library/Keychains/login.keychain-db`} 2>/dev/null || true
188
+ printf '%s\n' "$password" | ${Za(i)}
189
+ printf '%s\n' "$screen" | /usr/bin/python3 -c ${fh} > /Library/Preferences/com.apple.VNCSettings.txt
190
+ /bin/chmod 600 /Library/Preferences/com.apple.VNCSettings.txt`}function Za(i){let o=i?l`/usr/bin/python3 -c ${lh} > /etc/kcpassword
191
+ /bin/chmod 600 /etc/kcpassword
192
+ /usr/bin/defaults write /Library/Preferences/com.apple.loginwindow autoLoginUser admin`:l`/bin/rm -f /etc/kcpassword
193
+ /usr/bin/defaults delete /Library/Preferences/com.apple.loginwindow autoLoginUser 2>/dev/null || true`;return l`/bin/sh -c ${o.text}`}function ec(i,o){return Ta(i,{screenFrom:o,screenPort:qa,sudoWithPassword:"admin"})}var lh=`import sys
194
+ key = [0x7D, 0x89, 0x52, 0x23, 0xD2, 0xBC, 0xDD, 0xEA, 0xA3, 0xB9, 0x1F]
195
+ p = sys.stdin.buffer.readline().rstrip(b"\\n")
196
+ p += b"\\0" * (12 - len(p) % 12)
197
+ sys.stdout.buffer.write(bytes(b ^ key[i % len(key)] for i, b in enumerate(p)))`,fh=`import sys
198
+ key = bytes.fromhex("1734516E8BA8C5E2FF1C39567390ADCA")
199
+ p = sys.stdin.buffer.readline().rstrip(b"\\n")[:8].ljust(16, b"\\0")
200
+ print(bytes(a ^ b for a, b in zip(p, key)).hex().upper())`,ph=`import ctypes, sys
201
+ security = ctypes.CDLL("/System/Library/Frameworks/Security.framework/Security")
202
+ old = sys.stdin.buffer.readline().rstrip(b"\\n")
203
+ new = sys.stdin.buffer.readline().rstrip(b"\\n")
204
+ keychain = ctypes.c_void_p()
205
+ if security.SecKeychainOpen(sys.argv[1].encode(), ctypes.byref(keychain)):
206
+ sys.exit(1)
207
+ sys.exit(1 if security.SecKeychainChangePassword(keychain, len(old), old, len(new), new) else 0)`,tc=50,ks=30;async function ll(i=cs){if(await Re(i)!=="running")return{removed:[],cacheGb:0};let o=await G(r(R).sub("exec").arg(i).wrap(he(l`/usr/bin/python3 -c ${mh} ${tc} ${ks}`)).build());return JSON.parse(o)}var mh=`import json, os, shutil, subprocess, sys, time
208
+ limit, days = float(sys.argv[1]) * 1e9, float(sys.argv[2])
209
+ home = os.path.expanduser("~")
210
+ roots = [".bun/install/cache", ".npm/_cacache", "Library/pnpm/store", "Library/Caches/pnpm", ".cache/uv",
211
+ "Library/Caches/pip", "Library/Caches/CocoaPods", "Library/Caches/org.swift.swiftpm",
212
+ "Library/Developer/Xcode/DerivedData"]
213
+ old = time.time() - days * 86400
214
+ removed, entries = [], []
215
+ def size(path):
216
+ out = subprocess.run(["du", "-sk", path], capture_output=True, text=True).stdout.split()
217
+ return int(out[0]) * 1024 if out else 0
218
+ for root in roots:
219
+ base = os.path.join(home, root)
220
+ if not os.path.isdir(base): continue
221
+ for name in os.listdir(base):
222
+ path = os.path.join(base, name)
223
+ used = os.lstat(path).st_mtime
224
+ if used < old: removed.append(path)
225
+ else: entries.append((used, size(path), path))
226
+ total = sum(s for _, s, _ in entries)
227
+ for used, s, path in sorted(entries):
228
+ if total <= limit: break
229
+ removed.append(path)
230
+ total -= s
231
+ sandboxes = os.path.join(home, "sf")
232
+ for tasks in [d for d in os.listdir(sandboxes) if d.endswith("-tasks")] if os.path.isdir(sandboxes) else []:
233
+ for name in os.listdir(os.path.join(sandboxes, tasks)):
234
+ path = os.path.join(sandboxes, tasks, name)
235
+ if os.lstat(path).st_mtime < old: removed.append(path)
236
+ for path in removed:
237
+ shutil.rmtree(path, ignore_errors=True) if os.path.isdir(path) and not os.path.islink(path) else os.remove(path)
238
+ for dev in [d for d in os.listdir(sandboxes) if os.path.isdir(os.path.join(sandboxes, d, ".git"))] if os.path.isdir(sandboxes) else []:
239
+ subprocess.run(["git", "-C", os.path.join(sandboxes, dev), "worktree", "prune"], capture_output=True)
240
+ print(json.dumps({"removed": removed, "cacheGb": round(total / 1e9, 1)}))`;async function pl(i,o=Ns){let d=JSON.parse(await G(r(R).sub("list").flag("--format","json").build())),u=Date.now()-ks*86400000,f=d.filter((p)=>p.Source==="local"&&p.State!=="running"&&/-golden$/.test(p.Name)&&!i.includes(p.Name)&&p.Accessed!==void 0&&Date.parse(p.Accessed)<u);for(let p of f)await pe(r(R).sub("delete").arg(p.Name).build()),await Ss(p.Name,o);return f.map((p)=>p.Name)}function fl(i=cs){return vs(i,Ns)}var ic="/Users/admin/sf";function Rs(i={}){let o=i.stateDir??xs(gh(),".superfactory","tart"),d=i.vm??process.env.SUPERFACTORY_MACOS_VM??cs,u=(v)=>xs(o,`${v}.json`),f=async(v)=>{let P=Bun.file(u(v));return await P.exists()?await P.json():null},p=async()=>{if(!Tr("tart"))return{ready:!1,reason:"Tart is not installed.",fix:"Install it with `brew install cirruslabs/cli/tart`."};if(process.platform!=="darwin"||process.arch!=="arm64")return{ready:!1,reason:"Tart runs macOS VMs only on Apple silicon Macs."};return{ready:!0}},h=(v)=>new oc(v,S,o),S={name:"tart",check:p,sandbox:{create:async(v={})=>{let P=v.name??`sf-${crypto.randomUUID().slice(0,8)}`;if(!/^[A-Za-z0-9_-]{1,64}$/.test(P))throw new L(`Bad sandbox name: ${P}`);let x=await p();if(!x.ready)throw new L(`${x.reason} ${x.fix??""}`.trim());let E=v.metadata??{},I=await Fa(i.mirrors??{});await Ja({...i,allowNetwork:[...i.allowNetwork??[],...I.allow],vm:d,image:v.image??i.image,stateDir:o,onQueued:(fe)=>i.onQueued?.(P,fe)});let N={id:P,vm:d,dir:`${ic}/${P}`,projectId:E.projectId,createdAt:new Date().toISOString()},W=h(N),{cocoapods:re,cargo:C}=I.reachable;if(re)await q(W,bh(re),{cwd:"/"});if(C)await q(W,l`mkdir -p ~/.cargo && printf %s ${Ft(C)} > ~/.cargo/config.toml`,{cwd:"/"});await q(W,l`rm -rf ${N.dir} ${`${N.dir}-tasks`} && mkdir -p ${N.dir}`,{cwd:"/"});let B={...Object.fromEntries(I.env.map((fe)=>[fe.name,fe.value])),...v.envs};if(Object.keys(B).length)await W.filesystem.writeFile(Yt(N),yh(B)),await q(W,l`chmod 600 ${Yt(N)}`);return await nc(o,{recursive:!0,mode:448}),await Bun.write(u(P),JSON.stringify(N)),W},getById:async(v)=>{let P=await f(v);if(!P||await Re(P.vm)!=="running")return null;return h(P)},list:async()=>{let v=await hh(o).catch(()=>[]);return(await Promise.all(v.filter((x)=>x.endsWith(".json")&&!/\.(secrets|vm)\.json$/.test(x)).map((x)=>f(x.slice(0,-5))))).filter((x)=>x!==null).map(h)},destroy:async(v)=>{let P=await f(v);if(P&&await Re(P.vm)==="running")await q(h(P),l`rm -rf ${P.dir} ${`${P.dir}-tasks`} ${Yt(P)}`,{cwd:"/"});await sc(u(v),{force:!0})}}};return S}var Yt=(i)=>`${i.dir}.env`;class oc{record;owner;stateDir;provider="tart";sandboxId;filesystem;constructor(i,o,d){this.record=i;this.owner=o;this.stateDir=d;this.sandboxId=i.id,this.filesystem=Ar((u,f)=>q(this,u,f),"bsd")}runCommand(i,o={}){let d=Ve(i),u=o.background?l`nohup sh -c ${d.text} >/dev/null 2>&1 &`:d,{exec:f,stdin:p}=rc(this.record,u,o),{timeout:h,onStdout:w,onStderr:y}=o;return pe(f,{stdin:p,timeout:h,onStdout:w,onStderr:y})}async startProcess(i,o={}){let d=`/tmp/sf-${crypto.randomUUID()}.pid`,u=l`set -m; sh -c ${i} & p=$!; set +m; echo $p > ${d}; wait $p; rc=$?; kill -s TERM -- -$p 2>/dev/null; rm -f ${d}; exit $rc`,{exec:f,stdin:p}=rc(this.record,u,{cwd:o.cwd,env:o.env,interactive:!0}),h=ft(f,{...o,cwd:void 0,env:void 0,stdin:!0},async(w)=>{await q(this,l`[ -f ${d} ] && kill -s ${w} -- -$(cat ${d})`)});if(p)await h.write(p);if(!o.stdin)await h.closeStdin();return h}async getInfo(){return{id:this.sandboxId,provider:this.provider,status:await Re(this.record.vm)==="running"?"running":"stopped",createdAt:new Date(this.record.createdAt),timeout:0,metadata:{projectId:this.record.projectId,vm:this.record.vm,workdir:this.record.dir}}}async getUrl({port:i,protocol:o="http"}){return`${o}://${await Ps(this.record.vm)}:${i}`}screen(){return vs(this.record.vm,this.stateDir)}destroy(){return this.owner.sandbox.destroy(this.sandboxId)}getProvider(){return this.owner}getInstance(){return this.record}}function rc(i,o,d){let u=Object.entries(d.env??{}),f=u.length?`${u.map(([S,v])=>`${S}=${Buffer.from(v).toString("base64")}`).join(`
241
+ `)}
242
+
243
+ `:"",p=l`[ -f ${Yt(i)} ] && set -a && . ${Yt(i)} && set +a; ${u.length?wh:l``}cd ${d.cwd??i.dir} 2>/dev/null || cd; exec sh -c ${o.text}`,h=d.stdin===void 0?f||void 0:Buffer.concat([Buffer.from(f),Buffer.from(d.stdin)]).toString(),w=d.interactive||h!==void 0,y=r(R).sub("exec");if(w)y.flag("-i");return{exec:y.arg(i.vm).wrap(he(p)).build(),stdin:h}}async function Fr(i,o){await nc(o.logDir,{recursive:!0,mode:448});let d=xs(o.logDir,`${i}.log`);await sc(d,{force:!0});let u=r(R).sub("run").arg(i);if(!o.window)u.flag("--no-graphics");if(o.vnc)u.flag("--vnc-experimental");_(u.build(),{stdin:"ignore",stdout:{file:d},stderr:{file:d}}).unref();let f=r(R).sub("exec").arg(i).wrap(r(Xt).build()).build();for(let h=0;h<180;h++){if((await ee(f)).exitCode===0)break;if(h===179)throw new L(`${i} didn't answer within 3 minutes. See ${d}.`);await Bun.sleep(1000)}if(!o.vnc)return;let p=(await Bun.file(d).text()).match(/vnc:\/\/\S+/)?.[0];if(!p)throw new L(`Tart didn't print a VNC address. See ${d}.`);return p.replace(/[.,]+$/,"")}async function cn(){return JSON.parse(await G(r(R).sub("list").flag("--format","json").build())).map((o)=>({name:o.Name,state:o.State,accessed:o.Accessed}))}async function Re(i){return(await cn()).find((o)=>o.name===i)?.state}var wh=l`while IFS= read -r l && [ -n "$l" ]; do export "\${l%%=*}=$(printf %s "\${l#*=}" | base64 -D)"; done; `;function yh(i){return`${Object.entries(i).map(([d,u])=>{if(!/^[A-Za-z_]\w*$/.test(d))throw new L(`${d} isn't a variable name`);return`${d}=${l`${u}`.text}`}).join(`
244
+ `)}
245
+ `}function qe(i,o){return ee(r(R).sub("stop").arg(i).flag("--timeout",o).build())}function bh(i){return l`command -v pod >/dev/null || exit 0
246
+ [ "$(cat ~/.cocoapods-trunk 2>/dev/null)" = ${i} ] && exit 0
247
+ pod repo remove trunk >/dev/null 2>&1 || true
248
+ pod repo add-cdn trunk ${i} >/dev/null && printf %s ${i} > ~/.cocoapods-trunk`}import{join as Y}from"path";var Hr=["bun","npm","pnpm","yarn","uv","pip","poetry","cargo","go","maven","gradle","nuget","cocoapods"];function Os(i,o={}){let d=(u,...f)=>Y(i,u,...f);return{BUN_INSTALL_CACHE_DIR:d("bun"),BUN_INSTALL_GLOBAL_STORE:"0",npm_config_cache:d("npm"),npm_config_store_dir:d("pnpm"),npm_config_enable_global_virtual_store:"true",YARN_CACHE_FOLDER:d("yarn","v1"),YARN_GLOBAL_FOLDER:d("yarn","berry"),YARN_ENABLE_GLOBAL_CACHE:"true",UV_CACHE_DIR:d("uv"),PIP_CACHE_DIR:d("pip"),POETRY_CACHE_DIR:d("poetry"),CARGO_HOME:d("cargo"),GOMODCACHE:d("go","mod"),GOCACHE:d("go","build"),MAVEN_OPTS:[o.MAVEN_OPTS,`-Dmaven.repo.local=${d("maven")}`].filter(Boolean).join(" "),GRADLE_USER_HOME:d("gradle"),NUGET_PACKAGES:d("nuget"),CP_CACHE_DIR:d("cocoapods")}}function Ts(i,o=process.platform){let d=o==="darwin",u=o==="win32",f=process.env.LOCALAPPDATA??Y(i,"AppData","Local"),p=d?Y(i,"Library","Caches"):u?f:Y(i,".cache");return{bun:Y(i,".bun","install","cache"),npm:u?Y(f,"npm-cache","_cacache"):Y(i,".npm","_cacache"),pnpm:d?Y(i,"Library","pnpm","store"):u?Y(f,"pnpm","store"):Y(i,".local","share","pnpm","store"),yarn:d?Y(p,"Yarn"):u?Y(f,"Yarn","Cache"):Y(p,"yarn"),uv:u?Y(f,"uv","cache"):Y(i,".cache","uv"),pip:u?Y(f,"pip","Cache"):Y(p,"pip"),poetry:d?Y(p,"pypoetry"):u?Y(f,"pypoetry","Cache"):Y(p,"pypoetry"),maven:Y(i,".m2","repository"),nuget:Y(i,".nuget","packages"),cocoapods:Y(p,"CocoaPods"),swiftpm:Y(p,"org.swift.swiftpm")}}var Cs=["cargo","go","gradle"],As={BUN_INSTALL_GLOBAL_STORE:"0",npm_config_enable_global_virtual_store:"true"};function Ms(i,o){return[{link:Y(i,"cargo","config.toml"),target:Y(o,".cargo","config.toml")},{link:Y(i,"cargo","credentials.toml"),target:Y(o,".cargo","credentials.toml")},{link:Y(i,"gradle","gradle.properties"),target:Y(o,".gradle","gradle.properties")},{link:Y(i,"gradle","init.d"),target:Y(o,".gradle","init.d")}]}import{readdir as Sh,readFile as vh}from"fs/promises";import{join as Cc,relative as Ac,sep as Ph}from"path";import{rm as Ec}from"fs/promises";import{tmpdir as Us}from"os";import{join as Vr}from"path";var Fs="refs/superfactory/base",qt=(i)=>r(ye).in(i),Wr=async(i)=>qt(i).env({...await xu(i),GIT_LFS_SKIP_SMUDGE:"1"});async function Yr(i,o,d){let{workdir:u,baseRef:f,repo:p}=d,h=(await G(qt(o).sub("rev-parse").flag("--abbrev-ref").arg("HEAD").build())).trim(),w=h==="HEAD"?"sandbox":h,y=crypto.randomUUID(),S=Vr(Us(),`sf-in-${y}.bundle`),v;try{await G(qt(o).sub("bundle create").arg(S).arg("HEAD").build()),v=await Bun.file(S).bytes()}finally{await Ec(S,{force:!0})}await i.filesystem.writeFile(`/tmp/sf-in-${y}.b64`,Buffer.from(v).toString("base64"));let P=`/tmp/sf-in-${y}.b64`,x=`/tmp/sf-in-${y}.bundle`,E=l`base64 -d < ${P} > ${x}`;await wt(i,p?[l`cd ${p}`,E,l`git fetch -q -f ${x} ${`HEAD:refs/heads/${w}`}`,l`git worktree add -q -f ${u} ${w}`,l`git -C ${u} update-ref ${f} HEAD`,l`rm ${P} ${x}`]:[l`mkdir -p ${u} && cd ${u}`,E,l`git init -q .`,l`git fetch -q ${x} HEAD`,l`git checkout -q -B ${w} FETCH_HEAD`,l`git update-ref ${f} HEAD`,l`rm ${P} ${x}`]);let I=await G(qt(o).sub("ls-files").flag("-z").flag("--modified").flag("--others").flag("--exclude-standard").build());if(!I)return;let N=r(ot).flag("-c").flag("--directory",o).flag("--null").flag("--files-from","-"),W=await Ua(N.build(),I),re=`/tmp/sf-files-${y}.b64`;await i.filesystem.writeFile(re,Buffer.from(W).toString("base64")),await wt(i,[l`base64 -d < ${re} | tar -x -C ${u}`,l`rm ${re}`])}async function Rc(i,o,d){let u=crypto.randomUUID(),f=Vr(Us(),`sf-sync-${u}.bundle`),p;try{await G(qt(o).sub("bundle create").arg(f).arg("HEAD").build()),p=await Bun.file(f).bytes()}finally{await Ec(f,{force:!0})}let h=`/tmp/sf-sync-${u}.b64`,w=`/tmp/sf-sync-${u}.bundle`;await i.filesystem.writeFile(h,Buffer.from(p).toString("base64")),await wt(i,[l`cd ${d.workdir}`,l`base64 -d < ${h} > ${w}`,l`git fetch -q -f ${w} HEAD`,l`git checkout -q --force --detach FETCH_HEAD`,l`git clean -q -f -d`,l`git update-ref ${d.baseRef} HEAD`,l`rm ${h} ${w}`])}async function Oc(i,o,d){let{workdir:u,baseRef:f}=d,p=`/tmp/sf-out-${crypto.randomUUID()}.bundle`,h=`${f}..HEAD`;if((await wt(i,[l`git rev-list --count ${h}`],u)).trim()==="0")return;let y=await wt(i,[l`git bundle create -q ${p} ${h}`,l`base64 < ${p}`,l`rm ${p}`],u),S=Vr(Us(),`sf-${i.sandboxId}-${Date.now()}.bundle`);await Bun.write(S,Buffer.from(y.replace(/\s/g,""),"base64"));let v;try{await G((await Wr(o)).sub("fetch").flag("-q").arg(S).arg("HEAD").build()),v=(await G((await Wr(o)).sub("rev-parse").arg("FETCH_HEAD").build())).trim(),await $h(o),await G((await Wr(o)).sub("merge").flag("-q").flag("--ff-only").arg("FETCH_HEAD").build())}finally{await Bun.file(S).delete()}await wt(i,[l`git update-ref ${f} ${v}`],u)}async function $h(i){let o=()=>Wr(i),d=await G((await o()).sub("ls-files").flag("-z").flag("--others").flag("--exclude-standard").build()),u=(await o()).sub("diff").flag("--no-ext-diff").flag("-z").flag("--name-only").flag("--diff-filter","A").arg("HEAD").arg("FETCH_HEAD"),f=new Set((await G(u.build())).split("\x00"));for(let p of d.split("\x00").filter((h)=>h&&f.has(h))){let h=(await G((await o()).sub("hash-object").endOptions().arg(p).build())).trim(),w=(await G((await o()).sub("rev-parse").arg(`FETCH_HEAD:${p}`).build())).trim();if(h===w)await Bun.file(Vr(i,p)).delete()}}async function wt(i,o,d){let u=await q(i,ts(o),{cwd:d});if(u.exitCode!==0)throw new L(`In the sandbox: ${u.stderr.trim()}`);return u.stdout}var Kt="/tmp/superfactory-agent",Mc=5900;async function Xf(i,o){let d=i.name==="host",u=await i.sandbox.getById(o.id),f={projectId:o.projectId,taskId:o.taskId,node:o.node,ports:o.ports,vnc:o.vnc},p=u??await i.sandbox.create({name:o.id,envs:o.env,image:o.image,directory:o.worktree,metadata:f}),h={workdir:d?o.worktree:await kh(p),baseRef:Fs};if(!u&&!d)await Yr(p,o.worktree,h);return new qr(p,o.worktree,h,d)}async function em(i,o){if(i.shared)return new qr(i.sandbox,o.worktree,{workdir:o.worktree,baseRef:Fs},!0);let d={workdir:`${i.workdir}-tasks/${o.taskId}`,baseRef:`refs/superfactory/task-base/${o.taskId}`,repo:i.workdir};if((await q(i.sandbox,l`test -e ${`${d.workdir}/.git`}`)).exitCode!==0)await Yr(i.sandbox,o.worktree,d);return new qr(i.sandbox,o.worktree,d,!1)}class qr{sandbox;worktree;place;shared;constructor(i,o,d,u){this.sandbox=i;this.worktree=o;this.place=d;this.shared=u}get workdir(){return this.place.workdir}get id(){return this.sandbox.sandboxId}run(i,o={}){return q(this.sandbox,l`${i}`,{cwd:this.workdir,...o})}start(i,o={}){let d=this.sandbox;if(!d.startProcess)throw new L(`The ${this.sandbox.provider} provider can't run long-lived processes here yet.`);return es(d,l`${i}`,{cwd:this.workdir,...o})}url(i){return this.sandbox.getUrl({port:i})}async openVnc(){if(this.shared){if(!await as(Mc))throw new L("Screen Sharing is off on this Mac. Turn it on in System Settings > General > Sharing.");return{url:`vnc://127.0.0.1:${Mc}`}}let i=this.sandbox;if(i.screen)return i.screen();let o=(await q(this.sandbox,l`printenv SF_VNC_PASSWORD`)).stdout.trim();if(!o)throw new L("This sandbox was made without a screen (vnc: false).");return{url:await this.sandbox.getUrl({port:Gn}),password:o}}async adopt(i){if(this.shared||this.place.repo)throw new L("only a sandbox of its own can be adopted");await Yr(this.sandbox,i,this.place),this.worktree=i}async refresh(){if(!this.shared)await Rc(this.sandbox,this.worktree,this.place)}async pull(){if(!this.shared)await Oc(this.sandbox,this.worktree,this.place)}async spawnAgent(i){let{binary:o,args:d,...u}=i;if(this.shared)return this.start([o,...d],{...u,stdin:!0});let f=await Bun.file(o).bytes(),p=new Bun.CryptoHasher("sha256").update(f).digest("hex"),[h,w]=[`${Kt}.b64`,`${Kt}.sha256`];if((await q(this.sandbox,l`cat ${w} 2>/dev/null`)).stdout.trim()!==p){await this.sandbox.filesystem.writeFile(h,Buffer.from(f).toString("base64"));let S=await q(this.sandbox,l`base64 -d < ${h} > ${Kt} && chmod +x ${Kt} && rm ${h} && echo ${p} > ${w}`);if(S.exitCode!==0)throw new L(`Agent copy failed: ${S.stderr.trim()}`)}return this.start([Kt,...d],{...u,cwd:"/",stdin:!0})}async copyIn(i,o){let d=(await Sh(i,{recursive:!0,withFileTypes:!0})).filter((h)=>h.isFile()&&!h.parentPath.includes("node_modules")&&!Ac(i,h.parentPath).split(Ph).includes(".git")).map((h)=>Ac(i,Cc(h.parentPath,h.name))).sort(),u=await Promise.all(d.map(async(h)=>{let w=await vh(Cc(i,h)),y=w.toString("utf8");return Buffer.from(y,"utf8").equals(w)?{name:h,text:y}:{name:h,text:w.toString("base64"),binary:!0}})),f=new Bun.CryptoHasher("sha256").update(JSON.stringify(u)).digest("hex"),p=`${o}/.superfactory-copy`;if((await q(this.sandbox,l`cat ${p} 2>/dev/null`)).stdout.trim()===f)return o;await q(this.sandbox,l`rm -rf ${o}`);for(let{name:h,text:w,binary:y}of u){let S=`${o}/${h}`;if(!y){await this.sandbox.filesystem.writeFile(S,w);continue}await this.sandbox.filesystem.writeFile(`${S}.b64`,w);let v=await q(this.sandbox,l`base64 -d < ${`${S}.b64`} > ${S} && rm ${`${S}.b64`}`);if(v.exitCode!==0)throw new L(`Copy of ${h} failed: ${v.stderr.trim()}`)}return await this.sandbox.filesystem.writeFile(p,f),o}async destroy(){let{repo:i,workdir:o,baseRef:d}=this.place;if(!i)return this.sandbox.destroy();await q(this.sandbox,l`git -C ${i} worktree remove --force ${o}; git -C ${i} update-ref -d ${d}`)}}async function kh(i){let o=(await i.getInfo()).metadata?.workdir;return typeof o==="string"?o:Ie}function tm(i){switch(i.kind){case"host":return rs();case"apple-container":return Mr({name:"apple-container",image:i.image,caches:i.caches,allowNetwork:i.allowNetwork,cpus:i.cpus,memoryGb:i.memoryGb,reachesSandboxIp:!0,cacheDir:Eh(xh(),".superfactory","cache"),serviceFix:"Run `container system start`.",installFix:"Install it with `brew install container`, then run `container system start`."});case"docker":{let o=i.context!=="local"?i.context:void 0;return Mr({name:"docker",sshTarget:o,image:i.image,caches:i.caches,allowNetwork:i.allowNetwork,reachesSandboxIp:!o&&Boolean(process.env.SUPERFACTORY_DOCKER_SIBLING),sibling:o?void 0:process.env.SUPERFACTORY_DOCKER_SIBLING||void 0,serviceFix:o?`Check that ${o} is reachable over SSH and runs docker.`:"Start Docker: a small VM with `colima start --cpu 2 --memory 2`, or Docker Desktop or OrbStack.",installFix:"Install Docker (Docker Desktop, OrbStack or `brew install colima docker`)."})}case"tart":return Rs({image:i.goldenImage,base:i.goldenBase,cpus:i.cpus,memoryGb:i.memoryGb,window:i.window,autoLogin:i.autoLogin,allowNetwork:i.allowNetwork,mirrors:i.mirrors})}}var Ah=86400000,Bs=1073741824,Mh=3600000;function lc(i=process.env){let o=i.SUPERFACTORY_LIBRARIES_DIR||i.SUPERFACTORY_CACHE_DIR||i.SUPERFACTORY_CACHES_DIR||void 0,d=Number(i.SUPERFACTORY_LIBRARIES_MAX_GB||i.SUPERFACTORY_CACHE_MAX_GB||i.SUPERFACTORY_CACHES_MAX_GB);return{...o?{dir:o}:{},maxBytes:(d||50)*Bs,maxDays:Number(i.SUPERFACTORY_LIBRARIES_MAX_DAYS||i.SUPERFACTORY_CACHE_MAX_DAYS)||30}}function Fc(i){let o=ls();return{npm:i["machine.npmMirror"]||o.npm,python:i["machine.pythonMirror"]||o.python,go:i["machine.goMirror"]||o.go,cargo:i["machine.cargoMirror"]||o.cargo,cocoapods:i["machine.cocoapodsMirror"]||o.cocoapods}}var yt=[],Bc;function sm(i){Bc=i}function js(){return yt.map(({kind:i,url:o,error:d})=>({kind:i,url:o,error:d}))}function Bt(i){let o=Object.entries(Fc(i));return Object.fromEntries(o.filter(([,d])=>d&&!yt.some((u)=>u.href===d)))}async function nm(i){let o=Object.entries(Fc(i)).filter((h)=>!!h[1]),u=(await Promise.all(o.map(async([h,w])=>({kind:h,href:w,url:Nr(w),error:await fs(h,w)})))).filter((h)=>!!h.error),f=(h,w)=>w.some((y)=>y.href===h.href);for(let h of u)if(!f(h,yt))s.warn(`libraries: the ${h.kind} cache doesn't answer, installs use the public registry: ${h.error}`);for(let h of yt)if(!f(h,u))s.info(`libraries: the ${h.kind} cache answers again: ${h.url}`);let p=JSON.stringify(u)!==JSON.stringify(yt);if(yt=u,p)Bc?.()}function dn(i={},o=process.env){let{dir:d}=lc(o);return{...d?Os(d,o):As,...ps(i)}}function Nh(i,o=Dc()){let{dir:d}=i;return(d?Hr.map((f)=>[f,ze(d,f)]):Object.entries(Ts(o))).filter(([f])=>!Cs.includes(f))}async function rm(i={},o=Dc()){let{dir:d}=lc();if(!d)return;for(let p of Hr)await Oh(ze(d,p),{recursive:!0});for(let{link:p,target:h}of Ms(d,o)){if(!Rh(h)||await Jr(p).catch(()=>{return}))continue;await Th(h,p).catch(()=>{return})}let u=ze(d,"cargo","config.toml");if((await Jr(u).catch(()=>{return}))?.isSymbolicLink())return;if(i.cargo)await Ch(u,Ft(i.cargo));else if((await _h(u,"utf8").catch(()=>"")).includes('replace-with = "cache"'))await Uc(u)}var Uh=process.platform!=="darwin";async function om(i,o=Date.now()){let d=[],u=Nh(i);for(let[h,w]of u)await jc(w,h,[],d);d.sort((h,w)=>h.usedAt-w.usedAt);let f=d.reduce((h,w)=>h+w.bytes,0),p={units:0,bytes:0};for(let h of d){let w=o-h.usedAt>i.maxDays*Ah,y=h.unlinked&&!h.linked;if(!w&&(f<=i.maxBytes&&!y||o-h.usedAt<Mh))continue;if(!await Uc(h.path,{recursive:!0,force:!0}).then(()=>!0,()=>!1))continue;f-=h.bytes,p.units++,p.bytes+=h.bytes}for(let[,h]of u)for(let w of await Gs(h))await Hc(ze(h,w));if(p.units)s.info(`libraries: removed ${p.units} (${(p.bytes/Bs).toFixed(1)} GB), ${(f/Bs).toFixed(1)} GB kept`);return{...p,keptBytes:f}}var Dh={bun:(i)=>i.length===1&&i[0]!=="links"||i.length===2&&i[0]==="links",nuget:(i)=>i.length===2,uv:(i)=>i.length===2&&/^archive-v\d+$/.test(i[0]??""),cocoapods:(i)=>i.length===4&&i[0]==="Pods"&&(i[1]==="Release"||i[1]==="External")};async function jc(i,o,d,u){for(let f of await Gs(i)){let p=ze(i,f),h=await Jr(p).catch(()=>{return});if(!h||h.isSymbolicLink())continue;if(!h.isDirectory()){if(h.nlink<=1)u.push({path:p,bytes:h.size,usedAt:Math.max(h.atimeMs,h.mtimeMs)});continue}let w=[...d,f];if(Dh[o]?.(w)){let y=o==="bun"&&w.length===1&&Uh,S={path:p,bytes:0,usedAt:0,unlinked:y};await Gc(p,S),u.push(S)}else await jc(p,o,w,u)}}async function Gc(i,o){let d=await Jr(i).catch(()=>{return});if(!d||d.isSymbolicLink())return;if(o.usedAt=Math.max(o.usedAt,d.atimeMs,d.mtimeMs),!d.isDirectory()){if(d.nlink<=1)o.bytes+=d.size;else o.linked=!0;return}for(let u of await Gs(i))await Gc(ze(i,u),o)}async function Hc(i){let o=!0;for(let d of await Nc(i,{withFileTypes:!0}).catch(()=>[]))if(!d.isDirectory()||!await Hc(ze(i,d.name)))o=!1;return o&&await Ih(i).then(()=>!0,()=>!1)}var Gs=(i)=>Nc(i).catch(()=>[]);import{existsSync as bt,readdirSync as Lh,readFileSync as Qs,realpathSync as Wc}from"fs";import{mkdir as Vc,readdir as Fh,readFile as jh,rename as Wh,rm as Hs,writeFile as Yc}from"fs/promises";import{basename as Vs,dirname as Vh,join as te,sep as Yh}from"path";var Xe=te(import.meta.dir,"../../../../../plugins"),zc=()=>te(m().home,"plugins",H),qh=/(?:^|\/)plugins\/(sf-[\w-]+\/.+)$/,Ys=(i)=>bt(te(i,"sf-video-review",".claude-plugin","plugin.json")),qs=".built-in";function zt(i){if(!bt(te(i,".claude-plugin","plugin.json")))return!1;return Jh(i).every((o)=>bt(o))}var Ks="${CLAUDE_PLUGIN_ROOT}/";function Jh(i){let o=te(i,".mcp.json");if(!bt(o))return[];try{let d=JSON.parse(Qs(o,"utf8")).mcpServers;return Object.values(d??{}).flatMap((u)=>(u.args??[]).filter((f)=>f.startsWith(Ks)).map((f)=>te(i,f.slice(Ks.length))))}catch{return[te(o,"(unreadable)")]}}function Kr(){if(process.env.SUPERFACTORY_PLUGINS_DIR)return process.env.SUPERFACTORY_PLUGINS_DIR;return Ys(Xe)?Xe:zc()}var Kh=/^sf-video-studio\/hooks\//;function Xh(){return Bun.embeddedFiles.flatMap((i)=>{let o=i.name.match(qh)?.[1]?.replace(/\.$/,"");return o&&!Kh.test(o)?[{path:o,file:i}]:[]})}var Jc;function Qh(i){return Jc??=(async()=>{let o=new Bun.CryptoHasher("sha256");for(let{path:d,file:u}of i)o.update(`${d}\x00${u.size}\x00`).update(await u.arrayBuffer());return o.digest("hex")})(),Jc}var Ws;function Ri(){return Ws??=Zh().finally(()=>{Ws=void 0}),Ws}async function Zh(){if(process.env.SUPERFACTORY_PLUGINS_DIR)return;if(Ys(Xe))return tg();let i=zc(),o=Xh();if(!o.length){if(!Ys(i))s.warn("plugins: this agent has none built in: its sessions run without Superfactory's skills");return}let d=await Qh(o);if((await jh(te(i,qs),"utf8").catch(()=>"")).trim()===d&&o.every(({path:f})=>bt(te(i,f))))return;if(bt(i))s.info(`plugins: ${i} isn't this agent's build of them: writing them again`);await eg(i,o,d),s.info(`plugins: ${o.length} files of Superfactory's plugins written to ${i}`)}async function eg(i,o,d){await Vc(i,{recursive:!0}),await Hs(te(i,qs),{force:!0});for(let{path:p,file:h}of o){let w=te(i,p);await Vc(Vh(w),{recursive:!0});let y=`${w}.${process.pid}.partial`;try{await Yc(y,new Uint8Array(await h.arrayBuffer())),await Wh(y,w)}catch(S){throw await Hs(y,{force:!0}),S}}let u=new Set(o.map(({path:p})=>te(i,p))),f=new Set(o.map(({path:p})=>p.split("/")[0]??""));for(let p of f)for(let h of await Fh(te(i,p),{recursive:!0,withFileTypes:!0})){let w=te(h.parentPath,h.name);if(!h.isDirectory()&&!u.has(w))await Hs(w,{force:!0})}await Yc(te(i,qs),d)}async function tg(){if(Lh(Xe).filter((d)=>d.startsWith("sf-")).every((d)=>zt(te(Xe,d))))return;let{buildPlugins:o}=await import(te(Xe,"build.mjs"));s.info(`plugins: built ${(await o()).length} MCP servers in ${Xe}`)}function ml(i){let o=Kr(),d=i["plugins.enabled"],u=d.filter((p)=>zt(te(o,p))),f=d.filter((p)=>!u.includes(p));if(f.length)s.warn(`plugins: ${f.join(", ")} enabled but not complete on this machine (${o})`);return u.map((p)=>te(o,p))}var rg=/\$\{user_config\.([\w-]+)\}/g,Kc=(i)=>`CLAUDE_PLUGIN_OPTION_${i.toUpperCase().replace(/-/g,"_")}`;function Oi(i,o=[]){let d={};for(let u of i){let f=(h)=>h.split(Ks.slice(0,-1)).join(u).replace(rg,(w,y)=>o.includes(Kc(y))?`\${${Kc(y)}}`:w),p=(h={})=>Object.fromEntries(Object.entries(h).map(([w,y])=>[w,f(y)]).filter(([,w])=>!w.includes("${user_config.")));for(let[h,w]of Object.entries(ig(u)))d[`plugin:${ng(u)}:${h}`]=w.url?{...w,url:f(w.url),headers:p(w.headers)}:{command:f(w.command??""),args:(w.args??[]).map(f),env:p(w.env)}}return d}function Xc(i){try{return JSON.parse(Qs(te(i,".claude-plugin","plugin.json"),"utf8"))}catch{return{}}}var ng=(i)=>{let{name:o}=Xc(i);return typeof o==="string"&&o?o:Vs(i)};function sg(i,o){try{let d=Wc(i);return Wc(o).startsWith(d+Yh)}catch{return!1}}function ig(i){let o=Xc(i).mcpServers;if(o&&typeof o==="object"&&!Array.isArray(o))return o;let d=typeof o==="string"?te(i,o):te(i,".mcp.json");if(!sg(i,d))return{};try{let u=JSON.parse(Qs(d,"utf8"));return u.mcpServers??u}catch{return{}}}function im(i){return i["plugins.enabled"].includes("sf-video-studio")&&zt(te(Kr(),"sf-video-studio"))}function Ci(){return[te(Kr(),"sf-video-studio"),`${ed}/sf-video-studio`].find(zt)}function Qc(){let i=Kr();return Co.filter((o)=>zt(te(i,o)))}function ji(){return{SF_PLUGIN_RUNTIME:process.execPath}}var zs=[],Zc;function am(i){Zc=i}function Zs(){return zs}function cm(i){let o=i.filter((u)=>/^plugin:sf-[\w-]+:/.test(u.name));if(!o.length)return;let d=o.filter((u)=>u.status==="failed").map((u)=>({server:u.name,error:(u.error??"failed to start").slice(0,500)}));for(let{server:u,error:f}of d)s.warn(`plugins: ${u} didn't start: ${f}`);if(JSON.stringify(d)===JSON.stringify(zs))return;zs=d,Zc?.()}var og=new Set(Co),ed="/tmp/superfactory-plugins";async function dm(i,o){await Ri().catch((u)=>s.warn("plugins: couldn't write out the built-in plugins",u));let d=ml(i).filter((u)=>og.has(Vs(u)));return Promise.all(d.map((u)=>o.shared?u:o.copyIn(u,`${ed}/${Vs(u)}`)))}import{readFile as ag}from"fs/promises";function pc(i,o,d=process.env){if(i==="dedicated")return!0;if(i==="personal")return!1;return o||d.SUPERFACTORY_CLAUDE_ISOLATED==="1"}async function fc(){let i=await ag(m().settings,"utf8").catch(()=>"{}");try{let{values:o}=De("machine",JSON.parse(i));return o["machine.dedicated"]??"auto"}catch{return"auto"}}var dg=300000,ug=3600000,lg=0,fg=-600,pg=l`ObjC.import('ApplicationServices');
249
+ ObjC.import('Foundation');
250
+ ObjC.bindFunction('CGPreflightScreenCaptureAccess', ['bool', []]);
251
+ ObjC.bindFunction('AEDeterminePermissionToAutomateTarget', ['int', ['void *', 'unsigned int', 'unsigned int', 'bool']]);
252
+ const events = $.NSAppleEventDescriptor.descriptorWithBundleIdentifier('com.apple.systemevents');
253
+ JSON.stringify({
254
+ screen: $.CGPreflightScreenCaptureAccess(),
255
+ accessibility: $.AXIsProcessTrusted(),
256
+ automation: $.AEDeterminePermissionToAutomateTarget(events.aeDesc, 0x2a2a2a2a, 0x2a2a2a2a, false),
257
+ });`,mg=t({screen:n(),accessibility:n(),automation:b()});async function hg(){let i=await g(r(Is).flag("-l","JavaScript").script("-e",pg).timeoutMs(15000).by("system.permissions").build());if(i.exitCode!==0){s.warn(`system-permissions: couldn't ask tccd for this agent's grants: ${i.stderr.trim().slice(0,300)}`);return}return gg(mg.parse(JSON.parse(i.stdout.trim())))}function gg(i){return[...i.screen?[]:["screen_recording"],...i.accessibility?[]:["accessibility"],...i.automation===lg||i.automation===fg?[]:["automation"]]}async function wg(){await g(r(Z).script("-c",l`sudo -n launchctl kickstart -k system/com.apple.tccd.system; launchctl kickstart -k "gui/$(id -u)/com.apple.tccd"; sleep 2`).timeoutMs(30000).by("system.permissions").build())}var ti=[],sd,$t,rd=0,ei=!1;function Mi(){return[...ti]}function um(i){sd=i}async function nd(i,{ask:o=hg,restart:d=wg,now:u=Date.now()}={}){if(ei)return;ei=!0;try{let f=await o();if(f?.length&&u-rd>ug&&await i())rd=u,s.warn(`system-permissions: tccd refuses ${f.join(", ")} though this Mac granted them: restarting tccd`),await d(),f=await o();if(!f)return;let p=ti;if(ti=f,JSON.stringify(p)===JSON.stringify(f))return;if(f.length)s.warn(`system-permissions: this agent lacks ${f.map(ga).join("; ")}`);else s.info("system-permissions: this agent holds Screen Recording, Accessibility and Automation");sd?.()}catch(f){s.warn("system-permissions: couldn't check this agent's grants",f)}finally{ei=!1}}function lm(i){if($t)return;nd(i),$t=setInterval(()=>void nd(i),dg),$t.unref?.()}function pm(){if($t)clearInterval($t);$t=void 0}import{readFileSync as Cd}from"fs";import{randomBytes as Zr}from"crypto";import{EventEmitter as Jg}from"events";import{existsSync as _d,mkdirSync as Kg,writeFileSync as zg}from"fs";import{mkdir as tn,readdir as Xg,readFile as Pd,rm as et,writeFile as ai}from"fs/promises";import{createServer as Qg}from"net";import{join as ie}from"path";import{randomBytes as yg}from"crypto";import{readFileSync as bg,renameSync as id,rmSync as $g,writeFileSync as Sg}from"fs";import{chmod as vg,mkdir as Pg,readFile as kg,rename as od,rm as xg,writeFile as Eg}from"fs/promises";import{basename as Rg,dirname as Og}from"path";class Zt extends Error{path;constructor(i,o,d){super(`couldn't ${o} ${i}: ${_g(d)}`,{cause:d});this.path=i;this.name="StateFileError"}}async function Ge(i,o,d){let u;try{u=await kg(i,"utf8")}catch(w){if(ld(w))return o;throw new Zt(i,"read",w)}let f=ad(u,d);if(f.ok)return f.value;let p=dd(i),h=await od(i,p).then(()=>!0,()=>!1);return cd(i,u,f.error,h?p:void 0),o}function Ni(i,o,d){let u;try{u=bg(i,"utf8")}catch(w){if(ld(w))return o;throw new Zt(i,"read",w)}let f=ad(u,d);if(f.ok)return f.value;let p=dd(i),h=!0;try{id(i,p)}catch{h=!1}return cd(i,u,f.error,h?p:void 0),o}async function $e(i,o,d){let u=ud(i);try{if(await Pg(Og(i),{recursive:!0}),await Eg(u,`${JSON.stringify(o,null,2)}
258
+ `,d===void 0?{}:{mode:d}),d!==void 0)await vg(u,d);await od(u,i)}catch(f){throw await xg(u,{force:!0}),new Zt(i,"save",f)}}function qn(i,o,d){let u=ud(i);try{Sg(u,`${JSON.stringify(o,null,2)}
259
+ `,d===void 0?{}:{mode:d}),id(u,i)}catch(f){throw $g(u,{force:!0}),new Zt(i,"save",f)}}function ad(i,o){try{let d=JSON.parse(i);return{ok:!0,value:o?o(d):d}}catch(d){return{ok:!1,error:d}}}function cd(i,o,d,u){let f=Buffer.byteLength(o);s.warn(`state: ${i} is not valid JSON (${f?`${f} bytes`:"empty"}): ${u?`kept as ${Rg(u)}`:"couldn't keep it aside"}, starting it again`,d)}var dd=(i)=>`${i}.corrupt-${new Date().toISOString().slice(0,16).replace(":","")}`,ud=(i)=>`${i}.${process.pid}.${yg(4).toString("hex")}.tmp`,ld=(i)=>i.code==="ENOENT";function _g(i){let o=i.code;if(o==="ENOSPC")return"the disk is full (ENOSPC)";if(o==="EDQUOT")return"the disk quota is used up (EDQUOT)";if(o==="EACCES"||o==="EPERM")return`no permission (${o})`;return i instanceof Error?i.message:String(i)}import{createCipheriv as Ug}from"crypto";import{readFileSync as Dg}from"fs";import{connect as Lg}from"net";import{readFile as pd}from"fs/promises";async function mc(i){if(process.platform==="linux")return{uids:await Ig(i),everyone:!0};if(process.platform==="darwin")return Tg(i);return}async function Ig(i){let o=new Set;for(let d of["/proc/net/tcp","/proc/net/tcp6"]){let u=(await pd(d,"utf8").catch(()=>"")).split(`
260
+ `).slice(1);for(let f of u){let[,p,,h,,,,w]=f.trim().split(/\s+/),y=Number.parseInt(p?.split(":")[1]??"",16);if(h==="0A"&&y===i&&w)o.add(Number(w))}}return[...o]}async function Tg(i){let o=()=>r(qd).flag("-nP").flag("-i",`TCP:${i}`).flag("-sTCP:LISTEN").flag("-Fu").build(),d=fd((await g(o())).stdout);if(d.length||process.getuid?.()===0)return{uids:d,everyone:process.getuid?.()===0};let u=await g(r(A).flag("-n").wrap(o()).build());if(/^sudo:/m.test(u.stderr))return{uids:[],everyone:!1};return{uids:fd(u.stdout),everyone:!0}}var fd=(i)=>[...new Set([...i.matchAll(/^u(\d+)$/gm)].map((o)=>Number(o[1])))];async function hd(i){if(process.platform==="linux")return Cg(i);if(process.platform==="win32")return Ng(i);return}var bd=(i)=>/^127\./.test(i)||i==="::1"||/^::ffff:127\./i.test(i);async function Cg(i){let o=new Set;for(let d of["/proc/net/tcp","/proc/net/tcp6"]){let u=(await pd(d,"utf8").catch(()=>"")).split(`
261
+ `).slice(1);for(let f of u){let[,p,,h]=f.trim().split(/\s+/),[w="",y=""]=p?.split(":")??[];if(h==="0A"&&Number.parseInt(y,16)===i)o.add(Ag(w))}}return[...o]}function Ag(i){let d=(i.match(/.{8}/g)??[]).flatMap((h)=>(h.match(/../g)??[]).reverse().map((w)=>Number.parseInt(w,16)));if(d.length===4)return d.join(".");if(d.slice(0,10).every((h)=>h===0)&&d[10]===255&&d[11]===255)return`::ffff:${d.slice(12).join(".")}`;let f=[];for(let h=0;h<16;h+=2)f.push(((d[h]??0)<<8|(d[h+1]??0)).toString(16));let p=f.join(":");return p==="0:0:0:0:0:0:0:1"?"::1":p==="0:0:0:0:0:0:0:0"?"::":p}var Mg=l`$port = [int]$env:SF_LISTEN_PORT
262
+ @(Get-NetTCPConnection -State Listen -LocalPort $port -ErrorAction SilentlyContinue | ForEach-Object { [string]$_.LocalAddress }) -join "\n"`;async function Ng(i){let o=await g(r(Gd).flag("-NoProfile").flag("-NonInteractive").script("-Command",Mg).env({SF_LISTEN_PORT:String(i)}).timeoutMs(30000).by("machine.screen").build()).catch(()=>{return});if(o?.exitCode!==0)return;return o.stdout.split(/\r?\n/).map((d)=>d.trim()).filter(Boolean)}var vd=15000,Fg=17000;function Vn(i){let o=Lg(i),d=(u)=>{};return o.on("data",(u)=>d(u)),new Promise((u,f)=>{o.once("error",f),o.once("connect",()=>{o.off("error",f),o.on("error",(p)=>s.warn(`ports: ${i.host}:${i.port}: ${p.message}`)),u({write:(p)=>void o.write(p),close:()=>o.destroy(),onData:(p)=>d=p,onClose:(p)=>void o.on("close",p)})})})}function Bg(i){let o=new WebSocket(`${i.protocol==="https:"?"wss":"ws"}://${i.host}/websockify`,["binary"]);o.binaryType="arraybuffer";let d=(u)=>{};return o.onmessage=(u)=>{if(typeof u.data!=="string")d(Buffer.from(u.data))},new Promise((u,f)=>{o.onerror=()=>f(Error(`couldn't reach the screen at ${i.host}`)),o.onopen=()=>{o.onerror=null,u({write:(p)=>o.readyState===WebSocket.OPEN&&o.send(p),close:()=>o.close(),onData:(p)=>d=p,onClose:(p)=>o.addEventListener("close",()=>p())})}})}async function Pt(i){let o=new URL(i.url);if(o.protocol==="vnc:"&&o.hostname==="127.0.0.1")await Gg(Number(o.port)||5900);if(zr.has(i.url))ni.set(i.url,Date.now());let d=o.protocol==="vnc:"?await Vn({host:o.hostname,port:Number(o.port)||5900}):await Bg(o);if(!i.password)return d;let u=new si(d),f=setTimeout(()=>u.fail(Error("the screen didn't answer")),vd);try{await Wg(u,d,i.password)}catch(p){throw d.close(),p}finally{clearTimeout(f)}return qg(d,u.rest())}var ri=new Map,jg=30000;async function Gg(i){if(Date.now()-(ri.get(i)??0)<jg)return;let o=(await hd(i))?.filter((d)=>!bd(d));if(!o?.length){ri.set(i,Date.now());return}throw ri.delete(i),Error(`this machine's VNC server on port ${i} also listens on its network (${o.join(", ")}), where anyone could reach its screen: it isn't relayed until it listens on 127.0.0.1 alone${process.platform==="win32"?" (run join.ps1 again: it sets TightVNC to loopback only)":""}`)}var zr=new Map,ni=new Map;function hl(){let i=Number(process.env.SUPERFACTORY_SCREEN_PORT);if(!i)return;let o=process.env.SUPERFACTORY_SCREEN_PASSWORD_FILE,d;try{d=o?Dg(o,"utf8").trim()||void 0:void 0}catch{s.warn(`screen: can't read the screen's password (${o})`)}return{url:`vnc://127.0.0.1:${i}`,...d?{password:d}:{}}}function fm(i){return/^https?:$/.test(new URL(i.url).protocol)}function Li(i,o=Fg){let d=zr.get(i.url);if(d)return d;let u=Hg(i,o).catch((f)=>s.warn(`screen: couldn't warm up ${new URL(i.url).host}: ${f.message}`)).finally(()=>{zr.delete(i.url),ni.delete(i.url)});return zr.set(i.url,u),u}async function Hg(i,o){let d=await Pt(i),u=new si(d),f=setTimeout(()=>u.fail(Error("the screen didn't answer")),vd);try{if(!/^RFB 003\.00[78]\n$/.test((await u.read(12)).toString("latin1")))return;if(d.write(Buffer.from(`RFB 003.008
263
+ `)),![...await u.read((await u.read(1))[0]??0)].includes(1))return;if(d.write(Uint8Array.of(1)),(await u.read(4)).readUInt32BE()!==0)return;d.write(Uint8Array.of(1)),await u.read(24),clearTimeout(f);for(let h=o;h>0;h=(ni.get(i.url)??0)+o-Date.now())await Bun.sleep(h);s.info(`screen: ${new URL(i.url).host} warmed up`)}finally{clearTimeout(f),d.close()}}async function Wg(i,o,d){let u=(await i.read(12)).toString("latin1"),f=Number(/^RFB 003\.(\d{3})\n$/.exec(u)?.[1]);if(!f)throw Error(`not a VNC server (${JSON.stringify(u)})`);o.write(Buffer.from(f>=8?`RFB 003.008
264
+ `:f>=7?`RFB 003.007
265
+ `:`RFB 003.003
266
+ `));let p;if(f>=7){let h=[...await i.read((await i.read(1))[0]??0)];if(!h.length)throw Error(`the screen refused: ${await $d(i)}`);if(p=h.includes(2)?2:h.includes(1)?1:0,!p)throw Error(`the screen asks for a sign-in we don't do (${h.join(", ")})`);o.write(Uint8Array.of(p))}else p=(await i.read(4)).readUInt32BE();if(p===2)o.write(Vg(await i.read(16),d));if(p===2||f>=8){if((await i.read(4)).readUInt32BE()!==0)throw Error(`the screen refused its password${f>=8?`: ${await $d(i)}`:""}`)}}async function $d(i){return(await i.read((await i.read(4)).readUInt32BE())).toString("utf8")}function Vg(i,o){let d=Buffer.alloc(8);Buffer.from(o,"latin1").copy(d,0,0,8);for(let f=0;f<8;f++)d[f]=Yg(d[f]??0);let u=Ug("des-ecb",d,null).setAutoPadding(!1);return Buffer.concat([u.update(i),u.final()])}function Yg(i){let o=0;for(let d=0;d<8;d++)o|=(i>>d&1)<<7-d;return o}function qg(i,o){let d=(S)=>{},u=o.length?[o]:[],f=!1,p="version",h=8,w=Buffer.alloc(0);i.onData((S)=>f?d(S):u.push(S));let y=()=>{f=!0;for(let S of u)d(S);if(u=[],w.length)i.write(w)};return{onData(S){d=S,S(Buffer.from(`RFB 003.008
267
+ `))},write(S){if(f)return i.write(S);if(w=Buffer.concat([w,S]),p==="version"&&w.length>=12){if(h=Number(w.subarray(8,11).toString("latin1"))||8,w=w.subarray(12),h<7)return d(Sd(1)),y();d(Buffer.from([1,1])),p="choice"}if(p==="choice"&&w.length>=1){if(w[0]!==1)return i.close();if(w=w.subarray(1),h>=8)d(Sd(0));y()}},close:()=>i.close(),onClose:(S)=>i.onClose(S)}}function Sd(i){let o=Buffer.alloc(4);return o.writeUInt32BE(i),o}class si{buffer=Buffer.alloc(0);waiting;failed;constructor(i){i.onData((o)=>{this.buffer=Buffer.concat([this.buffer,o]),this.settle()}),i.onClose(()=>this.fail(Error("the screen closed the connection")))}read(i){return new Promise((o,d)=>{this.waiting={size:i,resolve:o,reject:d},this.settle()})}fail(i){this.failed=i,this.settle()}rest(){return this.buffer}settle(){let i=this.waiting;if(!i)return;if(this.buffer.length>=i.size){this.waiting=void 0;let o=this.buffer.subarray(0,i.size);this.buffer=this.buffer.subarray(i.size),i.resolve(o)}else if(this.failed)this.waiting=void 0,i.reject(this.failed)}}var Zg=1800000,Id=15000,en=3000,kd=5900;function ci(){return(process.env.SUPERFACTORY_X11VNC_BIN?_d(process.env.SUPERFACTORY_X11VNC_BIN):Bun.which("x11vnc")!==null)&&new hc().available()}class hc{displays=new Map;closing=new Set;running=new Set;stopping=!1;exitHook=!1;available(){if(process.env.SUPERFACTORY_XVFB_BIN)return _d(process.env.SUPERFACTORY_XVFB_BIN);return process.platform==="linux"&&Bun.which("Xvfb")!==null}async display(i){let o=await this.ensure(i);return o.usedAt=Date.now(),`:${o.number}`}async port(i){let o=await this.ensure(i);return{port:kd+o.number,kind:"vnc",relay:"machine"}}async isScreen(i,o){let d=await this.displays.get(i)?.catch(()=>{return});return d!==void 0&&o===kd+d.number}async authority(i){let o=await this.ensure(i);return o.authority?Pd(o.authority).catch(()=>{return}):void 0}async screen(i){let o=await this.ensure(i);if(o.closed)throw Error(`display :${o.number} is closed`);return o.usedAt=Date.now(),o.wm??=ow(o,this.track),(await this.vnc(o)).screen}vnc(i){if(i.closed)return Promise.reject(Error(`display :${i.number} is closed`));return i.vnc??=dw(i,this.track).then(async(o)=>{if(!i.closed)return o;throw await tt(o.process),Error(`display :${i.number} closed as its screen started`)},(o)=>{throw i.vnc=void 0,o}),i.vnc}close(i){let o=this.closeNow(i);return this.closing.add(o),o.finally(()=>this.closing.delete(o)).catch(()=>{return}),o}async closeNow(i){let o=await this.displays.get(i)?.catch(()=>{return});if(this.displays.delete(i),!o)return;await xd(o),s.info(`displays: closed :${o.number} of ${i}`)}async closeIdle(i,o=Date.now()){for(let[d,u]of this.displays){let f=await u.catch(()=>{return});if(i.has(d)&&f)f.usedAt=o;else if(!f||o-f.usedAt>=Zg)await this.close(d)}}async closeAll(){this.stopping=!0;while(this.displays.size)await Promise.all([...this.displays.keys()].map((i)=>this.close(i)));await Promise.all([...this.closing].map((i)=>i.catch(()=>{return}))),await Promise.all([...this.running].map(tt))}async handOver(){this.stopping=!0;let i=await Qr(),o=[];for(let[d,u]of[...this.displays]){let f=await u.catch(()=>{return}),p=f?.xvfb.pid,h=p?i.get(p):void 0;if(!f||f.closed||!p||!h)continue;this.displays.delete(d),f.closed=!0;let w=await f.vnc?.catch(()=>{return});await Promise.all([w?.process,f.wm].map((y)=>y&&tt(y))),this.running.delete(f.xvfb),await et(ie(Ae(),`${p}${oi}`),{force:!0}),o.push({cwd:d,number:f.number,pid:p,started:h,authority:f.authority})}if(!o.length)return;await tn(Ae(),{recursive:!0,mode:448}),await $e(ii(),o,384),s.info(`displays: ${o.map((d)=>`:${d.number}`).join(", ")} handed to the next agent`)}async adopt(){let i=await Ge(ii(),[]).catch((d)=>(s.warn("displays: none taken back",d),[]));if(await et(ii(),{force:!0}),!i.length)return;let o=await Qr();for(let d of i){if(o.get(d.pid)!==d.started||this.displays.has(d.cwd)){s.warn(`displays: :${d.number} the agent before handed over is gone`);continue}let u=this.track(new Td(d.pid,"Xvfb")),{cwd:f,number:p,authority:h}=d;this.keep(f,Promise.resolve({cwd:f,number:p,xvfb:u,authority:h,usedAt:Date.now()})),s.info(`displays: took :${d.number} of ${d.cwd} back from the agent before`)}}track=(i)=>{if(!i)return i;if(ew(i),this.running.add(i),i.once("exit",()=>this.running.delete(i)),!this.exitHook)this.exitHook=!0,process.once("exit",()=>{for(let o of this.running)Xr(o,"SIGKILL")});return i};async endLeftovers(){let i=(await Xg(Ae()).catch(()=>[])).filter((d)=>d.endsWith(oi));if(!i.length)return;let o=await Qr();await Promise.all(i.map(async(d)=>{let u=ie(Ae(),d),f=Number.parseInt(d,10),p=await Pd(u,"utf8").catch(()=>"");if(f>0&&p&&o.get(f)===p)s.info(`displays: ending pid ${f}, which an earlier run left`),await tw(f);await et(u,{force:!0})}))}ensure(i){let o=this.displays.get(i);if(!o){if(this.stopping)return Promise.reject(Error("the agent is stopping: no new display"));let d=rw(i,this.track);o=d,d.then(async(u)=>{if(!iw()||u.closed)return;let f=await this.vnc(u).catch((p)=>{s.warn(`displays: no screen for :${u.number}`,p)});if(f)await Li(f.screen)},()=>{return}),this.keep(i,d)}return o}keep(i,o){this.displays.set(i,o);let d=()=>this.displays.get(i)===o&&this.displays.delete(i);o.then((u)=>u.xvfb.once("exit",()=>{d(),xd(u)}),d)}}async function xd(i){i.closed=!0;let o=await i.vnc?.catch(()=>{return});if(await Promise.all([o?.process,i.wm].map((d)=>d&&tt(d))),await tt(i.xvfb),i.authority)await et(i.authority,{force:!0})}async function tt(i){let o=new Promise((u)=>{if(i.exitCode!==null||i.signalCode!==null)u(!0);else i.once("exit",()=>u(!0))}),d=(u)=>Promise.race([o,Bun.sleep(u).then(()=>!1)]);if(Xr(i,"SIGTERM"),await d(en))return;s.warn(`displays: ${i.spawnfile} (pid ${i.pid}) didn't end on SIGTERM: killed`),Xr(i,"SIGKILL"),await d(en),Xr(i,"SIGKILL")}function Xr(i,o){try{if(i.pid)return process.kill(-i.pid,o)}catch{}i.kill(o)}var Ae=()=>ie(m().home,"displays"),oi=".running",ii=()=>ie(Ae(),"handed-over.json");class Td extends Jg{pid;spawnfile;exitCode=null;signalCode=null;constructor(i,o){super();this.pid=i;this.spawnfile=o;let d=setInterval(()=>{try{process.kill(i,0)}catch{clearInterval(d),this.exitCode=0,this.emit("exit",0,null)}},500);d.unref()}kill(i){try{return process.kill(this.pid,i)}catch{return!1}}}function ew(i){let o=i?.pid;if(!i||!o)return i;let d=ie(Ae(),`${o}${oi}`),u=!1;return i.once("exit",()=>{u=!0,et(d,{force:!0})}),(async()=>{let f=(await Qr()).get(o);if(!f||u)return;if(await tn(Ae(),{recursive:!0,mode:448}),await ai(d,f,{mode:384}),u)await et(d,{force:!0})})().catch((f)=>s.warn(`displays: couldn't note pid ${o}`,f)),i}async function Qr(){let i=await g(r(oe).flag("-axww").flag("-o","pid=,lstart=").build()),o=new Map;for(let d of i.stdout.split(`
268
+ `)){let[,u,f]=/^\s*(\d+)\s+(\S.*?)\s*$/.exec(d)??[];if(u&&f)o.set(Number(u),f)}return o}async function tw(i){let o=(u)=>{for(let f of u===0?[i]:[-i,i])try{return process.kill(f,u),!0}catch{}return!1},d=async(u)=>{for(let f=Date.now()+u;Date.now()<f;await Bun.sleep(100))if(!o(0))return!0;return!o(0)};if(!o("SIGTERM")||await d(en))return;o("SIGKILL"),await d(en)}async function rw(i,o){let d=await nw(),u=o(_(r(bu).programPath(process.env.SUPERFACTORY_XVFB_BIN).flag("-displayfd",1).flag("-screen",0).arg("1920x1080x24").flag("-nolisten","tcp").flag("-auth",d).build(),{stdin:"ignore",stdout:"pipe",stderr:"ignore",detached:!0})),f=await new Promise((p,h)=>{let w="",y=setTimeout(()=>S(Error("Xvfb didn't say its display")),Id),S=(v)=>{clearTimeout(y),tt(u).then(()=>et(d,{force:!0})),h(v)};u.stdout.on("data",(v)=>{w+=v.toString();let P=/^(\d+)\n/.exec(w);if(!P)return;clearTimeout(y),p(Number(P[1]))}),u.on("exit",(v)=>S(Error(`Xvfb ended (${v}) before its display was up`)))});return s.info(`displays: :${f} for ${i}`),{cwd:i,number:f,xvfb:u,authority:d,usedAt:Date.now()}}async function nw(){await tn(Ae(),{recursive:!0,mode:448});let i=ie(Ae(),`${Zr(8).toString("hex")}.xauth`),o=(f)=>Buffer.concat([Ed(f.length),f]),d=Buffer.alloc(0),u=Buffer.concat([Ed(sw),o(d),o(d),o(Buffer.from("MIT-MAGIC-COOKIE-1")),o(Zr(16))]);return await ai(i,u,{mode:384,flag:"wx"}),i}var sw=65535;function Ed(i){let o=Buffer.alloc(2);return o.writeUInt16BE(i),o}function iw(){return!!process.env.SUPERFACTORY_X11VNC_BIN||Bun.which("x11vnc")!==null}function ow(i,o){if(!process.env.SUPERFACTORY_FLUXBOX_BIN&&Bun.which("fluxbox")===null)return;let d=aw();return o(_(r(ku).programPath(process.env.SUPERFACTORY_FLUXBOX_BIN).flag("-display",`:${i.number}`).flag("-rc",ie(d,".fluxbox","init")).env({HOME:d,XAUTHORITY:i.authority}).build(),{stdin:"ignore",stdout:"ignore",stderr:"ignore",detached:!0}))}function aw(){let i=ie(Ae(),"window-manager"),o=ie(i,".fluxbox");Kg(o,{recursive:!0,mode:448});let d={init:["session.configVersion: 99",`session.keyFile: ${ie(o,"keys")}`,`session.menuFile: ${ie(o,"menu")}`,`session.appsFile: ${ie(o,"apps")}`,`session.styleOverlay: ${ie(o,"overlay")}`,`session.screen0.windowMenu: ${ie(o,"windowmenu")}`,"session.screen0.rootCommand:","session.screen0.allowRemoteActions: false"].map((u)=>`${u}
269
+ `).join(""),keys:cw,menu:`[begin] (Superfactory)
270
+ [end]
271
+ `,windowmenu:`[begin]
272
+ [shade]
273
+ [stick]
274
+ [maximize]
275
+ [iconify]
276
+ [raise]
277
+ [lower]
278
+ [close]
279
+ [end]
280
+ `,apps:"",overlay:`background: none
281
+ `};for(let[u,f]of Object.entries(d))zg(ie(o,u),f,{mode:384});return i}var cw=`OnDesktop Mouse1 :HideMenus
282
+ OnTitlebar Mouse1 :MacroCmd {Raise} {Focus} {ActivateTab}
283
+ OnTitlebar Move1 :StartMoving
284
+ OnTitlebar Double Mouse1 :Maximize
285
+ OnTitlebar Mouse3 :WindowMenu
286
+ OnWindowBorder Move1 :StartMoving
287
+ OnLeftGrip Move1 :StartResizing bottomleft
288
+ OnRightGrip Move1 :StartResizing bottomright
289
+ OnWindow Mod1 Mouse1 :MacroCmd {Raise} {Focus} {StartMoving}
290
+ OnWindow Mod1 Mouse3 :MacroCmd {Raise} {Focus} {StartResizing NearestCorner}
291
+ Mod1 Tab :NextWindow {groups} (workspace=[current])
292
+ Mod1 Shift Tab :PrevWindow {groups} (workspace=[current])
293
+ `;async function dw({number:i,authority:o},d){let u=Zr(6).toString("base64url"),f=ie(m().home,"displays");await tn(f,{recursive:!0,mode:448});let p=ie(f,`${i}-${Zr(4).toString("hex")}.pass`);await ai(p,`${u}
294
+ `,{mode:384});let h=await uw(),w=d(_(r(vu).programPath(process.env.SUPERFACTORY_X11VNC_BIN).flag("-display",`:${i}`).flag("-localhost").flag("-rfbport",h).flag("-passwdfile",`rm:${p}`).flag("-forever").flag("-shared").flag("-threads").flag("-quiet").flag("-noshm").flag("-noremote").env({X11VNC_AVOID_WINDOWS:"never",XAUTHORITY:o}).build(),{stdin:"ignore",stdout:"pipe",stderr:"ignore",detached:!0}));if(!await new Promise((S)=>{let v="",P=setTimeout(()=>S(!1),Id);w.stdout.on("data",(x)=>{if(v===void 0)return;if(v+=x.toString(),!v.includes(`PORT=${h}
295
+ `))return;v=void 0,clearTimeout(P),S(!0)}),w.once("exit",()=>{clearTimeout(P),S(!1)})}))throw await tt(w),Error(`the screen of :${i} didn't start`);return{process:w,screen:{url:`vnc://127.0.0.1:${h}`,password:u}}}function uw(){return new Promise((i,o)=>{let d=Qg();d.once("error",o),d.listen(0,"127.0.0.1",()=>{let u=d.address();d.close(()=>i(typeof u==="object"&&u?u.port:0))})})}var lw=t({url:e().regex(/^vnc:\/\/127\.0\.0\.1:\d{1,5}$/),password:e().min(1).max(8)});function ds(){try{return lw.parse(JSON.parse(Cd(m().screen,"utf8")))}catch{return}}var rn=5900,Ad=`vnc://127.0.0.1:${rn}`,gl="machine";async function gc(){if(ds()||ci())return!0;return await wl()!==void 0}async function wl(){if(process.platform!=="darwin"||!await as(rn))return;return await Md()?{url:Ad}:void 0}async function Md(){let i=await mc(rn).catch(()=>{return});if(!i?.uids.every((o)=>o===0))return!1;return i.uids.length>0||!i.everyone}function fw(i="https://<server>"){let o=`on it, in PowerShell, run: irm ${i}/join.ps1 | iex`,d=pw();return d?`This machine has no screen: join.ps1 couldn't set it up (${d}). Once that's dealt with, ${o}`:`This machine has no screen yet: ${o}`}function pw(){try{let i=Cd(m().screenProblem,"utf8").replace(/^\uFEFF/,"").replace(/\s+/g," ").trim();return i?i.slice(0,500):void 0}catch{return}}async function Di(i,o){let d=ds();if(d)return d;if(ci())return i.screen(gl);if(process.platform==="darwin"){if(!await as(rn))throw new c("unavailable","Screen Sharing is off on this Mac: turn it on in System Settings \u203A General \u203A Sharing.");if(await Md())return{url:Ad};throw new c("unavailable","This Mac's port 5900 is held by a user's process, not its Screen Sharing: stop that process, then turn Screen Sharing on in System Settings \u203A General \u203A Sharing.")}if(process.platform==="win32")throw new c("unavailable",fw(o));throw new c("unavailable","This machine has no virtual display: Set up installs one (Xvfb and x11vnc).")}import{createSocket as XS}from"dgram";import{existsSync as lS,lstatSync as fS}from"fs";import{mkdtemp as pS,readFile as mS,realpath as Gf,rm as hS,stat as gS}from"fs/promises";import{tmpdir as wS}from"os";import{dirname as Ln,isAbsolute as Er,join as Hf,relative as oa,resolve as ia,sep as yS}from"path";import{existsSync as mw}from"fs";import{realpath as di}from"fs/promises";import{basename as hw,dirname as gw,isAbsolute as ww,join as yw,relative as bw,resolve as $w}from"path";async function ae(i,o){let d=await di(i),u=$w(d,o),f=mw(u)?await di(u):yw(await di(gw(u)),hw(u)),p=bw(d,f);if(p===""||p.startsWith("..")||ww(p))throw Error(`${o} is outside ${i}`);return f}import{constants as Ew}from"os";async function Sw(){let i=await g(r(oe).flag("-axww").flag("-o","pid=,ppid=,pgid=,sess=,stat=").timeoutMs(1e4).build()),o=new Map;for(let d of i.stdout.split(`
296
+ `)){let[u,f,p,h,w=""]=d.trim().split(/\s+/);if(!u||w.startsWith("Z"))continue;o.set(Number(u),{pid:Number(u),ppid:Number(f),pgid:Number(p),sess:Number(h)})}return o}function vw(i,o,d=process.pid){let u=o.get(d),f=new Set,p=(h)=>{let w=o.get(h);if(f.has(h)||h===d||!w)return;if(f.add(h),w.pgid>1&&w.pgid!==u?.pgid)i.groups.add(w.pgid);if(w.sess>1&&w.sess!==u?.sess)i.sessions.add(w.sess);for(let y of o.values())if(y.ppid===h)p(y.pid)};for(let h of i.pids)p(h);for(let h of o.values())if(i.groups.has(h.pgid)||i.sessions.has(h.sess))p(h.pid);for(let h of f)i.pids.add(h);return[...f]}async function Tt(i,{asRoot:o=!1,tries:d=10,pollMs:u=100}={}){if(process.platform==="win32")return await g(r(An).flag("/T").flag("/F").flag("/PID",i).timeoutMs(30000).build()),!0;let f={pids:new Set([i]),groups:new Set,sessions:new Set};for(let p=0;p<d;p++){let h=vw(f,await Sw());if(!h.length)return!0;let w=r(Js).flag("-s","KILL").argsOf(h).timeoutMs(1e4).build();if(o)await g(r(A).flag("-n").wrap(w).by("machine setup").timeoutMs(1e4).build());else for(let y of h)try{process.kill(y,"SIGKILL")}catch{}await Bun.sleep(u)}return!1}var Pw=100,li=15000;async function nn(i){let o=await wc().catch(()=>[]),d=new Set([i]);for(let u=!0;u;){u=!1;for(let f of o)if(!d.has(f.pid)&&(d.has(f.ppid)||f.pgid===i))d.add(f.pid),u=!0}return o.filter((u)=>d.has(u.pid)).slice(0,Pw).map(({pgid:u,...f})=>f)}async function Nd(i){if(i<=0)return;if(process.platform==="win32"){let u=(await nn(i)).map((f)=>f.pid);await g(r(An).flag("/T").flag("/F").flag("/PID",i).timeoutMs(li).build());for(let f of u)ui(f,"SIGKILL");return}let o=(await nn(i)).map((u)=>u.pid),d=(u)=>{ui(-i,u);for(let f of o)ui(f,u)};d("SIGTERM"),await Bun.sleep(1000),d("SIGKILL")}function ui(i,o){try{process.kill(i,o)}catch{}}async function wc(){if(process.platform==="win32")return xw();let i=await g(r(oe).flag("-axww").flag("-o","pid=,ppid=,pgid=,pcpu=,etime=,command=").timeoutMs(li).build());return fi(i.stdout)}function yl(i){if(i.endsWith("s"))return Number(i.slice(0,-1))||0;let[o,d=""]=i.includes("-")?i.split("-"):["0",i],u=d.split(":").map(Number);while(u.length<3)u.unshift(0);let[f=0,p=0,h=0]=u;return Number(o)*86400+f*3600+p*60+h}function fi(i){return i.split(`
297
+ `).flatMap((o)=>{let d=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+([\d.,]+)\s+(\S+)\s+(.*)$/.exec(o);if(!d)return[];let[,u,f,p,h,w,y]=d;return[{pid:Number(u),ppid:Number(f),pgid:Number(p),cpu:`${h}%`,elapsed:w??"",command:(y??"").slice(0,2000)}]})}var kw=l`Get-CimInstance Win32_Process | ForEach-Object { "{0}|{1}|{2}|{3}|{4}" -f $_.ProcessId, $_.ParentProcessId, [math]::Round(($_.KernelModeTime + $_.UserModeTime) / 1e7, 1), $(if ($_.CreationDate) { [int]((Get-Date) - $_.CreationDate).TotalSeconds } else { 0 }), ($_.CommandLine -replace '[\r\n]', ' ') }`;async function xw(){return(await g(r(Ke).flag("-NoProfile").flag("-NonInteractive").script("-Command",kw).timeoutMs(li).build())).stdout.split(/\r?\n/).flatMap((o)=>{let[d,u,f,p,...h]=o.split("|");if(!d||!u||Number.isNaN(Number(d)))return[];return[{pid:Number(d),ppid:Number(u),cpu:`${f}s`,elapsed:`${p}s`,command:h.join("|").slice(0,2000)}]})}var Rw=300;async function Ui(i,o,{input:d,endAsRoot:u=!1}={}){let f=_(i,{stdin:d===void 0?"ignore":"pipe",detached:process.platform!=="win32"});if(d!==void 0)f.stdin.on("error",()=>{}),f.stdin.end(d);let p=[f.stdout,f.stderr];for(let v of p)v.setEncoding("utf8"),v.on("data",o);let h=Promise.all(p.map((v)=>new Promise((P)=>v.once("close",P)))),w=new Promise((v)=>{f.once("error",(P)=>{o(`${P.message}
298
+ `),v(127)}),f.once("exit",async(P,x)=>{await Promise.race([h,Bun.sleep(Rw)]),v(P??128+(Ew.signals[x]??0))})}),y=f.pid??0;return{exited:w,kill:u?async()=>void await Tt(y,{asRoot:!0}):()=>Nd(y),processes:()=>nn(y)}}async function Ld(i,o,d,u){let f=await i.start(o,{...d,onStdout:u,onStderr:u});return{exited:f.wait().then((p)=>p.exitCode),kill:()=>f.kill("SIGKILL"),processes:async()=>{let p=await i.run(["ps","-A","-o","pid=,ppid=,pgid=,pcpu=,etime=,args="]);return fi(p.stdout).filter((h)=>!/^ps -A /.test(h.command)).map(({pgid:h,...w})=>w)}}}var Fi=(i,o)=>i!=="coordinator"&&o["machine.taskSudo"]===!1;function mm(i,o,d=process.platform){if(d!=="linux"||!Fi(i,o))return"";return"Root on this machine: not yours. You and everything you start (tests, the agents they start) run with no_new_privs, so `sudo`, `su` and setuid programs fail at once. System packages the project needs go in superfactory.yaml's setup, which the agent runs; anything else root must do here is your lead's (task_ask the user only for what only they can do)."}import{readFileSync as Bw}from"fs";import{userInfo as jw}from"os";import{deflateSync as Ow}from"zlib";var _w=Buffer.from([137,80,78,71,13,10,26,10]),Iw=(()=>{let i=new Uint32Array(256);for(let o=0;o<256;o++){let d=o;for(let u=0;u<8;u++)d=d&1?3988292384^d>>>1:d>>>1;i[o]=d>>>0}return i})();function Tw(i){let o=4294967295;for(let d of i)o=(Iw[(o^d)&255]??0)^o>>>8;return(o^4294967295)>>>0}function pi(i,o){let d=Buffer.alloc(8);d.writeUInt32BE(o.length,0),d.write(i,4,"latin1");let u=Buffer.alloc(4);return u.writeUInt32BE(Tw(Buffer.concat([d.subarray(4),o]))),Buffer.concat([d,o,u])}function mi(i,o,d){let u=Buffer.alloc(13);u.writeUInt32BE(i,0),u.writeUInt32BE(o,4),u.set([8,2,0,0,0],8);let f=i*3,p=Buffer.alloc((f+1)*o);for(let h=0;h<o;h++){let w=h*(f+1);p[w]=h?2:0;for(let y=0;y<f;y++){let S=d[h*f+y]??0;p[w+1+y]=h?S-(d[(h-1)*f+y]??0)&255:S}}return Buffer.concat([_w,pi("IHDR",u),pi("IDAT",Ow(p,{level:6})),pi("IEND",new Uint8Array(0))])}var Bd=20000,jd=40,Cw=600,Aw=5000,Mw=250,vt={raw:0,copyRect:1,desktopSize:-223};class Kn{pipe;width=0;height=0;pixels=new Uint8Array(0);bytes;updated;failed;buttons=0;constructor(i){this.pipe=i;this.bytes=new tu(i)}static async open(i){let o=new Kn(i),d=setTimeout(()=>o.bytes.fail(Error("the screen didn't answer")),Bd);try{await o.handshake()}catch(u){throw i.close(),u}finally{clearTimeout(d)}return o.loop().catch((u)=>{o.failed=u,o.updated?.reject(u)}),o}async handshake(){let{bytes:i,pipe:o}=this,d=(await i.read(12)).toString("latin1"),u=Number(/^RFB 003\.(\d{3})\n$/.exec(d)?.[1]);if(!u)throw Error(`not a VNC screen (${JSON.stringify(d)})`);o.write(Buffer.from(u>=8?`RFB 003.008
299
+ `:u>=7?`RFB 003.007
300
+ `:`RFB 003.003
301
+ `));let f;if(u>=7){let S=[...await i.read((await i.read(1))[0]??0)];if(!S.length)throw Error(`the screen refused: ${await this.reason()}`);if(!S.includes(1))throw Error("the screen asks for a password this agent doesn't have");o.write(Uint8Array.of(1)),f=1}else f=(await i.read(4)).readUInt32BE();if(f!==1)throw Error("the screen asks for a password this agent doesn't have");if(u>=8&&(await i.read(4)).readUInt32BE()!==0)throw Error(`the screen refused: ${await this.reason()}`);o.write(Uint8Array.of(1));let p=await i.read(24);await i.read(p.readUInt32BE(20)),this.resize(p.readUInt16BE(0),p.readUInt16BE(2));let h=Buffer.alloc(20);h[0]=0,h.set([32,24,0,1],4),h.writeUInt16BE(255,8),h.writeUInt16BE(255,10),h.writeUInt16BE(255,12),h.set([0,8,16],14),o.write(h);let w=[vt.raw,vt.copyRect,vt.desktopSize],y=Buffer.alloc(4+4*w.length);y[0]=2,y.writeUInt16BE(w.length,2),w.forEach((S,v)=>void y.writeInt32BE(S,4+4*v)),o.write(y)}async reason(){return(await this.bytes.read((await this.bytes.read(4)).readUInt32BE())).toString("utf8")}resize(i,o){this.width=i,this.height=o,this.pixels=new Uint8Array(i*o*4)}async loop(){let{bytes:i}=this;for(;;){let o=(await i.read(1))[0];if(o===0){let d=(await i.read(3)).readUInt16BE(1);for(let f=0;f<d;f++)await this.rect();let u=this.updated;this.updated=void 0,u?.resolve()}else if(o===1){let d=await i.read(5);await i.read(d.readUInt16BE(3)*6)}else if(o===2);else if(o===3)await i.read((await i.read(7)).readUInt32BE(3));else throw Error(`the screen sent a message this viewer doesn't know (${o})`)}}async rect(){let i=await this.bytes.read(12),o=i.readUInt16BE(0),d=i.readUInt16BE(2),u=i.readUInt16BE(4),f=i.readUInt16BE(6),p=i.readInt32BE(8);if(p===vt.desktopSize)return this.resize(u,f);if(p===vt.copyRect){let w=await this.bytes.read(4);return this.copy(w.readUInt16BE(0),w.readUInt16BE(2),o,d,u,f)}if(p!==vt.raw)throw Error(`the screen sent an encoding it wasn't asked for (${p})`);let h=await this.bytes.read(u*f*4);for(let w=0;w<f&&d+w<this.height;w++){let y=Math.min(u,this.width-o)*4;if(y>0)this.pixels.set(h.subarray(w*u*4,w*u*4+y),((d+w)*this.width+o)*4)}}copy(i,o,d,u,f,p){if(i+f>this.width||d+f>this.width||o+p>this.height||u+p>this.height)return;let h=[];for(let w=0;w<p;w++){let y=((o+w)*this.width+i)*4;h.push(this.pixels.slice(y,y+f*4))}h.forEach((w,y)=>void this.pixels.set(w,((u+y)*this.width+d)*4))}update(i=!1){if(this.failed)return Promise.reject(this.failed);let o=Buffer.alloc(10);o[0]=3,o[1]=i?1:0,o.writeUInt16BE(this.width,6),o.writeUInt16BE(this.height,8);let d=new Promise((u,f)=>{let p=setTimeout(()=>f(Error("the screen didn't send its picture")),Bd);this.updated={resolve:()=>{clearTimeout(p),u()},reject:(h)=>{clearTimeout(p),f(h)}}});return this.pipe.write(o),d}async picture(i=Aw){let o=Date.now()+i;await this.update();while(this.black()){if(Date.now()>=o)throw Error(`the screen sent only black for ${i/1000} s: its capture isn't working (on Windows, TightVNC's), though the desktop may be live`);await Bun.sleep(Mw),await this.update()}}black(){let{pixels:i}=this;for(let o=0;o<i.length;o+=4)if(i[o]||i[o+1]||i[o+2])return!1;return!0}get waiting(){return this.updated!==void 0}get closed(){return this.failed!==void 0}shot(i){let o=i?{width:i.width,height:i.height,pixels:Lw(this.pixels,this.width,i)}:{width:this.width,height:this.height,pixels:this.pixels},d=Math.min(1,Jt.width/o.width,Jt.height/o.height),u=Math.max(1,Math.round(o.width*d)),f=Math.max(1,Math.round(o.height*d)),p=d===1?Yd(o.pixels):Fw(o.pixels,o.width,o.height,u,f);return{png:mi(u,f,p).toString("base64"),width:u,height:f,screenWidth:o.width,screenHeight:o.height}}png(){return mi(this.width,this.height,Yd(this.pixels))}scale(){return Math.min(1,Jt.width/this.width,Jt.height/this.height)}async act(i){if(!i.length)return;let o=this.scale(),d=(u,f)=>({x:Math.min(this.width-1,Math.round(u/o)),y:Math.min(this.height-1,Math.round(f/o))});for(let u of i)switch(u.do){case"move":{let f=d(u.x,u.y);await this.pointer(f.x,f.y,this.buttons);break}case"click":{let f=d(u.x,u.y),p={left:1,middle:2,right:4}[u.button];await this.pointer(f.x,f.y,0);for(let h=0;h<(u.double?2:1);h++)await this.pointer(f.x,f.y,p),await this.pointer(f.x,f.y,0);break}case"drag":{let f=d(u.x,u.y),p=d(u.toX,u.toY);await this.pointer(f.x,f.y,0),await this.pointer(f.x,f.y,1);for(let h=1;h<=10;h++)await this.pointer(Math.round(f.x+(p.x-f.x)*h/10),Math.round(f.y+(p.y-f.y)*h/10),1);await this.pointer(p.x,p.y,0);break}case"scroll":{let f=d(u.x,u.y),p=u.steps>0?16:8;for(let h=0;h<Math.abs(u.steps);h++)await this.pointer(f.x,f.y,p),await this.pointer(f.x,f.y,0);break}case"type":for(let f of u.text)await this.press([Qd(f)]);break;case"key":await this.press(Dw(u.key));break;case"wait":await Bun.sleep(u.ms);break}await Bun.sleep(Cw)}async pointer(i,o,d){this.buttons=d;let u=Buffer.alloc(6);u[0]=5,u[1]=d,u.writeUInt16BE(i,2),u.writeUInt16BE(o,4),this.pipe.write(u),await Bun.sleep(jd)}async press(i){for(let o of i)this.pipe.write(Wd(o,!0));for(let o of[...i].reverse())this.pipe.write(Wd(o,!1));await Bun.sleep(jd)}close(){this.pipe.close()}}async function Yn(i,o=[],d,u){let f=await Kn.open(i);try{if(await f.picture(),o.length)await f.act(o),await f.picture();return d?.(f),f.shot(u?.({width:f.width,height:f.height}))}finally{f.close()}}function Wd(i,o){let d=Buffer.alloc(8);return d[0]=4,d[1]=o?1:0,d.writeUInt32BE(i,4),d}var Nw={ctrl:65507,control:65507,shift:65505,alt:65513,meta:65515,super:65515,win:65515,cmd:65515},Uw={space:32,enter:65293,return:65293,tab:65289,escape:65307,esc:65307,backspace:65288,delete:65535,insert:65379,home:65360,end:65367,pageup:65365,pagedown:65366,left:65361,up:65362,right:65363,down:65364};function Dw(i){let o=i.split("+");if(i.endsWith("++"))o.splice(-2,2,"+");let d=o.pop()??"",u=Uw[d.toLowerCase()],f=/^f(\d{1,2})$/i.exec(d),p=u??(f?65470+Number(f[1])-1:Qd(d));return[...o.map((h)=>Nw[h.toLowerCase()]??0),p].filter((h)=>h!==0)}function Qd(i){if(i===`
302
+ `||i==="\r")return 65293;if(i==="\t")return 65289;let o=i.codePointAt(0)??32;return o<256?o:16777216+o}function Lw(i,o,d){let u=new Uint8Array(d.width*d.height*4);for(let f=0;f<d.height;f++){let p=((d.y+f)*o+d.x)*4;u.set(i.subarray(p,p+d.width*4),f*d.width*4)}return u}function Yd(i){let o=new Uint8Array(i.length/4*3);for(let d=0,u=0;d<i.length;d+=4,u+=3)o[u]=i[d]??0,o[u+1]=i[d+1]??0,o[u+2]=i[d+2]??0;return o}function Fw(i,o,d,u,f){let p=new Uint8Array(u*f*3);for(let h=0;h<f;h++){let w=Math.floor(h*d/f),y=Math.max(w+1,Math.floor((h+1)*d/f));for(let S=0;S<u;S++){let v=Math.floor(S*o/u),P=Math.max(v+1,Math.floor((S+1)*o/u)),x=0,E=0,I=0;for(let re=w;re<y;re++)for(let C=v;C<P;C++){let B=(re*o+C)*4;x+=i[B]??0,E+=i[B+1]??0,I+=i[B+2]??0}let N=(y-w)*(P-v),W=(h*u+S)*3;p[W]=x/N,p[W+1]=E/N,p[W+2]=I/N}}return p}class tu{chunks=[];length=0;waiting;failed;constructor(i){i.onData((o)=>{this.chunks.push(o),this.length+=o.length,this.settle()}),i.onClose(()=>this.fail(Error("the screen closed the connection")))}read(i){return new Promise((o,d)=>{this.waiting={size:i,resolve:o,reject:d},this.settle()})}fail(i){this.failed??=i,this.settle()}take(i){let o=this.chunks[0];if(o&&o.length>=i){if(this.chunks[0]=o.subarray(i),!this.chunks[0].length)this.chunks.shift();return this.length-=i,o.subarray(0,i)}let d=Buffer.allocUnsafe(i),u=0;while(u<i){let f=this.chunks[0],p=Math.min(f.length,i-u);if(f.copy(d,u,0,p),u+=p,p===f.length)this.chunks.shift();else this.chunks[0]=f.subarray(p)}return this.length-=i,d}settle(){let i=this.waiting;if(!i)return;if(this.length>=i.size)this.waiting=void 0,i.resolve(this.take(i.size));else if(this.failed)this.waiting=void 0,i.reject(this.failed)}}var Gw=15000,Hw=500,Ww=1500,ru=l`
303
+ $ErrorActionPreference = 'Stop'
304
+ Add-Type -TypeDefinition '
305
+ using System;
306
+ using System.ComponentModel;
307
+ using System.Runtime.InteropServices;
308
+ public static class SfLsaSecret {
309
+ [StructLayout(LayoutKind.Sequential)] struct Text { public ushort Length; public ushort MaximumLength; public IntPtr Buffer; }
310
+ [StructLayout(LayoutKind.Sequential)] struct ObjectAttributes { public int Length; public IntPtr RootDirectory; public IntPtr ObjectName; public uint Attributes; public IntPtr SecurityDescriptor; public IntPtr SecurityQualityOfService; }
311
+ [DllImport("advapi32.dll")] static extern uint LsaOpenPolicy(IntPtr system, ref ObjectAttributes attributes, uint access, out IntPtr policy);
312
+ [DllImport("advapi32.dll")] static extern uint LsaStorePrivateData(IntPtr policy, ref Text name, ref Text data);
313
+ [DllImport("advapi32.dll")] static extern uint LsaRetrievePrivateData(IntPtr policy, ref Text name, out IntPtr data);
314
+ [DllImport("advapi32.dll")] static extern uint LsaFreeMemory(IntPtr buffer);
315
+ [DllImport("advapi32.dll")] static extern uint LsaClose(IntPtr policy);
316
+ [DllImport("advapi32.dll")] static extern int LsaNtStatusToWinError(uint status);
317
+ const uint CreateSecret = 0x20, GetPrivateInformation = 0x4, NotFound = 0xC0000034;
318
+ static void Check(uint status) { if (status != 0) throw new Win32Exception(LsaNtStatusToWinError(status)); }
319
+ static Text TextOf(string s) { Text t = new Text(); t.Buffer = Marshal.StringToHGlobalUni(s); t.Length = (ushort)(s.Length * 2); t.MaximumLength = (ushort)(t.Length + 2); return t; }
320
+ static IntPtr Open(uint access) { ObjectAttributes a = new ObjectAttributes(); IntPtr policy; Check(LsaOpenPolicy(IntPtr.Zero, ref a, access, out policy)); return policy; }
321
+ public static void Store(string name, string value) {
322
+ IntPtr policy = Open(CreateSecret); Text key = TextOf(name); Text data = TextOf(value);
323
+ try { Check(LsaStorePrivateData(policy, ref key, ref data)); }
324
+ finally { Marshal.FreeHGlobal(key.Buffer); Marshal.ZeroFreeGlobalAllocUnicode(data.Buffer); LsaClose(policy); }
325
+ }
326
+ public static string Read(string name) {
327
+ IntPtr policy = Open(GetPrivateInformation); Text key = TextOf(name); IntPtr data;
328
+ try {
329
+ uint status = LsaRetrievePrivateData(policy, ref key, out data);
330
+ if (status == NotFound) return null;
331
+ Check(status);
332
+ Text text = (Text)Marshal.PtrToStructure(data, typeof(Text));
333
+ string value = Marshal.PtrToStringUni(text.Buffer, text.Length / 2);
334
+ LsaFreeMemory(data);
335
+ return value;
336
+ } finally { Marshal.FreeHGlobal(key.Buffer); LsaClose(policy); }
337
+ }
338
+ }'
339
+ $winlogon = 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon'
340
+ $w = Get-ItemProperty -LiteralPath $winlogon -ErrorAction SilentlyContinue
341
+ $ours = $w -and $w.DefaultUserName -eq $env:USERNAME
342
+ `,Vw=l`${ru}
343
+ if ($ours) { $p = [SfLsaSecret]::Read('DefaultPassword'); if ($p) { [Console]::Out.Write($p) } }
344
+ `,Yw=l`${ru}
345
+ if ($ours -and $w.DefaultPassword) {
346
+ [SfLsaSecret]::Store('DefaultPassword', $w.DefaultPassword)
347
+ Remove-ItemProperty -LiteralPath $winlogon -Name DefaultPassword
348
+ 'moved'
349
+ }
350
+ `,qw=l`if (Get-Process LogonUI -ErrorAction SilentlyContinue) { 'locked' } else { 'open' }`,hi=(i,o)=>r(Ke).flag("-NoProfile").flag("-NonInteractive").script("-Command",i).by(o).timeoutMs(20000);function Jw(){return{user:jw().username,password:async()=>(await g(hi(Vw,"machine.unlock").build()).catch(()=>{return}))?.stdout||void 0,locked:async()=>(await g(hi(qw,"machine.unlock").build())).stdout.trim()==="locked",wake:[{do:"key",key:"space"}]}}function Kw(i){let o=()=>JSON.parse(Bw(i,"utf8"));return{user:"stand-in",password:async()=>o().password,locked:async()=>!!o().locked,wake:[{do:"key",key:"space"}]}}function bl(i=process.platform){let o=process.env.SUPERFACTORY_E2E_RUN_PID&&process.env.SUPERFACTORY_LOGIN_STAND_IN;if(o)return Kw(o);if(i==="win32")return Jw();if(i==="darwin")return"Superfactory keeps no password for this Mac's account: someone signs in at the Mac, or over Screen Sharing";return"Superfactory keeps no password for this machine's login: its users have none, and its virtual display has no lock"}var zw=300000,tr;async function hm(i=process.platform){if(i!=="win32"||process.env.SUPERFACTORY_E2E_RUN_PID)return;let o=await g(hi(Yw,"machine.login").build()).catch(()=>{return});if(o?.exitCode!==0)s.warn("machine: couldn't check Winlogon for a login password kept in clear (needs the agent elevated)");else if(o.stdout.includes("moved"))s.info("machine: moved the login password Winlogon kept in clear into an LSA secret")}async function yc(){if(tr&&Date.now()<tr.until)return tr.values;let i=bl(),o=typeof i==="string"?void 0:await i.password().catch(()=>{return});return tr={values:o?[o]:[],until:Date.now()+zw},tr.values}async function gm(i,o){if(typeof i==="string")return{unlocked:!1,said:i};if(!await i.locked())return{unlocked:!0,said:"Its screen isn't locked: nothing was typed."};let d=await i.password();if(!d)return{unlocked:!1,said:`Superfactory keeps no password for ${i.user} on this machine: someone has to sign in there.`};let u=await Kn.open(await Pt(await o()));try{if(await u.act([...i.wake,{do:"wait",ms:Ww}]),!await i.locked())return{unlocked:!0,said:"Its screen unlocked: nothing was typed."};await u.act([{do:"type",text:d},{do:"key",key:"enter"}])}finally{u.close()}for(let f=Date.now()+Gw;Date.now()<f;await Bun.sleep(Hw))if(!await i.locked())return s.info(`machine: a lead unlocked the screen with ${i.user}'s kept password`),{unlocked:!0,said:`Unlocked: the agent typed ${i.user}'s kept password on its screen.`};return{unlocked:!1,said:`Still locked after the agent typed ${i.user}'s kept password: it may have changed, or the screen the agent reaches isn't the lock screen (machine_screen shows it).`}}import{createHash as Ly}from"crypto";import{mkdir as on,mkdtemp as _u,readFile as Iu,rm as Tu,writeFile as sn}from"fs/promises";import{homedir as Fy,tmpdir as By}from"os";import{join as Se}from"path";import{createHash as Xw}from"crypto";import{lstat as Qw,mkdir as au,readFile as cu,realpath as nu,writeFile as du}from"fs/promises";import{dirname as ou,join as rr,sep as Zw}from"path";function no(i){return{label:i,dir:i,read:(o)=>ey(i,o),list:async(o)=>{if(!o.length)return[];return(await a(i,(u)=>u.sub("ls-files").flag("-z").endOptions().argsOf(o.map((f)=>`:(glob)${f}`))).catch(()=>"")).split("\x00").filter(Boolean)}}}async function ey(i,o){let d=await nu(i).catch(()=>{return});if(!d)return;let u=rr(d,o);if(!u.startsWith(d+Zw))return;if(await nu(u).catch(()=>{return})!==u)return;if(!(await Qw(u).catch(()=>{return}))?.isFile())return;return cu(u).catch(()=>{return})}async function gi(i,o,d){let u=d.length===64?"sha256":d.length===40?"sha1":void 0;if(!u||!/^[0-9a-f]+$/.test(d))throw Error(`${d} isn't an object id`);let f=Buffer.from(await Ua(r(ye).in(i).env(Qe(await it(i),Number(process.env.GIT_CONFIG_COUNT)||0)).sub("cat-file").arg(o).arg(d).by("project setup").timeoutMs(60000).build()));if(Xw(u).update(`${o} ${f.length}\x00`).update(f).digest("hex")!==d)throw Error(`the ${o} ${d} in ${i} isn't what its id says: it was changed`);return f}function ty(i,o){let d=[],u=0;while(u<i.length){let f=i.indexOf(32,u),p=i.indexOf(0,f);if(f<0||p<0||p+1+o>i.length)throw Error("a tree that can't be read");d.push({mode:i.subarray(u,f).toString("latin1"),name:i.subarray(f+1,p).toString("utf8"),id:i.subarray(p+1,p+1+o).toString("hex")}),u=p+1+o}return d}function ry(i,o,d){let u=o.length/2,f=new Map,p=(y)=>{let S=f.get(y);if(!S)S=gi(i,"tree",y).then((v)=>ty(v,u)),f.set(y,S);return S},h=gi(i,"commit",o).then((y)=>{let S=y.toString("utf8").match(/^tree ([0-9a-f]+)$/m)?.[1];if(!S)throw Error(`the commit ${o} names no tree`);return S}),w;return{label:`${d} at ${o.slice(0,12)}`,read:async(y)=>{let S=await h,v=y.split("/").filter((P)=>P&&P!==".");for(let[P,x]of v.entries()){let E=(await p(S)).find((N)=>N.name===x),I=P===v.length-1;if(!E||(I?!/^100(644|755)$/.test(E.mode):E.mode!=="40000"))return;if(I)return gi(i,"blob",E.id);S=E.id}return},list:async(y)=>{if(!y.length)return[];w??=a(i,(v)=>v.sub("ls-tree").flag("-r").flag("-z").flag("--name-only").arg(o)).then((v)=>v.split("\x00").filter(Boolean));let S=y.map((v)=>new Bun.Glob(v));return(await w).filter((v)=>S.some((P)=>P.match(v)))}}}var yi=new Map,wi=new Map,uu=(i)=>rr(m().home,"project-setups",`${i}.remote`.replace(/[^\w.-]/g,"-"));async function bc(i,o){let d=uu(i),u=(await cu(d,"utf8").catch(()=>"")).trim();if(u)return u;let f=(await a(o,(p)=>p.sub("config").arg("remote.origin.url"),[1]).catch(()=>"")).trim();if(!f)return;return await au(rr(d,".."),{recursive:!0}),await du(d,`${f}
351
+ `,{mode:384}),f}async function ny(i,o,d){let u=await bc(i,o);if(!u){let S=d||await ge(o);return s.warn(`project setup: ${i} has no remote: its setup is read from its local ${S}`),(await a(o,(v)=>v.sub("rev-parse").flag("--verify").arg(`${S}^{commit}`))).trim()}let f=d?`refs/heads/${d.replace(/^origin\//,"")}`:"HEAD",p=ou(uu(i)),w=(await a(p,(S)=>S.sub("ls-remote").arg(u).arg(f).env({GIT_CEILING_DIRECTORIES:ou(p)}),[],{github:await Ds(o)}).catch((S)=>{s.warn(`project setup: ${i}: ${u} can't be asked for ${f}: ${S.message}`);return}))?.match(/^([0-9a-f]{40}|[0-9a-f]{64})\t/m)?.[1]??yi.get(i);if(!w)throw Error(`its default branch couldn't be read from ${u}`);if(!await a(o,(S)=>S.sub("cat-file").arg("commit").arg(w)).then(()=>!0,()=>!1))await a(o,(S)=>S.sub("fetch").flag("-q").arg(u).arg(f));return w}async function kl(i,o,d){let u=wi.get(i);if(!u)u=ny(i,o,d).finally(()=>wi.delete(i)),wi.set(i,u);let f=await u;return yi.set(i,f),ry(o,f,d||"the default branch")}async function wm(i,o,d){if(!await bc(i,o))return;let u=await kl(i,o,d),f=yi.get(i);return f?{commit:f,files:u}:void 0}async function bi(i,o){for(let d of o){if(d.path.split("/").some((f)=>f===".."||f===""))continue;let u=rr(i,d.path);await au(rr(u,".."),{recursive:!0}),await du(u,d.bytes,{mode:493})}}import{createHash as py}from"crypto";import{accessSync as my,constants as hy,existsSync as wu,lstatSync as gy,realpathSync as or,statSync as fu}from"fs";import{chmod as wy,copyFile as yy,mkdir as by,rename as $y,rm as Si,symlink as Sy,writeFile as vy}from"fs/promises";import{userInfo as Py}from"os";import{delimiter as pu,dirname as ir,join as ar,relative as ky}from"path";import{inflateRawSync as xy}from"zlib";import{readdirSync as sy,renameSync as iy,rmSync as lu}from"fs";import{basename as oy,dirname as $i,join as ay}from"path";var cy=new Set(["EBUSY","EPERM","EACCES"]),dy=5,uy=1000;async function kc(i,o){let d=(f,p)=>fy(()=>iy(f,p),`renaming ${f} to ${p}`);if(process.platform!=="win32")return d(o,i);let u=ly(i);await d(i,u);try{await d(o,i)}catch(f){throw await d(u,i).catch((p)=>{throw Error(`${f.message}; then putting ${i} back failed too: ${p.message}`)}),f}}function ly(i){let o=`${i}.old`;try{return lu(o,{force:!0}),o}catch{return`${i}.${Date.now()}.old`}}function Bi(i){let o=oy(i),d=[],u;try{u=sy($i(i))}catch(f){return[`${$i(i)}: ${f.message}`]}for(let f of u.filter((p)=>p.startsWith(`${o}.`)&&p.endsWith(".old")))try{lu(ay($i(i),f),{force:!0})}catch(p){d.push(`${f}: ${p.message}`)}return d}async function fy(i,o){for(let d=1;;d++)try{return i()}catch(u){let f=u.code??"";if(!cy.has(f)||d>=dy)throw Error(`${o} failed${d>1?` ${d} times`:""}: ${u.message}`);await Bun.sleep(uy)}}var Ey=()=>process.env.SUPERFACTORY_BUN_RELEASES||"https://github.com/oven-sh/bun/releases/download",Ry=600000,Oy=600000,sr=(i,o=process.platform)=>o==="win32"?`${i}.exe`:i;function _y(i){if(!i)return;try{let{packageManager:o}=JSON.parse(i);if(typeof o!=="string")return;return/^bun@(\d+\.\d+\.\d+)(?:\+.*)?$/.exec(o.trim())?.[1]}catch{return}}var Iy=["","*/","*/*/"].flatMap((i)=>[`${i}bun.lock`,`${i}bun.lockb`]),vi=new Map;async function $u(i){let o=!i.dir;if(o&&vi.has(i.label))return vi.get(i.label);let d=new Set((await i.list(Iy).catch(()=>[])).map((f)=>f.split("/").slice(0,-1).join("/"))),u;for(let f of d){let p=await i.read(f?`${f}/package.json`:"package.json").catch(()=>{return}),h=_y(p?.toString("utf8"));if(h&&(!u||Bun.semver.order(h,u)>0))u=h}if(o)vi.set(i.label,u);return u}function Ty(i=process.platform,o=process.arch){let d=i==="win32"?"windows":i==="darwin"?"darwin":"linux";if(o==="arm64"){if(d==="linux")return["bun-linux-aarch64","bun-linux-aarch64-musl"];return d==="windows"?["bun-windows-aarch64","bun-windows-x64-baseline"]:[`bun-${d}-aarch64`]}let u=[`bun-${d}-x64`,`bun-${d}-x64-baseline`];return d==="linux"?[...u,"bun-linux-x64-musl","bun-linux-x64-musl-baseline"]:u}async function Pi(i){let o=await g(r(Rd).programPath(i).flag("--version").timeoutMs(30000).build()).catch(()=>{return}),d=o?.exitCode===0?o.stdout.trim():"";return/^\d+\.\d+\.\d+$/.test(d)?d:void 0}var Su=(i,o)=>{let d=ky(i,o);return d!==""&&!d.startsWith("..")&&!d.startsWith("/")&&!/^[a-zA-Z]:/.test(d)},Cy=(i)=>{try{return my(i,hy.W_OK),!0}catch{return!1}},Ay=(i,o)=>ar(i.BUN_INSTALL||ar(o,".bun"),"bin"),My=()=>!!process.env.SF_E2E_RUN_ID;function Ny(i,o,d){if(!My())return;let u=(w)=>{try{return or(w)}catch{return w}},f=u(Py().homedir),p=ar(f,".bun"),h=u(ir(o));if(h===p||Su(p,h)||d&&u(i)===f)throw Error(`a test may not replace the machine's own Bun (${o}): give it a home and BUN_INSTALL of its own`);if(!process.env.SUPERFACTORY_BUN_RELEASES&&!process.env.SUPERFACTORY_E2E_REAL_BUN)throw Error("a test may not download Bun's real releases: set SUPERFACTORY_BUN_RELEASES to a stand-in")}async function mu(){let i=Bun.which("bun",{PATH:process.env.PATH??""});if(!i)return;let o=(()=>{try{return or(i)}catch{return i}})();return{found:i,bin:o,version:await Pi(i)}}function Uy(i,o){let d=new DataView(i.buffer,i.byteOffset,i.byteLength),u=-1;for(let h=i.length-22;h>=Math.max(0,i.length-65557);h--)if(d.getUint32(h,!0)===101010256){u=h;break}if(u<0)throw Error("not a zip file");let f=d.getUint16(u+10,!0),p=d.getUint32(u+16,!0);for(let h=0;h<f;h++){if(d.getUint32(p,!0)!==33639248)throw Error("a broken zip file");let w=d.getUint16(p+10,!0),y=d.getUint32(p+20,!0),S=d.getUint16(p+28,!0),v=d.getUint16(p+30,!0),P=d.getUint16(p+32,!0),x=d.getUint32(p+42,!0),E=new TextDecoder().decode(i.subarray(p+46,p+46+S));if(p+=46+S+v+P,E!==o&&!E.endsWith(`/${o}`))continue;let I=x+30+d.getUint16(x+26,!0)+d.getUint16(x+28,!0),N=i.subarray(I,I+y);if(w===0)return N;if(w===8)return new Uint8Array(xy(N));throw Error(`${E}: compression method ${w} isn't supported`)}return}async function hu(i){let o=await fetch(i,{signal:AbortSignal.timeout(Ry),redirect:"follow"});if(!o.ok)throw Object.assign(Error(`${i}: HTTP ${o.status}`),{status:o.status});return new Uint8Array(await o.arrayBuffer())}class ki{home;constructor(i){this.home=i}installs=new Map;met=new Map;failed=new Map;nothingToDo(i){let o=this.failed.get(i);if(o!==void 0&&Date.now()-o<Oy)return!0;let d=this.met.get(i);if(!d)return!1;let u=Bun.which("bun",{PATH:process.env.PATH??""});try{return!!u&&or(u)===d.bin&&fu(d.bin).mtimeMs===d.mtimeMs}catch{return!1}}ensure(i){let o=this.installs.get(i);if(o)return o;let d=this.once(i).catch((u)=>({kind:"failed",error:u.message})).then((u)=>{if(u.kind==="failed")this.failed.set(i,Date.now());else this.failed.delete(i);return u}).finally(()=>this.installs.delete(i));return this.installs.set(i,d),d}remember(i,o){try{this.met.set(i,{bin:o,mtimeMs:fu(o).mtimeMs})}catch{}}async once(i){let o=await mu();if(o?.version&&Bun.semver.order(o.version,i)>=0)return this.remember(i,o.bin),{kind:"kept",version:o.version};let d=o&&/^bun(\.exe)?$/i.test(o.bin.split(/[\\/]/).pop()??"")&&Su(this.home,o.bin)&&Cy(ir(o.bin)),u=d?o.bin:ar(Ay(process.env,this.home),sr("bun"));Ny(this.home,u,!!d);let f=d?void 0:await Pi(u);if(f&&Bun.semver.order(f,i)>=0)return this.first(i,u,o?.version,f);await by(ir(u),{recursive:!0}),s.info(`bun: ${o?`${o.found} is ${o.version??"a Bun that won't run"}`:"no bun here"}: installing ${i} at ${u}`);let p=`${u}.${process.pid}.new`;try{await this.stage(i,p),Bi(u),await gu(u,p)}finally{await Si(p,{force:!0}).catch(()=>{return})}return await this.bunx(u),this.first(i,u,o?.version,i)}async first(i,o,d,u){let f=Bun.which("bun",{PATH:process.env.PATH??""});if(!f||or(f)!==or(o))Dy(ir(o));let p=await mu();if(p?.version!==u)return{kind:"failed",error:`Bun ${u} is at ${o}, but the PATH finds ${p?`${p.found} (${p.version??"won't run"})`:"no bun"} first`};return this.remember(i,p.bin),s.info(`bun: ${u} at ${o}${d?` (was ${d})`:""}, for a project's pin of ${i}`),{kind:"installed",version:u,bin:o,was:d}}async stage(i,o){let d=`${Ey()}/bun-v${i}`,u=new TextDecoder().decode(await hu(`${d}/SHASUMS256.txt`)),f=[];for(let p of Ty()){let h=new RegExp(`^([0-9a-f]{64})\\s+\\*?${p}\\.zip$`,"m").exec(u)?.[1];if(!h){f.push(`${p}: not in the release`);continue}let w=await hu(`${d}/${p}.zip`);if(py("sha256").update(w).digest("hex")!==h)throw Error(`${p}.zip: its checksum doesn't match SHASUMS256.txt`);let y=Uy(w,sr("bun"));if(!y)throw Error(`${p}.zip has no ${sr("bun")}`);await Si(o,{force:!0}),await vy(o,y,{mode:493}),await wy(o,493);let S=await Pi(o);if(S===i)return;f.push(`${p}: ${S?`says ${S}`:"won't run here"}`)}throw Error(`no Bun ${i} build runs here (${f.join("; ")})`)}async bunx(i){let o=ar(ir(i),sr("bunx"));if((()=>{try{return gy(o).isSymbolicLink()}catch{return!1}})())return;try{if(process.platform!=="win32"&&!wu(o)){await Sy(sr("bun"),o);return}let u=`${o}.${process.pid}.new`;await yy(i,u),Bi(o),await gu(o,u).finally(()=>Si(u,{force:!0}).catch(()=>{return}))}catch(u){s.warn(`bun: couldn't put bunx beside ${i}`,u)}}}var gu=(i,o)=>wu(i)?kc(i,o):$y(o,i);function Dy(i){let o=(u)=>process.platform==="win32"?u.toLowerCase()===i.toLowerCase():u===i,d=(process.env.PATH??"").split(pu).filter((u)=>u&&!o(u));process.env.PATH=[i,...d].join(pu)}var jy={macos:"macOS",linux:"Linux",windows:"Windows"};function Gy(i=process.platform){return i==="darwin"?"macos":i==="win32"?"windows":"linux"}async function vl(i){let o=await Iu(Se(i,me),"utf8").catch(()=>{return});if(o===void 0)return;let d=fo(o);return"file"in d?{file:d.file}:{error:Zl(d.issues)}}async function Cu(i,o){let d=await i.read(me);if(!d)return{kind:"none"};let u=fo(d.toString("utf8"));if(!("file"in u))return{kind:"invalid",error:Zl(u.issues)};let f=u.file.setup?.[o];if(!f)return{kind:"skipped",file:u.file,note:`no ${jy[o]} setup in ${me}`};let p=[{path:me,bytes:d}];for(let h of await Hy(i,f,u.file)){let w=await i.read(h);if(w)p.push({path:h,bytes:w});else if(h===f)return{kind:"invalid",error:`${me}: setup.${o}: ${f} isn't in the repo`}}return{kind:"setup",file:u.file,step:f,hash:Wy(o,p),files:p,source:i}}async function Hy(i,o,d){let u=new Set(typeof o==="string"?[o]:[]);for(let f of await i.list(d.setup?.inputs??[]))u.add(f);return[...u].sort()}function Wy(i,[o,...d]){let u=Ly("sha256").update(`${i}
352
+ `);if(o)u.update(o.bytes);for(let{path:f,bytes:p}of d)u.update(`\x00${f}\x00`),u.update(p);return u.digest("hex").slice(0,16)}function Vy(i,o){if(o==="windows")return typeof i==="string"?{shell:"powershell",code:`& './${i.replaceAll("'","''")}'; $ok = $?; if ($LASTEXITCODE) { exit $LASTEXITCODE }; if (-not $ok) { exit 1 }; exit 0`}:{shell:"powershell",code:i.run};let d='if [ "$SUPERFACTORY_SETUP_SUDO" != 1 ]; then sudo() { echo "superfactory.yaml setup: sudo is off on this machine (its setting machine.setupSudo)" >&2; return 1; }; export -f sudo; fi';if(typeof i!=="string")return{shell:"bash",code:`${d}
353
+ ${i.run}`};let u=`'./${i.replaceAll("'","'\\''")}'`;return{shell:"bash",code:`${d}
354
+ exec bash ${u}`}}var Au=k("SUPERFACTORY_SETUP_RETRY_MS",300000),Pu=k("SUPERFACTORY_SETUP_WAIT_MS",3000),Mu=3600000,Yy=10;class xe extends Error{state;done;place;constructor(i,o){super(`Preparing the machine: ${i.step??"the project's setup"}`);this.state=i;this.done=o}}class ro{changed;sudo;sourceOf;machineSettled;bun;states=new Map;runs=new Map;constructor(i=()=>{return},o=async()=>!1,d=async(p,h)=>no(h),u=async()=>{return},f=new ki(Fy())){this.changed=i;this.sudo=o;this.sourceOf=d;this.machineSettled=u;this.bun=f}list(){return[...this.states.values()]}forget(i){for(let[o,d]of this.states)if(d.sandbox===i)this.states.delete(o);this.changed()}async ensure(i,o,d,u={}){let f=`${i}:${d.sandbox??""}`,p={projectId:i,sandbox:d.sandbox,os:d.os},h=()=>new Date().toISOString(),w=await(async()=>d.sandbox?no(o):await this.sourceOf(i,o))().catch((I)=>I);if(!d.sandbox&&!(w instanceof Error))await this.pinnedBun(f,p,w,()=>this.ensure(i,o,d,u),u.waitMs);let y=await(async()=>{if(w instanceof Error)throw w;return Cu(w,d.os)})().catch((I)=>({kind:"skipped",note:`not run: its files couldn't be read (${I.message.slice(0,500)})`}));if(y.kind==="none"){if(this.states.delete(f))this.changed();return}if(y.kind==="invalid")throw this.set(f,{...p,state:"invalid",error:y.error.slice(0,4000),at:h()}),new c("bad_request",y.error);if(y.kind==="skipped"){if(this.states.get(f)?.note!==y.note)this.set(f,{...p,state:"skipped",note:y.note,at:h()});return this.states.get(f)}let S=this.states.get(f),v=this.runs.get(f);if(!v&&S?.hash===y.hash&&S.state==="ready")return S;let P=Date.now()-Date.parse(S?.at??"")>Au;if(!v&&S?.hash===y.hash&&S.state==="failed"&&!u.retry&&!P)throw new c("conflict",Eu(S));let x=v?.hash===y.hash?v:void 0;if(!x){if((await d.readReady(i)).includes(y.hash)){let I={...p,state:"ready",hash:y.hash,at:h()};if(S?.hash!==y.hash||S.state!=="ready")this.set(f,I);return I}await v?.done,x={hash:y.hash,done:this.runSetup(f,d,y,u.env??{})},this.runs.set(f,x),x.done.finally(()=>{if(this.runs.get(f)===x)this.runs.delete(f)})}let E=await Promise.race([x.done,Bun.sleep(u.waitMs??Pu)]);if(!E)throw new xe(this.states.get(f)??{...p,state:"running",at:h()},x.done);if(E.state==="failed")throw new c("conflict",Eu(E));return E}async pinnedBun(i,o,d,u,f=Pu){let p=await $u(d);if(!p||this.bun.nothingToDo(p))return;let h=this.bun.ensure(p).then((P)=>{if(P.kind==="failed")s.warn(`project setup: ${o.projectId}: Bun ${p} (package.json) not installed: ${P.error}`);return P});if(await Promise.race([h,Bun.sleep(f)]))return;let y=new Date().toISOString(),S=this.set(i,{...o,state:"running",step:`installing Bun ${p} (package.json's packageManager)`,startedAt:y,at:y}),v=h.then(async()=>{if(this.states.get(i)===S)this.states.delete(i);return await u().catch((x)=>x instanceof xe?x.done:{...S,state:"failed",error:x.message})??{...o,state:"ready",at:new Date().toISOString()}});throw new xe(S,v)}async runSetup(i,o,d,u){let f=new Date().toISOString(),p=performance.now(),h=typeof d.step==="string"?d.step:`setup.${o.os}.run`,w={projectId:i.split(":")[0]??"",sandbox:o.sandbox,os:o.os,hash:d.hash};this.set(i,{...w,state:"running",step:h,startedAt:f,at:f});let y=o.sandbox?`in ${o.sandbox}`:"on this machine";s.info(`project setup: ${w.projectId}: running ${h} ${y} from ${d.source.label} (${d.hash})`);let S=Se(m().home,"project-setups",`${w.projectId}${o.sandbox?`-${o.sandbox}`:""}.log`.replace(/[^\w.-]/g,"-")),v="",P=()=>Math.round((performance.now()-p)/100)/10,x;try{if(!o.sandbox)this.set(i,{...w,state:"running",step:"waiting for the machine's own setup",startedAt:f,at:f}),await this.machineSettled().catch(()=>{return}),this.set(i,{...w,state:"running",step:h,startedAt:f,at:new Date().toISOString()});let E=await this.sudo(),{shell:I,code:N}=Vy(d.step,o.os);if(!d.source.dir){let C=Se(m().home,"project-setups","runs");await on(C,{recursive:!0,mode:448}),x=await _u(Se(C,`${w.projectId}-`)),await bi(x,d.files)}let W=await o.run(N,I,{...u,...d.file.env,SUPERFACTORY_SETUP_SUDO:E?"1":"0"},(C)=>{v=(v+C).slice(-200000)},x);if(v=v||`${W.stdout}${W.stderr}`,await Ou(S,v),W.exitCode!==0){let C=W.timedOut?`timed out after ${P()} s`:W.exitCode===Jy?`exited 127, ${Qy(v,d,o)}`:`exited ${W.exitCode}`,B={...w,state:"failed",step:h,error:Ru(h,C,v),startedAt:f,seconds:P(),at:new Date().toISOString()};return s.warn(`project setup: ${w.projectId}: ${h} failed ${y} after ${B.seconds} s (log: ${S})`),this.set(i,B)}let re=await o.readReady(w.projectId);return await o.writeReady(w.projectId,[d.hash,...re.filter((C)=>C!==d.hash)].slice(0,Yy)),s.info(`project setup: ${w.projectId}: ready ${y} in ${P()} s`),this.set(i,{...w,state:"ready",step:h,startedAt:f,seconds:P(),at:new Date().toISOString()})}catch(E){return await Ou(S,v).catch(()=>{return}),this.set(i,{...w,state:"failed",step:h,error:Ru(h,`didn't run: ${E.message}`,v),startedAt:f,seconds:P(),at:new Date().toISOString()})}finally{if(x)await Tu(x,{recursive:!0,force:!0}).catch(()=>{return})}}set(i,o){return this.states.set(i,o),this.changed(),o}}function Eu(i){return`The project's setup (${me}, ${i.os}) failed: ${i.error??"it ended badly"}
355
+ Fix its cause (a fix to ${me} or its script counts for every task once it's on the default branch), then retry: task_start with retrySetup, or Retry in the app. A failure older than ${Math.round(Au/60000)} minutes is retried by itself at the next start.`}var qy=(i,o=20)=>i.trim().split(`
356
+ `).slice(-o).join(`
357
+ `);function Ru(i,o,d){let u=qy(d),f=o.includes("not found")?"":" (no output)";return`${i} ${o}${u?`:
358
+ ${u}`:f}`.slice(-4000)}var Jy=127,Ky=[/(?:^|[\s:])([\w.+-]+): (?:command )?not found\b/m,/env: '?([\w.+-]+)'?: No such file or directory/],zy=new Set("if then else elif while until do ! time sudo env nohup exec command builtin xargs".split(" ")),Xy=new Set("fi for done case esac in function select return exit export local readonly declare typeset set unset shift source . eval cd echo printf read test [ [[ true false trap wait type hash alias umask let break continue pushd popd shopt { }".split(" "));function Qy(i,o,d){for(let f of Ky){let p=f.exec(i)?.[1];if(p)return`command not found: ${p}`}let u=d.sandbox?[]:Zy(o).filter((f)=>!Bun.which(f)).slice(0,5);return u.length?`command not found: ${u.join(", ")} (not on this machine's PATH)`:"a command it runs wasn't found (not on the PATH it runs with)"}function Zy(i){let o=typeof i.step==="string"?i.files.find((p)=>p.path===i.step)?.bytes.toString("utf8")??"":i.step.run,d=new Set,u=/^#!\s*(\S+)(?:\s+(\S+))?/.exec(o);if(u)d.add(u[1]?.endsWith("/env")&&u[2]?u[2]:u[1]??"");let f=new Set([...o.matchAll(/^\s*(?:function\s+)?([\w.-]+)\s*\(\)/gm)].map((p)=>p[1]));for(let p of o.split(`
359
+ `)){if(/^\s*#/.test(p))continue;for(let h of p.split(/&&|\|\||[;|]|\$\(|`/)){let w=h.trim().split(/\s+/);while(w.length&&(/^\w+=/.test(w[0]??"")||zy.has(w[0]??"")))w.shift();let y=w[0]??"";if(/^[A-Za-z][\w.+-]*$/.test(y)&&!Xy.has(y)&&!f.has(y))d.add(y)}}return[...d].filter(Boolean).slice(0,50)}async function Ou(i,o){await on(Se(i,".."),{recursive:!0}),await sn(i,o)}function eb(i,o){return o==="powershell"?r(Ke).flag("-NoProfile").flag("-NonInteractive").flag("-ExecutionPolicy","Bypass").script("-Command",Ye(i)):r(Es).script("-c",Ye(i))}function Hi(i,o=Gy()){let d=Se(m().home,"project-setups"),u=(f)=>Se(d,`${f}.ready`);return{os:o,run:(f,p,h,w,y)=>g(eb(f,p).in(y??i).env(p==="powershell"?{...h,PSExecutionPolicyPreference:"Bypass"}:h).by("project setup").timeoutMs(Mu).maxOutputBytes(67108864).build(),{onStdout:w,onStderr:w}),readReady:async(f)=>(await Iu(u(f),"utf8").catch(()=>"")).split(`
360
+ `).filter(Boolean),writeReady:async(f,p)=>{await on(d,{recursive:!0}),await sn(u(f),`${p.join(`
361
+ `)}
362
+ `)}}}function ym(i,o,d){let u=(f)=>`$HOME/.superfactory/setup-${f}.ready`;return{os:d,sandbox:o,run:(f,p,h,w)=>i.run(["bash","-c",f],{env:h,timeout:Mu,onStdout:w,onStderr:w}),readReady:async(f)=>(await i.run(["sh","-c",`cat "${u(f)}" 2>/dev/null || true`])).stdout.split(`
363
+ `).filter(Boolean),writeReady:async(f,p)=>{await i.run(["sh","-c",`mkdir -p "$HOME/.superfactory" && printf '%s\\n' "$@" > "${u(f)}"`,"sh",...p])}}}var vc=(i,o)=>`superfactory/setup-${i}:${o}`;function bm(i,o,d,u){let f=async()=>{let p=await Cu(no(d),"linux");return p.kind==="setup"?p:void 0};return{os:"linux",sandbox:u,run:async(p,h,w,y)=>{let S=await f();if(!S)return{exitCode:1,stdout:"",stderr:"no Linux setup in superfactory.yaml"};let v=await _u(Se(By(),"sf-setup-image-"));try{await bi(Se(v,"files"),S.files),await on(Se(v,"run"));let P=Object.entries(w).map(([E,I])=>`export ${E}=${Pr(I)}`),x='if [ "$(id -u)" = 0 ] && ! command -v sudo >/dev/null 2>&1; then sudo() { while [ "${1#-}" != "$1" ]; do shift; done; "$@"; }; export -f sudo; fi';return await sn(Se(v,"run","setup.sh"),[...P,x,p,""].join(`
364
+ `)),await sn(Se(v,"run","done.sh"),`mkdir -p "$HOME/.superfactory" && printf '%s\\n' ${Pr(S.hash)} >> "$HOME/.superfactory/setup-${o}.ready"
365
+ `),await i.build(v,vc(o,S.hash),{root:w.SUPERFACTORY_SETUP_SUDO==="1",onOutput:y})}finally{await Tu(v,{recursive:!0,force:!0})}},readReady:async()=>{let p=await f();return p&&await i.has(vc(o,p.hash))?[p.hash]:[]},writeReady:async()=>{return}}}import{randomBytes as mf}from"crypto";import{existsSync as yr,lstatSync as hf,readdirSync as Fo,readFileSync as Nt}from"fs";import{mkdir as ke,rm as Bo}from"fs/promises";import{homedir as Mt,userInfo as No}from"os";import{basename as jo,delimiter as gf,dirname as Fe,isAbsolute as wf,join as j,relative as b$,resolve as _n}from"path";var X=()=>process.env.SUPERFACTORY_NO_ROOT==="1"||!!process.env.SUPERFACTORY_E2E_RUN_PID;import{existsSync as tb,realpathSync as Nu}from"fs";import{homedir as Uu}from"os";var Fu="/dev/disk/by-id/virtio-sfdata",rb=1073741824;async function Sc(i=g){if(!Jn())return[];let o=[],d=await un(i,Uu());if(d&&sb(d.source,Fu))o.push(await Du(i,"data",Uu(),[Lu(d.source)]));let u=await un(i,"/"),f=u?/^(\/dev\/(?:[a-z]+|nvme\d+n\d+))p?(\d+)$/.exec(u.source):null;if(u&&f?.[1]&&f[2])o.push(await Du(i,"root","/",[nb(f[1],f[2]),Lu(u.source)]));return o}function Jn(){if(X())return!1;return process.env.SUPERFACTORY_DISKS_FAKE==="1"||tb(Fu)}async function Du(i,o,d,u){let f=(await un(i,d))?.sizeGb??0;for(let h of u){let w=await i(h.command);if(w.exitCode!==0&&!h.unchanged(w)){let y=`${h.name} failed (${w.exitCode}): ${(w.stderr||w.stdout).trim()}`.slice(0,500);return s.warn(`disks: couldn't grow the ${o} disk: ${y}`),{disk:o,beforeGb:f,afterGb:f,error:y}}}let p=(await un(i,d))?.sizeGb??f;if(p>f)s.info(`disks: the ${o} filesystem grew from ${f} to ${p} GiB`);return{disk:o,beforeGb:f,afterGb:p}}var Lu=(i)=>({name:"resize2fs",command:r(A).flag("-n").wrap(r(yd).arg(i).build()).by("disk grow").timeoutMs(600000).build(),unchanged:()=>!1}),nb=(i,o)=>({name:"growpart",command:r(A).flag("-n").wrap(r(wd).arg(i).arg(o).build()).by("disk grow").timeoutMs(120000).build(),unchanged:(d)=>d.exitCode===1&&/NOCHANGE/.test(d.stdout+d.stderr)});async function un(i,o){let d=await i(r(gd).flag("-n").flag("-b").flag("-o","SOURCE,SIZE").arg(o).by("disk grow").build()),[u,f]=d.stdout.trim().split(/\s+/);if(d.exitCode!==0||!u||!f)return;return{source:u,sizeGb:Math.round(Number(f)/rb*10)/10}}function sb(i,o){if(process.env.SUPERFACTORY_DISKS_FAKE==="1")return!0;try{return Nu(i)===Nu(o)}catch{return!1}}import{randomBytes as ib,timingSafeEqual as ob}from"crypto";import{mkdirSync as ab,rmSync as Gu}from"fs";import{chmod as cb,mkdir as db,writeFile as Bu}from"fs/promises";import{join as Me}from"path";var ub=16,kt=(i)=>Me(i,"secrets.words");class oo{deployCredentials;sessions=new Map;constructor(i){this.deployCredentials=i}started(i,o,d){for(let u of Object.values(o))O(u);this.sessions.set(i,{env:{...o},given:new Set(Object.keys(o)),version:0,runDir:d,words:new Set});try{Gu(kt(d),{recursive:!0,force:!0}),Fm(Me(d,"secrets.version"),"0",z(384))}catch{}}async update(i,o,d=[]){let u=this.sessions.get(i);if(!u)return!1;for(let f of Object.values(o))O(f);if(u.env={...o},u.version+=1,!u.hooked&&!u.spare)u.spare=await this.arm(i,u);if(await de(Me(u.runDir,"secrets.version"),String(u.version),z(384)).catch((f)=>s.warn(`secrets: ${i}'s version file`,f)),d.length)s.info(`secrets: ${i} has new values of ${d.join(", ")}`);return!0}async beforeBash(i){let o=i?this.sessions.get(i):void 0;if(!i||!o||process.platform==="win32")return;if(o.hooked=!0,o.version===0)return;if(o.spare)o.spare=void 0;else await this.arm(i,o)}async beforeTool(i,o){if((await o.json().catch(()=>{return}))?.tool_name==="Bash")await this.beforeBash(i)}async arm(i,o){let d=ib(24).toString("hex");try{ab(kt(o.runDir),{recursive:!0,mode:z(448)}),await Bm(kt(o.runDir),d.slice(0,16),d,z(384))}catch(u){s.warn(`secrets: ${i}'s word file`,u);return}o.words.add(d);for(let u of o.words){if(o.words.size<=ub)break;this.retire(o,u)}return d}retire(i,o){if(i.words.delete(o),i.spare===o)i.spare=void 0;ju(Me(kt(i.runDir),o.slice(0,16)))}now(i){let o=this.sessions.get(i);if(!o)return;return{env:o.env,unset:[...o.given].filter((d)=>!(d in o.env)),version:o.version}}names(i){return Object.keys(this.sessions.get(i)?.env??{})}ended(i){let o=this.sessions.get(i);if(this.sessions.delete(i),o)ju(kt(o.runDir))}async serve(i,o){let d=i?this.now(i):void 0,u=i?this.sessions.get(i):void 0;if(!d||!u)return new Response("unknown session",{status:401});let f=await o.json().catch(()=>({}));if(f?.for!=="exec"&&f?.for!=="deploy"&&f?.for!=="shell")return new Response('say what for: {"for": "exec"} or {"for": "shell", "nonce": \u2026}',{status:400});if(f.for==="deploy"){if(!this.deployCredentials||!i)return new Response("no deploys here",{status:403});try{let p=await this.deployCredentials(i);for(let h of Object.values(p))O(h);return Response.json({...d,env:{...d.env,...p}})}catch(p){return new Response(p.message,{status:403})}}if(f.for==="shell"){let p=f.nonce,h=typeof p==="string"?[...u.words].find((w)=>lb(w,p)):void 0;if(!h)return new Response("only the session's env file loads its secrets into the shell",{status:403});this.retire(u,h)}return Response.json(d)}}function ju(i){try{Gu(i,{recursive:!0,force:!0})}catch(o){s.warn(`secrets: couldn't remove ${i}`,o)}}var lb=(i,o)=>i.length===o.length&&ob(Buffer.from(i),Buffer.from(o)),He=(i)=>`'${i.replaceAll("'","'\\''")}'`;function xi(){let i=Bun.main,d=i.startsWith("/$bunfs/")||i.includes("~BUN")?[process.execPath]:[process.execPath,i];return globalThis.superfactoryCli?[...d,"agent"]:d}var fb=(i)=>`"${i}"`;async function zi(i=m().bin){let o=process.platform==="win32";await db(i,{recursive:!0,mode:448});let d=Me(i,"sf"),u=[...xi(),"sf"],f=o?u.map((p)=>p.replaceAll("\\","/")):u;if(await Bu(d,`#!/bin/sh
366
+ exec ${f.map(He).join(" ")} "$@"
367
+ `,{mode:z(448)}),await cb(d,z(448)),o){await Bu(Me(i,"sf.cmd"),`@${u.map(fb).join(" ")} %*\r
368
+ `);let p=(process.env.PATH??"").split(";").filter(Boolean);if(!p.some((h)=>h.toLowerCase()===i.toLowerCase()))process.env.PATH=[i,...p].join(";")}return d}async function Gi(i,o=m().bin){if(process.platform==="win32")return{SUPERFACTORY_RUN_DIR:i};let d=Me(i,"secrets-env.sh"),u=Me(i,"secrets.version"),f=kt(i),p=`${He(Me(i,"secrets.word."))}$$`,h=["# Superfactory (T-126): sf on the PATH; this session's secrets after one changed. No values here.",`case ":$PATH:" in *:${He(o)}:*) ;; *) PATH=${He(o)}:"$PATH"; export PATH ;; esac`,`if [ -f ${He(u)} ] && [ "$(cat ${He(u)})" != "\${SUPERFACTORY_SECRETS_AT:-0}" ]; then`,` for __sf_word in ${He(f)}/*; do`,` mv "$__sf_word" ${p} 2>/dev/null || continue`,` eval "$(${He(Me(o,"sf"))} secret shell-env < ${p} 2>/dev/null)"`,` rm -f ${p}`," break"," done"," unset __sf_word","fi",""].join(`
369
+ `);return await de(d,h,z(384)),{CLAUDE_ENV_FILE:d,SUPERFACTORY_RUN_DIR:i,SUPERFACTORY_SECRETS_AT:"0"}}import{existsSync as Hu}from"fs";import{mkdir as pb,symlink as mb}from"fs/promises";import{homedir as hb}from"os";import{join as _i}from"path";var lt=(i=process.env)=>i.SUPERFACTORY_CLAUDE_ISOLATED==="1"||i.SUPERFACTORY_SANDBOX==="1",Wi={settingSources:["project","local"],strictMcpConfig:!0};async function qi(i=process.env){let o=m().claude;await pb(o,{recursive:!0,mode:448});let d=_i(i.CLAUDE_CONFIG_DIR||_i(hb(),".claude"),"projects"),u=_i(o,"projects");if(d!==u&&Hu(d)&&!Hu(u))await mb(d,u).catch(()=>{return});return i.CLAUDE_CONFIG_DIR=o,o}import{existsSync as Ju,readdirSync as gb,readFileSync as wb}from"fs";import{mkdir as Ti,readFile as yb,rm as Ku,writeFile as Wu}from"fs/promises";import{homedir as bb}from"os";import{basename as $b,join as cr}from"path";function Zn(){let i=process.env.SUPERFACTORY_SESSION_HOSTS?.toLowerCase();if(i==="0"||i==="off")return!1;if(i==="1"||i==="on")return!0;if(process.platform==="win32")return!1;return!(Ze()==="systemd"&&Xu())}function zu(){return[{file:"/etc/systemd/system/superfactory-agent.service",system:!0},{file:cr(bb(),".config/systemd/user/superfactory-agent.service"),system:!1}].find((o)=>Ju(o.file))}var Vu="keep-sessions.conf",Yu=`# Written by the Superfactory agent (T-281): its sessions' hosts outlive its restart to update (T-230);
370
+ # its stop ends them itself.
371
+ [Service]
372
+ KillMode=process
373
+ `;function Sb(i,o=[]){let d="control-group";for(let u of[i,...o])for(let[,f]of u.matchAll(/^KillMode=(\S*)\s*$/gm))d=f||"control-group";return d!=="process"}var vb={readDir:(i)=>gb(i),readFile:(i)=>wb(i,"utf8"),exists:Ju,killMode:(i)=>{let o=r(jt).sub("show");if(!i.system)o.flag("--user");let d=Ap(o.flag("-p","KillMode").flag("--value").arg($b(i.file)).by("session hosts").timeoutMs(1e4).build()),u=d.stdout.trim();return d.exitCode===0&&/^[a-z-]+$/.test(u)?u:void 0}};function Pb(i,o=vb){let d=`${i.file}.d`;try{let u=o.exists(d)?o.readDir(d).filter((f)=>f.endsWith(".conf")).sort().map((f)=>o.readFile(cr(d,f))):[];return Sb(o.readFile(i.file),u)}catch(u){let f=o.killMode(i);if(!qu)qu=!0,s.warn(`sessions: the agent can't read its unit (${u.message}): ${f?`systemd says KillMode=${f}`:"taken as join.sh writes it, KillMode=process"}. As root: chmod 644 ${i.file}; chmod 755 ${d} (superfactory host does it from SF-467 on)`);return f?f!=="process":!1}}var qu=!1,Yi=!1;function Xu(){let i=zu();if(!i)return!1;let o=Pb(i);if(o&&!Yi)Yi=!0,s.warn(`sessions: ${i.file} ends every process of the agent's service with it, so its sessions (and their background commands) restart with an update`);return o}async function km(){if(process.platform!=="linux"||Ze()!=="systemd")return;let i=process.env.SUPERFACTORY_SESSION_HOSTS?.toLowerCase();if(i==="0"||i==="off")return;let o=zu();if(!o||!Xu())return;let d=cr(`${o.file}.d`,Vu);if(o.system){if(X())return;let u=cr(m().run,Vu);await Ti(m().run,{recursive:!0,mode:448}),await Wu(u,Yu);let f=(p)=>T(r(A).flag("-n").wrap(p).by("session hosts").timeoutMs(60000).build());try{await f(r(vr).flag("-D").flag("-m","0644").argsOf([u,d]).build()),await f(r(jt).sub("daemon-reload").build())}finally{await Ku(u,{force:!0})}}else await Ti(`${o.file}.d`,{recursive:!0}),await Wu(d,Yu),await T(r(jt).sub("daemon-reload").flag("--user").timeoutMs(60000).build());Yi=!1,s.info(`sessions: ${d} keeps the agent's sessions through its restarts from now on`)}function Vi(i){let o=Bun.main,d=o.startsWith("/$bunfs/")||o.includes("~BUN"),u=globalThis.superfactoryCli===!0;if(!d)return r(se).programPath(process.execPath).arg(o).argsOf(u?["agent","session-host",i]:["session-host",i]).build();return r(rt).programPath(process.execPath).sub(u?"agent session-host":"session-host").arg(i).build()}async function vm(){let i=cr(m().run,"hosts");return await Ti(i,{recursive:!0,mode:448}),i}async function Sm(i){await Ce(m().handedOver,JSON.stringify(i))}async function $m(){let i=m().handedOver,o=await yb(i,"utf8").catch(()=>"[]");await Ku(i,{force:!0});try{let d=JSON.parse(o);return Array.isArray(d)?d:[]}catch{return[]}}import{existsSync as Xi,lstatSync as fn,readdirSync as tl,readFileSync as rl,realpathSync as kb,statSync as nl}from"fs";import{chmod as xb,readFile as Eb}from"fs/promises";import{dirname as Qu,isAbsolute as Rb,join as ur,relative as Ob}from"path";var Qi=(i,o=process.getuid?.()??-1)=>({pass:`u:${i}:x`,deny:`u:${i}:-`,shared:`u:${i}:rwX,u:${o}:rwX`,read:`u:${i}:rX`}),ln=(i,o)=>{let d=Ob(i,o);return d===""||!d.startsWith("..")&&!Rb(d)},_b=(i)=>{let o=[...new Set(i)].sort((d,u)=>d.length-u.length);return o.filter((d,u)=>!o.slice(0,u).some((f)=>ln(f,d)))};function pn(i){let o=_b(i.hidden),d=[...i.own],u=[],f,{cwd:p}=i;if(p){let S=i.projects.find((v)=>ln(v,p));if(i.projects.length&&!S)throw Error(`${p} isn't in its project's checkout`);if(S===p)f=p;else d.push({path:p,writable:!0}),u.push(p)}for(let S of i.projects){let v=ur(S,".git");d.push({path:v,writable:!0}),u.push(v)}if(f)d.push({path:f,writable:!0});for(let S of i.readable)d.push({path:S,writable:!1}),u.push(S);let h=d.filter((S,v)=>d.findIndex((P)=>P.path===S.path)===v),w=new Set(h.map((S)=>S.path)),y=new Set;for(let{path:S}of h){let v=o.find((P)=>ln(P,S)&&P!==S);if(!v)continue;for(let P=Qu(S);ln(v,P);P=Qu(P)){if(!w.has(P))y.add(P);if(P===v)break}}return{chain:[...y].sort((S,v)=>S.length-v.length),gates:h,once:u,...f?{root:f}:{}}}function Ib(i){let o=fn(i);if(o.isSymbolicLink()||!o.isDirectory()||kb(i)!==i)throw Error(`session user: ${i} isn't a folder by that name`);if(o.uid!==process.getuid?.())throw Error(`session user: ${i} isn't the agent's`)}var sl=8,Zi=(i)=>Array.from({length:sl},(o,d)=>`${i}-${d+1}`);function nt(i){try{for(let o of rl("/etc/passwd","utf8").split(`
374
+ `)){let[d,,u,f,,p]=o.split(":");if(d===i&&u&&f&&p)return{name:i,uid:Number(u),gid:Number(f),home:p}}}catch{}return}function il(i="/proc/sys/fs/protected_hardlinks"){try{return rl(i,"utf8").trim()==="1"}catch{return!1}}var ol=()=>ur(m().run,"session-acl.json");async function st(){try{let i=JSON.parse(await Eb(ol(),"utf8"));return{done:i.done??[],holders:i.holders??{},users:i.users??{}}}catch{return{done:[],holders:{},users:{}}}}var dr=(i)=>Ce(ol(),JSON.stringify(i));function Zu(i,o){let d;try{d=nl(o,{bigint:!0})}catch{return}if(!d.birthtimeNs)throw Error(`session user: ${o}'s file system keeps no birth time`);return`${i}:${o}@${d.ino}@${d.birthtimeNs}`}var el=Promise.resolve();function mn(i){let o=el.then(i,i);return el=o.catch(()=>{return}),o}function Tb(i,o,d,u=!1){let f=r(Zd).flag("-P");if(u)f.flag("-d");return f.flag(i,o).argsOf(d).by("session user").timeoutMs(600000).build()}async function ue(i,o,d,{defaults:u=!1,quiet:f=!1}={}){let p=d.filter((h)=>Xi(h));for(let h=0;h<p.length;h+=200){let w=await g(Tb(i,o,p.slice(h,h+200),u));if(w.exitCode!==0&&!f)throw Error(`setfacl ${i} ${o} failed: ${w.stderr.trim().slice(0,300)}`)}}function Cb(i){let o=process.getuid?.(),d=[],u=[],f=(h)=>{let w=[];try{w=tl(h)}catch{}for(let y of w){let S=ur(h,y),v;try{v=fn(S)}catch{continue}if(v.uid!==o)continue;if(v.isDirectory())f(S);else if(v.isFile()&&v.nlink===1)d.push(S)}u.push(h)},p=fn(i);if(p.uid!==o)return{files:d,folders:u};if(p.isDirectory())f(i);else if(p.isFile()&&p.nlink===1)d.push(i);return{files:d,folders:u}}async function Ab(i,o){for(let d of o){if(!Xi(d))continue;let{files:u,folders:f}=Cb(d);await ue("-m",i,u,{quiet:!0});for(let p=0;p<f.length;p+=200){let h=f.slice(p,p+200);await ue("-m",i,h,{quiet:!0}),await ue("-m",i,h,{defaults:!0,quiet:!0})}}}function El(i){let o=process.getuid?.();return Ki(i).filter((d)=>{try{let u=fn(d);return u.uid===o&&u.isFile()&&u.nlink===1}catch{return!1}})}function Ki(i){try{return tl(i).map((o)=>ur(i,o))}catch{return[]}}var hn=new Set;function Rl(i,o){return mn(async()=>{let d=await st(),u=d.users[o],f=u&&nt(u.name);if(f)return d.users[o]={name:f.name,at:Date.now()},await dr(d),f;let p=new Set(Object.values(d.users).map((w)=>w.name)),h=Zi(i).filter((w)=>!p.has(w)).map(nt).find((w)=>!!w);if(!h){let w=new Set(Object.values(d.holders).map((v)=>v.user)),y=Object.entries(d.users).filter(([,v])=>!w.has(v.name)).sort(([,v],[,P])=>v.at-P.at)[0],S=y&&nt(y[1].name);if(!y||!S)throw Error(`all ${sl} session users here run another project's sessions: none is free for ${o}`);s.info(`sessions: ${S.name} goes from ${y[0]} to ${o}: emptied first`),await Ub(S),delete d.users[y[0]],h=S}return d.users[o]={name:h.name,at:Date.now()},await dr(d),h})}var Mb=l`kill -KILL -1 2>/dev/null
375
+ true
376
+ `,Nb=l`kill -KILL -1 2>/dev/null
377
+ me=$(id -u)
378
+ chmod -R u+rwX "$HOME" 2>/dev/null
379
+ find "$HOME" -mindepth 1 -delete 2>/dev/null
380
+ for dir in /tmp /var/tmp /dev/shm /run/lock /dev/mqueue; do
381
+ [ -d "$dir" ] || continue
382
+ find "$dir" -xdev -user "$me" -type d -exec chmod u+rwx {} + 2>/dev/null
383
+ find "$dir" -xdev -mindepth 1 -user "$me" -delete 2>/dev/null
384
+ done
385
+ left=$(find "$HOME" -mindepth 1 2>/dev/null | head -1)
386
+ [ -z "$left" ] || { echo "its home still has $left" >&2; exit 1; }
387
+ for dir in /tmp /var/tmp /dev/shm /run/lock /dev/mqueue; do
388
+ [ -d "$dir" ] || continue
389
+ left=$(find "$dir" -xdev -mindepth 1 -user "$me" 2>/dev/null | head -1)
390
+ [ -z "$left" ] || { echo "$dir still has $left" >&2; exit 1; }
391
+ done
392
+ `,Ol=(i,o)=>g(Et(i,r(Vo).script("-c",o).argsOf(["session-user-end"]).build()));async function Ub(i){let o=await Ol(i,Nb);if(o.exitCode!==0)throw Error(`${i.name} couldn't be emptied: ${o.stderr.trim().slice(0,300)}`)}function gn(i,o,d,u){return mn(async()=>{let f=Qi(i),p=d.gates.filter((C)=>Xi(C.path));for(let C of[...d.chain,...p.map((B)=>B.path)])Ib(C);let h=await st();h.holders[o]={user:i,chain:d.chain,gates:p},hn.add(o),await dr(h);let w=Object.values(h.holders).filter((C)=>C.user===i),y=new Set(w.flatMap((C)=>C.gates.filter((B)=>B.writable).map((B)=>B.path))),S=d.chain.filter((C)=>!y.has(C));await ue("-m",f.pass,S),await ue("-m",f.deny,S,{defaults:!0});let v=new Set(h.done),P=(C)=>{let B=Zu(i,C);return!B||!v.has(B)},x=p.filter((C)=>C.path!==d.root&&P(C.path)),E=d.root&&P(d.root)?Ki(d.root).filter((C)=>C!==ur(d.root??"",".superfactory")).map((C)=>({path:C,writable:!0})):[];if(d.root){let C=nl(d.root).mode&4095;if(!(C&512))await xb(d.root,C|512)}if(x.length)s.info(`sessions: giving ${x.map((C)=>C.path).join(", ")} to ${i} (once)`);for(let C of[!0,!1])await Ab(C?f.shared:f.read,[...x,...E].filter((B)=>B.writable===C).map((B)=>B.path));await ue("-m",f.read,p.filter((C)=>!C.writable).flatMap((C)=>El(C.path)),{quiet:!0});for(let C of[!0,!1]){let B=p.filter((Dt)=>Dt.writable===C).map((Dt)=>Dt.path),fe=C?f.shared:f.read;await ue("-m",fe,B),await ue("-m",fe,B,{defaults:!0})}let I=new Set([...w.flatMap((C)=>[...C.chain,...C.gates.map((B)=>B.path)]),...u]),N=S.flatMap(Ki).filter((C)=>!I.has(C));await ue("-m",f.deny,N,{quiet:!0});let W=[...x.map((C)=>C.path),...E.length&&d.root?[d.root]:[]].map((C)=>Zu(i,C)).filter((C)=>!!C),re=await st();re.done=[...new Set([...re.done,...W])],await dr(re)})}async function eo(i,o){let d=r(Vo).script("-c",Db).argsOf(["session-reach",o]).build(),u=await g(Et(i,d));if(u.exitCode===0)return;return u.stdout.trim().split(`
393
+ `)[0]||`${o} (${u.stderr.trim().slice(0,200)})`}var Db=l`p=$1
394
+ d=
395
+ set -f
396
+ IFS=/
397
+ for part in \${p#/}; do
398
+ d="$d/$part"
399
+ [ "$d" = "$p" ] && break
400
+ [ -x "$d" ] || { echo "$d"; exit 1; }
401
+ done
402
+ [ -x "$p" ] || { echo "$p"; exit 1; }
403
+ `;function Il(i){return mn(async()=>{let o=await st(),d=Object.values(o.holders).filter((w)=>w.user===i),u=Qi(i),f=new Set(d.flatMap((w)=>w.gates.filter((y)=>y.writable).map((y)=>y.path))),p=[...new Set(d.flatMap((w)=>w.chain))].filter((w)=>!f.has(w)),h=[...new Set(d.flatMap((w)=>w.gates.filter((y)=>!y.writable).map((y)=>y.path)))];await ue("-m",u.pass,p),await ue("-m",u.read,h),await ue("-m",u.read,h.flatMap(El),{quiet:!0})})}function xt(i,{kill:o=!0}={}){return mn(async()=>{let d=await st(),u=d.holders[i];if(delete d.holders[i],hn.delete(i),!u)return;let f=Qi(u.user),p=Object.values(d.holders).filter((P)=>P.user===u.user),h=new Set(p.flatMap((P)=>P.gates.map((x)=>x.path))),w=new Set(p.flatMap((P)=>P.chain)),y=u.gates.map((P)=>P.path).filter((P)=>!h.has(P));await ue("-m",f.deny,y.filter((P)=>!w.has(P)),{quiet:!0}),await ue("-m",f.pass,y.filter((P)=>w.has(P)),{quiet:!0}),await ue("-m",f.deny,y.filter((P)=>w.has(P)),{defaults:!0,quiet:!0});let S=u.chain.filter((P)=>!w.has(P)&&!h.has(P));await ue("-m",f.deny,S,{quiet:!0}),await dr(d);let v=nt(u.user);if(o&&!p.length&&v){if((await Ol(v,Mb)).exitCode!==0)s.warn(`sessions: couldn't end what ${v.name} left running`)}})}var Cl=(i)=>hn.add(i);async function Al(i){let o=(await st()).holders[i]?.user;return o?nt(o):void 0}async function lo(){let i=await st();for(let o of Object.keys(i.holders))if(!hn.has(o))await xt(o)}var Lb=l`umask 002
404
+ if [ -n "$1" ]; then
405
+ mkdir -p "$HOME/.claude"
406
+ [ -L "$HOME/.claude/projects" ] || rm -rf "$HOME/.claude/projects"
407
+ ln -sfn "$1" "$HOME/.claude/projects"
408
+ fi
409
+ shift
410
+ exec "$@"
411
+ `;function Et(i,o,d={}){let u={HOME:i.home,PATH:process.env.PATH??"/usr/bin:/bin",USER:i.name,LOGNAME:i.name,...d.env},f=r(Vo).script("-c",Lb).argsOf(["session-user",d.claudeProjects??""]).wrap(o).build(),p=r(Qt).flag("-i");if(d.cwd)p.flag("--chdir",d.cwd);let h=p.argsOf(Object.entries(u).map(([w,y])=>`${w}=${y}`)).wrap(f).build();return r(A).flag("-n").flag("-u",i.name).wrap(r(qo).flag("--no-new-privs").wrap(h).build()).by("session user").timeoutMs(o.timeoutMs).build()}import{existsSync as lr,lstatSync as Dl,readdirSync as Fb,realpathSync as Bb,statSync as jb}from"fs";import{readFile as Gb,rm as Hb}from"fs/promises";import{userInfo as Wb}from"os";import{dirname as yn,isAbsolute as Vb,join as fr,relative as Yb}from"path";var wn="read,write,execute,delete,append,readattr,writeattr,readextattr,writeextattr,readsecurity,delete_child",po="read,execute,readattr,readextattr,readsecurity",Ml="read,write,execute,delete,append,writeattr,writeextattr",mo="write,append,delete,writeattr,writeextattr,writesecurity,chown,delete_child",Oe="file_inherit,directory_inherit";function qb(i,o){return{pass:`group:${i} allow search`,denyNew:`group:${i} deny ${Ml},${Oe},only_inherit,limit_inherit`,deny:`group:${i} deny ${Ml}`,shared:`group:${i} allow ${wn},${Oe}`,agent:`user:${o} allow ${wn},${Oe}`,sharedInside:`group:${i} allow ${wn},${Oe},only_inherit`,readInside:`group:${i} allow ${po},${Oe},only_inherit`,sharedNow:`group:${i} allow ${wn},${Oe}`,readNow:`group:${i} allow ${po},${Oe}`,read:`group:${i} allow ${po},${Oe}`,registry:`group:${i} allow search,add_file,delete_child`,keepEntries:`group:${i} deny add_file,add_subdirectory,delete_child`,readOnly:`group:${i} deny ${mo},${Oe}`,readOnlyNew:`group:${i} deny ${mo},${Oe},only_inherit`,readOnlyNewHere:`group:${i} deny ${mo},${Oe},only_inherit,limit_inherit`}}var wo=(i,o)=>`user:${i} allow ${o?"list,add_file,search,delete_child,add_subdirectory,readattr,writeattr,readextattr,writeextattr,readsecurity":"list,search,readattr,readextattr,readsecurity"}`,Rt=(i,o)=>{let d=Yb(i,o);return d===""||!d.startsWith("..")&&!Vb(d)};function we(i){try{return Bb(i)}catch{return i}}function go(i){let o=[...new Set(i)].sort((d,u)=>d.length-u.length);return o.filter((d,u)=>!o.slice(0,u).some((f)=>Rt(f,d)))}function bn(i){let o=go(i.hidden.map(we)),d=(v)=>o.some((P)=>Rt(P,v)),u=go(i.shared.map(we)),f=(v)=>u.some((P)=>Rt(P,v)),p=i.own.map((v)=>({...v,path:we(v.path)})).filter((v,P,x)=>x.findIndex((E)=>E.path===v.path)===P),h=go(i.readable.map(we)).filter((v)=>d(v)&&!f(v)),w=[...p.map((v)=>v.path),...u,...h],y=new Set;for(let v of w){let P=o.find((x)=>Rt(x,v));if(!P)continue;for(let x=yn(v);Rt(P,x);x=yn(x))if(y.add(x),x===P)break}let S=new Set(w);return{chain:[...y].filter((v)=>!S.has(v)).sort((v,P)=>v.length-P.length),own:p,shared:u,readable:h,closed:(i.closed??[]).map(({checkout:v,open:P})=>({checkout:we(v),open:P.map(we)})),leadsClaude:i.leadsClaude?we(i.leadsClaude):void 0}}var bo=()=>fr(m().run,"session-users.json");async function Ll(){try{let i=JSON.parse(await Gb(bo(),"utf8"));return{done:i.done??[],given:i.given??[],users:i.users??{}}}catch{return{done:[],given:[],users:{}}}}function Ne(i){try{return`${i}@${jb(i).ino}`}catch{return i}}var Nl=Promise.resolve();function Fl(i){let o=Nl.then(i,i);return Nl=o.catch(()=>{return}),o}async function K(i,o,d,{recursive:u=!1,quiet:f=i==="-a"}={}){let p=d.filter((h)=>lr(h));for(let h=0;h<p.length;h+=200){let w=r(Jd);if(u)w.flag("-R");let y=await g(w.flag(i,o).argsOf(p.slice(h,h+200)).by("session user").timeoutMs(600000).build());if(y.exitCode!==0&&!f)s.warn(`sessions: chmod ${i} "${o}" didn't for all: ${y.stderr.trim().slice(0,300)}`)}}function at(i){try{return Fb(i).map((o)=>fr(i,o))}catch{return[]}}function $n(i,o,d){return Fl(async()=>{let u=qb(i.group,i.agent),f=await Ll();await Bl(o,f.users[o]??[]);let p=d.own.map((E)=>E.path),h=new Set([...Object.values(f.users).flat(),...p]);await K("+a",u.pass,d.chain),await K("+a",u.denyNew,d.chain);let w=[...d.chain,...d.shared,...d.readable],y=new Set([...w,...p]),S=new Set([...y,...f.given,...h]),v=d.chain.flatMap(at).filter((E)=>!S.has(E));await K("+a",u.deny,v),await K("-a",u.deny,[...y]);let P=d.shared.filter((E)=>!f.done.includes(Ne(E)));if(P.length){s.info(`sessions: sharing ${P.join(", ")} with the task sessions' users (once)`);let E=P.flatMap(at);await K("+a",u.shared,E,{recursive:!0}),await K("+a",u.agent,E,{recursive:!0}),await K("+a",u.shared,P),await K("+a",u.agent,P)}let x=new Set([...f.done,...P.map(Ne)]);for(let E of d.closed)await Jb(i.group,u,E,x);if(d.leadsClaude)await Xb(u,d.leadsClaude,x);for(let E of[!0,!1]){let I=d.own.filter((W)=>W.writable===E).map((W)=>W.path);if(!I.length)continue;let N=I.flatMap(at);await K("+a",E?u.sharedNow:u.readNow,N,{recursive:!0,quiet:!0}),await K("+a",u.agent,N,{recursive:!0,quiet:!0}),await K("+a",E?u.sharedInside:u.readInside,I),await K("+a",u.agent,I),await K("+a",wo(o,E),I)}await K("+a",u.read,d.readable),await Ce(bo(),JSON.stringify({done:[...x],given:[...new Set([...f.given,...w])],users:{...f.users,[o]:p}}))})}async function Jb(i,o,d,u){let{checkout:f}=d,p=fr(f,".git","worktrees"),h=[...d.open,p],w=new Set;for(let I of h)for(let N=yn(I);Rt(f,N);N=yn(N))if(w.add(N),N===f)break;let y=`closed:${Ne(f)}`;if(!u.has(y)){s.info(`sessions: closing ${f} to the task sessions' users but for its worktrees (once)`);let I=[...w].flatMap(at).filter((N)=>!w.has(N)&&!h.includes(N));await K("+a",o.readOnly,I,{recursive:!0}),await K("+a",o.keepEntries,[...w]),await K("+a",o.readOnlyNew,[f]),await K("+a",o.readOnlyNewHere,[...w].filter((N)=>N!==f)),u.add(y)}let S=`owned:${Ne(f)}`;if(!u.has(S)){let I=await Ul(i,[f],h);await K("+a",o.readOnly,I.filter((N)=>!w.has(N))),u.add(S)}for(let I of h.filter((N)=>!u.has(Ne(N))))await K("+a",o.shared,[I]),await K("+a",o.agent,[I]),u.add(Ne(I));let v=`keep:${Ne(p)}`;if(lr(p)&&!u.has(v))await K("+a",o.keepEntries,[p]),u.add(v);let P=at(p).flatMap((I)=>["commondir","gitdir"].map((N)=>fr(I,N))),x=process.getuid?.(),E=P.filter((I)=>{let N=Dl(I,{throwIfNoEntry:!1});return N&&N.uid!==x});if(E.length)await K("+a",o.readOnly,await Ul(i,E,[]));for(let I of P.filter((N)=>lr(N)&&!u.has(`ro:${Ne(N)}`)))await K("+a",o.readOnly,[I]),u.add(`ro:${Ne(I)}`)}var Kb=`use strict; use warnings;
412
+ use Fcntl qw(O_RDONLY O_NOFOLLOW O_NONBLOCK :mode);
413
+ my ($agent, @uids) = @ARGV;
414
+ my %pool = map { $_ => 1 } grep { /^[0-9]+$/ && $_ >= 470 } @uids;
415
+ my $symlink = eval { Fcntl::O_SYMLINK() } // 0x200000;
416
+ local $/ = "\\0";
417
+ my $bad;
418
+ while (my $path = <STDIN>) {
419
+ chomp $path;
420
+ my @at = lstat $path or next;
421
+ my $flags = S_ISLNK($at[2]) ? O_RDONLY | $symlink : O_RDONLY | O_NOFOLLOW | O_NONBLOCK;
422
+ my $fh;
423
+ unless (sysopen $fh, $path, $flags) { $bad //= $path; next; }
424
+ my @was = stat $fh;
425
+ my $ok = sub { $pool{$_[4]} && (S_ISDIR($_[2]) || S_ISLNK($_[2]) || (S_ISREG($_[2]) && $_[3] == 1)) };
426
+ # The inode it opened is the one it saw at that name, a pool user's of one name then and now.
427
+ my $same = $was[0] == $at[0] && $was[1] == $at[1];
428
+ unless ($same && $ok->(@at) && $ok->(@was) && chown($agent, -1, $fh)) { $bad //= $path; close $fh; next; }
429
+ my @now = stat $fh;
430
+ $bad //= $path if $now[4] != $agent || (S_ISREG($now[2]) && $now[3] != 1);
431
+ print $path, "\\0";
432
+ close $fh;
433
+ }
434
+ if (defined $bad) {
435
+ print STDERR "session user: $bad changed while it was taken (another owner or kind, or more than one link): the checkout isn't closed\\n";
436
+ exit 1;
437
+ }
438
+ `,zb=l`set -eu
439
+ PATH=/usr/bin:/bin:/usr/sbin:/sbin
440
+ agent=$1 group=$2 count=$3
441
+ shift 3
442
+ gid=$(dscl . -read "/Groups/$group" PrimaryGroupID | awk '{ print $2 }')
443
+ case $gid in ''|0|*[!0-9]*) echo "session user: there is no group $group" >&2; exit 1 ;; esac
444
+ uids=$(dscl . -list /Users PrimaryGroupID | awk -v g="$gid" '$2 == g { print $1 }' |
445
+ while read -r name; do dscl . -read "/Users/$name" UniqueID | awk '{ print $2 }'; done)
446
+ total=$# i=0
447
+ for p in "$@"; do
448
+ i=$((i + 1))
449
+ if [ "$i" -le "$count" ]; then set -- "$@" "$p"; else set -- "$@" -path "$p" -prune -o; fi
450
+ done
451
+ shift "$total"
452
+ set -- "$@" "("
453
+ for uid in $uids; do
454
+ case $uid in ''|0|*[!0-9]*) continue ;; esac
455
+ [ "$uid" -ge 470 ] || continue
456
+ set -- "$@" -uid "$uid" -o
457
+ done
458
+ set -- "$@" -false ")"
459
+ auid=$(id -u "$agent")
460
+ listed=$(mktemp -t sf-own)
461
+ taken=$(mktemp -t sf-own)
462
+ trap 'rm -f "$listed" "$taken"' EXIT
463
+ find -P "$@" "(" -type d -o -type l -o "(" -type f -links 1 ")" ")" -print0 >"$listed"
464
+ /usr/bin/perl -e ${Kb} -- "$auid" $uids <"$listed" >"$taken"
465
+ left=$(find -P "$@" -print | head -n 1)
466
+ [ -z "$left" ] || { echo "session user: $left is still a session user's (a file with more than one link, or not a file, folder or link): the checkout isn't closed" >&2; exit 1; }
467
+ cat "$taken"
468
+ `;async function Ul(i,o,d){let u=o.filter((p)=>lr(p));if(!u.length)return[];let f=await g(r(A).flag("-n").wrap(r(Sr).script("-c",zb).argsOf(["mac-own",pr(),i,u.length,...u,...d]).build()).by("session user").timeoutMs(1800000).build());if(f.exitCode!==0)throw Error(`the sessions' files in ${u[0]} couldn't be made the agent's: ${(f.stderr||f.stdout).trim().slice(0,300)}`);return f.stdout.split("\x00").filter(Boolean)}async function Xb(i,o,d){let u=`closed:${Ne(o)}`;if(d.has(u)||!lr(o))return;let f=fr(o,"sessions");await K("-a",i.shared,[o]),await K("-a",i.registry,[f]);for(let p of[...at(o),...at(f)])if(Dl(p,{throwIfNoEntry:!1})?.uid!==process.getuid?.())await Hb(p,{recursive:!0,force:!0}).catch((h)=>s.warn(`sessions: couldn't remove ${p}, a session user's, from the leads' Claude folder`,h));d.add(u)}function $o(i){return Fl(async()=>{let o=await Ll();await Bl(i,o.users[i]??[]),delete o.users[i],await Ce(bo(),JSON.stringify(o))})}async function Bl(i,o){if(!o.length)return;await K("-a",wo(i,!0),o),await K("-a",wo(i,!1),o)}var Qb=l`set -eu
469
+ group=$1
470
+ shift
471
+ base=/Users/$group
472
+ made=
473
+ free_id() {
474
+ used=$( { dscl . -list /Users UniqueID; dscl . -list /Groups PrimaryGroupID; } | awk '{ print $2 }')
475
+ id=470
476
+ while printf '%s\\n' "$used" | grep -qx "$id"; do id=$((id + 1)); done
477
+ echo "$id"
478
+ }
479
+ gid=$(dscl . -read "/Groups/$group" PrimaryGroupID 2>/dev/null | awk '{ print $2 }')
480
+ if [ -z "$gid" ]; then
481
+ gid=$(free_id)
482
+ dscl . -create "/Groups/$group" PrimaryGroupID "$gid"
483
+ dscl . -create "/Groups/$group" RealName "Superfactory task sessions"
484
+ dscl . -create "/Groups/$group" Password '*'
485
+ made=1
486
+ fi
487
+ # Root's, never theirs to write: each user's home is in it, its own.
488
+ install -d -m 755 -o root -g wheel "$base"
489
+ chown root:wheel "$base"
490
+ chmod 755 "$base"
491
+ for name in "$@"; do
492
+ uid=$(dscl . -read "/Users/$name" UniqueID 2>/dev/null | awk '{ print $2 }')
493
+ if [ -z "$uid" ]; then
494
+ uid=$(free_id)
495
+ dscl . -create "/Users/$name"
496
+ dscl . -create "/Users/$name" UniqueID "$uid"
497
+ dscl . -create "/Users/$name" PrimaryGroupID "$gid"
498
+ dscl . -create "/Users/$name" UserShell /usr/bin/false
499
+ dscl . -create "/Users/$name" RealName "Superfactory task session"
500
+ dscl . -create "/Users/$name" IsHidden 1
501
+ dscl . -create "/Users/$name" Password '*'
502
+ made=1
503
+ fi
504
+ dscl . -create "/Users/$name" NFSHomeDirectory "$base/$name"
505
+ [ "$(dscl . -read "/Users/$name" PrimaryGroupID | awk '{ print $2 }')" = "$gid" ] ||
506
+ { echo "session user: $name isn't in $group" >&2; exit 1; }
507
+ if dsmemberutil checkmembership -U "$name" -G admin | grep -q 'is a member'; then
508
+ echo "session user: $name is an admin" >&2; exit 1
509
+ fi
510
+ printf 'user %s %s\\n' "$name" "$uid"
511
+ done
512
+ # The kernel checks access entries by the users' ids as the directory service last told it: a user
513
+ # made again with an earlier one's uid must not pass for it.
514
+ if [ -n "$made" ]; then dsmemberutil flushcache; fi
515
+ printf 'group %s %s\\n' "$group" "$gid"
516
+ `,Zb=l`set -eu
517
+ name=$1 uid=$2 home=$3 path=$4 tmp=$5 dir=$6 projects=$7
518
+ shift 7
519
+ case $uid in ''|0|*[!0-9]*) echo "session user: no uid for $name" >&2; exit 1 ;; esac
520
+ cd /
521
+ exec /bin/launchctl asuser "$uid" /usr/bin/sudo -u "$name" -- /usr/bin/env -i HOME="$home" PATH="$path" \\
522
+ USER="$name" LOGNAME="$name" SHELL=/bin/zsh TMPDIR="$tmp" \\
523
+ /bin/sh -c 'cd "$1" || exit 1
524
+ if [ -n "$2" ]; then
525
+ mkdir -p "$HOME/.claude"
526
+ [ -L "$HOME/.claude/projects" ] || rm -rf "$HOME/.claude/projects"
527
+ ln -sfn "$2" "$HOME/.claude/projects"
528
+ fi
529
+ shift 2; umask 002; exec "$@"' sh "$dir" "$projects" "$@"
530
+ `,e$=l`set -eu
531
+ group=$1 name=$2 uid=$3
532
+ bad() { echo "session user: $1" >&2; exit 1; }
533
+ case $uid in ''|0|*[!0-9]*) bad "no uid for $name" ;; esac
534
+ case $group in ''|-*|*[!a-z0-9_-]*) bad "not a pool: $group" ;; esac
535
+ n=$(awk -v n="$name" -v g="$group-" 'BEGIN { if (index(n, g) == 1) print substr(n, length(g) + 1) }')
536
+ case $n in ''|*[!0-9]*) bad "not a pool user: $name" ;; esac
537
+ [ "$(dscl . -read "/Users/$name" UniqueID | awk '{ print $2 }')" = "$uid" ] ||
538
+ bad "$name isn't uid $uid"
539
+ home=/Users/$group/$name
540
+ /usr/bin/pkill -9 -U "$uid" || true
541
+ i=0
542
+ while /usr/bin/pgrep -U "$uid" >/dev/null && [ $i -lt 50 ]; do sleep 0.1; i=$((i + 1)); done
543
+ if [ -e "$home" ] || [ -L "$home" ]; then
544
+ /usr/bin/chflags -R -P nouchg,nouappnd "$home" 2>/dev/null || true
545
+ rm -rf "$home"
546
+ fi
547
+ [ ! -e "$home" ] || bad "$home couldn't be emptied"
548
+ install -d -m 700 -o "$name" -g "$group" "$home"
549
+ printf '[safe]\\n\\tdirectory = *\\n' >"$home/.gitconfig"
550
+ printf '[install]\\nbackend = "clonefile_each_dir"\\n' >"$home/.bunfig.toml"
551
+ chown root:wheel "$home/.gitconfig" "$home/.bunfig.toml"
552
+ chmod 644 "$home/.gitconfig" "$home/.bunfig.toml"
553
+ `,t$=(i,o)=>`/Users/${i}/${o}`;async function So(i,o){let d=await g(r(A).flag("-n").wrap(r(Sr).script("-c",Qb).argsOf(["mac-users",i,...o]).build()).by("session user").timeoutMs(60000).build());if(d.exitCode!==0)throw Error(`couldn't make ${i}'s users: ${(d.stderr||d.stdout).trim().slice(0,300)}`);let u=-1,f=[];for(let p of d.stdout.trim().split(`
554
+ `)){let[h,w,y]=p.split(" ");if(h==="group")u=Number(y);else if(h==="user"&&w)f.push({name:w,uid:Number(y),gid:-1,home:t$(i,w),group:i})}if(u<0)throw Error(`couldn't make the group ${i}`);return{gid:u,users:f.map((p)=>({...p,gid:u}))}}function Sn(i,o,{cwd:d="/",tmp:u="/private/tmp",claudeProjects:f=""}={}){let p=r(Sr).script("-c",Zb).argsOf(["mac-session",i.name,i.uid,i.home,process.env.PATH??"/usr/bin:/bin:/usr/sbin:/sbin",u,d,f]).wrap(o).build();return r(A).flag("-n").wrap(p).by("session user").timeoutMs(o.timeoutMs).build()}async function vn(i){let o=await g(r(A).flag("-n").wrap(r(Sr).script("-c",e$).argsOf(["mac-home",i.group,i.name,i.uid]).build()).by("session user").timeoutMs(120000).build());if(o.exitCode!==0)throw Error(`couldn't empty ${i.name}'s home: ${(o.stderr||o.stdout).trim().slice(0,300)}`)}async function jl(i){return(await g(r($r).flag("-U",i.uid).timeoutMs(1e4).build())).exitCode===0}function Gl(i,o,d,u,f){let p=r(Qt).argsOf(Object.entries(d).map(([h,w])=>`${h}=${w}`)).wrap(u).timeoutMs(u.timeoutMs).build();return Sn(i,p,{cwd:o,tmp:f})}var pr=()=>Wb().username;import{copyFile as r$,mkdir as _t,readdir as n$,readFile as s$,rename as i$,rm as Po,stat as hr,symlink as o$}from"fs/promises";import{userInfo as Hl}from"os";import{dirname as zl,join as Q}from"path";import{Readable as a$}from"stream";var Wl="\\Superfactory\\",Pn={system:"S-1-5-18",administrators:"S-1-5-32-544",ownerRights:"S-1-3-4",creatorOwner:"S-1-3-0"},ct=(i)=>Q(m().run,"session-users",i),Xl=(i)=>Q(ct(i),"spec.json"),Ql=(i)=>Q(ct(i),"host.log"),c$=Vi;function Vl(i){if(i.includes('"'))throw Error(`a session host's command can't have a quote: ${i}`);return`"${i}"`}function d$(i){let o=c$(Xl(i));return{execute:"cmd.exe",arguments:`/d /s /c "${[o.program,...o.argv].map(Vl).join(" ")} 2>>${Vl(Ql(i))}"`}}var u$=l`
555
+ $ErrorActionPreference = 'Stop'
556
+ $group = $env:SF_SESSION_GROUP
557
+ $users = @(ConvertFrom-Json $env:SF_SESSION_USERS)
558
+ $taskPath = $env:SF_SESSION_TASK_PATH
559
+ function New-Secret {
560
+ $bytes = New-Object byte[] 24
561
+ [Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
562
+ 'Sf1!' + [Convert]::ToBase64String($bytes)
563
+ }
564
+ $made = Get-LocalGroup -Name $group -ErrorAction SilentlyContinue
565
+ if (-not $made) { $made = New-LocalGroup -Name $group -Description 'Superfactory task sessions' }
566
+ $groupSid = $made.SID.Value
567
+ # Its logon rights: a batch job's only.
568
+ $rights = @{
569
+ SeBatchLogonRight = $true
570
+ SeDenyInteractiveLogonRight = $true
571
+ SeDenyRemoteInteractiveLogonRight = $true
572
+ SeDenyNetworkLogonRight = $true
573
+ }
574
+ $dir = Join-Path $env:TEMP ('sf-rights-' + [guid]::NewGuid().ToString('N'))
575
+ New-Item -ItemType Directory $dir | Out-Null
576
+ try {
577
+ $nowFile = Join-Path $dir 'now.inf'
578
+ secedit /export /cfg $nowFile /areas USER_RIGHTS | Out-Null
579
+ $now = Get-Content $nowFile
580
+ $lines = @()
581
+ foreach ($right in $rights.Keys) {
582
+ $line = $now | Where-Object { $_.Split('=')[0].Trim() -eq $right } | Select-Object -First 1
583
+ $ids = @()
584
+ if ($line) { $ids = @(($line -split '=', 2)[1].Trim() -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ }) }
585
+ $names = @($ids | ForEach-Object { $_.TrimStart('*') })
586
+ if ($names -notcontains $groupSid -and $names -notcontains $group) { $lines += "$right = $((@($ids) + "*$groupSid") -join ',')" }
587
+ }
588
+ if ($lines.Count) {
589
+ $text = @('[Unicode]', 'Unicode=yes', '[Version]', 'signature="$CHICAGO$"', 'Revision=1', '[Privilege Rights]') + $lines
590
+ $wantFile = Join-Path $dir 'want.inf'
591
+ Set-Content $wantFile $text -Encoding Unicode
592
+ secedit /configure /db (Join-Path $dir 'want.sdb') /cfg $wantFile /areas USER_RIGHTS /quiet | Out-Null
593
+ if ($LASTEXITCODE -ne 0) { throw "secedit couldn't give $group its logon rights ($LASTEXITCODE)" }
594
+ }
595
+ } finally { Remove-Item -Recurse -Force $dir -ErrorAction SilentlyContinue }
596
+ $hidden = 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList'
597
+ if (-not (Test-Path $hidden)) { New-Item -Path $hidden -Force | Out-Null }
598
+ $admins = @()
599
+ try { $admins = @(Get-LocalGroupMember -SID 'S-1-5-32-544' | ForEach-Object { $_.SID.Value }) }
600
+ catch { $admins = @(([ADSI]'WinNT://./Administrators,group').psbase.Invoke('Members') | ForEach-Object { (New-Object Security.Principal.SecurityIdentifier ([byte[]]$_.GetType().InvokeMember('objectSid', 'GetProperty', $null, $_, $null)), 0).Value }) }
601
+ $settings = New-ScheduledTaskSettingsSet -MultipleInstances Parallel -ExecutionTimeLimit ([TimeSpan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
602
+ foreach ($want in $users) {
603
+ $name = $want.name
604
+ $user = Get-LocalUser -Name $name -ErrorAction SilentlyContinue
605
+ if (-not $user) {
606
+ $user = New-LocalUser -Name $name -Password (ConvertTo-SecureString (New-Secret) -AsPlainText -Force) -AccountNeverExpires -PasswordNeverExpires -UserMayNotChangePassword -Description 'Superfactory task session'
607
+ }
608
+ $sid = $user.SID.Value
609
+ if ($admins -contains $sid) { throw "$name is an administrator: it can't run task sessions" }
610
+ if (-not $user.Enabled) { Enable-LocalUser -Name $name }
611
+ $members = @(Get-LocalGroupMember -Group $group | ForEach-Object { $_.SID.Value })
612
+ if ($members -notcontains $sid) { Add-LocalGroupMember -Group $group -Member $sid }
613
+ New-ItemProperty -Path $hidden -Name $name -Value 0 -PropertyType DWord -Force | Out-Null
614
+ $task = Get-ScheduledTask -TaskPath $taskPath -TaskName $name -ErrorAction SilentlyContinue
615
+ $same = $task -and $task.Actions.Count -eq 1 -and $task.Actions[0].Execute -eq $want.execute -and $task.Actions[0].Arguments -eq $want.arguments -and $task.Principal.LogonType -eq 'Password' -and $task.Principal.RunLevel -eq 'Limited' -and $task.Principal.UserId.Split('\\')[-1] -eq $name
616
+ if (-not $same) {
617
+ $secret = New-Secret
618
+ Set-LocalUser -Name $name -Password (ConvertTo-SecureString $secret -AsPlainText -Force)
619
+ $action = New-ScheduledTaskAction -Execute $want.execute -Argument $want.arguments
620
+ Register-ScheduledTask -TaskPath $taskPath -TaskName $name -Action $action -Settings $settings -User $name -Password $secret -RunLevel Limited -Force | Out-Null
621
+ $secret = $null
622
+ }
623
+ "user $name $sid"
624
+ }
625
+ # The agent's home: its own, whatever an older join or a person left there.
626
+ $agentHome = $env:SF_SESSION_AGENT_HOME
627
+ if ($agentHome -and (Test-Path -LiteralPath $agentHome)) {
628
+ $me = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
629
+ $keep = @('S-1-5-18', 'S-1-5-32-544', $me)
630
+ $acl = Get-Acl -LiteralPath $agentHome
631
+ $open = @($acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]) | Where-Object { $_.AccessControlType -eq 'Allow' -and ($_.IsInherited -or $keep -notcontains $_.IdentityReference.Value) })
632
+ if ($open.Count) {
633
+ $args = @($agentHome, '/inheritance:r', '/grant:r', '*S-1-5-18:(OI)(CI)F', '/grant:r', '*S-1-5-32-544:(OI)(CI)F', '/grant:r', "*$($me):(OI)(CI)F")
634
+ foreach ($rule in $open) { if ($keep -notcontains $rule.IdentityReference.Value) { $args += @('/remove:g', "*$($rule.IdentityReference.Value)") } }
635
+ & icacls.exe @args /C /Q | Out-Null
636
+ if ($LASTEXITCODE -ne 0) { throw "icacls couldn't make $agentHome the agent's own ($LASTEXITCODE)" }
637
+ "closed $agentHome"
638
+ }
639
+ }
640
+ "group $group $groupSid"
641
+ `,l$=l`
642
+ $ErrorActionPreference = 'Stop'
643
+ $name = $env:SF_SESSION_USER
644
+ $folder = $env:SF_SESSION_FOLDER
645
+ $owner = "$env:COMPUTERNAME\\$name"
646
+ for ($i = 0; $i -lt 50; $i++) {
647
+ $left = @(Get-Process -IncludeUserName -ErrorAction SilentlyContinue | Where-Object { $_.UserName -eq $owner })
648
+ if (-not $left.Count) { break }
649
+ $left | Stop-Process -Force -ErrorAction SilentlyContinue
650
+ Start-Sleep -Milliseconds 100
651
+ }
652
+ if ($left.Count) { throw "$name still runs $($left.Count) processes" }
653
+ if ($folder -and (Test-Path -LiteralPath $folder)) {
654
+ $items = @(Get-ChildItem -LiteralPath $folder -Force)
655
+ foreach ($item in $items) {
656
+ try { Remove-Item -LiteralPath $item.FullName -Recurse -Force }
657
+ catch {
658
+ & takeown.exe /F $item.FullName /R /A /D Y 2>&1 | Out-Null
659
+ & icacls.exe $item.FullName /reset /T /C /Q 2>&1 | Out-Null
660
+ Remove-Item -LiteralPath $item.FullName -Recurse -Force
661
+ }
662
+ }
663
+ }
664
+ `;async function ef(i,o,d){let u=await g(r(Ko).flag("-NoProfile").flag("-NonInteractive").flag("-ExecutionPolicy","Bypass").script("-Command",i).env(o).by("session user").timeoutMs(d).build());if(u.exitCode!==0)throw Error((u.stderr||u.stdout).trim().slice(0,500));return u.stdout}async function xo(i,o){for(let h of o)await _t(ct(h),{recursive:!0});let d=o.map((h)=>({name:h,...d$(h)})),u=await ef(u$,{SF_SESSION_GROUP:i,SF_SESSION_USERS:JSON.stringify(d),SF_SESSION_TASK_PATH:Wl,SF_SESSION_AGENT_HOME:zl(m().state)},300000).catch((h)=>{throw Error(`couldn't make ${i}'s accounts: ${h.message}`)}),f="",p=[];for(let h of u.trim().split(/\r?\n/)){let[w,y,S]=h.trim().split(" ");if(w==="group"&&S)f=S;else if(w==="user"&&y&&S)p.push({name:y,sid:S,group:i,groupSid:"",folder:ct(y),home:Q(ct(y),"home"),task:`${Wl}${y}`});else if(w==="closed")s.info(`sessions: the agent's home is its own again (${h.slice(7)})`)}if(!f)throw Error(`couldn't make the group ${i}`);return{groupSid:f,users:p.map((h)=>({...h,groupSid:f}))}}async function kn(i){await _t(i.folder,{recursive:!0}),await Po(Q(i.home,".claude","projects"),{force:!0}).catch(()=>{return}),await ef(l$,{SF_SESSION_USER:i.name,SF_SESSION_FOLDER:i.folder},120000),await Le(i.folder,`*${i.sid}:(OI)(CI)(M)`),await Le(i.folder,`*${Pn.ownerRights}:(OI)(CI)(RC)`);for(let o of f$(i.home))await _t(o,{recursive:!0})}var f$=(i)=>[i,Q(i,"AppData","Roaming"),Q(i,"AppData","Local","Temp")];function Eo(i,o,d,u){let{home:f}=i,p=Q(f,"AppData","Local","Temp"),h=/^[A-Za-z]:/.exec(f)?.[0]??"",w={HOME:f,USERPROFILE:f,HOMEDRIVE:h,HOMEPATH:f.slice(h.length),APPDATA:Q(f,"AppData","Roaming"),LOCALAPPDATA:Q(f,"AppData","Local"),USERNAME:i.name,...u},y={XDG_CONFIG_HOME:".config",XDG_CACHE_HOME:".cache",XDG_DATA_HOME:".local/share",XDG_STATE_HOME:".local/state",BUN_INSTALL:".bun"};for(let[v,P]of Object.entries(y))if(d(o[v]))w[v]=Q(f,P);let S=o.TMPDIR&&!d(o.TMPDIR)?o.TMPDIR:p;return Object.assign(w,{TMPDIR:S,TMP:S,TEMP:S}),w}var Ro=()=>Q(m().run,"session-users.json");async function Oo(){try{let i=JSON.parse(await s$(Ro(),"utf8"));return{done:i.done??[],users:i.users??{}}}catch{return{done:[],users:{}}}}async function p$(i){let o=await hr(i).then((d)=>d.ino,()=>0);return`${i}@${o}`}var Yl=Promise.resolve();function tf(i){let o=Yl.then(i,i);return Yl=o.catch(()=>{return}),o}async function Le(i,o,d="grant"){let u=await g(r(Yo).arg(i).flag(d==="deny"?"/deny":"/grant",o).flag("/C").flag("/Q").by("session user").timeoutMs(600000).build());if(u.exitCode!==0)throw Error(`icacls couldn't ${d} ${o} on ${i}: ${(u.stderr||u.stdout).trim()}`)}var ql="WD,AD,WEA,WA,DE,DC,WDAC,WO",m$=()=>process.env.USERDOMAIN?`${process.env.USERDOMAIN}\\${Hl().username}`:Hl().username;async function vo(i){if(!await hr(i).catch(()=>{return}))return;let o=await g(r(Yo).arg(i).flag("/setowner",m$()).flag("/T").flag("/C").flag("/Q").by("session user").timeoutMs(1800000).build());if(o.exitCode!==0)throw Error(`icacls couldn't make ${i} the agent's: ${(o.stderr||o.stdout).trim()}`)}var h$=[".claude","CLAUDE.md",".mcp.json",Q(".superfactory","coordinator"),Q(".superfactory","instructions"),Q(".git","config"),Q(".git","hooks"),Q(".git","info")],g$=["commondir","gitdir"];async function Ot(i,o){let d=await g(r(Yo).arg(i).flag("/remove:g",`*${o}`).flag("/C").flag("/Q").by("session user").timeoutMs(600000).build());if(d.exitCode!==0&&await hr(i).catch(()=>{return}))s.warn(`sessions: icacls couldn't take ${o}'s entries from ${i}: ${d.stderr.trim()}`)}function xn(i,o){return tf(async()=>{let d=await Oo();for(let y of d.users[i.name]??[])await Ot(y,i.sid);let u=`*${i.groupSid}`,f=new Set(d.done),p=async(y,S,v="")=>{let P=`${v}${await p$(y)}`;if(f.has(P))return;await S(),f.add(P)};for(let y of o.shared)await p(y,async()=>{s.info(`sessions: sharing ${y} with the task sessions' accounts (once)`),await Le(y,`${u}:(OI)(CI)(M)`)});for(let y of o.readable)await p(y,()=>Le(y,`${u}:(OI)(CI)(RX)`));let h=[];for(let{checkout:y,open:S,admin:v=[]}of o.closed??[]){for(let P of S)await p(P,()=>Le(P,`${u}:(OI)(CI)(M)`));await p(y,async()=>{s.info(`sessions: closing ${y} to the task sessions' accounts but for its worktrees (once)`),await vo(y),await Le(y,`*${Pn.ownerRights}:(OI)(CI)(RX)`),await Le(y,`${u}:(OI)(CI)(${ql})`,"deny"),await Ot(Q(y,".git","worktrees"),i.groupSid)},"owned:");for(let P of h$)await vo(Q(y,P));for(let P of v){for(let x of g$){let E=Q(P,x);await vo(E),await p(E,()=>Le(E,`${u}:(${ql})`,"deny"),"ro:")}h.push(P)}}if(o.leadsClaude){let y=o.leadsClaude;await p(y,()=>w$(y,i.groupSid),"closed:")}let w=[];for(let y of[...o.own,...h.map((S)=>({path:S,writable:!0}))]){if(await _t(y.path,{recursive:!0}),await Le(y.path,`*${i.sid}:(OI)(CI)(${y.writable?"M":"RX"})`),y.writable)await Le(y.path,`*${Pn.ownerRights}:(OI)(CI)(RC)`);w.push(y.path)}await Ce(Ro(),JSON.stringify({done:[...f],users:{...d.users,[i.name]:w}}))})}async function w$(i,o){let d=Q(i,"sessions");await Ot(i,o),await Ot(d,o),await Ot(d,Pn.creatorOwner)}async function rf(i,o){let d=Q(i.home,".claude","projects");await _t(zl(d),{recursive:!0}),await Po(d,{force:!0}).catch(()=>{return}),await o$(o,d,"junction")}function _o(i){return tf(async()=>{let o=await Oo();for(let d of o.users[i.name]??[])await Ot(d,i.sid);delete o.users[i.name],await Ce(Ro(),JSON.stringify(o))})}async function y$(){return Object.keys((await Oo()).users)}async function nf(i,o){if(!i||!/\.exe$/i.test(i)||!o(i))return i;let d=await hr(i),u=Q(process.env.ProgramFiles||"C:\\Program Files","Superfactory","claude"),f=Q(u,`${Math.round(d.mtimeMs)}-${d.size}`),p=Q(f,"claude.exe");if(!await hr(p).catch(()=>{return}))await _t(f,{recursive:!0}),await r$(i,`${p}.part`),await i$(`${p}.part`,p),s.info(`sessions: Claude Code for the task sessions' accounts is ${p}`);for(let h of await n$(u).catch(()=>[]))if(Q(u,h)!==f)await Po(Q(u,h),{recursive:!0,force:!0}).catch(()=>{return});return p}function Io(i){return{socketIn:i.folder,program:()=>r(yu).flag("/run").flag("/tn",i.task).by("session user").timeoutMs(60000).build(),specFile:Xl(i.name),log:Ql(i.name)}}function To(i,o,d={}){let u=Date.now();return new Promise((f)=>{let p=Te.start(o,Io(i)),h="",w="",y=!1,S;p.stdout.on("data",(P)=>{let x=P.toString();h+=x,d.onStdout?.(x)}),p.stderr.on("data",(P)=>{let x=P.toString();w+=x,d.onStderr?.(x)}),p.on("error",(P)=>{S=P.message});let v=o.timeoutMs?setTimeout(()=>{y=!0,p.kill("SIGKILL")},o.timeoutMs):void 0;if(p.spawned.promise.then(()=>{if(p.pid!==void 0)d.onStart?.(p.pid)}),d.input instanceof a$)throw Error("a stream as stdin isn't run as another account");if(d.input!==void 0)p.stdin.write(Buffer.from(d.input));p.stdin.end(),p.once("exit",(P,x)=>{clearTimeout(v),f({stdout:h,stderr:S?`${w}${w&&!w.endsWith(`
665
+ `)?`
666
+ `:""}${S}
667
+ `:w,exitCode:P??(y?124:1),signal:x,timedOut:y,truncated:!1,durationMs:Date.now()-u})})})}var Jl=32,mr=new Set,Kl=new Map;async function sf(i,o){let d=Kl.get(o);if(d)return d;let u=(await xo(i,[o])).users[0];if(!u)throw Error(`there is no account ${o}`);return Kl.set(o,u),u}async function Ao(i){for(let o=1;o<=Jl;o++){let d=`${i}-${o}`;if(mr.has(d))continue;mr.add(d);try{let u=await sf(i,d);return await kn(u),u}catch(u){mr.delete(d),s.warn(`sessions: passing over ${d}`,u)}}throw Error(`all ${Jl} of ${i}'s accounts are running sessions or installs, or can't be used`)}var Rn=(i)=>async()=>{await kn(i).catch((o)=>s.warn(`sessions: couldn't end what ${i.name} left, or empty its folder`,o)),await _o(i).catch((o)=>s.warn(`sessions: couldn't take ${i.name}'s folders back`,o)),mr.delete(i.name)};async function of(i){for(let o of await y$())if(!mr.has(o)&&o.startsWith(`${i}-`))await Rn(await sf(i,o))()}var Go="sf-session",Ho=".run",At={config:".config",data:".local/share",state:".local/state"},$$=["uv","pnpm","mise","pipx","pypoetry","fnm","containers"];function S$(i,o){let d=[];if(o){for(let[u,f]of Object.entries(At))d.push({kind:"over",from:j(o,u),path:j(i,f)});for(let u of $$)d.push({kind:"shared",path:j(i,At.data,u)})}return d.push({kind:"runtime",path:j(i,Ho)}),d}var le=(i,o)=>{let d=b$(i,o);return d===""||!d.startsWith("..")&&!wf(d)};function Qn(i){let o=[...new Set(i)].sort((d,u)=>d.length-u.length);return o.filter((d,u)=>!o.slice(0,u).some((f)=>le(f,d)))}function Wo(i){let d=Qn(i.hidden).map((w)=>({kind:"hide",path:w})),u=Qn(i.writable),f=Qn((i.sdks??[]).map((w)=>w.path)).filter((w)=>!u.some((y)=>le(y,w)||le(w,y))).map((w)=>({path:w,layer:i.sdks?.find((y)=>y.path===w)?.layer})),p=Qn(i.readable).filter((w)=>!u.some((y)=>le(y,w))&&!f.some((y)=>le(y.path,w))),h=[...u.map((w)=>({kind:"bind",path:w,writable:!0})),...p.map((w)=>({kind:"bind",path:w,writable:!1})),...f.map((w)=>({kind:"sdk",...w})),...(i.fixed??[]).map((w)=>({kind:"file",path:w}))].sort((w,y)=>w.path.length-y.path.length);if(d.push(...h),d.push({kind:"home",path:i.home},...S$(i.home,i.task)),i.claude){let w=j(i.home,".claude"),y=ko(i.claude.cwd);d.push({kind:"over",from:j(i.claude.transcripts,y),path:j(w,"projects",y)}),d.push({kind:"runtime",path:j(w,"sessions")})}return d}var v$=["objects","refs","logs","lfs"],yf=["commondir","gitdir"],gr=(i)=>{try{return hf(i).isDirectory()}catch{return!1}};function bf(i){return i.filter((o)=>gr(j(o,".git"))&&i.some((d)=>d!==o&&le(o,d)))}async function $f(i){let o=[];for(let d of v$){let u=j(i,".git",d);if(await ke(u).catch(()=>{return}),gr(u))o.push(u)}return o}var P$=(i)=>{try{return hf(i).isFile()}catch{return!1}};function k$(i,o){let d=j(i,".git","worktrees"),u=jo(o),f=[];try{f=Fo(d)}catch{}let p=new Set([j(o,".git"),j(we(o),".git")]);return f.filter((h)=>h===u||h.startsWith(u)&&/^\d+$/.test(h.slice(u.length))).sort((h,w)=>h.length-w.length||h.localeCompare(w)).map((h)=>j(d,h)).find((h)=>{if(!gr(h)||!yf.every((y)=>P$(j(h,y))))return!1;let w=Nt(j(h,"gitdir"),"utf8").trim();return p.has(_n(h,w))})}async function Sl(i){return[j(i,".superfactory","worktrees"),...await $f(i)]}var Sf=(i,o)=>o.filter((d)=>d!==i&&le(i,d)).flatMap((d)=>k$(i,d)??[]),x$=(i)=>i.flatMap((o)=>yf.map((d)=>j(o,d))),xm=(i)=>gr(i)&&gr(j(i,".git"));async function In(i){return Promise.all(bf(i).map(async(o)=>({checkout:o,open:await Sl(o),admin:[...new Set(Sf(o,i))]})))}async function vf(i){let o=bf(i),d=i.filter((f)=>!o.includes(f)),u=[];for(let f of o){let p=[...new Set(Sf(f,i))];d.push(...await $f(f),...p),u.push(...x$(p))}return{writable:d,readable:o,fixed:u}}async function Pm(i,o){if(!await ce().then((h)=>!!h,()=>!0))return{};let u=Qe(await it(i),Number(o.GIT_CONFIG_COUNT)||0),f=await E$(),p=o.PATH??process.env.PATH??"";return f?{...u,PATH:[f,p].filter(Boolean).join(gf)}:u}async function E$(){let i=Bun.which("git");if(process.platform==="win32"||!i)return;let o=j(m().run,"lead-git");await ke(o,{recursive:!0,mode:448});let d=(f)=>`'${f.replaceAll("'","'\\''")}'`,u=[...xi(),"git-guard"].map(d).join(" ");return await de(j(o,"git"),["#!/bin/sh","# A lead's git (session-user.ts, leadGitWrapper): the repository's program settings as they are now, off.",`guard=$(PATH=${d(Fe(i))}:"$PATH" ${u} "$@") || exit 1`,`[ -n "$guard" ] || { echo "git: not run: Superfactory's git guard said nothing for this repository" >&2; exit 1; }`,'eval "$guard"',`exec ${d(i)} "$@"`,""].join(`
668
+ `),448),o}var R$=`use POSIX ();
669
+ $0 = "session-reaper";
670
+ my $host = fork() // die "session reaper: fork: $!\\n";
671
+ if (!$host) { exec { $ARGV[0] } @ARGV; die "session reaper: $ARGV[0]: $!\\n"; }
672
+ $SIG{$_} = sub { kill $_[0], $host } for qw(HUP INT QUIT TERM USR1 USR2 WINCH);
673
+ while (1) {
674
+ my $done = waitpid(-1, 0);
675
+ if ($done == $host) { exit(POSIX::WIFEXITED($?) ? POSIX::WEXITSTATUS($?) : 128 + POSIX::WTERMSIG($?)); }
676
+ exit 1 if $done < 0 && $!{ECHILD};
677
+ }`,O$=l`set -eu
678
+ PATH=/usr/sbin:/usr/bin:/sbin:/bin
679
+ export PATH
680
+ auid=$1 agid=$2 user=$3 uid=$4 gid=$5 home=$6 path=$7 stage=$8 count=$9
681
+ shift 9
682
+ # Root as itself too (T-472): a root-owned file the session copies in with \`cp -a\` is then one it may not
683
+ # chown (EPERM, which cp lets go), not one whose owner can't be said there (EOVERFLOW, which fails the copy).
684
+ map="X-mount.idmap=u:$auid:$uid:1 u:0:0:1 g:$agid:$gid:1 g:0:0:1"
685
+ as_user() { /usr/bin/setpriv --reuid="$uid" --regid="$gid" --clear-groups -- "$@"; }
686
+ # A folder to mount, entered: its real path must be its path (no link on the way leads elsewhere), and its
687
+ # owner \`$2\` when given; root then mounts it from \`.\`, so what is renamed or linked there after this
688
+ # changes nothing of what is mounted.
689
+ from() {
690
+ cd -P "$1" 2>/dev/null && [ "$(pwd -P)" = "$1" ] && { [ -z "\${2:-}" ] || [ "$(stat -c %u .)" = "$2" ]; } ||
691
+ { echo "session user: $1 isn't a folder of its own to mount: a link is on its way, or it is another's" >&2; exit 1; }
692
+ }
693
+ # The folder entered (\`from\`) mounted at the staging folder of operand $i, as the session user's.
694
+ stage_here() {
695
+ mkdir "$stage/$i"
696
+ mount --no-canonicalize --bind -o "$map" . "$stage/$i"
697
+ cd /
698
+ }
699
+ # Where a mount goes, made if missing, then entered as \`from\` does: root mounts onto \`.\`.
700
+ onto() {
701
+ [ -d "$1" ] || mkdir -p "$1"
702
+ from "$1"
703
+ }
704
+ # A folder in its home, made as it if missing (from inside it: the agent's home around it is the agent's),
705
+ # then entered: its real path must be its path in the home, so no link on the way leads elsewhere, and
706
+ # what a session renames or links there after this changes nothing of what root mounts as \`.\`.
707
+ enter() {
708
+ case $1 in "$home"/*) ;; *) echo "session user: $1 isn't in $home" >&2; exit 1 ;; esac
709
+ [ -d "$1" ] || (cd "$home" && as_user mkdir -p "\${1#"$home"/}")
710
+ real_home=\${real_home:-$(cd -P "$home" && pwd -P)}
711
+ cd -P "$1" && [ "$(pwd -P)" = "$real_home/\${1#"$home"/}" ] ||
712
+ { echo "session user: $1 isn't a folder of $user's" >&2; exit 1; }
713
+ }
714
+ mkdir -p "$stage"
715
+ mount -t tmpfs -o mode=700 sf-stage "$stage"
716
+ i=0 sdk=
717
+ for op in "$@"; do
718
+ [ "$i" -lt "$count" ] || break
719
+ i=$((i + 1))
720
+ last=$sdk sdk=
721
+ case $op in
722
+ b:rw:*) from "\${op#b:rw:}" "$auid"; stage_here ;;
723
+ b:ro:*) from "\${op#b:ro:}"; stage_here; mount -o remount,bind,ro "$stage/$i" ;;
724
+ o:*)
725
+ dir=\${op#o:}
726
+ [ -d "$dir" ] || install -d -m 700 -o "$uid" -g "$gid" "$dir"
727
+ from "$dir" "$uid"
728
+ mkdir "$stage/$i"
729
+ mount --no-canonicalize --bind . "$stage/$i"
730
+ cd / ;;
731
+ v:*) from "\${op#v:}" "$auid"; stage_here ;;
732
+ s:*)
733
+ enter "\${op#s:}"
734
+ [ "$(stat -c %u .)" = "$uid" ] || { echo "session user: \${op#s:} isn't $user's" >&2; exit 1; }
735
+ mkdir "$stage/$i"
736
+ mount --no-canonicalize --bind . "$stage/$i"
737
+ cd / ;;
738
+ S:*)
739
+ sdk=$i
740
+ from "\${op#S:}"
741
+ stage_here
742
+ mount -o remount,bind,ro "$stage/$i" ;;
743
+ f:*)
744
+ # A file of the agent's: opened, then checked to be that very file (no link to another), and mounted
745
+ # from what was opened, read-only.
746
+ file=\${op#f:}
747
+ { [ -f "$file" ] && [ ! -L "$file" ]; } || { echo "session user: $file isn't a file to mount" >&2; exit 1; }
748
+ exec 3<"$file"
749
+ { [ "$(readlink /proc/self/fd/3)" = "$file" ] && [ -f /proc/self/fd/3 ] && [ "$(stat -L -c %u /proc/self/fd/3)" = "$auid" ]; } ||
750
+ { echo "session user: $file isn't a file of the agent's by that name" >&2; exit 1; }
751
+ : >"$stage/$i"
752
+ mount --no-canonicalize --bind -o "$map" /proc/self/fd/3 "$stage/$i"
753
+ exec 3<&-
754
+ mount -o remount,bind,ro "$stage/$i" ;;
755
+ @*)
756
+ [ -n "$last" ] || continue
757
+ layer=\${op#@} up="$stage/$i"
758
+ mkdir "$up"
759
+ if [ -n "$layer" ]; then
760
+ from "$layer" "$auid"
761
+ mount --no-canonicalize --bind -o "X-mount.idmap=u:$auid:$uid:1 u:0:0:1 g:$agid:$gid:1 g:0:0:1" . "$up"
762
+ cd /
763
+ else
764
+ mount -t tmpfs -o mode=700 sf-sdk "$up"
765
+ install -d -o "$uid" -g "$gid" "$up/upper"
766
+ mkdir "$up/work"
767
+ fi
768
+ # A session writes its layer: its upper and work folders are opened as entered, never named again.
769
+ from "$up/upper"
770
+ exec 3<.
771
+ from "$up/work"
772
+ exec 4<.
773
+ cd /
774
+ mkdir "$stage/o$last"
775
+ mount -t overlay -o "nosuid,nodev,lowerdir=$stage/$last,upperdir=/proc/self/fd/3,workdir=/proc/self/fd/4" sf-sdk "$stage/o$last"
776
+ exec 3<&- 4<&-
777
+ umount "$up" "$stage/$last" ;;
778
+ esac
779
+ done
780
+ i=0
781
+ while [ "$i" -lt "$count" ]; do
782
+ i=$((i + 1)); op=$1; shift
783
+ case $op in
784
+ h:*) mkdir -p "\${op#h:}"; mount -t tmpfs -o mode=755 sf-hidden "\${op#h:}" ;;
785
+ H:*) mkdir -p "\${op#H:}"; mount -t tmpfs -o "mode=700,uid=$uid,gid=$gid" sf-hidden "\${op#H:}" ;;
786
+ b:r?:*) onto "\${op#b:r?:}"; mount --no-canonicalize --move "$stage/$i" .; cd / ;;
787
+ f:*)
788
+ file=\${op#f:}
789
+ { [ -f "$file" ] && [ ! -L "$file" ]; } || { echo "session user: $file isn't a file to mount onto" >&2; exit 1; }
790
+ mount --no-canonicalize --move "$stage/$i" "$file" ;;
791
+ o:*) onto "\${op#o:}"; mount --no-canonicalize --move "$stage/$i" .; cd / ;;
792
+ v:*)
793
+ at=$i dir=\${1#@}
794
+ i=$((i + 1)); shift
795
+ enter "$dir"; mount --no-canonicalize --move "$stage/$at" .; cd / ;;
796
+ s:*) enter "\${op#s:}"; mount --no-canonicalize --move "$stage/$i" .; cd / ;;
797
+ r:*)
798
+ dir=\${op#r:}
799
+ # One a session left a file or a link (its folder is the session user's): made again, never in the way.
800
+ { [ -d "$dir" ] && [ ! -L "$dir" ]; } || rm -f "$dir"
801
+ enter "$dir"; mount --no-canonicalize -t tmpfs -o "mode=700,uid=$uid,gid=$gid" sf-runtime .; cd / ;;
802
+ S:*)
803
+ at=$i dir=\${op#S:}
804
+ i=$((i + 1)); shift
805
+ onto "$dir"; mount --no-canonicalize --move "$stage/o$at" .; cd / ;;
806
+ *) echo "session user: no mount $op" >&2; exit 1 ;;
807
+ esac
808
+ done
809
+ umount "$stage"
810
+ rmdir "$stage"
811
+ cd /
812
+ exec /usr/bin/env -i HOME="$home" PATH="$path" USER="$user" LOGNAME="$user" \\
813
+ /usr/bin/setpriv --reuid="$uid" --regid="$gid" --init-groups --no-new-privs --inh-caps=-all \\
814
+ --bounding-set=-all -- /usr/bin/perl -e ${R$} -- "$@"
815
+ `,_$=(i)=>{let o=_n(i.path);if(i.kind==="bind")return[`b:${i.writable?"rw":"ro"}:${o}`];if(i.kind==="home")return[`o:${o}`];if(i.kind==="over")return[`v:${_n(i.from)}`,`@${o}`];if(i.kind==="shared")return[`s:${o}`];if(i.kind==="runtime")return[`r:${o}`];if(i.kind==="sdk")return[`S:${o}`,`@${i.layer?_n(i.layer):""}`];if(i.kind==="file")return[`f:${o}`];return[`${i.own?"H":"h"}:${o}`]},I$=()=>`/run/superfactory-session-${process.pid}-${Math.random().toString(36).slice(2,10)}`;function Jo(i,o,d){let u=No(),f=o.flatMap(_$),p=r(Kd).script("-c",O$).argsOf(["session-user",u.uid,u.gid,i.name,i.uid,i.gid,i.home,process.env.PATH??"/usr/bin:/bin",I$(),f.length,...f]).wrap(d).build(),h=r(Vd).flag("--mount").flag("--pid").flag("--fork").flag("--mount-proc").flag("--propagation","private").wrap(p).build();return r(A).flag("-n").wrap(h).by("session user").timeoutMs(d.timeoutMs).build()}var On;function ce(){return On??=A$().catch((i)=>`it couldn't be set up: ${i.message}`),On.then((i)=>{if(typeof i!=="string"){if(Do)Do=!1,lo().catch((o)=>s.warn("sessions: couldn't let go of what the session users of the agent before held",o));return Ct=void 0,i}if(kf(i)){if(On=void 0,Ct=`${i}: its task sessions run as the agent's own user, as before T-372. Make the pool (as root: superfactory host, or useradd its users), and they run as those users from the next session on.`,!It.has(i))It.add(i),s.warn(`sessions: ${Ct}`);return}if(Ct=void 0,T$(i)){if(On=void 0,Ct=`they are refused until they can run as the session user: ${i}`,!It.has(i))It.add(i),s.warn(`sessions: task sessions are refused here until they can run as the session user: ${i}`);throw Error(`task sessions here run only as the session user, and it isn't ready: ${i}. Root fixes it on this machine: its project's lead or the main lead, with machine_run root (docs/security/session-user.md \u203A Fails closed); each new session tries again.`)}if(!It.has(i)){if(It.add(i),i!==dt)s.warn(`sessions: task sessions run as the agent's own user: ${i}`)}return})}var It=new Set,dt="off here",Ct,Pf="no user of the session users' pool was ever made here",kf=(i)=>i.startsWith(Pf);function T$(i,o=C$()){return o&&i!==dt&&!kf(i)}function C$(){if(Pe())return!0;let i=process.env.SUPERFACTORY_SESSION_USER?.trim();return process.platform==="linux"&&(!!i||Jn()&&lt())}var $c=()=>Ct,Do=!1;async function A$(){let i=process.env.SUPERFACTORY_SESSION_USER?.trim();if(i==="off"||i==="0")return dt;if(process.platform==="darwin")return N$(i);if(process.platform==="win32")return U$(i);if(process.platform!=="linux")return dt;if(!i&&!(Jn()&&lt())){if(Jn())await af([No().username]);return dt}let o=i||Go;if(!/^[a-z_][a-z0-9_-]{0,31}$/.test(o))return`SUPERFACTORY_SESSION_USER isn't a user name: ${o}`;if(!lt())return"its Claude isn't isolated (SUPERFACTORY_CLAUDE_ISOLATED=1)";if(!Zn())return"sessions don't run through hosts here";if(X())return"this agent runs nothing as root";if(Pe())return M$(o);let d=j(Mt(),"session-home"),u=cf(o);if(!u){let y=await g(r(A).flag("-n").wrap(r(eu).flag("--user-group").flag("--no-create-home").flag("--home-dir",d).flag("--shell","/usr/sbin/nologin").arg(o).build()).by("session user").timeoutMs(30000).build());if(u=cf(o),!u)return`there is no user ${o}, and it couldn't be made: ${y.stderr.trim().slice(0,300)}`;s.info(`sessions: made the user ${o} for task sessions`)}if(u.uid===process.getuid?.()||u.uid===0)return`${o} is the agent's own user, or root`;await af([o,No().username]);let f={name:o,uid:u.uid,gid:u.gid,home:d},p=m().run;await ke(p,{recursive:!0,mode:448});let h=await g(Jo(f,Wo({hidden:[Mt(),U()],writable:[p],readable:[],home:d}),L$(p))),w=h.stdout.trim();if(h.exitCode!==0||w!==`${u.uid} gone mine`)return`the agent couldn't start a program as ${o} in a world of its own: ${(h.stderr||w).trim().slice(0,300)}`;return s.info(`sessions: task sessions run as ${o} (uid ${u.uid}), each in mounts and processes of its own`),f}async function M$(i){let o=Zi(i).map(nt),d=o[0];if(o.every((p)=>!p))return`${Pf} (${i}-1\u2026)`;if(!d||o.some((p)=>!p))return`the pool of users ${i}-1\u2026 isn't whole in this machine's image`;if(o.some((p)=>p?.uid===process.getuid?.()||p?.uid===0))return`a user of ${i} is the agent's own user, or root`;if(!il())return"the engine's host lets a user hardlink files it can't write (sysctl fs.protected_hardlinks=1)";let u=j(m().run,"session-user-probe");await ke(u,{recursive:!0,mode:448});let f=`probe-${process.pid}`;try{let p=pn({hidden:Ee(),own:[{path:u,writable:!0}],projects:[],readable:[]});await gn(d.name,f,p,[Fe(d.home),d.home]);let h=await g(Et(d,Ef(u))),w=h.stdout.trim();if(h.exitCode!==0||w!==`${d.uid} gone mine`)return`the agent couldn't start a program as ${d.name} out of its files: ${(h.stderr||w).trim().slice(0,300)}`}finally{await xt(f,{kill:!1}).catch(()=>{return}),await Bo(u,{recursive:!0,force:!0}).catch(()=>{return})}return s.info(`sessions: task sessions run as ${i}-<n>, a user of each project's own, out of the agent's files`),{name:i,uid:d.uid,gid:d.gid,home:j(Fe(d.home),i),pool:i}}async function xf(i,o){return{...await Rl(i.pool??i.name,o),pool:i.pool}}async function N$(i){if(!i&&!lt())return dt;let o=i||Go;if(!/^[a-z_][a-z0-9_-]{0,24}$/.test(o))return`SUPERFACTORY_SESSION_USER isn't a group name: ${o}`;if(!lt())return"its Claude isn't isolated (SUPERFACTORY_CLAUDE_ISOLATED=1)";if(!Zn())return"sessions don't run through hosts here";if(X())return"this agent runs nothing as root";let{users:d}=await So(o,[`${o}-0`]),u=d[0];if(!u)return`there is no user ${o}-0, and it couldn't be made`;if(u.uid===process.getuid?.()||u.uid===0)return`${u.name} is the agent's own user, or root`;await vn(u);let f=j(m().run,"session-user-probe");await ke(f,{recursive:!0,mode:448});let p={group:o,agent:pr()};try{await $n(p,u.name,bn({hidden:Ee(),own:[{path:f,writable:!0}],shared:[],readable:[]}));let h=await g(Sn(u,Ef(f))),w=h.stdout.trim();if(h.exitCode!==0||w!==`${u.uid} gone mine`)return`the agent couldn't start a program as ${u.name} out of its files: ${(h.stderr||w).trim().slice(0,300)}`}finally{await $o(u.name).catch(()=>{return}),await Bo(f,{recursive:!0,force:!0}).catch(()=>{return})}return s.info(`sessions: task sessions run as users of their own (${o}-<n>), out of the agent's files`),{...u,group:o}}async function U$(i){if(!i&&!lt())return dt;let o=i||Go;if(!/^[a-z_][a-z0-9_-]{0,15}$/.test(o))return`SUPERFACTORY_SESSION_USER isn't a group name: ${o}`;if(!lt())return"its Claude isn't isolated (SUPERFACTORY_CLAUDE_ISOLATED=1)";if(process.env.SUPERFACTORY_ADMINISTRATOR!=="1")return"the agent isn't elevated (join.ps1 -Administrator)";if(X())return"this agent runs nothing as an administrator";let{users:d}=await xo(o,[`${o}-0`]),u=d[0];if(!u)return`there is no account ${o}-0, and it couldn't be made`;let f=j(ct(o),"home");await ke(f,{recursive:!0});let p=j(m().run,"session-user-probe");await ke(p,{recursive:!0});try{await kn(u),await xn(u,{own:[{path:p,writable:!0}],shared:[f],readable:Be()});let h=Eo(u,process.env,Tn,{}),w=await To(u,D$(p,h)),y=w.stdout.trim();if(w.exitCode!==0||y!==`${u.name} gone mine`)return`the agent couldn't start a program as ${u.name} out of its files: ${(w.stderr||y).trim().slice(0,300)}`}finally{await _o(u).catch(()=>{return}),await Bo(p,{recursive:!0,force:!0}).catch(()=>{return})}return await of(o).catch((h)=>s.warn("sessions: couldn't end what the session accounts of the agent before left",h)),s.info(`sessions: task sessions run as accounts of their own (${o}-<n>), out of the agent's files`),{name:u.name,uid:-1,gid:-1,home:f,group:o,sid:u.sid}}async function Tm(i,o){if(!Pe())return;let d=await ce();if(!d)return;let u=await er(d,[i,o],o,{},r(En).flag("-r").flag("-f").arg(o).timeoutMs(600000).build());await Xn(u).finally(u.release)}function D$(i,o){return r(Ko).flag("-NoProfile").flag("-NonInteractive").script("-Command",l`
816
+ $me = [Security.Principal.WindowsIdentity]::GetCurrent().Name.Split('\\')[-1]
817
+ $state = try { [IO.File]::ReadAllBytes($env:SF_SESSION_STATE) | Out-Null; 'there' } catch { 'gone' }
818
+ $mine = try { [IO.File]::WriteAllText((Join-Path $env:SF_SESSION_FOLDER 'probe'), 'probe'); 'mine' } catch { 'not' }
819
+ "$me $state $mine"
820
+ `).env({...o,SF_SESSION_STATE:m().state,SF_SESSION_FOLDER:i}).timeoutMs(120000).build()}function Ef(i){return r(Z).script("-c",l`printf '%s %s %s\n' "$(id -u)" "$(cat ${m().state} >/dev/null 2>&1 && echo there || echo gone)" "$(touch ${j(i,"probe")} 2>/dev/null && echo mine || echo not)"`).build()}function L$(i){return r(Z).script("-c",l`printf '%s %s %s\n' "$(id -u)" "$(test -e ${m().state} && echo there || echo gone)" "$(test -O ${i} && echo mine || echo not)"`).build()}async function af(i){if(!yr("/dev/kvm"))return;let o=F$("kvm");if(!o)return;for(let d of i.filter((u)=>!o.includes(u))){let u=await g(r(A).flag("-n").wrap(r(Xd).flag("--append").flag("--groups","kvm").arg(d).build()).by("session user").timeoutMs(30000).build());if(u.exitCode===0)s.info(`sessions: ${d} may use /dev/kvm (the kvm group)`);else s.warn(`sessions: couldn't add ${d} to the kvm group: ${u.stderr.trim().slice(0,300)}`)}}function F$(i){try{for(let o of Nt("/etc/group","utf8").split(`
821
+ `)){let[d,,,u]=o.split(":");if(d===i)return u?u.split(","):[]}}catch{}return}function cf(i){try{for(let o of Nt("/etc/passwd","utf8").split(`
822
+ `)){let[d,,u,f]=o.split(":");if(d===i&&u&&f)return{uid:Number(u),gid:Number(f)}}}catch{}return}var Mo="Your checkout's .git/config is your lead's, only to read: your task's branch already tracks its namesake on origin (git push and git pull go there; git push -u pushes, then says it couldn't write the config: nothing to fix; a bare git push pushes any branch you are on to its namesake on origin), and git settings you need go in ~/.gitconfig (git config --global) or on the command (git -c).";function _m(i){if(!i)return"";if(i.sid)return`This machine: you run as a Windows account of your own (${i.group}-<n>, a standard user in the group ${i.group}), without administrator rights or the agent's files; no other session runs as it. Your project's checkout (shared with the other sessions' accounts), your run, temp and attachment folders are yours as usual; your HOME (also USERPROFILE, APPDATA, LOCALAPPDATA and TEMP) is a folder of your own, empty when your session starts and emptied when it ends. What you leave running ends with your session. Programs installed for all users (Program Files) and those on your PATH work; what needs an administrator (installing system packages, services, drivers) goes in superfactory.yaml's setup, which the agent runs from the default branch as its remote has it: a change to it on your branch runs here once it is merged. ${Mo} Your worktree's install, and the project's pre-push hook and checks before the agent's pushes, run as a session account too. Anything else an administrator must do here is your lead's (task_ask the user only for what only they can do).`;if(i.group)return`This machine: you run as a user of your own (${i.group}-<n>, in the group ${i.group}), without admin, sudo or the agent's files; no other session runs as it. Your project's checkout (shared with the other sessions' users), your run, temp and attachment folders are yours as usual; your HOME (/Users/${i.group}/<your user>) is your own, empty when your session starts and emptied when it ends: your caches don't carry over. What you leave running ends with your session. System packages the project needs go in superfactory.yaml's setup, which the agent runs from the default branch as its remote has it: a change to it on your branch runs here once it is merged. ${Mo} Your worktree's install, and the project's pre-push hook and checks before the agent's pushes, run as a session user too. Anything else an admin must do here is your lead's (task_ask the user only for what only they can do).`;if(Pe())return`This machine: a Docker container, where you run as your project's own user (${i.name}-<n>), without sudo, root or the agent's files (sudo and setuid programs fail at once). No other project's session runs as it, but your project's other tasks' sessions do: your HOME (its Claude folder, caches and toolchains) is shared with them. Your project's checkout, your run, temp and attachment folders are yours as usual. It has no Docker of its own. System packages the project needs go in superfactory.yaml's setup, which the agent runs from the default branch as its remote has it: a change to it on your branch runs here once it is merged. Your worktree's install, and the project's pre-push hook and checks before the agent's pushes, run as your project's user too. Anything else root must do here is your lead's (task_ask the user only for what only they can do).`;return`This machine: you run as the user ${i.name}, without sudo, root or the agent's files (sudo, su and setuid programs fail at once). Your HOME, ${i.home}, is shared with the other tasks' sessions here, with its toolchains (~/.rustup, ~/.cargo, ~/.bun, uv's and pnpm's in ~/.local/share) and caches; but ~/.config, ~/.local/share and ~/.local/state (XDG_CONFIG_HOME, XDG_DATA_HOME, XDG_STATE_HOME) are your task's own (your teammates here share them; they go when the task closes), and XDG_RUNTIME_DIR (${j(i.home,Ho)}) is your session's alone: an app you run keeps its settings, sockets and logs apart from other tasks'. Your project's checkout, your run, temp and attachment folders are yours as usual. ${Mo} Docker is your own rootless one (DOCKER_HOST is set; root's /var/run/docker.sock refuses you): run, build and compose as usual; its containers see your checkout and temp folders. System packages the project needs go in superfactory.yaml's setup, which the agent runs from the default branch as its remote has it: a change to it on your branch runs here once it is merged. Your worktree's install, and the project's pre-push hook and checks before the agent's pushes, run as ${i.name} too. Anything else root must do here is your lead's (task_ask the user only for what only they can do).`}var $l=(i)=>`unix:///run/user/${i.uid}/docker.sock`;async function B$(i,o){let d=Ee(),u=(x)=>d.some((E)=>le(E,x)),{writable:f,readable:p,fixed:h}=await vf([o.runDir,o.cwd,...o.projects,...o.attachments,...o.tmp?[o.tmp]:[]]),w=br(),y=w?{transcripts:w,cwd:we(o.cwd)}:void 0,S=o.task?Object.keys(At).map((x)=>j(o.task??"",x)):[];for(let x of[...f,...S])await ke(x,{recursive:!0,mode:448});if(y)await ke(j(y.transcripts,ko(y.cwd)),{recursive:!0,mode:448});let v=[...Be(),...[...o.plugins,...o.github?[o.github]:[]].filter((x)=>u(x)&&yr(x)),...p],P=[];for(let x of If()){let E=o.task?V$(o.task,jo(o.runDir),x):void 0;if(E)for(let I of["upper","work"])await ke(j(E,I),{recursive:!0,mode:493});P.push({path:x,layer:E})}return Wo({hidden:d,writable:f,readable:v,fixed:h,claude:y,home:i.home,task:o.task,sdks:P})}var Ee=()=>[...new Set([Mt(),process.env.HOME||Mt(),U()])],Tn=(i)=>!!i&&Ee().some((o)=>le(o,i)),df=32,We=new Map,uf=new Map;async function zo(i,o){let d=uf.get(o);if(d)return d;let u=(await So(i.group??"",[o])).users[0];if(!u)throw Error(`there is no user ${o}`);return uf.set(o,u),u}async function Rf(i){for(let o=1;o<=df;o++){let d=`${i.group}-${o}`;if(We.has(d))continue;let u=await zo(i,d);if(We.has(d))continue;if(We.set(d,u),await jl(u)){We.delete(d);continue}return await vn(u).catch((f)=>{throw We.delete(d),f}),u}throw Error(`all ${df} of ${i.group}'s users are running sessions or installs`)}var wr=(i)=>async()=>{await vn(i).catch((o)=>s.warn(`sessions: couldn't end what ${i.name} left, or empty its home`,o)),await $o(i.name).catch((o)=>s.warn(`sessions: couldn't take ${i.name}'s folders back`,o)),We.delete(i.name)},br=()=>{let i=process.env.CLAUDE_CONFIG_DIR;return i?we(j(i,"projects")):void 0};function Xo(i){let o=br(),d=o?j(o,ko(we(i.cwd))):void 0;return[...[i.runDir,...i.attachments,...i.tmp?[i.tmp]:[]].map((u)=>({path:u,writable:!0})),...d?[{path:d,writable:!0}]:[],...i.github?[{path:i.github,writable:!1}]:[]]}async function Im(i,o){if(i.sid&&i.group)return H$(i.group,o);if(Pe())return j$(i,o);if(!i.group){let u=await B$(i,o);return{user:i,program:(f)=>Jo(i,u,f),pidOf:K$,release:async()=>{return}}}let d=await Rf(i);try{let u=Xo(o);for(let p of u)await ke(p.path,{recursive:!0,mode:448});let f=[...o.projects,o.cwd];await $n({group:i.group,agent:pr()},d.name,bn({hidden:Ee(),own:u,shared:f,readable:[...Be(),...o.plugins],closed:await In(f),leadsClaude:process.env.CLAUDE_CONFIG_DIR}))}catch(u){throw await wr(d)(),u}return{user:d,program:(u)=>Sn(d,u,{tmp:Qo(o.tmp),claudeProjects:br()}),held:d.name,release:wr(d)}}async function j$(i,o){let d=await xf(i,o.projects[0]??o.cwd),u=Xo(o);for(let w of u)await ke(w.path,{recursive:!0,mode:448});let f=`${jo(o.runDir)}-${mf(4).toString("hex")}`,p=pn({hidden:Ee(),own:u,projects:o.projects,cwd:o.cwd,readable:[...Be(),...o.plugins.filter((w)=>Tn(w)&&yr(w))]}),h=()=>xt(f);return await gn(d.name,f,p,[Fe(d.home),d.home]).catch(async(w)=>{throw await h().catch(()=>{return}),w}),await G$(d).catch(async(w)=>{throw await h().catch(()=>{return}),w}),{user:d,program:(w)=>Et(d,w,{claudeProjects:br()}),held:`${Lo}${f}`,release:h}}async function G$(i){let o=process.execPath;if(!await eo(i,o))return;s.info(`sessions: ${i.name} can't reach ${o}: its folders given again`),await Il(i.name);let d=await eo(i,o);if(d)throw Error(`session user: ${i.name} can't run ${o}: ${d} shuts it out (its mode or access list). Root fixes it with setfacl -m u:${i.name}:${d===o?"rx":"x"} ${d}; docs/security/session-user.md`)}var Lo="acl:";async function H$(i,o){let d=await Ao(i),u=Rn(d),f;try{let p=Xo(o),h=process.env.SUPERFACTORY_CLAUDE_BIN||Bun.which("claude")||void 0;f=await nf(h,(v)=>Tn(v));let w=h&&f!==h?Fe(h):void 0,y=[...o.projects,o.cwd];await xn(d,{own:p,shared:y,readable:[...Be(),...o.plugins].filter((v)=>v!==w),closed:await In(y),leadsClaude:process.env.CLAUDE_CONFIG_DIR});let S=br();if(S)await rf(d,S)}catch(p){throw await u(),p}return{user:Of(d),program:(p)=>p,host:Io(d),claudeBin:f,endsWithAgent:!0,release:u}}var Of=(i)=>({name:i.name,uid:-1,gid:-1,home:i.home,group:i.group,sid:i.sid});async function Em(i,o){if(o.startsWith(Lo)){let u=o.slice(Lo.length);return Cl(u),{release:()=>xt(u),user:await Al(u)}}if(!i.group||!o.startsWith(`${i.group}-`))return{release:async()=>{return}};let d=await zo(i,o);return We.set(o,d),{release:wr(d),user:d}}async function Am(i){if(Pe()){if(i)await lo();else Do=!0;return}if(!i?.group||i.sid)return;let o=j(m().run,"session-users.json"),d=[];try{d=Object.keys(JSON.parse(Nt(o,"utf8")).users??{})}catch{}for(let u of d)if(u!==i.name&&!We.has(u)&&u.startsWith(`${i.group}-`))await wr(await zo(i,u))()}var Qo=(i)=>i??"/private/tmp";function Be(){let i=Ee(),o=(d)=>i.some((u)=>le(u,d));return[m().bin,Fe(process.execPath),..._f(process.env.PATH??"",o)].filter((d)=>o(d)&&yr(d))}var Xn=(i,o)=>i.run?i.run(o):g(i.command,o);async function er(i,o,d,u,f){if(i.sid&&i.group){let P=await Ao(i.group),x=Rn(P);try{await xn(P,{own:[],shared:o,readable:Be(),closed:await In(o)})}catch(N){throw await x(),N}let E={...u,...io(Of(P),{...process.env,...u})},I={...f,cwd:d,env:{...f.env,...E}};return{command:I,release:x,run:(N)=>To(P,I,N)}}if(Pe()){let P=await xf(i,o[0]??d),x=`run-${mf(6).toString("hex")}`,E=pn({hidden:Ee(),own:[],projects:o.slice(0,1),cwd:d,readable:Be()}),I=()=>xt(x);await gn(P.name,x,E,[Fe(P.home),P.home]).catch(async(W)=>{throw await I().catch(()=>{return}),W});let N={...u,...io(P,{...process.env,...u})};return{command:Et(P,f,{cwd:d,env:N}),release:I}}if(i.group){let P=await Rf(i),x=wr(P);try{await $n({group:i.group,agent:pr()},P.name,bn({hidden:Ee(),own:[],shared:o,readable:Be(),closed:await In(o)}))}catch(I){throw await x(),I}let E={...u,...io(P,{...process.env,...u})};return{command:Gl(P,d,E,f,E.TMPDIR??Qo(void 0)),release:x}}let p={...u,...io(i,{...process.env,...u})},h=Ee(),w=If().map((P)=>({path:P})),y=await vf(o),S=Wo({hidden:h,writable:y.writable,readable:[...Be(),...y.readable],fixed:y.fixed,home:i.home,sdks:w}),v=r(Qt).flag("--chdir",d).argsOf(Object.entries(p).map(([P,x])=>`${P}=${x}`)).wrap(f).timeoutMs(f.timeoutMs).build();return{command:Jo(i,S,v),release:async()=>{return}}}function _f(i,o){let d=[],u=i.split(gf).filter((f)=>wf(f)&&(o(f)||process.platform==="darwin"));for(let f of u){if(o(f))d.push(f);let p=[];try{p=Fo(f)}catch{}for(let h of p){let w=we(j(f,h));if(w!==j(f,h)&&o(w)&&!le(f,w))d.push(Fe(w))}}return d}var W$=[".git","release","version","licenses","platforms"];function If(i=process.env.PATH??""){let o=Ee(),d=(h)=>o.some((w)=>le(w,h)&&w!==h),u=Mt(),f=[...o,...[".config",".local/share",".local/state",".ssh",".gnupg",".docker",".claude",".netrc"].map((h)=>j(u,h)),...process.env.CLAUDE_CONFIG_DIR?[process.env.CLAUDE_CONFIG_DIR]:[]],p=[];for(let h of _f(i,d)){let w;for(let y=h,S=0;S<=3&&d(y);y=Fe(y),S++){if(f.some((v)=>le(y,v))||le(U(),y))break;if(y!==h&&W$.some((v)=>yr(j(y,v))))w=y}if(w)p.push(w)}return Qn(p)}var V$=(i,o,d)=>j(i,"sdk",o,d.replaceAll("/","%"));function io(i,o){let d={CLAUDE_CONFIG_DIR:j(i.home,".claude")};if(i.sid)return{...Eo(i,o,Tn,pf(o,[lf,...ff])),...d};let u=Ee(),f=(S)=>!!S&&u.some((v)=>le(v,S)),p={...Y$(i,o),HOME:i.home,USER:i.name,LOGNAME:i.name,...i.group||Pe()?{}:{DOCKER_HOST:$l(i)},...pf(o,Pe()?[lf]:ff),...d},h={XDG_CONFIG_HOME:At.config,XDG_CACHE_HOME:".cache",XDG_DATA_HOME:At.data,XDG_STATE_HOME:At.state,XDG_RUNTIME_DIR:Ho,BUN_INSTALL:".bun"},w=i.group||Pe()?[]:["XDG_CONFIG_HOME","XDG_DATA_HOME","XDG_STATE_HOME","XDG_RUNTIME_DIR"];for(let[S,v]of Object.entries(h))if(w.includes(S)||f(o[S]))p[S]=j(i.home,v);let y=!!i.group&&!!o.TMPDIR&&/^(\/private)?\/var\/folders\//.test(o.TMPDIR);if((f(o.TMPDIR)||y)&&!le(j(Mt(),".cache","sf-tmp"),o.TMPDIR??"")){let S=i.group?Qo(void 0):"/tmp";Object.assign(p,{TMPDIR:S,TMP:S,TEMP:S})}return p}function Y$(i,o){if(!i.pool||i.name===i.pool)return{};let d=j(Fe(i.home),i.pool),u={};for(let[f,p]of Object.entries(o))if(p===d||p?.startsWith(`${d}/`))u[f]=`${i.home}${p.slice(d.length)}`;return u}var lf=["safe.directory","*"],q$=["branch.autoSetupMerge","false"],J$=["push.default","current"],ff=[q$,J$];function pf(i,o){let d=Number(i.GIT_CONFIG_COUNT)||0,u={};for(let f=0;f<d;f++)for(let p of[`GIT_CONFIG_KEY_${f}`,`GIT_CONFIG_VALUE_${f}`])u[p]=i[p]??"";return{...u,...Qe(o,d)}}function K$(i,o){if(!o)return;let d=[o];for(let u=0;u<6&&d.length;u++){let f=[];for(let p of d)for(let h of z$(p)){let w=X$(h);if(w.length>1&&w.at(-1)===i)return h;f.push(h)}d=f}return}function z$(i){try{return Fo(`/proc/${i}/task`).flatMap((o)=>Nt(`/proc/${i}/task/${o}/children`,"utf8").trim().split(/\s+/).filter(Boolean).map(Number))}catch{return[]}}function X$(i){try{return(Nt(`/proc/${i}/status`,"utf8").match(/^NSpid:\s*(.*)$/m)?.[1]??"").trim().split(/\s+/).filter(Boolean).map(Number)}catch{return[]}}import{mkdtemp as Zo,rm as ea}from"fs/promises";import{tmpdir as ta}from"os";import{join as ut}from"path";var kr=(i)=>`refs/superfactory/platforms/${i}`,Cf=[".env",".env.*","*.pem","*.key","*.p12","*.pfx","*.keystore","*.jks","id_rsa*","id_ecdsa*","id_ed25519*",".npmrc",".pypirc",".netrc",".git-credentials","credentials.json","*.tfvars"].map((i)=>`**/${i}`),Af=Cf.map((i)=>`:(exclude,glob)${i}`),Tf=Cf.map((i)=>`:(glob)${i}`),Q$={GIT_AUTHOR_NAME:"Superfactory",GIT_AUTHOR_EMAIL:"superfactory@localhost",GIT_COMMITTER_NAME:"Superfactory",GIT_COMMITTER_EMAIL:"superfactory@localhost"};async function Rm(i,o,d){if(d&&!d.shared)return await d.pull(),Z$(i,o,d);let u=await ao(i,`Superfactory: ${o}'s working tree (uncommitted changes)`);return await a(i,(f)=>f.sub("update-ref").arg(kr(o)).arg(u.commit)),u}async function ao(i,o,d){let u=await Cn(i,"HEAD"),f=await Zo(ut(ta(),"sf-snapshot-"));try{let p={GIT_INDEX_FILE:ut(f,"index")};await a(i,(S)=>S.sub("read-tree").arg("HEAD").env(p)),await a(i,(S)=>S.sub("add").flag("--all").endOptions().argsOf([".",...Af]).env(p));let h=[];if(d){let S=await Promise.all([a(i,(x)=>x.sub("diff").flag("--name-only").flag("--no-renames").flag("--diff-filter","MT").flag("-z").endOptions().argsOf(Tf).env(p)),a(i,(x)=>x.sub("ls-files").flag("--others").flag("--exclude-standard").flag("-z").endOptions().argsOf(Tf).env(p))]),v=[],P=await a(i,(x)=>x.sub("diff").flag("--cached").flag("--name-only").flag("--no-renames").flag("--diff-filter","ACMT").flag("-z").arg("HEAD").env(p));for(let x of P.split("\x00").filter(Boolean))if(await d(x,ut(i,x)))v.push(x);if(v.length)await a(i,(x)=>x.sub("reset").flag("--quiet").arg("HEAD").endOptions().argsOf(v).env(p));h.push(...S.flatMap((x)=>x.split("\x00").filter(Boolean)),...v),h.sort()}let w=(await a(i,(S)=>S.sub("write-tree").env(p))).trim();if(w===await Cn(i,"HEAD^{tree}"))return{commit:u,uncommitted:!1,left:h};return{commit:(await a(i,(S)=>S.sub("commit-tree").arg(w).flag("-p",u).flag("-m",o).env(Q$))).trim(),uncommitted:!0,left:h}}finally{await ea(f,{recursive:!0,force:!0})}}async function Z$(i,o,d){let u=kr(o),f=`/tmp/sf-snapshot-${crypto.randomUUID()}.bundle`,p=await q(d.sandbox,ts([l`idx=$(mktemp)`,l`GIT_INDEX_FILE=$idx git read-tree HEAD`,l`GIT_INDEX_FILE=$idx git add --all -- . ${Af}`,l`tree=$(GIT_INDEX_FILE=$idx git write-tree)`,l`rm -f "$idx"`,l`if [ "$tree" = "$(git rev-parse 'HEAD^{tree}')" ]; then echo "head $(git rev-parse HEAD)"; exit 0; fi`,l`commit=$(GIT_AUTHOR_NAME=Superfactory GIT_AUTHOR_EMAIL=superfactory@localhost GIT_COMMITTER_NAME=Superfactory GIT_COMMITTER_EMAIL=superfactory@localhost git commit-tree "$tree" -p HEAD -m ${`Superfactory: ${o}'s working tree (uncommitted changes)`})`,l`git update-ref ${u} "$commit"`,l`git bundle create -q ${f} ${u} --not HEAD`,l`echo "snapshot $commit"`,l`base64 < ${f}`,l`rm -f ${f}`]),{cwd:d.workdir});if(p.exitCode!==0)throw Error(`snapshot in the sandbox: ${p.stderr.trim()}`);let[h="",...w]=p.stdout.split(`
823
+ `),[y,S=""]=h.trim().split(" ");if(y==="head")return await a(i,(P)=>P.sub("update-ref").arg(u).arg(S)),{commit:S,uncommitted:!1};let v=await Zo(ut(ta(),"sf-snapshot-"));try{let P=ut(v,"snapshot.bundle");await Bun.write(P,Buffer.from(w.join("").replace(/\s/g,""),"base64")),await a(i,(x)=>x.sub("fetch").flag("-q").arg(P).arg(`+${u}:${u}`))}finally{await ea(v,{recursive:!0,force:!0})}return{commit:S,uncommitted:!0}}async function Om(i,o,d,u=!1){let f=[];if(!u){for(let h of new Set(d))if(await Cn(i,`${h}^{commit}`).catch(()=>{return}))f.push(h)}let p=await Zo(ut(ta(),"sf-bundle-"));try{let h=ut(p,"code.bundle");return await a(i,(y)=>{let S=y.sub("bundle create").flag("-q").arg(h).arg(kr(o));return u?S:S.flag("--not").flag("--remotes").argsOf(f)},[128]).then(()=>!0,()=>!1)&&await Bun.file(h).exists()?await Bun.file(h).bytes():void 0}finally{await ea(p,{recursive:!0,force:!0})}}async function Mn(i,o){return Cn(i,`${o}^{commit}`).then(()=>!0,()=>!1)}async function Cn(i,o){return(await a(i,(d)=>d.sub("rev-parse").flag("--verify").flag("-q").arg(o))).trim()}import{createWriteStream as eS,existsSync as Mf}from"fs";import{mkdir as Uf,mkdtemp as tS,open as rS,readdir as nS,rename as Nf,rm as Nn,stat as Un}from"fs/promises";import{tmpdir as sS}from"os";import{basename as na,dirname as ra,join as xr,relative as iS}from"path";import{pipeline as oS}from"stream/promises";function aS(){return k("SUPERFACTORY_COPY_RETRY_MS",600000)}async function Ut(i,o){let d=Date.now()+aS();for(let u=500;;u=Math.min(u*2,15000))try{return await o()}catch(f){if(f instanceof yo||f instanceof Lc||Date.now()+u>d)throw f;s.warn(`copy: ${i} failed, again in ${u} ms`,f),await Bun.sleep(u)}}var Df=4;async function Lf(i,o){let d=await Un(o).catch(()=>{return});if(!d)throw new c("not_found",`no file or folder ${o} there`);if(!d.isFile()&&!d.isDirectory())throw new c("bad_request",`${o} is neither a file nor a folder`);let u=na(o),f={kind:"file",name:u,file:o,size:d.size};if(d.isDirectory()){let p=await tS(xr(sS(),"sf-copy-")),h=xr(p,"folder.tar");try{await cS(h,o)}catch(w){throw await Nn(p,{recursive:!0,force:!0}),new c("internal",`couldn't pack ${o}: ${w.message}`)}f={kind:"folder",name:u,file:h,size:(await Un(h)).size,scratch:p}}return dS(i,f),{kind:f.kind,name:f.name,size:f.size}}async function cS(i,o){let d=_(r(ot).flag("-c").flag("--file","-").arg(na(o)).in(ra(o)).build(),{stdin:"ignore"}),u="";d.stderr.on("data",(p)=>{u=`${u}${p}`.slice(-2000)});let[,f]=await Promise.all([oS(d.stdout,eS(i)),new Promise((p,h)=>{d.once("error",h),d.once("close",p)})]);if(f!==0)throw Error(`tar failed (${f}): ${u.trim()}`)}async function dS(i,o){try{let d=Bun.file(o.file),u=new Bun.CryptoHasher("sha256"),f=Math.ceil(o.size/td),p=new Set;for(let w=0;w<f;w++){let y=new Uint8Array(await d.slice(w*td,(w+1)*td).arrayBuffer());u.update(y);let S=Ut(`part ${w}`,async()=>{while(await i.putPart(w,y)==="behind")await Bun.sleep(500)}).finally(()=>p.delete(S));if(S.catch(()=>{return}),p.add(S),p.size>=Df)await Promise.race(p)}await Promise.all(p);let h=u.digest("hex");await Ut("its end",()=>i.sent({ok:!0,kind:o.kind,size:o.size,parts:f,sha256:h}))}catch(d){if(!(d instanceof yo))await i.sent({ok:!1,error:`sending failed: ${jf(d)}`}).catch(()=>{return})}finally{if(o.scratch)await Nn(o.scratch,{recursive:!0,force:!0})}}async function Ff(i,o,d){let u=await Un(i).catch(()=>{return}),f=u?.isDirectory()?xr(i,o):i,p=f===i?u:await Un(f).catch(()=>{return});if(p&&(d==="folder"||p.isDirectory()))throw new c("conflict",`${f} exists: copy to a new path, or remove it first`);return f}async function Bf(i,o,d,u){await Uf(ra(o),{recursive:!0});let f=xr(ra(o),`.${na(o)}.sf-copy-${u}`),p=await rS(f,"w");uS(i,{target:o,partial:f,kind:d,handle:p})}async function uS(i,o){let d=`${o.partial}.d`,u=!0;try{let f=new Bun.CryptoHasher("sha256"),p=0,h,w=new Map,y=[];for(let v=0;;){for(let x=v;x<v+Df&&(!h?.ok||x<h.parts);x++)if(!w.has(x)){let E=Ut(`part ${x}`,()=>i.getPart(x));E.catch(()=>{return}),w.set(x,E)}let P=await w.get(v);if(w.delete(v),P){await o.handle.write(P),f.update(P),p+=P.length;let x=Ut(`part ${v} taken`,()=>i.tookPart(v));x.catch(()=>{return}),y.push(x),v++;continue}if(h=await Ut("the sender's end",()=>i.sentResult()),h&&!h.ok)return;if(h?.ok&&v>=h.parts)break}await Promise.all(y),await o.handle.close(),u=!1;let S=f.digest("hex");if(!h?.ok||S!==h.sha256||p!==h.size)throw Error(`what arrived (${p} bytes, ${S}) isn't what was sent: send it again`);if(o.kind==="file")await Nf(o.partial,o.target);else{await Uf(d,{recursive:!0}),await T(r(ot).flag("--extract").flag("--file",iS(d,o.partial)).in(d).build());let[v]=await nS(d);if(!v)throw Error("the folder's tar was empty");await Nf(xr(d,v),o.target)}await Ut("its end",()=>i.received({ok:!0,path:o.target,size:p,sha256:S}))}catch(f){if(!(f instanceof yo))await i.received({ok:!1,error:`receiving failed: ${jf(f)}`}).catch(()=>{return})}finally{if(u)await o.handle.close().catch(()=>{return});if(Mf(o.partial))await Nn(o.partial,{force:!0});if(Mf(d))await Nn(d,{recursive:!0,force:!0})}}var jf=(i)=>(i instanceof Error?i.message:String(i)).slice(0,1500);var bS=5900,$S=1000;class xl{deps;made=new Map;codes=new Map;copied=new Map;constructor(i){this.deps=i}key=(i)=>`${i.projectId}/${i.taskId}`;place(i,o,d){let u=this.key(i),f=this.made.get(u);if(f)return f;let p=(async()=>{let h=await this.deps.project(i.projectId),w={id:i.taskId,title:o};for(;;)try{return await this.deps.places.forTask(h,w,await this.deps.settings(i.projectId),void 0,{platform:!0,setUp:!1})}catch(y){if(!(y instanceof xe))throw y;d?.(),await y.done}})();return this.made.set(u,p),p.catch(()=>this.made.delete(u)),p}async synced(i,o,d,u){let f=await this.place(i,o,u),{cwd:p}=f;if(!await Mn(p,d.commit)){let w=d.bundle?await this.deps.downloadBundle(i,d.commit):void 0;if(w)await this.fetchBundle(p,i,w);if(!await Mn(p,d.commit))await a(p,(y)=>y.sub("fetch").flag("-q").arg("origin")).catch(()=>{return});if(!await Mn(p,d.commit))throw new c("conflict","needs a full bundle: this machine hasn't the commits it builds on")}await a(p,(w)=>w.sub("checkout").flag("-q").flag("--force").flag("--detach").arg(d.commit));let h=[...this.copied.get(this.key(i))??[]];if(await a(p,(w)=>h.reduce((y,S)=>y.flag("-e",S),w.sub("clean").flag("-q").flag("--force").flag("-d"))),f.sandbox&&!f.sandbox.shared)await f.sandbox.refresh();for(;;)try{await this.deps.places.setUpFromCode(await this.deps.project(i.projectId),f,await this.deps.settings(i.projectId));break}catch(w){if(!(w instanceof xe))throw w;u?.(),await w.done}return this.codes.set(this.key(i),{...d,bundle:!1}),f}async fetchBundle(i,o,d){let u=await pS(Hf(wS(),"sf-platform-"));try{let f=Hf(u,"code.bundle");await Bun.write(f,d);let p=kr(o.taskId);await a(i,(h)=>h.sub("fetch").flag("-q").arg(f).arg(`+${p}:${p}`)).catch(async()=>{await a(i,(h)=>h.sub("fetch").flag("-q").arg("origin")).catch(()=>{return}),await a(i,(h)=>h.sub("fetch").flag("-q").arg(f).arg(`+${p}:${p}`))})}finally{await hS(u,{recursive:!0,force:!0})}}result(i,o){let d=this.codes.get(this.key(i));return{...d?{code:d}:{},ports:o.ports}}async run(i){let o={projectId:i.projectId,taskId:i.taskId},d={type:"platform.output",...o,runId:i.runId,chunk:""},u=(B)=>this.deps.push({...d,step:B}),f=await this.synced(o,i.title,i.code,()=>this.deps.push({...d,setup:!0}));u("running");let p=new Date().toISOString(),h=i.cwd?Rr(f.sandbox?.workdir??f.cwd,i.cwd):void 0,w=await this.deps.settings(o.projectId),y=i.timeoutMs??w["agents.commandTimeoutSeconds"]*1000,S=!!f.sandbox&&!f.sandbox.shared,v=S?{}:await this.deps.githubEnv(i.projectId),P=Object.entries(v).flatMap(([B,fe])=>/token/i.test(B)?[fe]:[]),x=S?void 0:await Dn(),E=x?await er(x,[(await this.deps.project(o.projectId)).path,f.cwd],h??f.cwd,{},xS(i.shell,i.command)):void 0,I=this.deps.runs,W=await I.start({id:i.runId,owner:{kind:"platform",...o},command:i.command,background:i.background,secrets:[...Object.values(i.secretEnv),...P,...S?[]:await yc()],onText:(B)=>this.deps.push({type:"platform.output",...o,runId:i.runId,chunk:B.slice(-65536)}),start:(B)=>f.sandbox&&S?Ld(f.sandbox,kS("linux",i.shell,i.command),{...h?{cwd:h}:{},env:i.secretEnv},B):E?Ui(E.command,B,{input:ES({...v,...i.secretEnv}),endAsRoot:!Pe()}):Ui(Ls(process.platform,i.shell,i.command).in(h??f.cwd).env(v).secretEnv(i.secretEnv).by("platform.run").lowPriority().noNewPrivileges(Fi("task",w)).build(),B)}).catch(async(B)=>{throw await E?.release(),B}),re=!1;I.whenEnded(W).then(async(B)=>{if(await E?.release().catch((fe)=>s.warn(`platforms: ${o.projectId}/${o.taskId}'s session user`,fe)),await this.deps.uploadLog(o,W,I.logOf(W)).catch((fe)=>s.warn(`platforms: ${o.projectId}/${o.taskId}'s log`,fe)),re)this.deps.push({type:"platform.run.ended",...o,run:Wf(i,p,B)})});let C=await I.wait(W,i.background?$S:y);return u("returning"),re=!0,{...this.result(o,f),run:Wf(i,p,C)}}async read(i){let o={projectId:i.projectId,taskId:i.taskId},d=await this.synced(o,i.title,i.code),u=()=>new c("not_found",`no file ${i.path} there`);try{let f;if(d.sandbox&&!d.sandbox.shared){let p=Rr(d.sandbox.workdir,i.path),h=await d.sandbox.sandbox.filesystem.readFile(p).catch(()=>{throw u()});f=sa(i.path,new TextEncoder().encode(h))}else{let p=await PS(d.cwd,i.path),h=p?await gS(p).catch(()=>{return}):void 0;if(!p||!h?.isFile())throw u();f=sa(i.path,await mS(p))}return{...this.result(o,d),file:f}}catch(f){if(!(f instanceof c)||f.code!=="not_found"&&f.code!=="bad_request")throw f;return{...this.result(o,d),file:sa(i.path,new Uint8Array),unreadable:{code:f.code,message:f.message}}}}async send(i){let o={projectId:i.projectId,taskId:i.taskId},d=i.sessionId?await ae(this.deps.sessionFolder(i.sessionId,o),i.path).catch(()=>{throw new c("bad_request",`${i.path}: a path inside the task's folder`)}):await this.copyPath(o,i.title,i.path);return Lf(this.copyServer(o,i.copyId),d)}async receive(i){let o={projectId:i.projectId,taskId:i.taskId},d=i.sessionId?this.deps.sessionFolder(i.sessionId,o):(await this.copyPlace(o,i.title)).cwd,u=!i.sessionId&&Er(i.path)&&!await Dn(),f=u?ia(i.path):await Vf(d,i.path),p=await Ff(f,i.name,i.kind);if(!u)await Vf(d,p);if(!i.sessionId){let h=oa(d,p);if(h&&!h.startsWith("..")&&!Er(h)){let w=this.copied.get(this.key(o))??new Set;w.add(`/${h.split(yS).join("/").replace(/[*?[\\]/g,"\\$&")}`),this.copied.set(this.key(o),w)}}return await Bf(this.copyServer(o,i.copyId),p,i.kind,i.copyId),{ok:!0}}copyServer(i,o){let d=this.deps.copyServer(i,o);if(!d)throw new c("unavailable","this machine isn't linked to a server");return d}async copyPath(i,o,d){let u=await this.copyPlace(i,o);if(Er(d)&&!await Dn())return ia(d);let f=Rr(u.cwd,d);if(f===u.cwd)return f;return ae(u.cwd,f).catch(()=>{throw new c("bad_request",`${d}: a path inside the task's folder`)})}async copyPlace(i,o){let d=await this.place(i,o);if(d.sandbox&&!d.sandbox.shared)throw new c("bad_request","the task's copy there is in a sandbox: copies reach a platform's own machine only");return d}async expose(i){let o={projectId:i.projectId,taskId:i.taskId},d=i.code?await this.synced(o,i.title,i.code):await this.place(o,i.title);if(i.screen&&!d.ports.some((p)=>p.kind==="vnc")){if(!d.sandbox&&await Dn())throw new c("forbidden","this machine's own screen is the desktop of the account its agent runs as, and the task's commands here run as a session user of their own, so it isn't shown to the task; a lead can look at it (machine_screen)");let p=d.sandbox?void 0:await this.deps.machineScreen();if(!p)throw new c("conflict","this platform has no screen to show");d.ports=[...d.ports,{port:Number(new URL(p.url).port)||bS,kind:"vnc"}]}if(i.port===void 0)return this.result(o,d);let u=i.port;if(d.sandbox&&!d.sandbox.shared&&!d.ports.some((p)=>p.kind==="web"&&p.port===u))throw new c("bad_request",`the sandbox there shows ports ${d.ports.filter((p)=>p.kind==="web").map((p)=>p.port).join(", ")}`);let f=d.ports.some((p)=>p.port===u)?d.ports:[...d.ports,{port:u,kind:"web"}];return d.ports=f,{...this.result(o,d),answer:await vS(await this.webAddress(d,u),i.path)}}async webAddress(i,o){if(!i.sandbox||i.sandbox.shared)return{host:"127.0.0.1",port:o};let d=new URL(await i.sandbox.url(o));return{host:d.hostname,port:Number(d.port)}}async address(i,o){let d=await this.made.get(this.key(i)),u=d?.ports.find((f)=>f.port===o);if(!d||!u)throw new c("not_found",`the task's place here doesn't show port ${o}`);if(u.kind==="vnc"){if(d.sandbox)return{screen:await d.sandbox.openVnc()};let f=await this.deps.places.hostScreenAt(d.cwd,o)??await this.deps.machineScreen();return f?{screen:f}:{host:"127.0.0.1",port:o}}return this.webAddress(d,o)}async view(i){let o={projectId:i.projectId,taskId:i.taskId},d=await this.expose({...i,screen:!0}),u=d.ports.find((h)=>h.kind==="vnc");if(!u)throw new c("conflict","this platform has no screen to show");let f=await this.address(o,u.port),p=await("screen"in f?Pt(f.screen):Vn(f)).catch((h)=>{throw new c("unavailable",`couldn't reach the screen: ${h.message}`)});return{...d,screen:await Yn(p,i.actions)}}async end(i){let o=this.key(i);await this.deps.runs.stopWhere((f)=>f.kind==="platform"&&f.projectId===i.projectId&&f.taskId===i.taskId);let d=await this.made.get(o)?.catch(()=>{return});this.made.delete(o),this.codes.delete(o),this.copied.delete(o),await this.deps.places.taskEnded(i.projectId,ho(i.taskId)).catch(()=>{return});let u=await this.deps.project(i.projectId).catch(()=>{return});if(u&&d&&d.cwd!==u.path)await a(u.path,(f)=>f.sub("worktree remove").flag("--force").arg(d.cwd)).catch(()=>{return})}}function Wf(i,o,d){return{id:i.runId,command:i.command,shell:i.shell,cwd:i.cwd,at:o,code:{...i.code,bundle:!1},exitCode:d.exitCode,durationMs:Math.round(d.durationSeconds*1000),...d.state==="running"&&!i.background?{running:!0}:{},...d.state==="timedOut"?{timedOut:!0}:{},...d.state==="stopped"?{stopped:!0}:{},...i.background?{background:!0}:{},...d.processes?{processes:d.processes}:{},outputTail:SS(d.output,Uo),truncated:d.truncated}}var SS=(i,o)=>i.split(`
824
+ `).slice(-o).join(`
825
+ `);async function vS(i,o="/"){let d=await fetch(`http://${i.host}:${i.port}${o}`,{redirect:"manual",signal:AbortSignal.timeout(1e4)}).catch(()=>{return});if(!d)return{status:0,excerpt:"nothing answers: start the server on 0.0.0.0 there"};let u=d.headers.get("content-type")??"",f=/text|json|javascript/.test(u)?await d.text():`(${u||"no type"})`;return{status:d.status,excerpt:f.slice(0,4000)}}function Rr(i,o){let d=ia(i,o),u=oa(i,d);if(u.startsWith("..")||Er(u))throw new c("bad_request","a path inside the task's folder");return d}async function PS(i,o){let d=Rr(i,o),u=d,f=(y)=>!!fS(y,{throwIfNoEntry:!1});while(u!==i&&!f(u)&&Ln(u)!==u)u=Ln(u);let p=await Gf(i),h=await Gf(u).catch(()=>{return}),w=h===void 0?"..":oa(p,h);if(w.startsWith("..")||Er(w))throw new c("bad_request",`${o}: a path inside the task's folder`);return u===d?h:void 0}async function Vf(i,o){let d=Rr(i,o),u=d;while(!lS(u)&&Ln(u)!==u)u=Ln(u);if(u!==i)await ae(i,u).catch(()=>{throw new c("bad_request",`${o}: a path inside the task's folder`)});return d}function sa(i,o){let d=o.length>up;return{path:i,size:o.length,text:new TextDecoder().decode(d?o.subarray(0,up):o),truncated:d}}function kS(i,o,d){if(o!=="default")throw new c("bad_request",`${o} is Windows' own: this platform has bash`);return["bash","-lc",d]}async function Dn(){let i=await ce();return i?.sid?void 0:i}function xS(i,o){if(i!=="default")return Ls(process.platform,i,o).build();return r(Es).script("-c",l`while IFS= read -r -d '' pair; do export "$pair"; done
826
+ exec bash -l -c ${o}`).build()}function ES(i){return Object.entries(i).map(([o,d])=>{if(!/^[A-Za-z_]\w*$/.test(o)||d.includes("\x00"))throw new c("bad_request",`bad variable ${o}`);return`${o}=${d}\x00`}).join("")}function Ls(i,o,d){let u=Ye(d);if(o==="default"){let f=r(Es);return(i==="win32"?f.programPath(Xs()):f).flag("-l").script("-c",u)}if(i!=="win32")throw new c("bad_request",`${o} runs on Windows only: this platform has bash`);return o==="powershell"?r(Ke).flag("-NoProfile").flag("-NonInteractive").script("-Command",u):r(su).flag("/d").flag("/s").script("/c",u)}import{realpathSync as qS}from"fs";import{uptime as JS}from"os";import{readFileSync as RS,statSync as OS}from"fs";import{join as _S}from"path";var IS=(i)=>l`
827
+ $ErrorActionPreference = 'Stop'
828
+ $code = "\`$want = '${i}'\`n" + {
829
+ $ErrorActionPreference = 'Stop'
830
+ $agent = Get-ScheduledTask 'Superfactory agent'
831
+ if ($agent.Actions[0].Arguments -notmatch '-AgentHome "([^"]+)"') { throw 'The agent task names no -AgentHome' }
832
+ $agentHome = $Matches[1]
833
+ $log = Join-Path $agentHome 'update.log'
834
+ try {
835
+ $server = (Get-Content (Join-Path $agentHome 'agent.json') -Raw | ConvertFrom-Json).serverUrl
836
+ "$(Get-Date -Format o) running $server/join.ps1 again" | Out-File $log -Encoding utf8
837
+ for ($try = 1; ; $try++) {
838
+ $joinScript = Invoke-RestMethod "$server/join.ps1"
839
+ if ($want -eq 'any' -or $joinScript.Contains("\`$SuperfactorySha256 = '$want'")) { break }
840
+ if ($try -ge 40) { throw "$server/join.ps1 still names another build than $want after 10 minutes" }
841
+ "$(Get-Date -Format o) $server/join.ps1 names another build than $want (its old replica, mid-rollout?): asking again in 15 s" | Out-File $log -Append -Encoding utf8
842
+ Start-Sleep -Seconds 15
843
+ }
844
+ & ([scriptblock]::Create($joinScript)) *>&1 | Out-File $log -Append -Encoding utf8
845
+ "$(Get-Date -Format o) join.ps1 ended" | Out-File $log -Append -Encoding utf8
846
+ } catch { "$(Get-Date -Format o) join.ps1 failed: $_ (line $($_.InvocationInfo.ScriptLineNumber))" | Out-File $log -Append -Encoding utf8 }
847
+ finally { Unregister-ScheduledTask 'Superfactory update' -Confirm:$false }
848
+ }.ToString()
849
+ $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($code))
850
+ $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand $encoded"
851
+ $principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
852
+ Register-ScheduledTask 'Superfactory update' -Action $action -Principal $principal -Force | Out-Null
853
+ Start-ScheduledTask 'Superfactory update'
854
+ `;async function xc(i){if(i!==void 0&&!/^[0-9a-f]{64}$/.test(i))throw Error(`${i} isn't a build's SHA-256`);await T(r(Ke).flag("-NoProfile").flag("-NonInteractive").script("-Command",IS(i??"any")).timeoutMs(60000).build())}var TS=()=>k("SUPERFACTORY_UPDATE_JOIN_POLL_MS",5000),CS=()=>k("SUPERFACTORY_UPDATE_JOIN_WAIT_MS",1800000),AS=(i=U())=>_S(i,"update.log");async function Cm(i,o){let d=AS();for(let u=Date.now()+CS();Date.now()<u&&!o?.aborted;){await Bun.sleep(TS());let f=MS(d,i);if(f)return f}return}function MS(i,o){let d;try{if(OS(i).mtimeMs<o-1000)return;d=RS(i,"utf8")}catch{return}let u=d.replace(/^\uFEFF/,"").split(/\r?\n/).map((y)=>y.trim()).filter(Boolean),f=u.at(-1)??"",p=u.findLast((y)=>y.startsWith("== "))?.slice(3),h=p?` (at "${p}")`:"",w=/^\S+ join\.ps1 failed: (.*)$/.exec(f);if(w)return`join.ps1 failed${h}: ${w[1]?.trim()}`;if(/^\S+ join\.ps1 ended$/.test(f))return`join.ps1 ended without updating it${h}`;return}import{readFileSync as NS,renameSync as US,writeFileSync as DS}from"fs";import{homedir as zf}from"os";import{join as Zf}from"path";var tp="io.bringes.superfactory.agent",LS=()=>Zf(zf(),"Library","LaunchAgents",`${tp}.plist`),FS=`<key>ProcessType</key><string>Interactive</string>
855
+ <key>Nice</key><integer>0</integer>
856
+ `,Yf=/\s*<key>ProcessType<\/key>\s*<string>[^<]*<\/string>/g,qf=/\s*<key>Nice<\/key>\s*<integer>[^<]*<\/integer>/g,Jf=["/usr/bin","/bin","/usr/sbin","/sbin"],BS=/<key>EnvironmentVariables<\/key>\s*<dict>/,Kf=/(<key>PATH<\/key>\s*<string>)([^<]*)(<\/string>)/;function jS(i,o,d){let u=[Zf(o,".local","bin"),...d==="arm64"?["/opt/homebrew/bin","/opt/homebrew/sbin"]:[],"/usr/local/bin"],f=i.split(":").filter((p)=>p&&!Jf.includes(p));return[...new Set([...f,...u,...Jf])].join(":")}function GS(i,o,d){let u=i.match(Kf),f=jS(u?.[2]??"",o,d);if(u)return u[2]===f?i:i.replace(Kf,`$1${f}$3`);return i.replace(BS,(p)=>`${p}
857
+ <key>PATH</key><string>${f}</string>`)}function HS(i){if(!i.trimStart().startsWith("<?xml"))return;let o=[...i.matchAll(Yf)],d=[...i.matchAll(qf)];if(o.length===1&&/Interactive/.test(o[0]?.[0]??"")&&d.length===1&&/<integer>0</.test(d[0]?.[0]??""))return;let u=i.replace(Yf,"").replace(qf,""),f=u.lastIndexOf("</dict>");if(f<0)return;let p=u.slice(0,f).endsWith(`
858
+ `)?" ":`
859
+ `;return`${u.slice(0,f)}${p}${FS}${u.slice(f)}`}function Pc(){let i=LS(),o;try{o=NS(i,"utf8")}catch{return}let d=HS(o)??o;if(!d.trimStart().startsWith("<?xml"))return;let u=GS(d,zf(),process.arch);if(u===o)return;try{DS(`${i}.new`,u),US(`${i}.new`,i)}catch(f){s.warn(`update: couldn't update ${i}; its service starts the new build as before`,f);return}return s.info("update: its launchd job runs as interactive work with the person's toolchain on PATH from now on"),r(Z).script("-c",WS).arg("sh").arg(tp).arg(i).build()}var WS=l`domain=gui/$(id -u)
860
+ grep -q '<key>LimitLoadToSessionType</key><string>Background</string>' "$2" && domain=user/$(id -u)
861
+ /bin/launchctl bootout "$domain/$1" 2>/dev/null
862
+ for i in 1 2 3 4 5 6 7 8 9 10; do
863
+ /bin/launchctl bootstrap "$domain" "$2" && exit 0
864
+ sleep 1
865
+ done
866
+ exit 1`;import{existsSync as rp}from"fs";import{userInfo as VS}from"os";var np="/usr/local/sbin/superfactory-root";async function co(i,o,d=process.platform,u=np){if(X())throw aa("this agent runs nothing as root (SUPERFACTORY_NO_ROOT)");if(d==="win32"){if(process.env.SUPERFACTORY_ADMINISTRATOR==="1")return o;throw aa("this Windows machine's agent isn't elevated (join.ps1 -Administrator), so it runs nothing as an administrator")}if(process.getuid?.()===0)return o;if(d==="linux"&&rp(u))return r(A).flag("-n").wrap(r(Od).programPath(u).script("-c",Ye(i)).build());if(!await YS())throw aa(`the agent's user (${VS().username}) has no passwordless sudo here`);return r(A).flag("-n").wrap(o.build())}function jm(i=process.platform,o=np,d=process.env){if(i!=="linux"||!(d[Ji]||rp(o)))return!1;return Rp(),!0}var aa=(i)=>new c("unavailable",`No root on this machine: ${i}.`),YS=()=>T(r(A).flag("-n").wrap(r(Xt).build()).by("machine.run root").timeoutMs(1e4).build()).then(()=>!0,()=>!1);var sp=1000,KS=5;function Pl(){return{agentStartedAt:new Date(performance.timeOrigin).toISOString(),bootedAt:new Date(Math.round((Date.now()-JS()*1000)/1000)*1000).toISOString()}}function ca(i,o,d){return Ls("win32","powershell",`shutdown.exe ${i} /t ${o} /f /c '${d.replaceAll("'","''")}'; exit $LASTEXITCODE`)}async function da(i,o){let d=await g(i);if(d.exitCode!==0)throw new c("unavailable",`Windows refused the ${o} (shutdown.exe exited ${d.exitCode}): ${(d.stderr||d.stdout).trim().slice(0,500)}`)}async function zS(i=process.platform){if(i==="win32")return ca("/r",KS,"Superfactory: a lead restarts this machine").by("machine.restart").timeoutMs(30000).build();let o=i==="darwin"?"shutdown -r now":"systemctl reboot";return(await co(o,Ls(i,"default",o))).by("machine.restart").timeoutMs(60000).build()}function ip(){let i=Ze();if(i){if(process.platform==="win32"&&process.env.SUPERFACTORY_ADMINISTRATOR==="1")return{join:!0};if(process.platform==="darwin"&&i==="launchd")return{relaunch:Pc()};return{}}let o=Gt();if(o.updates&&o.restart==="relaunch")return{relaunch:r(rt).programPath(qS(process.execPath)).sub("agent run").in(process.cwd()).build()};throw new c("unavailable",`This agent can't restart itself: nothing would start it again (${o.updates?"no service runs it":o.why}).`)}function Mm(){try{return ip(),!0}catch{return!1}}async function Tc(i,o){let d=Pl();if(i==="reboot"){let f=await zS();if(process.platform==="win32")return s.info("machine: a lead restarts this machine"),await da(f,"restart"),d;return setTimeout(()=>{s.info("machine: a lead restarts this machine"),T(f).catch((p)=>s.warn("machine: the restart a lead asked for failed",p))},sp),d}let u=ip();return setTimeout(()=>{s.info("agent: a lead restarts it"),(u.join?xc():o(u.relaunch)).catch((f)=>s.warn("agent: the restart a lead asked for failed",f))},sp),d}var QS=1000;async function op(){try{let{wired:i,ipv4:o}=await Ba(),d=i&&qc(i.mac),u=i&&ep(i.address,i.prefix);return{...i&&d&&u?{wired:{...i,mac:d,broadcast:u}}:{},ipv4:o.slice(0,32)}}catch(i){s.warn("machine: couldn't list its network adapters",i);return}}async function Nm(i,o){let u=(await Ba()).ipv4.find((h)=>ep(h.address,h.prefix)===o)?.address;if(!u)throw new c("conflict",`this machine has no address on the network of ${o}`);let f=Bh(i),p=XS({type:"udp4",reuseAddr:!0});try{await new Promise((w,y)=>{p.once("error",y),p.bind(0,u,()=>{p.off("error",y),w()})}),p.setBroadcast(!0);let h=0;for(let w=0;w<zh;w++){if(w)await Bun.sleep(Gh);await new Promise((y,S)=>p.send(f,Hh,o,(v)=>v?S(v):y())),h++}return s.info(`machine: sent ${h} wake packets for ${i} to ${o} from ${u}`),{from:u,sent:h}}catch(h){throw new c("unavailable",`couldn't send the wake packet: ${h.message}`)}finally{p.close()}}async function ZS(i=process.platform){if(i==="win32")return ca("/s",60,"Superfactory: this machine shuts down").by("machine.shutdown").timeoutMs(30000).build();let o="shutdown -h +1";return(await co(o,Ls(i,"default",o))).by("machine.shutdown").timeoutMs(60000).build()}async function Lm(){let i=await ZS();if(process.platform==="win32")return s.info("machine: shutting down, as its owner asked"),da(i,"shutdown");setTimeout(()=>{s.info("machine: shutting down, as its owner asked"),T(i).catch((o)=>s.warn("machine: the shutdown asked for failed",o))},QS)}var H=typeof SF_AGENT_VERSION==="string"?SF_AGENT_VERSION:ba.version,la=(i)=>T(r(i).flag("--version").timeoutMs(1e4).build()).then(()=>!0,()=>!1);function Tl(i=process.platform,o=process.env){if(i!=="win32"||o.SUPERFACTORY_ADMINISTRATOR!=="1")return"";return'This machine: Windows, set aside for Superfactory, and you run as its administrator (elevated). Install what the task needs yourself, without asking the user: `winget install --silent --accept-package-agreements --accept-source-agreements <id>` (Visual Studio Build Tools: Microsoft.VisualStudio.2022.BuildTools with `--override "--quiet --wait --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"`; Rust: Rustlang.Rustup), then open a new shell for its PATH. Leave alone what other tasks on this machine rely on.'}var t0=l`$c = Get-CimInstance Win32_ComputerSystem; "$($c.Manufacturer)|$($c.Model)"`,r0=/virtual|vmware|qemu|kvm|kubevirt|xen|parallels|bochs|innotek/i;async function _c(i=process.platform){try{if(i==="darwin")return/^VirtualMac/.test(await T(r(Fd).flag("-n").arg("hw.model").timeoutMs(1e4).by("machine.vm").build()));if(i==="win32")return r0.test(await T(r(zd).flag("-NoProfile").flag("-NonInteractive").script("-Command",t0).timeoutMs(30000).by("machine.vm").build()));if(i==="linux")return await T(r(Hd).flag("--vm").timeoutMs(1e4).by("machine.vm").build()),!0}catch{}return!1}function n0(){let i=process.env.SUPERFACTORY_OS_FAKE;if(i==="darwin"||i==="linux"||i==="windows")return i;return process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux"}async function Ic(i=e0()){let o=!!process.env.SUPERFACTORY_SANDBOX,[d,u,f,p,h,w,y]=await Promise.all([mt(process.env.SUPERFACTORY_CLAUDE_BIN),la(ye),la(_s),process.platform==="darwin"&&process.arch==="arm64"?la(R):!1,o?ds()!==void 0:gc(),o?!1:_c(),fc()]),S=["host",...p?["tart"]:[]],v=o?void 0:await op();return{name:i,kind:o?"sandbox":"host",os:n0(),arch:process.arch==="arm64"?"arm64":"x64",agentVersion:H,autoUpdate:Gt().updates,claudeVersion:d,capabilities:{runners:S,git:u,gh:f,screen:h,...w?{vm:w}:{},...o?{}:{dedicated:pc(y,w)},plugins:Qc(),...Zs().length?{pluginFailures:Zs()}:{},...js().length?{mirrorFailures:js()}:{},...Mi().length?{macPermissionsMissing:Mi()}:{},...zn()?{claudeLoginSignedOut:zn()}:{}},...v?{lan:v}:{}}}async function uo(i,o){return{id:i,...await Ic(o),status:"online",lastSeenAt:new Date().toISOString()}}async function _l(){if(process.platform!=="darwin")return[];let i=await T(r(Ud).arg("SPDisplaysDataType").flag("-json").timeoutMs(20000).build());return(JSON.parse(i).SPDisplaysDataType??[]).flatMap((d)=>d.spdisplays_ndrvs??[]).map((d,u)=>{let[f=0,p=0]=(d._spdisplays_pixels??"").match(/\d+/g)?.map(Number)??[],h=d._name??`Display ${u+1}`;return{id:String(u+1),name:h,width:Math.max(1,f),height:Math.max(1,p),main:d.spdisplays_main==="spdisplays_yes",virtual:/virtual|dummy/i.test(h)}})}
867
+ export{Ce,ac,Qf,as,Gn,cc,dc,al,Ii,an,to,uc,Ei,cl,cs,Ai,Ns,dl,so,ul,Wn,ll,pl,fl,cn,Xf,em,tm,lc,sm,Bt,nm,dn,rm,om,Ri,ml,Oi,im,Ci,ji,am,cm,dm,pc,fc,Mi,um,lm,pm,Ge,Ni,$e,qn,mc,Vn,Pt,hl,fm,Li,hc,ds,gl,gc,wl,Di,ae,Tt,wc,yl,Ui,Fi,mm,Kn,Yn,bl,hm,yc,gm,no,bc,kl,wm,kc,Bi,vl,xe,ro,Hi,ym,vc,bm,X,Sc,Jn,oo,zi,Gi,lt,Wi,qi,Zn,km,Vi,vm,Sm,$m,Qn,Sl,xm,Pm,ce,$c,Tm,_m,$l,Im,Em,Am,Xn,er,io,Rm,ao,Om,xl,Ls,xc,Cm,Pc,co,jm,Pl,Mm,Tc,Nm,Lm,H,Tl,_c,Ic,uo,_l};