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.
- package/README.md +34 -2
- package/THIRD-PARTY-NOTICES.md +27604 -0
- package/bin/superfactory.js +57 -0
- package/cli/agent-rf446fr1.js +2 -0
- package/cli/agent-state-wv62c1td.js +2 -0
- package/cli/bin-0cvfmkhh.js +33 -0
- package/cli/bin-0t68hf99.js +3 -0
- package/cli/bin-19vpzq7g.js +4 -0
- package/cli/bin-37w316c6.js +3 -0
- package/cli/bin-3dsqxzbz.js +3 -0
- package/cli/bin-4j0jjd8g.js +3 -0
- package/cli/bin-4tdqjbbd.js +229 -0
- package/cli/bin-4zvje4sn.js +502 -0
- package/cli/bin-674kd343.js +7 -0
- package/cli/bin-8jdkg4ke.js +3 -0
- package/cli/bin-d99yte0j.js +5 -0
- package/cli/bin-fgvkq9cq.js +867 -0
- package/cli/bin-fkp3j5f3.js +3 -0
- package/cli/bin-fypan1f6.js +951 -0
- package/cli/bin-gg19acwr.js +4 -0
- package/cli/bin-ghp5x0x5.js +139 -0
- package/cli/bin-gk00mnmn.js +5 -0
- package/cli/bin-gne2w036.js +29 -0
- package/cli/bin-grxzwpe8.js +3 -0
- package/cli/bin-h57gajkz.js +8 -0
- package/cli/bin-mbpvzx2b.js +8 -0
- package/cli/bin-nnq8kd9z.js +4 -0
- package/cli/bin-ven2efjq.js +3 -0
- package/cli/bin-yqb1d1mw.js +22 -0
- package/cli/bin-z5b3tt05.js +20 -0
- package/cli/bin-za1by1n5.js +3 -0
- package/cli/bin-zpfe0pxz.js +1 -0
- package/cli/bin.js +3 -0
- package/cli/child-agent-qgeqvs03.js +4 -0
- package/cli/connect-chn8pxyf.js +2 -0
- package/cli/container-j6zr9gww.js +4 -0
- package/cli/dev-gsaehf19.js +7 -0
- package/cli/health-nqzge5kh.js +2 -0
- package/cli/home-lock-5seng0k3.js +2 -0
- package/cli/host-7dfjhf0z.js +1507 -0
- package/cli/index-1wseh1tm.js +2 -0
- package/cli/index-axfe8zef.js +2 -0
- package/cli/index-s9pw90xe.js +2 -0
- package/cli/install-17r8t45e.js +2 -0
- package/cli/join-551zg7yr.js +31 -0
- package/cli/local-server-2smsafvg.js +2 -0
- package/cli/machine-zfjmpw7h.js +2 -0
- package/cli/main-0mxhd968.js +33 -0
- package/cli/main-53qmhxmd.js +303 -0
- package/cli/move-to-xrr2b135.js +2 -0
- package/cli/npm-package.json +1 -0
- package/cli/pair-phone-070c9ztt.js +5 -0
- package/cli/prompt-psc4drtd.js +2 -0
- package/cli/reached-vwzx2cdg.js +2 -0
- package/cli/sessions-bm4mk37y.js +3 -0
- package/cli/sf-cli-s42gkp0b.js +2 -0
- package/cli/sf-db-r8f1a20b.js +23 -0
- package/cli/sf-deploy-wqaa4fdm.js +21 -0
- package/cli/sf-pr-rg3q3tn6.js +13 -0
- package/cli/sf-test-pff158qc.js +10 -0
- package/cli/tart-isolation-wr3xwfmw.js +3 -0
- package/cli/tray-4rr0y1dv.png +0 -0
- package/cli/tray-mac-offline-89dva0gs.png +0 -0
- package/cli/tray-mac-paused-hq3a1cxv.png +0 -0
- package/cli/tray-mac-tvtavf0g.png +0 -0
- package/cli/tray-offline-xj6b5ta4.png +0 -0
- package/cli/tray-paused-6pzdv5ze.png +0 -0
- package/cli/vm-keeper-p0ggcw3z.js +3 -0
- package/package.json +50 -4
- package/plugins/sf-video-review/.claude-plugin/plugin.json +17 -0
- package/plugins/sf-video-review/.mcp.json +9 -0
- package/plugins/sf-video-review/dist/video-review.mjs +135 -0
- package/plugins/sf-video-review/skills/video-review/SKILL.md +65 -0
- package/plugins/sf-video-studio/.claude-plugin/plugin.json +17 -0
- package/plugins/sf-video-studio/.mcp.json +19 -0
- package/plugins/sf-video-studio/dist/demo-video.mjs +139 -0
- package/plugins/sf-video-studio/dist/narration-voice.mjs +134 -0
- package/plugins/sf-video-studio/dist/video-generation.mjs +131 -0
- package/plugins/sf-video-studio/fonts/DejaVuSansMono-Bold.ttf +0 -0
- package/plugins/sf-video-studio/fonts/DejaVuSansMono.ttf +0 -0
- package/plugins/sf-video-studio/fonts/LICENSE-DejaVu +187 -0
- package/plugins/sf-video-studio/hooks/hooks.json +17 -0
- package/plugins/sf-video-studio/hooks/no-robot-voice.sh +77 -0
- package/plugins/sf-video-studio/kokoro/package-lock.json +1137 -0
- package/plugins/sf-video-studio/kokoro/package.json +11 -0
- package/plugins/sf-video-studio/skills/demo-video/SKILL.md +101 -0
- package/plugins/sf-video-studio/skills/narration-voice/SKILL.md +49 -0
- package/plugins/sf-video-studio/skills/video-generation/SKILL.md +30 -0
- package/server/dist/account.js +3 -0
- package/server/dist/backup-process.js +2 -0
- package/server/dist/backup.js +3 -0
- package/server/dist/chunk-0tbq288f.js +3055 -0
- package/server/dist/chunk-18n7tr66.js +3 -0
- package/server/dist/chunk-1kgfrgmv.js +3 -0
- package/server/dist/chunk-1rnmxaav.js +209 -0
- package/server/dist/chunk-26zhqbyn.js +25 -0
- package/server/dist/chunk-34mn2zj2.js +2 -0
- package/server/dist/chunk-3psgsw9t.js +2 -0
- package/server/dist/chunk-8zbwppny.js +391 -0
- package/server/dist/chunk-9pn7q001.js +3 -0
- package/server/dist/chunk-9y7a9gkf.js +2 -0
- package/server/dist/chunk-bhm6jzch.js +8 -0
- package/server/dist/chunk-dbzjsqvb.js +17 -0
- package/server/dist/chunk-fxn504n0.js +2 -0
- package/server/dist/chunk-g6pwaap3.js +2 -0
- package/server/dist/chunk-gefgv8rg.js +7 -0
- package/server/dist/chunk-jg8b833v.js +2 -0
- package/server/dist/chunk-jy148bhn.js +3 -0
- package/server/dist/chunk-ky4nz39j.js +7 -0
- package/server/dist/chunk-mbd1y9qk.js +2 -0
- package/server/dist/chunk-neyhk32g.js +13 -0
- package/server/dist/chunk-nrz953bx.js +2 -0
- package/server/dist/chunk-padvv31s.js +2 -0
- package/server/dist/chunk-q1s2ez77.js +3 -0
- package/server/dist/chunk-q403h2bh.js +10 -0
- package/server/dist/chunk-t64r6enn.js +4 -0
- package/server/dist/chunk-vccappg7.js +59 -0
- package/server/dist/chunk-vj60fbhw.js +2 -0
- package/server/dist/chunk-xj26rwda.js +3 -0
- package/server/dist/chunk-xyw98jst.js +5 -0
- package/server/dist/main.js +43 -0
- package/server/dist/move.js +3 -0
- package/server/drizzle/pg/0000_baseline.sql +632 -0
- package/server/drizzle/pg/0001_transcripts_packed.sql +2 -0
- package/server/drizzle/pg/0002_vm_server_origin.sql +1 -0
- package/server/drizzle/pg/0003_reached_machines.sql +1 -0
- package/server/drizzle/pg/0004_link_records.sql +2 -0
- package/server/drizzle/pg/0005_task_columns.sql +7 -0
- package/server/drizzle/pg/0006_task_bundle.sql +3 -0
- package/server/drizzle/pg/0007_server_log.sql +9 -0
- package/server/drizzle/pg/0008_notification_pauses.sql +6 -0
- package/server/drizzle/pg/0009_vm_replaces.sql +1 -0
- package/server/drizzle/pg/0010_question_told_once.sql +10 -0
- package/server/drizzle/pg/0011_node_next_key.sql +3 -0
- package/server/drizzle/pg/0012_task_work.sql +8 -0
- package/server/drizzle/pg/0013_task_secret_grants.sql +9 -0
- package/server/drizzle/pg/0014_node_paused.sql +2 -0
- package/server/drizzle/pg/0015_ssh_machines.sql +19 -0
- package/server/drizzle/pg/0016_node_wake.sql +1 -0
- package/server/drizzle/pg/0017_node_uninstall_key.sql +1 -0
- package/server/drizzle/pg/0018_release_starts.sql +6 -0
- package/server/drizzle/pg/0019_session_memory.sql +7 -0
- package/server/drizzle/pg/meta/_journal.json +146 -0
- package/server/drizzle/sqlite/0000_pre_drizzle_schema.sql +351 -0
- package/server/drizzle/sqlite/0001_cluster.sql +36 -0
- package/server/drizzle/sqlite/0002_task_records.sql +22 -0
- package/server/drizzle/sqlite/0003_indexes.sql +12 -0
- package/server/drizzle/sqlite/0004_project_machines.sql +19 -0
- package/server/drizzle/sqlite/0005_session_events.sql +7 -0
- package/server/drizzle/sqlite/0006_task_platforms.sql +8 -0
- package/server/drizzle/sqlite/0007_session_event_tags.sql +7 -0
- package/server/drizzle/sqlite/0008_sprints.sql +7 -0
- package/server/drizzle/sqlite/0009_project_vms.sql +19 -0
- package/server/drizzle/sqlite/0010_server_repairs.sql +4 -0
- package/server/drizzle/sqlite/0011_drop_todos.sql +2 -0
- package/server/drizzle/sqlite/0012_hypervisors.sql +14 -0
- package/server/drizzle/sqlite/0013_manager_leads.sql +2 -0
- package/server/drizzle/sqlite/0014_session_text.sql +35 -0
- package/server/drizzle/sqlite/0015_vm_resize_machine_instructions_access.sql +22 -0
- package/server/drizzle/sqlite/0016_tunnel.sql +23 -0
- package/server/drizzle/sqlite/0017_session_secret_grants.sql +7 -0
- package/server/drizzle/sqlite/0018_https.sql +18 -0
- package/server/drizzle/sqlite/0019_secret_grant_runs.sql +1 -0
- package/server/drizzle/sqlite/0020_session_transcripts.sql +16 -0
- package/server/drizzle/sqlite/0021_claude_signed_out.sql +2 -0
- package/server/drizzle/sqlite/0022_machine_disabled.sql +1 -0
- package/server/drizzle/sqlite/0023_machine_access_granted_by.sql +1 -0
- package/server/drizzle/sqlite/0024_machine_vms.sql +27 -0
- package/server/drizzle/sqlite/0025_machine_tunnel_fallback.sql +1 -0
- package/server/drizzle/sqlite/0026_tunnel_peer_linked.sql +3 -0
- package/server/drizzle/sqlite/0027_tunnel_upgrade_grace.sql +2 -0
- package/server/drizzle/sqlite/0028_dialed_machines.sql +2 -0
- package/server/drizzle/sqlite/0029_node_link.sql +3 -0
- package/server/drizzle/sqlite/0030_sprint_calendar.sql +1 -0
- package/server/drizzle/sqlite/0031_transcripts_packed.sql +2 -0
- package/server/drizzle/sqlite/0032_vm_server_origin.sql +1 -0
- package/server/drizzle/sqlite/meta/_journal.json +237 -0
- package/server/src/account.ts +2 -0
- package/server/src/backup.ts +2 -0
- package/server/src/features/backups/backup-process.ts +2 -0
- package/server/src/main.ts +2 -0
- package/server/src/move.ts +2 -0
- package/ui/dist/_expo/static/css/global-d378e211074d97e633bc15418ccf57d4.css +2 -0
- package/ui/dist/_expo/static/css/xterm-8a7c4e0dca731c11dbe6bdff98fb667c.css +1 -0
- package/ui/dist/_expo/static/js/web/Network-f300a5960620f5029c91c06cae29dba5.js +3 -0
- package/ui/dist/_expo/static/js/web/[...rest]-9e454d985f211f5c983f42bec15b6ad9.js +1 -0
- package/ui/dist/_expo/static/js/web/[managerId]-2580b90e8d862ad66197eecb1dc04a12.js +1 -0
- package/ui/dist/_expo/static/js/web/[managerId]-39308153b42eed025c0abb9242ae6c71.js +1 -0
- package/ui/dist/_expo/static/js/web/[managerId]-8b7a94ec818e50a371b6b2750b73df6a.js +1 -0
- package/ui/dist/_expo/static/js/web/[managerId]-ac3a14c7607e4576d7e6c39c1014bcaf.js +1 -0
- package/ui/dist/_expo/static/js/web/[managerId]-e8549b2313a119437c373e30207518c0.js +1 -0
- package/ui/dist/_expo/static/js/web/[ref]-9b46f1ec4348f980e9838b68d47c34bf.js +2 -0
- package/ui/dist/_expo/static/js/web/[sessionId]-09e376674fb8b3edc4ae8aa9b3a189d7.js +1 -0
- package/ui/dist/_expo/static/js/web/[sessionId]-0e5fdba25c9f78220cea4cb66227743d.js +1 -0
- package/ui/dist/_expo/static/js/web/[sessionId]-104af3c3885009e6a8d204b6fd6e2c3a.js +1 -0
- package/ui/dist/_expo/static/js/web/[sessionId]-863a34ca3835b469134ddbc4ebc6fafc.js +1 -0
- package/ui/dist/_expo/static/js/web/[taskId]-1218e1dd3ecf175ffb7701fc886d62c9.js +1 -0
- package/ui/dist/_expo/static/js/web/[taskId]-31a48c7017dbd096f8ece9dc102a9762.js +1 -0
- package/ui/dist/_expo/static/js/web/[taskId]-a56cf85bcfd14f2d6b5d4180ea17e8d7.js +1 -0
- package/ui/dist/_expo/static/js/web/[taskId]-f2a157b3cb676b3c5d04c8eadfe90cdd.js +1 -0
- package/ui/dist/_expo/static/js/web/__common-1ad58e53e08528a67b99f53a1690b669.js +2078 -0
- package/ui/dist/_expo/static/js/web/__expo-metro-runtime-1f8f5d3ca6b7f58204d51e14506d73fb.js +5 -0
- package/ui/dist/_expo/static/js/web/_layout-057457e97e0af20433ed41b39cb5e809.js +1 -0
- package/ui/dist/_expo/static/js/web/_layout-2a7d73d5356823e1f7d2dab23e440d09.js +7 -0
- package/ui/dist/_expo/static/js/web/_layout-42e6a6b7855655d456015ce41aefdd39.js +1 -0
- package/ui/dist/_expo/static/js/web/_layout-a5e5a5b2fb3bfbfcc2914131976679e7.js +1 -0
- package/ui/dist/_expo/static/js/web/_layout-b2cbba92506f66815a5d744fd7cd5d8c.js +1 -0
- package/ui/dist/_expo/static/js/web/_layout-b4d13dc52bbcb65b18b4e52813d53883.js +198 -0
- package/ui/dist/_expo/static/js/web/_layout-fb0f75b354800de2e1582dc963f5c148.js +1 -0
- package/ui/dist/_expo/static/js/web/index-41299a961569cc8e5410ec53ba2b87c4.js +4 -0
- package/ui/dist/_expo/static/js/web/index-6c2bb0d3b6d00c5c007a663e9f4ce108.js +1 -0
- package/ui/dist/_expo/static/js/web/index-70484f7d2769d9ae01dac1fdb22aef1d.js +14 -0
- package/ui/dist/_expo/static/js/web/index-7d764cb7cefe0a217728c24d44990057.js +14 -0
- package/ui/dist/_expo/static/js/web/index-a5eb3d0c6aa4c483674beb5de428634c.js +12 -0
- package/ui/dist/_expo/static/js/web/index-b1c2543003cba86eeb3abfa4d21fd8da.js +14 -0
- package/ui/dist/_expo/static/js/web/index-d200aded5448966e5e05d9ccb77b56a4.js +5 -0
- package/ui/dist/_expo/static/js/web/index-ea43f51ceec4a981c942fc6dce9cedc4.js +2378 -0
- package/ui/dist/_expo/static/js/web/index-efa68d817a7febbf8c0163303bf4cd49.js +29 -0
- package/ui/dist/_expo/static/js/web/licenses-30f8c0555f7f4d434a68ee4706fa433d.js +1 -0
- package/ui/dist/_expo/static/js/web/pair-3f6f72208023894f43f4f07db5116cca.js +1 -0
- package/ui/dist/_expo/static/js/web/rich-markdown-editor-dea9c0f7c0306da4146e54ee44cce173.js +228 -0
- package/ui/dist/_expo/static/js/web/sign-in-67d2a0c00232e0e6f40efade1a83dc4b.js +4 -0
- package/ui/dist/_expo/static/js/web/terminal-view-32db8e6f8a21dd073f6a310862d36db8.js +90 -0
- package/ui/dist/apple-touch-icon.png +0 -0
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- package/ui/dist/favicon.ico +0 -0
- package/ui/dist/favicon.svg +10 -0
- package/ui/dist/icon-192.png +0 -0
- package/ui/dist/icon-512.png +0 -0
- package/ui/dist/index.html +45 -0
- package/ui/dist/legal/privacy-policy.md +174 -0
- package/ui/dist/legal/terms-of-use.md +76 -0
- package/ui/dist/load-again.js +42 -0
- package/ui/dist/manifest.webmanifest +12 -0
- package/ui/dist/metadata.json +1 -0
- package/ui/dist/sounds/bell.wav +0 -0
- package/ui/dist/sounds/chime.wav +0 -0
- package/ui/dist/sounds/knock.wav +0 -0
- package/ui/dist/sounds/pop.wav +0 -0
- package/ui/dist/sw.js +121 -0
|
@@ -0,0 +1,951 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{e,J,b,i,n,o,t,Vl,M,I,Fs,gs,rr,h,we,f,yn,Vt,Kt,$o,te,xh,Ph,gt,K,It,Th,_h,Ve,Kl,bn,Ih,Eh,Ah,Yl,D,To,Oh,me,Xl,Fh,tp,Wh,qh,ur,sp,_o,Vh,Vc,lr,Hs,Yt,np,Io,rp,yt,zs,Yh,Ne,Le,Sn,Jh,ya,Et,At,Oo,bt,ba,mr,Xh,eg,sg,Zc,ap,rg,ke,ed,cp,xn,jo,Mo,Sa,dp,dg,ug,$a,Uo,fg,hg,De,lp,hp,gr,yp,bp,vp,xg,Ia,$s,Ho,nd,Sp,Pg,Tg,st,_g,$p,Ig,Eg,Ea,Ag,rd,Ot,jg,Mg,Ct,Ps,Ee,wr,re,Go,Wg,vt,Xg,sw,ja,nt}from"./bin-4tdqjbbd.js";import{St,Ma,pd,fd,hd,Ue,Zt,Fe,_s,Ks,bd,kd,$t,A,Ys,Qt,Cd,jd,La,Md,En,Js,jt,Zs,Qs,se,rt,Xt,Bd,Wd,oe,vr,Yd,$r,Qd,tu,Is,Ke,Z,ot,R,cu,du,uu,lu,pu,fu,mu,hu,wu,es,l,r,g,xt,T,_,Jo,Pu,Tu}from"./bin-h57gajkz.js";import{Ce,ac,Qf,dc,al,Ii,an,to,Ei,cs,Ai,Ns,dl,so,ul,Wn,ll,pl,fl,cn,lc,sm,Bt,nm,dn,rm,om,Ri,ml,Oi,im,Ci,ji,am,cm,dm,pc,fc,um,lm,pm,Ge,Ni,$e,qn,mc,Pt,ds,gl,gc,wl,Di,ae,Tt,wc,yl,Ui,Fi,mm,Yn,bl,hm,yc,gm,no,kl,wm,kc,Bi,xe,ro,Hi,X,Sc,oo,zi,Gi,lt,Wi,qi,Zn,km,Vi,vm,Sm,$m,Qn,Sl,xm,Pm,ce,$c,_m,$l,Im,Em,Am,io,Rm,ao,Om,xl,Ls,xc,Cm,Pc,co,jm,Pl,Mm,Tc,Nm,Lm,H,Tl,_c,Ic,uo,_l}from"./bin-fgvkq9cq.js";import{ea,jl,ms,E,mn,Ml,hs,hn,Wm,Nl,Ac,Rc,qm,ta,Oc,Ll,Ym,Jm,Zm,Dl,Cc,sa,na,c,tr,gn,a,ue,pt,We,ee,ia,Fl,nh,rh,oh,Us,ge,ih}from"./bin-gne2w036.js";import{Pe,z,de,U,m,Al,fs,W,F}from"./bin-nnq8kd9z.js";import{Xo,Gp,P,jr,Mr,Nr,ei,Wp,ti,Lr,si,Nu,Lu,ni,be,sn,ns,ri,qp,oi,ii,ai,Vp,Kp,Ae,he,jn,Du,Ga,dt,Mn,Wa,Dr,Ur,Yp,ci,qa,di,Uu,Fu,Cs,Jp,Va,Nn,nn,ui,Zp,Ka,Bu,Qp,ut,Re,rs,os,Ya,Hu,Xp,ef,tf,sf,Fr,li,nf,zu,Gu,pe,rn,rf,Wu,Ut,Br,qu,of,pi,af,Vu,Ja,Hr,Za,He,on,cf,fi,df,uf,Ln,mi,Ku,Qa,ze,lf,Yu,pf,Ju,hi,ff,Zu,mf,hf,gf,wf,yf,bf,kf,vf,Sf,$f,xf,zr,gi,Pf,Xa,Q,Qu,fe,Xu,Tf,_f,If,Ef,wi,Af,Rf,Of,ec,yi,bi,tc,sc,Dn,Gr,Cf,jf,el,Mf,tl,Nf,Wr,Lf,Df,Uf,Ff,sl,Bf,Un,ki,Fn,qr,nl,Hf,Bn,Vr,vi,rl,nc,zf,Kr,Yr,Hn,Gf,zn,rc,oc,Wf,is,Oe,Ft,Jr,Zr,Si,Vf,js,Ms,ic,$i,q,Kf,Yf,Qr,Xr,ol,Jf,xi,Pi,Ti,_i,il,Zf,eo}from"./bin-4zvje4sn.js";import{ca,C,Wt,wo,ah,ch,dh,uh,lh,ph,fh,mh,hh,wh,bo}from"./bin-za1by1n5.js";import{mt,Gl,Te,qt,Uc,qe,Wl}from"./bin-z5b3tt05.js";import{Gt,Ze}from"./bin-0t68hf99.js";import{lo,Il,Ht,us,un,Dm,zt,pn,Ki,ls}from"./bin-4j0jjd8g.js";import{Ol}from"./bin-yqb1d1mw.js";import{El}from"./bin-674kd343.js";import{Hm,zm}from"./bin-mbpvzx2b.js";import{Rl}from"./bin-gk00mnmn.js";import{fn}from"./bin-8jdkg4ke.js";import{k}from"./bin-37w316c6.js";import{O,s}from"./bin-gg19acwr.js";import{wn}from"./bin-ven2efjq.js";import{Me}from"./bin-fkp3j5f3.js";import{randomBytes as Jj}from"crypto";import{existsSync as zj}from"fs";import{hostname as Xj}from"os";import{createHash as x$,timingSafeEqual as M$}from"crypto";var Mu="/control",Dp=t({serverUrl:J(),token:e().min(1),fingerprint:e().min(1).optional()}),Up=t({serverUrl:J(),nodeId:e().min(1),key:e().min(16),fingerprint:e().min(1).optional()}),Fp=t({path:we,name:e().min(1).optional()}),Bp=t({on:n().default(!0)}),Hp=t({on:n().default(!0),running:_o.default("finish")});import{gunzipSync as v$}from"zlib";var Vd="/git/",Kd=134217728,S$=67108864,P$=600000,Jt=(d,u)=>u===`sf/${d}`||u.startsWith(`sf/${d}-`),$$=/^0+$/,ww=(d,u)=>`http://127.0.0.1:${d}${Vd}${u}`;class Jd{deps;defaults=new Map;constructor(d){this.deps=d}async handle(d){let u=new URL(d.url),p=/^\/git\/([^/]+)\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/(info\/refs|git-receive-pack)$/.exec(u.pathname),w=h.safeParse(p?.[1]);if(!p||!w.success)return qs(404,"not a push to a project's repository");let[,,y,v,S]=p;if(S==="info/refs"&&u.searchParams.get("service")!=="git-receive-pack")return qs(403,"Superfactory's push gateway takes pushes only: fetch from GitHub itself");let x=E$(d),j=x?await this.deps.pusher(x).catch(()=>{return}):void 0;if(!j||j.projectId!==w.data)return new Response(`Superfactory: a push here is a session's of this project (sf git-credential)
|
|
3
|
+
`,{status:401,headers:{"www-authenticate":'Basic realm="Superfactory push gateway"'}});let L=await this.deps.projectToken(w.data).catch(()=>{return});if(!L)return qs(503,"Superfactory: this project's GitHub token isn't here now; try again");let N=`${new URL(L.host).origin}/${y}/${v}.git/${S}${u.search}`;if(S==="info/refs")return this.forward(d,N,L,void 0);if(d.method!=="POST")return qs(405,"a push is a POST");let B=new Uint8Array(await d.arrayBuffer());if(B.byteLength>Kd)return qs(413,"Superfactory takes no push over 128 MB");let G;try{let ne=d.headers.get("content-encoding")==="gzip"?R$(B):B;G=T$(ne)}catch(ne){return qs(400,`Superfactory: not a push git sends (${ne.message})`)}let V=await this.defaultBranch(w.data,y,v,L),Y=G.updates.flatMap((ne)=>{let ie=I$(ne,V,j.rule);return ie?[{ref:ne.ref,why:ie}]:[]});if(Y.length)return s.info(`github: refused a task's push to ${y}/${v}: ${Y.map((ne)=>`${ne.ref} (${ne.why})`).join(", ")}`),A$(G.updates,Y,G.capabilities);return this.forward(d,N,L,B)}async forward(d,u,p,w){let y=new Headers({authorization:gw(p.token)});for(let j of["accept","content-type","content-encoding","git-protocol","user-agent"]){let L=d.headers.get(j);if(L)y.set(j,L)}let v=await(this.deps.fetch??fetch)(u,{method:d.method,headers:y,...w?{body:w}:{},redirect:"manual"}).catch((j)=>j);if(v instanceof Error)return qs(502,`Superfactory: GitHub wasn't reached (${v.message})`);let S=v.status===401?403:v.status,x=new Headers;for(let j of["content-type","cache-control","expires","pragma"]){let L=v.headers.get(j);if(L)x.set(j,L)}return new Response(v.body,{status:S,headers:x})}defaultBranch(d,u,p,w){let y=`${d} ${u}/${p}`.toLowerCase(),v=this.defaults.get(y);if(v&&v.until>Date.now())return v.branch;let S=new URL(w.host).origin,x=(this.deps.fetch??fetch)(`${S}/${u}/${p}.git/info/refs?service=git-upload-pack`,{headers:{authorization:gw(w.token)},redirect:"manual"}).then(async(j)=>{if(!j.ok)throw Error(`GitHub answered ${j.status}`);return/symref=HEAD:(refs\/heads\/[^\s\0]+)/.exec(await j.text())?.[1]}).catch((j)=>{this.defaults.delete(y),s.info(`github: no default branch of ${u}/${p} (${j.message}): main and master refused`);return});return this.defaults.set(y,{branch:x,until:Date.now()+P$}),x}}function I$(d,u,p){if(!d.ref.startsWith("refs/heads/"))return"a task pushes branches only, never a tag";if($$.test(d.new))return"a task never deletes a branch";if(p.any)return;let w=d.ref.slice(11);if((u?[u]:["refs/heads/main","refs/heads/master"]).includes(d.ref))return"a task never pushes the default branch: its PR is merged by a person's approval";if(p.taskId&&Jt(p.taskId,w))return;return p.taskId?`a task pushes its own branch only (sf/${p.taskId}-\u2026), never another's work or where approved work lands`:"only a task's session pushes, and its own branch only"}function T$(d){let u=[],p=[],w=new TextDecoder;for(let y=0;;){if(y+4>d.length)throw Error("it ends before its commands do");let v=w.decode(d.subarray(y,y+4));if(!/^[0-9a-fA-F]{4}$/.test(v))throw Error("a line without its length");let S=Number.parseInt(v,16);if(S===0)break;if(S<4||y+S>d.length)throw Error("a line longer than the request");let x=w.decode(d.subarray(y+4,y+S)).replace(/\n$/,"");y+=S;let j=x.indexOf("\x00");if(j>=0){if(!u.length)p=x.slice(j+1).split(" ").filter(Boolean);x=x.slice(0,j)}if(x.startsWith("push-cert"))throw Error("a signed push");if(x.startsWith("shallow "))continue;let[L,N,B]=x.split(" ");if(!L||!N||!B||!/^[0-9a-f]{40,64}$/.test(L)||!/^[0-9a-f]{40,64}$/.test(N))throw Error("a command that isn't one");u.push({old:L,new:N,ref:B})}if(!u.length)throw Error("no ref to update");return{updates:u,capabilities:p}}function R$(d){try{return v$(d,{maxOutputLength:S$})}catch(u){if(u.code==="ERR_BUFFER_TOO_LARGE")throw Error("it inflates to more than a push's commands");throw u}}function A$(d,u,p){let w=new Map(u.map((j)=>[j.ref,j.why])),y=xo(`unpack ok
|
|
4
|
+
`)+d.map((j)=>xo(`ng ${j.ref} ${w.get(j.ref)??"refused with the rest of this push"}
|
|
5
|
+
`)).join("")+"0000",v=p.includes("side-band-64k")||p.includes("side-band"),S=`Superfactory refused this push: ${u.map((j)=>`${j.ref}: ${j.why}`).join("; ")}
|
|
6
|
+
`,x=v?`${xo(`\x02${S}`)}${xo(`\x01${y}`)}0000`:y;return new Response(x,{status:200,headers:{"content-type":"application/x-git-receive-pack-result","cache-control":"no-cache"}})}function xo(d){return(Buffer.byteLength(d)+4).toString(16).padStart(4,"0")+d}var gw=(d)=>`Basic ${Buffer.from(`x-access-token:${d}`).toString("base64")}`;function E$(d){let u=/^Basic\s+(.+)$/i.exec(d.headers.get("authorization")??"")?.[1];if(!u)return;let p=Buffer.from(u,"base64").toString(),w=p.indexOf(":");return w>=0?p.slice(w+1):void 0}var qs=(d,u)=>new Response(`${u}
|
|
7
|
+
`,{status:d});import{createHash as C$,randomBytes as _$}from"crypto";var O$=()=>k("SUPERFACTORY_DEPLOY_GRANT_MS",18000000),kw=new Set(["done","rolled-back","failed"]),yw=(d)=>C$("sha256").update(d).digest("hex");class zd{file;constructor(d){this.file=d}mint(d){let u=`sfdg_${_$(24).toString("hex")}`;O(u);let{sessionId:p,kind:w,projectId:y,taskId:v,managerId:S}=d,x=this.read();return x[yw(u)]={sessionId:p,kind:w,projectId:y,taskId:v,managerId:S,expiresAt:Date.now()+O$()},this.write(x),u}of(d){let u=d.headers.get("authorization")?.replace(/^Bearer\s+/i,"")??"";if(!u.startsWith("sfdg_"))return;let p=yw(u),w=this.read()[p];return w&&w.expiresAt>Date.now()?{hash:p,grant:w}:void 0}revoke(d){let u=this.read();delete u[d],this.write(u)}read(){return Ni(this.file,{})}write(d){let u=Date.now(),p=Object.fromEntries(Object.entries(d).filter(([,w])=>w.expiresAt>u));qn(this.file,p,384)}}var j$=1e4;async function bw(d,u){let p=d.state.controlPort,w={hostname:"127.0.0.1",idleTimeout:0,maxRequestBodySize:Kd,fetch:(j)=>d.route(j)},y=(j)=>{try{return Bun.serve({...w,port:j})}catch{return}},v=Date.now()+(u?j$:0),S=p?y(p):void 0;while(p&&!S&&Date.now()<v)await Bun.sleep(200),S=y(p);d.server=S??Bun.serve({...w,port:0}),d.state.controlPort=d.server.port??0;let x=!!p&&d.state.controlPort===p;if(p&&!x)s.warn(`control: port ${p} is taken: listening on ${d.state.controlPort}`);return x}async function vw(d,u){let p=new URL(u.url);if(p.pathname==="/mcp"){let y=d.deployGrants.of(u);return y?L$(d,y,u):d.mcp.handle(u)}if(p.pathname===Fn&&u.method==="POST")return await d.secretEnvs.beforeTool(d.mcp.contextOf(u)?.sessionId,u.clone()),d.mcp.preToolUse(u);if(p.pathname===qr&&u.method==="POST")return d.mcp.postToolUse(u);if(p.pathname===wn&&u.method==="POST")return d.secretEnvs.serve(d.mcp.contextOf(u)?.sessionId,u);if(p.pathname.startsWith(Vd)&&d.pushGateway)return d.pushGateway.handle(u);if(!p.pathname.startsWith(Mu))return new Response("not found",{status:404});if(!N$(u.headers.get("authorization")??"",`Bearer ${d.state.controlToken}`))return new Response("unauthorized",{status:401});let w=`${u.method} ${p.pathname.slice(Mu.length)}`;try{switch(w){case"GET /status":return Response.json(d.status());case"POST /enroll":return Response.json(await d.enroll(Dp.parse(await u.json())));case"POST /link":return Response.json(await d.linkTo(Up.parse(await u.json())));case"POST /projects":return Response.json(await d.registerProject(Fp.parse(await u.json())));case"POST /away":return await d.setAway(Bp.parse(await u.json().catch(()=>({}))).on),Response.json(d.status());case"POST /pause":{let{on:y,running:v}=Hp.parse(await u.json().catch(()=>({}))),{moved:S,stayed:x}=await d.setPaused(y,v);return Response.json({...d.status(),moved:S,stayed:x})}case"POST /shutdown":return setTimeout(()=>void d.stop(),10),Response.json({ok:!0});default:return new Response("not found",{status:404})}}catch(y){return s.warn(`control ${w} failed`,y),Response.json({error:y.message},{status:400})}}async function L$(d,{hash:u,grant:p},w){let y=await w.json().catch(()=>{return});if(y?.method!=="tools/call"||y.params?.name!=="deploy_record")return new Response("a deploy's grant records its stages only (sf deploy record)",{status:403});let{expiresAt:v,...S}=p,x=await d.mcp.callTool("deploy_record",y.params.arguments??{},{...S,cwd:"",signal:w.signal}),j=y.params.arguments?.stage;if(!x.isError&&typeof j==="string"&&kw.has(j))d.deployGrants.revoke(u);return Response.json({jsonrpc:"2.0",id:y.id??null,result:x})}function N$(d,u){let p=(w)=>x$("sha256").update(w).digest();return M$(p(d),p(u))}import{randomBytes as c0}from"crypto";import{rm as u0}from"fs/promises";import{randomBytes as Q$}from"crypto";import{mkdirSync as J$,rmSync as z$}from"fs";import{join as X$}from"path";import{appendFileSync as U$,closeSync as F$,openSync as B$,readSync as W$,rmSync as H$,writeFileSync as Sw}from"fs";var G$=250,q$=256,V$=1048576,Pw=65536,$w=200,Y$=500;class Xd{path;secrets;onText;cap;written=0;dropped=0;pending="";timer;holdBack;constructor(d,u,p=()=>{return},w=Ah){this.path=d;this.secrets=u;this.onText=p;this.cap=w;this.holdBack=Math.max(q$,...u.map((y)=>y.length)),Sw(d,"",{mode:384})}write(d){this.pending+=d,this.timer??=setTimeout(()=>this.flush(),G$)}end(){this.flush(!0)}get bytes(){return this.written+Buffer.byteLength(this.pending)}tail(d=$w){let{text:u,fromByte:p}=this.from(this.written-Pw*4),w=u.endsWith(`
|
|
8
|
+
`),y=(w?u.slice(0,-1):u).split(`
|
|
9
|
+
`);return{text:y.slice(-d).join(`
|
|
10
|
+
`),truncated:y.length>d||p>0,newlineEnd:w}}read(d){this.flush();let u=d.maxBytes??Pw,p={totalBytes:this.bytes,droppedBytes:this.dropped};if(d.grep){let{text:v,fromByte:S}=this.from(d.sinceByte??0),x=d.grep.toLowerCase(),j=S,L=[],N=0;for(let B of v.split(`
|
|
11
|
+
`)){if(B.toLowerCase().includes(x)&&++N<=Y$)L.push(`${j}: ${B.slice(0,2000)}`);j+=Buffer.byteLength(B)+1}return{...p,fromByte:S,toByte:p.totalBytes,text:Iw(L.join(`
|
|
12
|
+
`),u),matches:N}}if(d.sinceByte!==void 0){let{text:v,fromByte:S}=this.from(d.sinceByte),x=K$(v,u);return{...p,fromByte:S,toByte:S+Buffer.byteLength(x),text:x}}let w=this.tail(d.tail??$w),y=Iw(w.text,u);return{...p,fromByte:p.totalBytes-Buffer.byteLength(y)-(w.newlineEnd?1:0),toByte:p.totalBytes,text:y}}all(){return new Uint8Array(Buffer.from(this.from(this.dropped).text))}remove(){clearTimeout(this.timer),H$(this.path,{force:!0})}flush(d=!1){clearTimeout(this.timer),this.timer=void 0;let u=d?0:this.holdBack,p=Xg(this.pending,this.pending.length-u,this.secrets);if(!d&&this.pending.length>V$)p=Math.max(p,this.pending.length-u);if(p<=0)return;let w=vt(this.pending.slice(0,p),this.secrets);this.pending=this.pending.slice(p);let y=Buffer.from(w);if(U$(this.path,y),this.written+=y.length,this.onText(w),this.written-this.dropped>this.cap*1.5)this.keepEnd()}from(d){this.flush();let u=Math.min(Math.max(d,this.dropped),this.written),p=this.fileBytes(u,this.written);return{text:vt(p.toString("utf8")+this.pending,this.secrets),fromByte:u}}fileBytes(d,u){let p=Buffer.alloc(Math.max(0,u-d));if(!p.length)return p;let w=B$(this.path,"r");try{W$(w,p,0,p.length,d-this.dropped)}finally{F$(w)}return p}keepEnd(){let d=this.written-this.cap;Sw(this.path,this.fileBytes(d,this.written)),this.dropped=d}}function Iw(d,u){let p=Buffer.from(d);if(p.length<=u)return d;let w=p.subarray(p.length-u).toString("utf8"),y=w.indexOf(`
|
|
13
|
+
`);return y>=0&&y<w.length-1?w.slice(y+1):w}function K$(d,u){let p=Buffer.from(d);return p.length<=u?d:p.subarray(0,u).toString("utf8")}var Z$=(d=process.env)=>({graceMs:(Number(d.SUPERFACTORY_COMMAND_GRACE_SECONDS)||Ih)*1000,keepMs:Eh*1000});class Sr{dir;timing;runs=new Map;constructor(d,u=Z$()){this.dir=d;this.timing=u;z$(d,{recursive:!0,force:!0}),J$(d,{recursive:!0,mode:448})}static newId(d){return`${Q$(12).toString("base64url")}.${d}`}async start(d){if(this.runs.has(d.id))throw new c("conflict",`run ${d.id} exists already`);let u=new Xd(X$(this.dir,`${d.id}.log`),d.secrets??[],d.onText),p=Promise.withResolvers(),w={id:d.id,owner:d.owner,command:d.command,background:!!d.background,startedAt:Date.now(),state:"running",exitCode:null,log:u,ended:p.promise,waiting:0};this.runs.set(w.id,w);try{w.running=await d.start((y)=>u.write(y))}catch(y){return u.write(`${y instanceof Error?y.message:String(y)}
|
|
14
|
+
`),this.finish(w,127),p.resolve(),w.id}return w.running.exited.then((y)=>{this.finish(w,y),p.resolve()},()=>{this.finish(w,1),p.resolve()}),w.id}async wait(d,u,p){let w=this.find(d,p);if(w.state==="running"&&u>0){w.waiting+=1,this.unarm(w);let y;try{await Promise.race([w.ended,new Promise((v)=>y=setTimeout(v,u))])}finally{clearTimeout(y),w.waiting-=1}}if(w.state==="running"&&!w.waiting&&!w.background)this.arm(w);return this.view(w,!0)}async stop(d,u,p="stopped"){let w=this.find(d,u);return await this.end(w,p),this.view(w,!1)}output(d,u,p){let w=this.find(d,u);return{runId:w.id,state:w.state,exitCode:w.exitCode,...w.log.read(p)}}list(d){return[...this.runs.values()].filter((u)=>Yl(u.owner,d)).map((u)=>this.summary(u))}spans(){return[...this.runs.values()].map((d)=>({startedAt:d.startedAt,endedAt:d.endedAt}))}async whenEnded(d){let u=this.find(d);return await u.ended,this.view(u,!1)}logOf(d){return this.find(d).log.all()}async stopWhere(d){let u=[...this.runs.values()].filter((p)=>p.state==="running"&&d(p.owner));await Promise.all(u.map((p)=>this.end(p,"stopped")))}async stopAll(){await this.stopWhere(()=>!0);for(let d of this.runs.values())d.log.remove();this.runs.clear()}find(d,u){let p=this.runs.get(d);if(!p||u&&!Yl(p.owner,u))throw new c("not_found",`no run ${d} here (a finished one is kept an hour)`);return p}async end(d,u){if(d.state!=="running")return;d.state=u,this.unarm(d),await d.running?.kill().catch(()=>{return}),await Promise.race([d.ended,Bun.sleep(5000)])}finish(d,u){if(d.endedAt)return;if(d.endedAt=Date.now(),d.state==="running")d.state="exited",d.exitCode=u;this.unarm(d),d.log.end(),setTimeout(()=>{if(this.runs.get(d.id)!==d)return;this.runs.delete(d.id),d.log.remove()},this.timing.keepMs).unref?.()}arm(d){this.unarm(d),d.stopsAt=Date.now()+this.timing.graceMs,d.reaper=setTimeout(()=>void this.end(d,"timedOut"),this.timing.graceMs)}unarm(d){clearTimeout(d.reaper),d.reaper=void 0,d.stopsAt=void 0}summary(d){return{runId:d.id,owner:d.owner,command:d.command,state:d.state,exitCode:d.exitCode,startedAt:new Date(d.startedAt).toISOString(),durationSeconds:Math.round(((d.endedAt??Date.now())-d.startedAt)/100)/10,...d.background?{background:!0}:{},outputBytes:d.log.bytes,...d.stopsAt?{stopsAt:new Date(d.stopsAt).toISOString()}:{}}}async view(d,u){let p=u&&d.state==="running"?await d.running?.processes().catch(()=>[]):void 0,w=d.log.tail();return{...this.summary(d),output:w.text,truncated:w.truncated,...p&&d.state==="running"?{processes:p}:{}}}}import{existsSync as eI}from"fs";import{open as tI,readdir as Tw,realpath as Lo,stat as No}from"fs/promises";import{isAbsolute as Rw,join as Vs,relative as Vn,sep as Do}from"path";var Zd=1048576,Aw=8000,Ew=5000,sI=200,nI=20000,iI=3000;class cc{projects;statuses=new Map;lists=new Map;ignoredLists=new Map;constructor(d){this.projects=d}async list(d,u){let p=await this.root(d),w=await this.inside(p,u);if(!(await No(w)).isDirectory())throw new c("bad_request",`${u} isn't a folder`);let y=await this.status(p),v=await this.ignored(p),{entries:S,truncated:x}=await this.entries(p,w,y,v),j=0,L=await Promise.all(S.map(async(N)=>N.kind==="dir"&&j++<sI?{...N,children:(await this.entries(p,Vs(p.dir,N.path),y,v).catch(()=>{return}))?.entries}:N));return{path:u,entries:L,truncated:x}}async read(d,u){let p=await this.root(d),w=await this.inside(p,u);if(Cw(await this.ignored(p),Vn(p.dir,w).split(Do).join("/")))throw new c("forbidden",`${u} is ignored by git: only people who work on the project see it`);let y=await No(w);if(!y.isFile())throw new c("bad_request",`${u} isn't a file`);let v=await tI(w,"r");try{let S=Buffer.alloc(Math.min(y.size,Zd)),{bytesRead:x}=await v.read(S,0,S.length,0),j=S.subarray(0,x),L=j.subarray(0,Aw).includes(0);return{path:u,text:L?"":j.toString("utf8"),size:y.size,truncated:y.size>Zd,binary:L}}finally{await v.close()}}async find(d,u,p){let w=await this.root(d),y=u.toLowerCase(),v=(await this.files(w)).map((j)=>({path:j,rank:dI(j.toLowerCase(),y)})).filter((j)=>j.rank>0).sort((j,L)=>L.rank-j.rank||j.path.length-L.path.length||j.path.localeCompare(L.path)),S=await this.status(w);return{entries:v.slice(0,p).map(({path:j})=>({path:j,name:j.split("/").at(-1)??j,kind:"file",git:S.get(j)})),truncated:v.length>p}}async grep(d,u,p){let w=await this.root(d);if(await ue(w.dir)){let S=await a(w.dir,(j)=>j.sub("grep").flag("-z").flag("-n").flag("-I").flag("-i").flag("-F").flag("--untracked").flag("--no-color").flag("-e",u).endOptions().arg(".").argsOf(this.excluded(w)),[1]),x=[];for(let j of S.split(`
|
|
15
|
+
`)){let[L,N,...B]=j.split("\x00");if(!L||!N)continue;if(x.push({path:L,line:Number(N),text:B.join("\x00").slice(0,500)}),x.length>p)break}return{matches:x.slice(0,p),truncated:x.length>p}}let y=u.toLowerCase(),v=[];for(let S of await this.files(w))if((await this.textOf(w,S))?.split(`
|
|
16
|
+
`).forEach((j,L)=>{if(j.toLowerCase().includes(y))v.push({path:S,line:L+1,text:j.slice(0,500)})}),v.length>p)break;return{matches:v.slice(0,p),truncated:v.length>p}}async root(d){let u=await Lo(this.projects.path(d.projectId)),p=await Lo(d.taskId?ee(u,d.taskId):u),w=d.taskId?Vs(u,".superfactory","worktrees",d.taskId):u;if(p!==u&&p!==w)throw new c("forbidden",`${d.taskId}'s worktree is outside the project`);return{dir:p,project:p===u,showIgnored:d.showIgnored??!1}}async inside(d,u){let p=Vs(d.dir,u),w=await Lo(p).catch(()=>{throw new c("not_found",`no ${u} here`)}),y=Vn(d.dir,w);if(y.startsWith("..")||Rw(y))throw new c("forbidden",`${u} is outside the project`);if(this.hidden(d,y))throw new c("forbidden",`${u} isn't shown`);return w}hidden(d,u){if(u.split(Do).includes(".git"))return!0;return d.project&&u.startsWith(Vs(".superfactory","worktrees"))}excluded(d){return d.project?[":(exclude).superfactory/worktrees"]:[]}async entries(d,u,p,w){let y=(await Tw(u,{withFileTypes:!0})).sort(rI),v=[];for(let S of y.slice(0,Ew)){let x=await this.entry(d,u,S,p);if(x&&!Cw(w,x.path))v.push(x)}return v.sort((S,x)=>Number(x.kind==="dir")-Number(S.kind==="dir")||S.name.localeCompare(x.name,void 0,{sensitivity:"base"})),{entries:v,truncated:y.length>Ew}}async entry(d,u,p,w){let y=Vs(u,p.name),v=Vn(d.dir,y).split(Do).join("/");if(this.hidden(d,Vn(d.dir,y)))return;let S=p.isSymbolicLink()?await Lo(y).catch(()=>{return}):y;if(!S)return;let x=Vn(d.dir,S);if(x.startsWith("..")||Rw(x)||this.hidden(d,x))return;let j=await No(S).catch(()=>{return});if(!j)return;let L=j.isDirectory()?"dir":"file";return{path:v,name:p.name,kind:L,...L==="file"?{size:j.size}:{},git:L==="file"?w.get(v):aI(w,v)}}status(d){return this.cached(this.statuses,d.dir,async()=>{if(!await ue(d.dir))return new Map;let u=await a(d.dir,(y)=>y.sub("status").flag("--porcelain").flag("-z").flag("--untracked-files","all")),p=new Map,w=u.split("\x00");for(let y=0;y<w.length;y++){let v=w[y]??"";if(v.length<4)continue;let S=v.slice(0,2);if(p.set(v.slice(3),oI(S)),S.includes("R")||S.includes("C"))y++}return p})}ignored(d){if(d.showIgnored)return Promise.resolve([]);return this.cached(this.ignoredLists,d.dir,async()=>{if(!await ue(d.dir))return[];return(await a(d.dir,(p)=>p.sub("ls-files").flag("-z").flag("--others").flag("--ignored").flag("--exclude-standard").flag("--directory"))).split("\x00").filter(Boolean)})}files(d){return this.cached(this.lists,d.dir,async()=>{if(await ue(d.dir))return(await a(d.dir,(p)=>p.sub("ls-files").flag("-z").flag("--cached").flag("--others").flag("--exclude-standard").endOptions().arg(".").argsOf(this.excluded(d)))).split("\x00").filter(Boolean);return this.walk(d)})}async walk(d){let u=[],p=[d.dir];while(p.length>0&&u.length<nI){let w=p.shift()??"";for(let y of await Tw(w,{withFileTypes:!0}).catch(()=>[])){let v=Vs(w,y.name),S=Vn(d.dir,v);if(this.hidden(d,S)||y.name==="node_modules")continue;if(y.isDirectory())p.push(v);else if(y.isFile())u.push(S.split(Do).join("/"))}}return u}async textOf(d,u){let p=Vs(d.dir,u);if(!eI(p))return;if((await No(p)).size>Zd)return;let y=Buffer.from(await Bun.file(p).arrayBuffer());return y.subarray(0,Aw).includes(0)?void 0:y.toString("utf8")}cached(d,u,p){let w=d.get(u);if(w&&Date.now()-w.at<iI)return w.value;let y=p();return d.set(u,{at:Date.now(),value:y}),y.catch(()=>d.delete(u)),y}}var rI=(d,u)=>Number(u.isDirectory())-Number(d.isDirectory())||d.name.localeCompare(u.name,void 0,{sensitivity:"base"});function oI(d){if(d==="??")return"untracked";if(d.includes("U")||d==="AA"||d==="DD")return"conflicted";if(d.includes("R"))return"renamed";if(d.includes("A"))return"added";if(d.includes("D"))return"deleted";return"modified"}function Cw(d,u){return d.some((p)=>p.endsWith("/")?`${u}/`.startsWith(p):p===u)}function aI(d,u){let p=`${u}/`;for(let[w,y]of d)if(w.startsWith(p))return y==="untracked"?"untracked":"modified";return}function dI(d,u){let p=d.slice(d.lastIndexOf("/")+1);if(p===u)return 4;if(p.includes(u))return 3;if(d.includes(u))return 2;let w=0;for(let y of d)if(y===u[w])w++;return w===u.length?1:0}import{homedir as s0}from"os";import{homedir as hI}from"os";var cI=30000,uI=l`$ErrorActionPreference = 'Stop'
|
|
17
|
+
Add-Type -Namespace Sf -Name Dpi -MemberDefinition '[DllImport("user32.dll")] public static extern bool SetProcessDpiAwarenessContext(IntPtr value); [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();'
|
|
18
|
+
try { [void][Sf.Dpi]::SetProcessDpiAwarenessContext([IntPtr]::new(-4)) } catch { [void][Sf.Dpi]::SetProcessDPIAware() }
|
|
19
|
+
Add-Type -AssemblyName System.Windows.Forms
|
|
20
|
+
$all = [System.Windows.Forms.Screen]::AllScreens | ForEach-Object { [ordered]@{ id = $_.DeviceName; primary = $_.Primary; x = $_.Bounds.X; y = $_.Bounds.Y; width = $_.Bounds.Width; height = $_.Bounds.Height } }
|
|
21
|
+
ConvertTo-Json -InputObject @($all) -Compress`,lI=l`ObjC.import("AppKit");
|
|
22
|
+
const all = $.NSScreen.screens.js;
|
|
23
|
+
const top = all.length ? all[0].frame.size.height : 0;
|
|
24
|
+
JSON.stringify(all.map((s, i) => {
|
|
25
|
+
const f = s.frame;
|
|
26
|
+
return {
|
|
27
|
+
id: String(ObjC.unwrap(s.deviceDescription.objectForKey("NSScreenNumber"))),
|
|
28
|
+
name: ObjC.unwrap(s.localizedName),
|
|
29
|
+
primary: i === 0,
|
|
30
|
+
x: f.origin.x,
|
|
31
|
+
y: top - f.origin.y - f.size.height,
|
|
32
|
+
width: f.size.width,
|
|
33
|
+
height: f.size.height,
|
|
34
|
+
};
|
|
35
|
+
}));`,pI=o(t({id:M([e(),b()]),name:e().optional(),primary:n(),x:b(),y:b(),width:b(),height:b()}));async function Fo(d=process.platform){let u=d==="win32"?r(tu).flag("-NoProfile").flag("-NonInteractive").script("-Command",uI):d==="darwin"?r(Is).flag("-l","JavaScript").script("-e",lI):void 0;if(!u)return[];let p=await T(u.timeoutMs(cI).by("machine.monitors").build());return pI.parse(JSON.parse(p.trim()||"[]")).slice(0,16).map((w)=>tp.parse({id:String(w.id).slice(0,64),...w.name?{name:w.name.slice(0,100)}:{},primary:w.primary,x:Math.round(w.x),y:Math.round(w.y),width:Math.max(1,Math.round(w.width)),height:Math.max(1,Math.round(w.height))}))}async function _w(d,u){let p=Ls(process.platform,"default",u.command),w=u.root?await co(u.command,p):p,y=await d.start({id:u.runId,owner:{kind:"machine",...u.projectId?{projectId:u.projectId}:{},...u.by?{by:u.by}:{}},command:u.command,secrets:await yc(),start:(x)=>Ui(w.in(hI()).by(u.root?"machine.run root":"machine.run").lowPriority().build(),x)}),v=await d.wait(y,u.timeoutSeconds*1000),S=v.output.split(`
|
|
36
|
+
`);return{runId:v.runId,exitCode:v.exitCode,timedOut:v.state==="timedOut",running:v.state==="running",durationSeconds:v.durationSeconds,output:S.slice(-Uo).join(`
|
|
37
|
+
`),truncated:v.truncated||S.length>Uo,...v.processes?{processes:v.processes}:{},...v.stopsAt?{stopsAt:v.stopsAt}:{}}}async function Ow(d,u,p){let w=p?await Fo():[],y=await Pt(await Di(d,u));return Yn(y,[],void 0,p?(v)=>mI(w,v,p):void 0)}function mI(d,u,p){let w=Wh(d,u),y=w[p-1];if(y)return y;throw new c("bad_request",w.length?`This machine's screen has ${w.length} monitors: screen 1 to ${w.length} (1 is the main one).`:"This machine's screen is one display: leave screen out.")}import{existsSync as xw}from"fs";import{readdir as fI,realpath as hc,stat as jw}from"fs/promises";import{homedir as gI}from"os";import{dirname as wI,isAbsolute as yI,join as uc,relative as kI}from"path";var Mw=500,Lw=(d,u)=>{let p=kI(d,u);return!p.startsWith("..")&&!yI(p)};async function Nw(d,u=""){let p=await hc(gI()),w=await hc(d??p).catch(()=>{throw new c("not_found",`${d} doesn't exist`)});if(!Lw(p,w))throw new c("forbidden","only folders inside the home folder");if(!(await jw(w)).isDirectory())throw new c("bad_request",`${d} isn't a folder`);let v=(await fI(w,{withFileTypes:!0}).catch(()=>{throw new c("forbidden",`${w} can't be read`)})).filter((x)=>!x.name.startsWith(".")&&(x.isDirectory()||x.isSymbolicLink())).filter((x)=>x.name.toLowerCase().includes(u.toLowerCase())).sort((x,j)=>x.name.localeCompare(j.name,void 0,{sensitivity:"base"})),S=(await Promise.all(v.slice(0,Mw).map((x)=>bI(p,w,x.name)))).filter((x)=>x!==void 0);return{path:w,parent:w===p?void 0:wI(w),root:p,folders:S,truncated:v.length>Mw}}async function bI(d,u,p){let w=uc(u,p),y=await hc(w).catch(()=>{return});if(!y||!Lw(d,y))return;if(!(await jw(y).catch(()=>{return}))?.isDirectory())return;return{name:p,path:w,project:xw(uc(y,".superfactory")),git:xw(uc(y,".git"))}}async function Dw(d,u,p){if(!p||!Vc.safeParse(u).success)throw s.warn(`refused to open ${u}: not a task's page on this machine's server`),new c("bad_request","only a task's page on this machine's server opens");let w=new URL(u,new URL(p).origin).href,y=De("machine",await Cs()).values;if(!lp({machine:y})["machine.openTasks"].value.includes(d))return;let v=process.env.SUPERFACTORY_OPEN,S=r(process.platform==="darwin"?Zs:Qs).programPath(v&&(Bun.which(v)??v)).arg(w).timeoutMs(15000),x=await g(S.build());if(x.exitCode!==0)s.warn(`couldn't open ${w} in the browser (exit ${x.exitCode})`)}import{mkdtemp as vI,rm as SI,stat as PI}from"fs/promises";import{tmpdir as $I}from"os";import{join as Uw}from"path";var Fw="refs/superfactory/backup/worktree";async function Bw(d,u){let p=await vI(Uw($I(),"sf-backup-"));try{let w=Uw(p,"code.bundle"),y=await II(d,w);return await u(w),{...y,bytes:(await PI(w)).size}}finally{await SI(p,{recursive:!0,force:!0})}}async function II(d,u){let p=(await a(d,(v)=>v.sub("rev-parse").flag("--verify").arg("HEAD"))).trim(),w=(await a(d,(v)=>v.sub("rev-parse").flag("--abbrev-ref").arg("HEAD"))).trim(),{commit:y}=await ao(d,"Superfactory: the working tree, backed up");await a(d,(v)=>v.sub("update-ref").arg(Fw).arg(y));try{await a(d,(v)=>v.sub("bundle create").flag("-q").arg(u).flag("--all"))}finally{await a(d,(v)=>v.sub("update-ref").flag("-d").arg(Fw))}return{head:p,branch:w==="HEAD"?void 0:w,worktreeCommit:y}}async function Hw(d){return(await a(d,(u)=>u.sub("remote"))).split(`
|
|
38
|
+
`).map((u)=>u.trim()).filter(Boolean)}async function Gw(d,u){if(!await ue(d))throw new c("conflict","the project's folder isn't a git repository");let p=await Hw(d);if(p.length){if((p.includes("origin")?(await a(d,(y)=>y.sub("config").arg("remote.origin.url"),[1])).trim():"")!==u)throw new c("conflict",`the project already has a remote (${p.join(", ")}): it isn't local-only`)}else await a(d,(w)=>w.sub("remote add").arg("origin").arg(u)),Du(d);return{github:await Ae(d)}}async function qw(d,u){if(!await ue(d))throw new c("conflict","the project's folder isn't a git repository");let p=(await a(d,(w)=>w.sub("config").arg("remote.origin.url"),[1])).trim();if(!p)return;if(p!==u)throw new c("conflict",`the project's origin is ${p}, not the address attached`);await a(d,(w)=>w.sub("remote remove").arg("origin")),Du(d)}var Ww=(d)=>d.message.split(`
|
|
39
|
+
`).find((u)=>u.trim())??"git refused";async function TI(d){return(await a(d,(p)=>p.sub("branch").flag("--format","%(refname:short)"))).split(`
|
|
40
|
+
`).map((p)=>p.trim()).filter(Boolean)}async function RI(d,u){let p=await a(d,(v)=>v.sub("ls-remote").flag("--symref").arg("origin")),w=new Set,y;for(let v of p.split(`
|
|
41
|
+
`)){let[S,x]=v.split("\t").map((j)=>j?.trim());if(S?.startsWith("ref: ")&&x==="HEAD")y=S.slice(5).replace(/^refs\/heads\//,"");else if(x?.startsWith("refs/heads/"))w.add(x.slice(11))}if(w.has(u))return u;if(y&&w.has(y))return y;return["main","master"].find((v)=>w.has(v))}async function Vw(d,u){if(!(await Hw(d).catch(()=>[])).includes("origin"))return{kind:"refused",reason:"the project has no origin: attach a repository first"};let p=await Ga(d,u.settings),w=await dt(d,`refs/heads/${p}`);if(!w)return{kind:"refused",reason:`the project has no ${p} branch`};let y;try{if(y=await RI(d,p),y)await a(d,(N)=>N.sub("fetch").flag("--quiet").arg("origin").arg(`+refs/heads/${y}:refs/remotes/origin/${y}`))}catch(N){return{kind:"refused",reason:`couldn't fetch from origin: ${Ww(N)}`}}let v=y?await dt(d,`refs/remotes/origin/${y}`):void 0,S;if(!v)S="pushed";else if(v===w)S="up-to-date";else if(await Mn(d,v,w))S="pushed";else if(await Mn(d,w,v)){let N=await Ur(d,p,w,v);if(N)return{kind:"refused",reason:N};S="fast-forward"}else{let N=await a(d,(ie)=>ie.sub("merge-base").arg(w).arg(v)).then(()=>!0,()=>!1),B=await Dr(d,w,v,!N);if(!B)return{kind:"refused",reason:"git couldn't merge the two histories (git 2.38 or later is needed)"};let G=await Ae(d)??"origin";if(B.conflicts.length){let ie=`Merge ${G}'s ${y} into ${p}`,ye=await u.openTask(ie)??await u.createTask({title:ie,description:AI(G,p,y,B.conflicts,N),kind:"task",dependsOn:[],labels:[],level:"normal",urgent:!0,status:"todo"});return{kind:"conflicts",base:p,files:B.conflicts,task:ye.id}}let V=await he(d),Y=(await a(d,(ie)=>ie.env(V).sub("commit-tree").arg(B.tree).flag("-p",w).flag("-p",v).flag("-m",`Merge ${G}'s ${y} into ${p}`))).trim(),ne=await Ur(d,p,w,Y);if(ne)return{kind:"refused",reason:ne};S="merged"}let x=[],j=[],L=async(N,B)=>{try{await a(d,(G)=>G.sub("push").flag("--quiet").flag("--set-upstream").arg("origin").arg(`refs/heads/${N}:refs/heads/${B}`)),x.push(N)}catch(G){j.push(`${N} (${Ww(G)})`)}};if(await L(p,y??p),j.length)return{kind:"refused",reason:`couldn't push ${j[0]}`};for(let N of await TI(d))if(N!==p)await L(N,N);if(j.length)return{kind:"refused",reason:`pushed ${x.join(", ")}, but not ${j.join("; ")}`};return{kind:"synced",base:p,how:S,branches:x}}function AI(d,u,p,w,y){return[`This project was local-only and is now joined to the GitHub repository ${d} (T-466). Both have commits of their own on ${u}, and merging ${d}'s ${p} into ${u} conflicts in: ${w.join(", ")}.`,"","In this task's worktree (its branch starts from the project's local main):",`1. \`git fetch origin\`, then \`git merge origin/${p}${y?"":" --allow-unrelated-histories"}\`.`,"2. Resolve every conflict keeping both sides' intent: nothing of either history may be lost. Ask the user (task_ask) when the two sides want different things.","3. Run the checks, commit the merge, push the branch.","",`Never force-push, reset or rebase ${u} or origin's ${p}. Once this task is approved and its PR merged, the project's lead syncs the project with GitHub again (the base then only moves forward).`].join(`
|
|
42
|
+
`)}import{lstat as py,readdir as JI,realpath as ay,rm as zI,rmdir as XI}from"fs/promises";import{join as hy,relative as ZI,resolve as eT,sep as tT}from"path";import{mkdtemp as DI,rm as UI,stat as FI}from"fs/promises";import{tmpdir as BI}from"os";import{extname as ty,join as Qw}from"path";import{rm as EI,stat as CI}from"fs/promises";var _I=2097152,OI=4,xI=2,Yw=10,MI=600000,jI="2",LI=[{width:640,fps:5,colors:128},{width:480,fps:4,colors:64}];async function Kw(d,u,p){for(let w of LI)if(await NI(d,u,p,w)&&(await CI(p)).size<=_I)return!0;return await EI(p,{force:!0}),!1}async function NI(d,u,p,{width:w,fps:y,colors:v}){let S=!!u&&u>Yw,x=S?(u??0)/OI:0,j=S?`select='lt(mod(t,${x.toFixed(3)}),${xI})',setpts=N/${y}/TB,`:"",L=`fps=${y},${j}scale=${w}:-2:flags=lanczos,split[a][b];[a]palettegen=max_colors=${v}[p];[b][p]paletteuse=dither=bayer`,N=r(Zt).flag("-hide_banner").flag("-loglevel","error").flag("-y").flag("-i",d).flag("-threads",jI).flag("-vf",L);if(!S)N.flag("-t",String(Yw));return(await g(N.arg(p).timeoutMs(MI).by("github.preview").build())).exitCode===0}var Jw="superfactory-media",WI="Superfactory task videos",HI="Videos of Superfactory tasks and their previews, linked from their pull requests: one per task video, named after the task and its content's hash. Kept up to date by Superfactory, and deleted after 180 days (github.videoRetentionDays); not a release of this repository.",GI=12,zw=100,qI={".mp4":"video/mp4",".m4v":"video/x-m4v",".mov":"video/quicktime",".webm":"video/webm",".gif":"image/gif"},VI=86400000,Xw=new Map;function bc(d,u){let p=(Xw.get(d)??Promise.resolve()).then(u,u);return Xw.set(d,p.catch(()=>{return})),p}function sy(d,u,p,w){return bc(u,async()=>{let y=new Map;try{let v=await vc(d,u,!0);if(!v)throw Error("GitHub has no media release");let S=await Ec(d,u,v),x=new Set;for(let j of w){let L=`${p}-${await KI(j.path)}`,N=`${L}${ty(j.name).toLowerCase()}`;x.add(N).add(`${L}.gif`);let B=S.find((G)=>G.name===N);try{let G=B??await oy(d,v,N,j.path);if(!B)S.push(G);let V=await YI(d,v,S,`${L}.gif`,j);y.set(j.name,{url:G.browser_download_url,...V?{preview:V}:{}})}catch(G){y.set(j.name,{failed:ey(G)})}}for(let j of S.filter((L)=>ry(p,L.name)&&!x.has(L.name)))await Mc(d,u,j).catch(()=>{return})}catch(v){for(let S of w)if(!y.has(S.name))y.set(S.name,{failed:ey(v)})}return y})}async function YI(d,u,p,w,y){let v=p.find((x)=>x.name===w);if(v)return v.browser_download_url;let S=await DI(Qw(BI(),"sf-preview-"));try{let x=Qw(S,w);if(!await Kw(y.path,y.durationSeconds,x))return;let j=await oy(d,u,w,x);return p.push(j),j.browser_download_url}catch{return}finally{await UI(S,{recursive:!0,force:!0})}}function ny(d,u,p,w=Date.now()){return bc(u,async()=>{let y=await vc(d,u,!1);if(!y)return 0;let v=w-p*VI,S=(await Ec(d,u,y)).filter((x)=>x.created_at&&Date.parse(x.created_at)<v);for(let x of S)await Mc(d,u,x);return S.length})}function iy(d,u,p){return bc(u,async()=>{let w=await vc(d,u,!1);if(!w)return 0;let y=(await Ec(d,u,w)).filter((v)=>ry(p,v.name));for(let v of y)await Mc(d,u,v);return y.length})}var ry=(d,u)=>u.startsWith(`${d}-`)&&/^[0-9a-f]+\.\w+$/.test(u.slice(d.length+1));async function vc(d,u,p){let w=()=>fe(d,(y)=>y.sub("api").arg(`repos/${u}/releases/tags/${Jw}`));try{return await w()}catch(y){if(!QI(y))throw y}if(!p)return;try{return await fe(d,(y)=>y.sub("api").flag("--method","POST").arg(`repos/${u}/releases`).flag("-f",`tag_name=${Jw}`).flag("-f",`name=${WI}`).flag("-f",`body=${HI}`).flag("-F","prerelease=true").flag("-f","make_latest=false"))}catch(y){if(/already_exists|HTTP 422/.test(jc(y)))return w();throw y}}async function Ec(d,u,p){let w=[];for(let y=1;;y++){let v=await fe(d,(S)=>S.sub("api").arg(`repos/${u}/releases/${p.id}/assets?per_page=${zw}&page=${y}`));if(w.push(...v),v.length<zw)return w}}async function oy(d,u,p,w){let y=u.upload_url.replace(/\{[^}]*\}$/,""),v=qI[ty(p)]??"application/octet-stream";return fe(d,(S)=>S.sub("api").flag("--method","POST").arg(`${y}?name=${encodeURIComponent(p)}`).flag("--header",`Content-Type: ${v}`).flag("--input",w))}async function Mc(d,u,p){await Q(d,(w)=>w.sub("api").flag("--method","DELETE").arg(`repos/${u}/releases/assets/${p.id}`))}var Zw=new Map;async function KI(d){let u=await FI(d),p=`${u.size}:${u.mtimeMs}`,w=Zw.get(d);if(w?.key===p)return w.hash;let y=new Bun.CryptoHasher("sha256");for await(let S of Bun.file(d).stream())y.update(S);let v=y.digest("hex").slice(0,GI);return Zw.set(d,{key:p,hash:v}),v}var jc=(d)=>d instanceof xt?d.result.stderr||d.result.stdout:String(d),QI=(d)=>/\bHTTP 404\b|Not Found/.test(jc(d));function ey(d){let u=jc(d),p=u.split(`
|
|
43
|
+
`).find((y)=>y.trim())?.trim()??"GitHub refused it";return{short:/\bHTTP 40[134]\b|Resource not accessible|Must have admin rights|Bad credentials/i.test(u)?"no permission to upload":"upload failed",reason:p}}var dy=86400000,sT=/\.(mp4|m4v|mov|webm)$/i;async function my(d,u,p=Date.now()){let w=hg(),y=new Map,v=new Set;for(let L of await d.sessions.list())if(y.set(L.id,L.projectId),["exited","failed"].includes(L.state)&&!d.sessions.isLive(L.id))v.add(L.id);if(!u)await nT(d,p);for(let L of d.projects.ids()){let N=(await d.projects.settings(L))["retention.mediaDays"];if(!N)continue;let B=d.projects.path(L),G=await cy(E(B).media,B),V=(G?await Lc(G):[]).filter((ne)=>ne.info.isDirectory());if(V.length===0)continue;let Y=await iT(d,L);if(!Y){w.skipped.push(`${L}: its task list couldn't be read, so its media was kept`);continue}for(let ne of V){if(!Y.closed(ne.name))continue;let ie=hy(E(B).media,ne.name),ye=!1;if(await be(B,ie,!1,async(Qe)=>{for(let ht of await Lc(Qe.at(""),Qe.at))if(uy(ht.info,p-N*dy))await ly(ht.path,ht.info,u,w.media),ye||=sT.test(ht.name)}).catch((Qe)=>w.skipped.push(`${L}: ${ne.name}: ${Qe.message}`)),u)continue;await be(B,E(B).media,!1,(Qe)=>XI(Qe.at(ne.name))).catch(()=>{return});let ve=ye&&await Ae(B);if(ve)await iy(B,ve,ne.name).catch((Qe)=>s.warn(`retention: ${L}/${ne.name}: its videos on GitHub stayed`,Qe))}}let S=new Map,x=async(L)=>{if(!S.has(L)){let N=L&&d.projects.ids().includes(L)?await d.projects.settings(L):await d.projects.globalSettings();S.set(L,N["retention.sessionLogDays"])}return S.get(L)??0},j=await cy(m().sessionLogs,m().home);for(let{name:L,path:N,info:B}of j?await Lc(j):[]){let G=L.replace(/\.jsonl$/,"");if(!L.endsWith(".jsonl")||y.has(G)&&!v.has(G)||d.sessions.isLive(G))continue;let V=await x(y.get(G));if(!V)continue;if(uy(B,p-V*dy))await ly(N,B,u,w.sessionLogs)}return w}async function nT(d,u){for(let p of d.projects.ids()){let w=(await d.projects.settings(p))["github.videoRetentionDays"],y=d.projects.path(p),v=w?await Ae(y):void 0;if(!v)continue;await ny(y,v,w,u).catch((S)=>s.warn(`retention: ${p}: its old videos on GitHub stayed`,S))}}async function iT(d,u){let p=await d.tasks.list(u).catch(()=>[]);if(p.length===0)return;let w=new Map(p.map((y)=>[y.id,y]));return{closed:(y)=>{let v=w.get(y);return!v||v.archived||Ne.includes(v.status)}}}async function cy(d,u){if(!(await py(d).catch(()=>{return}))?.isDirectory())return;let[w,y]=await Promise.all([ay(d),ay(u)]).catch(()=>[]);return w&&y&&w.startsWith(y+tT)&&w===eT(y,ZI(u,d))?w:void 0}async function Lc(d,u=(p)=>hy(d,p)){let p=await JI(d).catch(()=>[]);return(await Promise.all(p.map(async(y)=>({name:y,path:u(y),info:await py(u(y)).catch(()=>{return})})))).flatMap((y)=>y.info&&!y.info.isSymbolicLink()?[{...y,info:y.info}]:[])}var uy=(d,u)=>d.isFile()&&d.mtimeMs<u;async function ly(d,u,p,w){if(!p)await zI(d,{force:!0});w.files+=1,w.bytes+=u.size}import{existsSync as fy}from"fs";import{mkdir as rT,writeFile as oT}from"fs/promises";import{join as Kn}from"path";var Xs=(d)=>Kn(m().attachments,d),Jn=({projectId:d,taskId:u})=>Kn(m().attachments,"tasks",d,u);async function Bo(d,u,p,w){await rT(d,{recursive:!0,mode:z(448)});let y=aT(d,u),v=Kn(d,y);return await oT(v,w,{mode:z(384),flag:"wx"}),{name:y,path:v,contentType:p,size:w.byteLength}}function Wo(d,u,p=[]){if(!p.length)return u;let w=p.filter((y)=>!fy(Kn(d,y)));if(w.length)throw new c("not_found",`not attached: ${w.join(", ")}`);return`${u}
|
|
44
|
+
|
|
45
|
+
${hp}
|
|
46
|
+
${p.map((y)=>`- ${Kn(d,y)}`).join(`
|
|
47
|
+
`)}`}function aT(d,u){let p=u.lastIndexOf("."),[w,y]=p>0?[u.slice(0,p),u.slice(p)]:[u,""],v=u;for(let S=2;fy(Kn(d,v));S++)v=`${w.slice(0,110)}-${S}${y}`.slice(-120);return v}import{randomUUID as jk}from"crypto";import{existsSync as FR}from"fs";import{mkdir as BR}from"fs/promises";import{homedir as WR}from"os";import{join as Lk}from"path";function gy(d){let u=d,p=(S)=>typeof u[S]==="string"&&u[S]?u[S]:void 0,w=(S)=>typeof u[S]==="number"&&u[S]?u[S]:void 0,y=(()=>{switch(d["runner.kind"]){case"host":return;case"tart":return{image:p("runner.macos.goldenImage"),cpus:w("runner.macos.cpu"),memoryGb:w("runner.macos.memory")};default:return{image:p("runner.image")}}})();if(!y)return;let v=Object.fromEntries(Object.entries(y).filter(([,S])=>S!==void 0));return Object.keys(v).length?v:void 0}var dT=Bn({}),wy=Gp(dT);var qo=(d)=>d.token&&d.accountId?{id:d.accountId,name:d.account??"a Claude account"}:void 0;function Vo(d,u){if(d.claudeAccount?.id===u?.id){if(u&&d.claudeAccount)d.claudeAccount.name=u.name;return}d.claudeAccount=u?{id:u.id,name:u.name,since:new Date().toISOString()}:void 0}function ts(d){let{CLAUDE_CODE_OAUTH_TOKEN:u,...p}=d;return p}class Nc{child;place;session;origin;deps;childId;run;account;limit;loginFailed;outbox;restarting=!1;reviving;secretNames;abort=new AbortController;constructor(d,u,p,w,y){this.child=d;this.place=u;this.session=p;this.origin=w;this.deps=y;this.childId=d.nodeId,this.outbox=q.inMemory(p.id),this.follow()}async start(d,u){return this.run=d,this.account=u,this.secretNames=d.secretNames,this.child.call("sessions.run",d)}get permissionMode(){return this.run?.permissionMode}async send(d,u,p){let{reply:w,relay:y}=p;await this.reviving?.catch(()=>{return});let v=this.outbox.handed(d,u,w);if(this.child.stopped)return this.revive();let S={sessionId:this.session.id,text:d,author:u,relay:y,mayWait:Za(u,p)};await this.child.call("sessions.send",S).catch((x)=>{throw this.outbox.remove([v.id]),x})}async stop(){if(this.child.stopped)this.session.state="exited";else await this.child.call("sessions.stop",{sessionId:this.session.id})}async wrapUp(d){if(this.child.stopped)return;await this.child.call("sessions.wrapUp",{sessionId:this.session.id,timeoutSeconds:Math.round(d/1000)})}async interrupt(){if(!this.child.stopped)await this.child.call("sessions.interrupt",{sessionId:this.session.id})}async nudge(){if(this.child.stopped)return this.revive();await this.child.call("sessions.nudge",{sessionId:this.session.id})}async restartClaude(){throw new c("conflict","a sandboxed session's Claude comes with its sandbox: stop it, and your next message starts it again")}boundary(d){if(this.child.stopped)return;let u=this.session.id;this.task().then((p)=>this.child.call("sessions.boundary",{sessionId:u,boundary:d,task:p})).catch((p)=>s.warn(`sessions: boundary for ${u} not sent`,p))}jobOutput(d){return this.childOrGone().call("sessions.jobOutput",{sessionId:this.session.id,jobId:d})}async stopJob(d){await this.childOrGone().call("sessions.stopJob",{sessionId:this.session.id,jobId:d})}async secrets(d,u,p){let w=ts(d);if(this.run){let v={...this.run.env};for(let S of this.secretNames??[])delete v[S];this.run.env={...v,...w}}if(this.secretNames=Object.keys(w),this.child.stopped)return;let y=this.session.id;await this.child.call("sessions.secrets",{sessionId:y,env:w,leadEnv:{},changed:p})}githubChanged(d){if(this.run)this.run.github=d;return this.child.stopped?void 0:this.child}async note(d){let{session:u}=this;await this.child.call("sessions.limitState",{sessionId:u.id,note:d,pausedUntil:u.pausedUntil??null,pausedFor:u.pausedUntil?u.pausedFor:void 0})}async restartOn(d,u){let p=this.run;if(!p)return;let{CLAUDE_CODE_OAUTH_TOKEN:w,...y}=p.env??{};if(d.token)O(d.token);if(this.account=qo(d),Vo(this.session,this.account),u)this.outbox.handed(u,Ve);this.run={...p,session:this.session,messages:this.outbox.resend(),resume:!0,env:{...y,...d.token?{CLAUDE_CODE_OAUTH_TOKEN:d.token}:{}}},this.restarting=!0;try{await this.child.call("sessions.stop",{sessionId:this.session.id}),await this.child.call("sessions.run",this.run)}finally{this.restarting=!1}}idle(){return!!this.run&&this.session.state==="idle"&&!this.restarting&&!this.limit&&!this.loginFailed&&!this.session.pausedUntil}waiting(){return this.outbox.unread().length>0}sandboxGone(){this.abort.abort();let{state:d}=this.session;if(d==="exited"||d==="failed")return!1;return Object.assign(this.session,{state:"exited",endedAt:new Date().toISOString(),ports:[],previews:[]}),!0}follow(){let{child:d,session:u}=this;d.observe((p)=>{if(p.type==="mcp.gaveUp"&&p.sessionId===u.id)this.deps.gaveUp(u.id,p.callId);if(p.type!=="session.event"||p.event.sessionId!==u.id)return;let{event:w}=p;if(w.type==="state"){if(u.state=w.state,w.phase)u.phase=w.phase}if(w.type==="user_message")this.outbox.observed(w.text,w.author);if(this.outbox.saw(w),this.deps.activity.onEvent(u.id,w),w.type==="login_failed")this.loginFailed=w.reason;if(w.type==="result")this.turnEnded();if(this.deps.heard?.(u,w),w.type==="usage_limit"&&w.status==="rejected")this.limit={resetsAt:w.resetsAt};if(w.type==="result"&&this.limit){let v=this.limit;this.limit=void 0,this.deps.switchAccount(this,{reason:"limit",...v})}if(w.type==="state"&&["exited","failed"].includes(w.state)&&w.phase!=="respawning"&&!this.restarting)u.pausedUntil=void 0,u.pausedFor=void 0,this.outbox.clear();if(w.type==="result")this.place.sandbox?.pull().catch((v)=>s.warn(`sessions: pull from ${u.id} failed`,v)).then(()=>this.deps.synced?.(u))})}turnEnded(){let d=this.loginFailed,u=this.outbox.turnEnded(!!d);if(this.loginFailed=void 0,!d){this.deps.loginWorked(this.session);return}this.limit=void 0,this.deps.switchAccount(this,{reason:"signed_out",why:d,answering:u})}revive(){return this.reviving??=(async()=>{let{place:d,session:u}=this,p=this.run;if(!p||!d.sandbox||!u.projectId)throw new c("unavailable",`session ${u.id} can't run again here`);let w=await this.deps.children.for(d.sandbox,d.runner,u.projectId);if(await this.deps.children.handOver(w.nodeId,u),this.child=w,this.childId=w.nodeId,u.nodeId=w.nodeId,this.follow(),this.run={...p,session:u,resume:!0,github:await this.deps.github.forSession(u.projectId),messages:this.outbox.resend()},await w.call("sessions.run",this.run),u.taskId&&!u.teammate)await this.deps.tasks.update({projectId:u.projectId,taskId:u.taskId},{sessionId:u.id,node:w.nodeId});s.info(`sessions: ${u.id} runs again on ${w.nodeId}, its sandbox's new agent`)})().finally(()=>{this.reviving=void 0}),this.reviving}childOrGone(){if(this.child.stopped)throw new c("conflict","its sandbox's agent is gone, and its Claude's jobs with it");return this.child}task(){let{projectId:d,taskId:u}=this.session;if(!d||!u)return Promise.resolve(void 0);return this.deps.tasks.get({projectId:d,taskId:u}).catch(()=>{return})}}import{createHash as cT}from"crypto";import{existsSync as Bc,readFileSync as uT,realpathSync as yy,statSync as lT}from"fs";import{mkdir as pT,rm as hT,stat as mT,writeFile as fT}from"fs/promises";import{basename as vy,join as en,resolve as gT,sep as wT}from"path";var yT=3600000,kT=60000,ky=".superfactory-fetched";async function Sy(d,u){let p=d["plugins.marketplace"].filter((j)=>u.lead||j.who==="everyone"),w=(j)=>ST(j,u),y=await Promise.all(p.map((j)=>bT(j,w).then((L)=>({plugin:j,dir:L}),(L)=>({plugin:j,problem:Iy(L.message)})))),v=[],S=[],x={};for(let j of y){let{plugin:L}=j;if(!("dir"in j)){s.warn(`marketplace plugins: ${L.plugin} from ${L.marketplace} didn't load: ${j.problem}`),v.push(`- ${L.plugin} (${L.marketplace}) didn't load: ${j.problem}`);continue}S.push(j.dir);for(let[N,B]of Object.entries(L.env)){let G=u.secretEnv[B];if(G!==void 0)x[N]=G;else v.push(`- ${L.plugin} reads ${N} from the secret ${B}, which doesn't reach this session. Ask the user for it with secret_request (name ${B}, for the project); a new session, or this one restarted, then has it.`)}}return{dirs:S,env:x,prompt:v.length?["## Plugins from marketplaces","",...v].join(`
|
|
48
|
+
`):""}}function Py(d,u){return Promise.all(d.map((p)=>u.shared?p:u.copyIn(p,`/tmp/superfactory-plugins/marketplace/${$y(p)}/${vy(p)}`)))}async function bT(d,u){let p=await u({url:Dc(d.marketplace),ref:d.ref}),w=vT(p),y=w.plugins?.find((x)=>x?.name===d.plugin);if(!y)throw Error(`its marketplace has no plugin named ${d.plugin}`);let{source:v}=y;if(typeof v==="string"){let x=v!=="."&&!v.startsWith("./");return by(p,x?en(w.metadata?.pluginRoot??".",v):v)}let S=v?.sha??v?.ref??"";switch(v?.source){case"github":return u({url:Dc(String(v.repo)),ref:S});case"url":if(!String(v.url).startsWith("https://"))throw Error("its git address isn't https://");return u({url:String(v.url),ref:S});case"git-subdir":return by(await u({url:Dc(String(v.url)),ref:S}),String(v.path??"."));default:throw Error(`its source (${v?.source??"none"}) isn't one Superfactory fetches: a folder of the marketplace, github, url or git-subdir`)}}function vT(d){let u=en(d,".claude-plugin","marketplace.json");if(!Bc(u))throw Error("it isn't a marketplace: it has no .claude-plugin/marketplace.json");try{return JSON.parse(uT(u,"utf8"))}catch{throw Error("its .claude-plugin/marketplace.json isn't valid JSON")}}function by(d,u){let p=gT(d,u),w=Bc(p)?yy(p):"",y=yy(d);if(!w||w!==y&&!w.startsWith(y+wT)||!lT(w).isDirectory())throw Error(`its folder ${u} isn't in the marketplace`);return p}function Dc(d){if(/^https:\/\/[^\s@]+$/.test(d))return d;if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(d))throw Error(`${d} isn't an https:// git address or owner/repo`);let u=process.env.SUPERFACTORY_MARKETPLACES_DIR;return u?en(u,d):`https://github.com/${d}.git`}var Fc=new Map;function ST(d,{projectId:u,github:p}){let w=p&&$T(d.url,p.host)?p:void 0,y=vy(d.url).replace(/\.git$/,"").replace(/[^\w.-]/g,"-"),v=en(m().home,"marketplaces",`${y}-${$y(`${d.url}\x00${d.ref}\x00${w?u:""}`)}`),S=Fc.get(v);if(S)return S;let x=PT(v,d,w).finally(()=>Fc.delete(v));return Fc.set(v,x),x}async function PT(d,{url:u,ref:p},w){if(p&&!/^[\w.][\w./-]*$/.test(p))throw Error(`${p} isn't a branch, tag or commit`);let y=await mT(en(d,ky)).then((v)=>v.mtimeMs,()=>{return});if(y!==void 0&&(Date.now()-y<yT||/^[0-9a-f]{40}$/.test(p)))return d;try{if(!Bc(en(d,".git")))await pT(d,{recursive:!0}),await a(d,(v)=>v.sub("init").flag("-q"));return await a(d,(v)=>v.sub("fetch").flag("-q").flag("--depth",1).arg(u).arg(p||"HEAD").timeoutMs(kT),[],{github:w}),await a(d,(v)=>v.sub("reset").flag("-q").flag("--hard").arg("FETCH_HEAD")),await fT(en(d,ky),new Date().toISOString()),s.info(`marketplace plugins: fetched ${u}${p?` at ${p}`:""} into ${d}`),d}catch(v){if(y===void 0)throw await hT(d,{recursive:!0,force:!0}),Error(`couldn't fetch ${u}${p?` at ${p}`:""}: ${Iy(v.message)}`);return s.warn(`marketplace plugins: couldn't fetch ${u} again, the copy from before stays`,v),d}}var $T=(d,u)=>URL.canParse(d)&&new URL(d).origin===new URL(u).origin,$y=(d)=>cT("sha256").update(d).digest("hex").slice(0,12),Iy=(d)=>d.trim().split(`
|
|
49
|
+
`)[0]?.slice(0,300)||"failed";import{existsSync as Ty}from"fs";import{mkdir as Wc,mkdtemp as IT,rename as TT,rm as RT,writeFile as Ry}from"fs/promises";import{basename as AT,dirname as ET,join as Xn}from"path";var Hc="project-skills";function Yo(d,{lead:u}){return d.skills.filter((p)=>u||p.who==="everyone")}async function Gc(d){if(!d.length)return;let u=new Bun.CryptoHasher("sha256").update(JSON.stringify(d)).digest("hex").slice(0,16),p=Xn(m().home,Hc,u);if(Ty(Xn(p,".claude-plugin","plugin.json")))return p;await Wc(ET(p),{recursive:!0});let w=await IT(`${p}.`);try{await CT(w,d),await TT(w,p)}catch(y){if(await RT(w,{recursive:!0,force:!0}),!Ty(p))throw y}return p}async function Ay(d,u){let p=await Gc(d);if(!p)return[];if(u.shared)return[p];return[await u.copyIn(p,`/tmp/superfactory-plugins/${Hc}-${AT(p)}`)]}async function CT(d,u){await Wc(Xn(d,".claude-plugin"),{recursive:!0});let p={name:Hc,description:"Skills this project wrote for its agents in Superfactory",version:"1.0.0"};await Ry(Xn(d,".claude-plugin","plugin.json"),`${JSON.stringify(p,null,2)}
|
|
50
|
+
`);for(let w of u)await Wc(Xn(d,"skills",w.name),{recursive:!0}),await Ry(Xn(d,"skills",w.name,"SKILL.md"),_T(w))}function _T(d){return`${["---",`name: ${d.name}`,`description: ${JSON.stringify(d.description)}`,"---"].join(`
|
|
51
|
+
`)}
|
|
52
|
+
|
|
53
|
+
${d.body.trim()}
|
|
54
|
+
`}import{join as My}from"path";import{readFileSync as OT}from"fs";function vs(){let d=process.env.SUPERFACTORY_FAKE_NOW_FILE;if(!d)return Date.now();try{let u=Date.parse(OT(d,"utf8").trim());return Number.isNaN(u)?Date.now():u}catch{return Date.now()}}var Ey=k("SUPERFACTORY_PAUSE_CHECK_MS",30000),Cy="Your Claude account hit its usage limit, so this session now runs on another one. Carry on where you stopped.",_y="Claude's usage limit has reset. Carry on where you stopped.",Ko=3600000,Oy="Your Claude account was signed out, so this session now runs on another one. Carry on where you stopped.",qc="A Claude account is signed in again. Carry on where you stopped.";var jy=()=>k("SUPERFACTORY_LOGIN_ASK_AGAIN_MS",2000),Qo={reason:"resume",due:!1},tn=(d)=>!!d.jobs?.length,Ly=["in_review","needs_input"],Yc=(d)=>d.reason==="limited_elsewhere"||d.reason==="rebalance";function Ny(d,u){switch(d.reason){case"limit":return{limited:{resetsAt:d.resetsAt,accountId:u}};case"limited_elsewhere":return{limited:{resetsAt:d.until,accountId:u}};case"signed_out":return{signedOut:{reason:d.why,accountId:u}};case"rebalance":return u?{rebalance:{accountId:u}}:{};case"resume":return{}}}function Kc(d,u){return d.resetsAt??u?.waitUntil??new Date(vs()+Ph).toISOString()}function Dy(d,u,p){let w=u.account;switch(d.reason){case"limit":return{change:"switched",account:w,limited:p?.name,until:Kc(d,u)};case"limited_elsewhere":return{change:"switched",account:w,limited:p?.name,until:d.until};case"signed_out":return{change:"signed_out",account:w,from:p?.name??Mi};default:return{change:"balanced",account:w,from:p?.name}}}function Uy(d,u){let p=u?.name??Mi,w=d.reason==="rebalance"?"has much less room than another":"reached its usage limit";return`Claude account ${p} ${w}, so this Claude stopped while it waits for its next message: that message starts it again, in the same conversation, on the account with room then.`}function Fy(d){if(d.reason==="limit")return Cy;if(d.reason==="signed_out"&&d.answering===0)return Oy;return}var Mi="This machine's Claude login";class Qc extends Zr{abort=new AbortController;level;secretEnv;leadEnv;startTicket;origin;resumeOnStart;leftRunning;noting;failures=0;startedClosed;startStep;claudeRepair;userLayer;restartAfterTurn;saving;place;killedResumes;memoryResumes;pluginsChecked;startedBy;permissionMode;world;account;runFrom;nextLogin;handle;constructor(d,u){super(...d);this.level=u.level,this.secretEnv=u.secretEnv,this.leadEnv=u.leadEnv,this.startTicket=u.startTicket,this.origin=u.origin,this.userLayer=u.userLayer,this.place=u.place}}var By=300000,Wy=5000,Jc=8,Hy="Superfactory: your Claude was restarted on this conversation in the middle of your turn. Carry on from where you were.",at="superfactory",Gy=new Set([129,130,137,143]),qy=()=>k("SUPERFACTORY_KILLED_RESUME_MS",3000),Vy=()=>k("SUPERFACTORY_MEMORY_ROOM_WAIT_MS",600000),Yy=15000,zc=3,Ky=1e4,Pr=(d,u,p=[])=>Wo(Xs(d),u,p),Xc=["easy","normal","hard"],Qy=["starting","running","waiting_input","stopping"],zo=["starting","running","stopping"],Jy=new Set(["starting","running","idle","waiting_input"]),xT=/^(TMPDIR|TMP|TEMP|HOME|USER|LOGNAME|CLAUDE_CONFIG_DIR|DOCKER_HOST|XDG_\w*|SUPERFACTORY_\w*|GIT_CONFIG\w*)$/;function Zo(d){return Object.fromEntries(Object.entries(d??{}).filter(([u])=>!xT.test(u)))}function ra(d,u){return{SF_LIVE_REVIEW:String(d["testing.liveReview"]),SF_VIDEO_QUALITY:d["videos.quality"],CLAUDE_CODE_PROMPT_CACHE_TTL:d["agents.longCache"]?"1h":"5m",MCP_TOOL_TIMEOUT:String(eu(d)),BASH_DEFAULT_TIMEOUT_MS:String(d["agents.commandTimeoutSeconds"]*1000),BASH_MAX_TIMEOUT_MS:String(bn*1000),...Fe,...u.projectId?{SUPERFACTORY_PROJECT:u.projectId}:{},SUPERFACTORY_SESSION:u.id,...u.taskId?{SUPERFACTORY_TASK:u.taskId}:{},...u.projectId&&u.taskId?Kp(d,{projectId:u.projectId,taskId:u.taskId}):{}}}function oa(d,u,p,w){let y=d==="coordinator",v=y?w?.model??p["coordinator.model"]:p[`agents.levels.${u}.model`],S=y?p["coordinator.permissionMode"]:"inherit";return{model:v==="inherit"?void 0:v,effort:y?w?.effort??p["coordinator.effort"]:p[`agents.levels.${u}.effort`],permissionMode:S==="inherit"?jT()??p["claude.permissionMode"]:S}}var eu=(d)=>d["agents.answerWaitHours"]*60*60*1000,tt=(d)=>{let[,u,p]=d.match(/^([A-Za-z]):[\\/](.*)$/)??[];return u?`//${u.toLowerCase()}/${(p??"").replaceAll("\\","/")}`:`/${d}`},aa=(d)=>d.phase.kind==="queued",zy=(d)=>d.state!=="exited"&&d.state!=="failed",da=(d,u)=>(d.kind==="task"||d.kind==="epic")&&!d.teammate&&d.projectId===u.projectId&&d.taskId===u.id&&!!u.sessionId&&u.sessionId!==d.id;function Xy(d,u){let p=cf(),w,y=new Promise((v,S)=>{w=setTimeout(()=>{if(d.process)return;let x=p>=60000?`${Math.round(p/60000)} min`:`${Math.round(p/1000)} s`;S(new c("unavailable",`it took over ${x}, stuck at ${d.startStep??"its start"}`))},p)});return Promise.race([u,y]).finally(()=>clearTimeout(w))}var Ss=(d)=>!!d.process||["queued","starting","respawning"].includes(d.phase.kind),Ir=(d)=>!!d.process?.alive||Oe(d.phase)||d.phase.kind==="respawning"||!!d.session.pausedUntil&&!MT(d.phase),MT=(d)=>d.kind==="stopping"||d.kind==="ended"&&!!d.stopped;function Zy(d){return["Read(./**)",...[My(m().attachments,d.session.id)].map((p)=>`Read(${tt(p)}/**)`)]}var ek=(d)=>d.map((u)=>`Edit(${tt(u)}/**)`),xy=(d)=>[`Read(${d}/projects/**/*.jsonl)`,`Read(${d}/projects/*/*-*-*-*-*/**)`],tk=()=>[`Read(${tt(m().state)})`,`Read(${tt(My(m().home,"identity.pem"))})`,`Read(${tt(m().tunnelKey)})`,`Read(${tt(m().sessionMessages)}/**)`,...xy(tt(m().claude)),`Read(${tt(m().run)}/**)`,`Read(${tt(m().sessionLogs)}/**)`,`Read(${tt(m().outboxes)}/**)`,`Read(${tt(m().sessionRecords)}/**)`,`Read(${tt(m().github)}/**)`,`Read(${tt(m().githubTasks)}/**)`,`Read(${tt(m().screen)})`,`Read(${tt(m().permissionRules)})`,"Read(~/.claude.json)",...xy("~/.claude"),"Read(~/.ssh/**)","Read(~/.config/superfactory/**)","Read(~/.claude/.credentials.json)"];function jT(){let d=process.env.SUPERFACTORY_PERMISSION_MODE;return["acceptEdits","auto","bypassPermissions","manual","dontAsk","plan"].find((p)=>p===d)}function Tr(d={}){let u={};for(let[p,w]of Object.entries(d)){let y=yn(p);if(y)s.warn(`sessions: secret ${JSON.stringify(p)} dropped: ${y}`);else u[p]=w}return u}function ua(d={}){let u=Tr(d);for(let p of Object.keys(u)){if(!p.startsWith(sg))continue;s.warn(`sessions: secret ${JSON.stringify(p)} dropped: the deploy's, for sf deploy exec only`),delete u[p]}return u}var la=(d,u)=>[...ba(d,u)?[]:eg({ownRepo:!u||mr(u.github)}),...Xh()];function Li(d,u,p){return ba(d,u)?p:pa(p)}function pa(d){for(let u of Object.keys(d))s.warn(`sessions: the Lead's secret ${u} dropped: not the Lead's session`);return{}}function sk(d,u){let{video:p,videoFile:w,...y}=u??{};if(p!==void 0)return{error:"task_ask from a sandbox sends the video's bytes"};if(w===void 0)return{args:y};let v=Bf.safeParse(w);if(!v.success||!gt.safeParse(v.data.name).success)return{error:"the video must be a .mp4, .m4v, .mov or .webm file"};if(y.taskId!==void 0&&y.taskId!==d.taskId)return{error:"from a sandbox, a question's video goes with the session's own task only"};return{args:y,video:{name:v.data.name,bytes:Buffer.from(v.data.data,"base64")}}}var su=(d,u)=>!u&&bt(d)&&!d.sandbox;import{join as _R}from"path";var nk=t({pid:i().positive(),startedAt:b()}),LT=5000,ik=200;async function rk(d){let u=await wc(),p=Date.now(),w=new Set([d]);for(let y=!0;y;){y=!1;for(let v of u)if(!w.has(v.pid)&&w.has(v.ppid))w.add(v.pid),y=!0}return w.delete(d),u.filter((y)=>w.has(y.pid)).slice(0,ik).map((y)=>({pid:y.pid,startedAt:p-yl(y.elapsed)*1000}))}function ok(d,u){let p=[...d??[]];for(let w of u)if(!p.some((y)=>ak(y,w)))p.push(w);return p.slice(-ik)}var ak=(d,u)=>d.pid===u.pid&&Math.abs(d.startedAt-u.startedAt)<LT;async function ha(d){if(!d.length)return[];let u=Date.now(),p=(await wc()).filter((w)=>d.some((y)=>ak(y,{pid:w.pid,startedAt:u-yl(w.elapsed)*1000}))).map((w)=>w.pid).filter((w)=>w!==process.pid);for(let w of p)if(!await Tt(w,{tries:3}).catch(()=>!1)&&process.platform!=="win32")await Tt(w,{asRoot:!0,tries:3}).catch((v)=>s.warn(`sessions: couldn't end ${w}, left running`,v));return p}import{readdir as NT,readFile as nu,rm as ma,rmdir as DT}from"fs/promises";import{join as Rr}from"path";async function ck(d){let u=!0;for(let p of[...d.projects.ids(),void 0]){let w=uk(d.projects,p),y=(await NT(w).catch(()=>[])).filter((S)=>S.endsWith(".json")),v=!1;for(let S of y)await UT(d,p,Rr(w,S),S).catch((x)=>{s.info(`sessions: ${S}'s record moves at the next try: ${x.message}`),v=!0});if(u&&=!v,!y.length||v)continue;await ma(Rr(w,".tmp"),{recursive:!0,force:!0}),await DT(w).catch(()=>{return})}return u}var uk=(d,u)=>u?E(d.path(u)).sessions:Rr(m().coordinator,"sessions");async function lk(d,u,p){return jl(await nu(Rr(uk(d,p),`${u}.json`),"utf8"))}async function UT(d,u,p,w){let y=await nu(p,"utf8").then(jl).catch(()=>{return}),v=y&&await FT(d,y,w,u);if(!y||!v)s.warn(`sessions: dropped ${p}: it doesn't match its project, task or file`);else await d.records.change(y.id,(S)=>S.session?S:{...S,session:{...y,jobs:void 0}});await ma(p,{force:!0})}async function FT(d,u,p,w){if(!w)return p===`${u.id}.json`;let y=u.claudeSessionId??u.id;if(u.kind==="coordinator"||u.managerId)return!1;if(p!==`${u.id}.json`||u.projectId!==w||!f.safeParse(y).success)return!1;let v=d.projects.path(w),S=u.taskId?await d.task({projectId:w,taskId:u.taskId}):void 0;if(u.taskId&&!S)return!1;return(S?[v,Rr(E(v).root,"worktrees",S.id)]:[v]).includes(u.cwd)&&u.runner===(S?.runner??"host")}var BT=o(t({id:f,state:Vt,untaken:o(e()).optional()})),WT=I(f,$o);async function pk(d){let u=m(),p=WT.safeParse(await dk(u.sessionOrigins));for(let[y,v]of Object.entries(p.success?p.data:{}))await d.change(y,(S)=>({origin:v,...S}));let w=BT.safeParse(await dk(u.resumeAfterRestart));for(let{id:y,state:v,untaken:S}of w.success?w.data:[]){await d.change(y,(j)=>({...j,resume:{state:v}}));let x=S?.length?await q.open(y):void 0;for(let j of S??[])x?.add(j,"superfactory")}await ma(u.sessionOrigins,{force:!0}),await ma(u.resumeAfterRestart,{force:!0})}async function dk(d){try{return JSON.parse(await nu(d,"utf8"))}catch{return}}var iu="stalled",hk="stuck",HT=/(__task_ask|__chat_ask|^AskUserQuestion)$/,GT=new Set([Ve,"review"]);function ru(d){if(d.type==="user_message"||d.type==="state")return!1;if(d.type==="notice"&&d.kind===iu)return!1;if(d.type==="raw")return d.payload?.type!=="tool_progress";return!0}class ou{sessions=new Map;onEvent(d,u){if(u.type==="state"&&(u.state==="exited"||u.state==="failed")){this.sessions.delete(d);return}let p=this.track(d);if(ru(u))p.lastProgress=Date.now();switch(u.type){case"state":if(u.state==="running")p.lastProgress=Date.now();else if(u.state!=="waiting_input")p.tools.clear();return;case"init":Object.assign(p,{inTurn:!0,acted:!1,lastText:void 0,sinceTool:"",askedWithTool:!1});return;case"user_message":p.withPerson=!GT.has(u.author);return;case"tool_use":if(u.parentToolUseId)return;if(p.tools.add(u.toolUseId),p.acted=!0,p.sinceTool="",HT.test(u.name))p.askedWithTool=!0;return;case"tool_result":p.tools.delete(u.toolUseId);return;case"assistant_text":if(u.delta||u.parentToolUseId)return;p.lastText=u.text,p.sinceTool=[p.sinceTool,u.text].filter(Boolean).join(`
|
|
55
|
+
|
|
56
|
+
`);return;case"result":p.inTurn=!1,p.tools.clear();return}}get(d){return this.sessions.get(d)}all(){return this.sessions.entries()}track(d){let u=this.sessions.get(d);if(!u)u={inTurn:!1,lastProgress:Date.now(),tools:new Set,acted:!1,sinceTool:"",askedWithTool:!1,withPerson:!1},this.sessions.set(d,u);return u}}var fk=60000,qT=30000;function mk(){return k("SUPERFACTORY_STALL_AFTER_MS",12*fk)}function fa(d,u=Date.now()){return`No progress for ${Math.max(1,Math.round((u-Date.parse(d))/fk))} min`}class au{deps;stalled=new Map;timer;constructor(d){this.deps=d;this.timer=setInterval(()=>this.check(),Math.min(qT,mk()/2)),this.timer.unref?.()}onEvent(d,u){if(u.type==="state"&&u.state!=="running"&&u.state!=="waiting_input"||ru(u))this.clear(d)}runsTool(d){return(this.deps.activity.get(d)?.tools.size??0)>0}check(d=Date.now()){for(let[u,p]of this.deps.activity.all()){if(this.stalled.has(u)||p.tools.size||d-p.lastProgress<mk())continue;if(!this.deps.inTurn(u))continue;let w=new Date(p.lastProgress).toISOString();this.stalled.set(u,w),this.deps.stalled(u,w)}}stop(){clearInterval(this.timer)}clear(d){if(!this.stalled.delete(d))return;this.deps.stalled(d,void 0)}}import{randomUUID as ER}from"crypto";import{existsSync as Ck}from"fs";import{mkdir as _k,stat as CR}from"fs/promises";import{join as Er}from"path";function wk(d,{lead:u,secretNames:p}){let w=d.connections.filter((x)=>u||x.who==="everyone"),y=(x)=>VT(x).filter((j)=>!p.includes(j)),v=w.filter((x)=>!y(x).length),S=w.map((x)=>({c:x,secrets:y(x)})).filter(({secrets:x})=>x.length);return{servers:Object.fromEntries(v.map((x)=>[x.name,YT(x)])),tools:v.map((x)=>`mcp__${x.name}`),prompt:QT(v,S)}}function VT(d){return[...new Set([d.secret,...Object.values(d.env)].filter(Boolean))]}var gk=(d)=>`\${${d}}`;function YT(d){if(d.command)return{type:"stdio",command:d.command,args:d.args,env:Object.fromEntries(Object.entries(d.env).map(([p,w])=>[p,gk(w)]))};let u=d.secret?{Authorization:`Bearer ${gk(d.secret)}`}:{};return{type:"http",url:d.url??"",headers:{...d.headers,...u}}}var KT=(d)=>d.command?[d.command,...d.args].join(" "):new URL(d.url??"").host;function QT(d,u){if(!d.length&&!u.length)return"";let p=["## Connections","","MCP servers this project set up for you. Use them for live data (analytics, errors, issues) instead of guessing, and say which one an answer came from."];for(let w of d)if(p.push("",`### ${w.name}: tools mcp__${w.name}__* (${KT(w)})`),w.about.trim())p.push("",w.about.trim());for(let{c:w,secrets:y}of u)p.push("",`### ${w.name}: not connected`,"",`These secrets it needs don't reach this session: ${y.join(", ")}. Ask the user for each with secret_request (scope project); a new session, or this one restarted, then has ${w.name}'s tools.`);return p.join(`
|
|
57
|
+
`)}import{mkdir as $k,readdir as cR}from"fs/promises";import{homedir as uR,userInfo as lR}from"os";import{join as Ik}from"path";import{existsSync as nR}from"fs";import{mkdir as bu,rm as Pk,writeFile as iR}from"fs/promises";import{homedir as rR}from"os";import{join as vu}from"path";import{mkdtemp as yk,rm as kk}from"fs/promises";import{tmpdir as bk}from"os";import{join as ga}from"path";var JT=Number(process.env.SUPERFACTORY_REPO_MIRROR_MS??60000),zT=/^refs\/(heads|tags)\/[^\s~^:?*[\\]+$/;async function XT(d){let u=await a(d,(w)=>w.sub("for-each-ref").flag("--format","%(objectname) %(refname)").arg("refs/heads").arg("refs/tags")),p={};for(let w of u.split(`
|
|
58
|
+
`)){let[y,v]=w.trim().split(" ");if(y&&v&&zT.test(v))p[v]=y}return p}var ZT=(d,u)=>Object.keys(d).length===Object.keys(u).length&&Object.entries(d).every(([p,w])=>u[p]===w),eR=(d,u)=>a(d,(p)=>p.sub("rev-parse").flag("--verify").flag("--quiet").arg(`${u}^{commit}`)).then(()=>!0,()=>!1);async function tR(d){return(await a(d,(p)=>p.sub("rev-list").flag("--max-parents","0").flag("--all")).catch(()=>"")).split(`
|
|
59
|
+
`).filter(Boolean).at(-1)?.trim()}async function vk(d,u,p,w={}){let y=await bo.manifest(p,u),v=await XT(d);if(!w.full&&ZT(v,y.refs))return{pushed:!1};let S=await yk(ga(bk(),"sf-repo-"));try{let x=sw(y.seq+1),j=ga(S,x),L=!!w.full||y.seq===0,N=await sR(d,j,v,L?[]:Object.values(y.refs));if(N)await bo.upload(p,u,x,j);let B=y.rootCommit??await tR(d),G=await bo.push(p,u,{base:y.seq,refs:v,...B?{rootCommit:B}:{},...N?{bundle:x,...L?{full:!0}:{}}:{}});if(G.compact)return vk(d,u,p,{full:!0});return{pushed:!0,seq:G.seq,...N?{bundle:x}:{},full:L&&N}}finally{await kk(S,{recursive:!0,force:!0})}}async function sR(d,u,p,w){let y=Object.keys(p);if(!y.length)return!1;let v=[];for(let S of new Set(w))if(await eR(d,S))v.push(S);try{return await a(d,(S)=>{if(S.sub("bundle create").flag("-q").arg(u).argsOf(y),v.length)S.flag("--not").argsOf(v);return S}),!0}catch(S){if(/empty bundle/i.test(S.message))return!1;throw S}}async function Sk(d,u,p,w){let y=await bo.manifest(d,u);if(!y.seq||!y.bundles.length)return;let v=[w,"main","master"].find((j)=>j&&y.refs[`refs/heads/${j}`])??Object.keys(y.refs).find((j)=>j.startsWith("refs/heads/"))?.slice(11)??"main";await a(p,(j)=>j.sub("init").flag("--quiet").flag("-b",v));let S=await yk(ga(bk(),"sf-restore-"));try{for(let{name:j}of y.bundles){let L=ga(S,j);await bo.download(d,u,j,L),await a(p,(N)=>N.sub("fetch").flag("--quiet").arg(L).arg("+refs/*:refs/superfactory/restore/*"))}}finally{await kk(S,{recursive:!0,force:!0})}for(let[j,L]of Object.entries(y.refs))await a(p,(N)=>N.sub("update-ref").arg(j).arg(L));let x=await a(p,(j)=>j.sub("for-each-ref").flag("--format","%(refname)").arg("refs/superfactory/restore"));for(let j of x.split(`
|
|
60
|
+
`).map((L)=>L.trim()).filter(Boolean))await a(p,(L)=>L.sub("update-ref").flag("-d").arg(j));return await a(p,(j)=>j.sub("reset").flag("--hard").flag("--quiet")),y}class gu{deps;timer;running=new Map;constructor(d){this.deps=d}start(){this.timer=setInterval(()=>void this.round(),JT)}stop(){clearInterval(this.timer)}async round(){await Promise.all(this.deps.own().map((d)=>this.push(d.id,d.path).catch(()=>{return})))}push(d,u){let p=this.running.get(d);if(p)return p.then(()=>this.push(d,u));let w=this.deps.link();if(!w)return Promise.resolve(void 0);let y=(async()=>{if(!await jn(u))return;return We(u,()=>vk(u,d,w)).catch((v)=>{throw s.warn(`repo mirror: ${d} wasn't pushed to the server`,v),v})})();return this.running.set(d,y),y.finally(()=>{if(this.running.get(d)===y)this.running.delete(d)})}}var Ar=()=>process.env.SUPERFACTORY_PROJECTS_DIR??vu(rR(),"projects");async function yu(d){let u=(await a(d,(v)=>v.sub("remote")).catch(()=>"")).split(`
|
|
61
|
+
`).map((v)=>v.trim()).filter(Boolean).sort((v,S)=>Number(S==="origin")-Number(v==="origin")),p=await Promise.all(u.map((v)=>a(d,(S)=>S.sub("config").arg(`remote.${v}.url`)).then((S)=>S.trim()))),y=(await a(d,(v)=>v.sub("rev-list").flag("--max-parents","0").arg("HEAD")).catch(()=>"")).split(`
|
|
62
|
+
`).filter(Boolean).at(-1)?.trim();return{remotes:p,...y?{rootCommit:y}:{}}}var oR=(d)=>{let u=/^git@([^:]+):(.+)$/.exec(d);return u?`https://${u[1]}/${u[2]}`:void 0};class Su{deps;running=new Map;constructor(d){this.deps=d}identity(d){return yu(this.deps.projects.path(d))}checkout(d){let p=(this.running.get(d.projectId)??Promise.resolve()).catch(()=>{return}).then(()=>this.checkoutNow(d));return this.running.set(d.projectId,p),p.catch(()=>{return}).then(()=>{if(this.running.get(d.projectId)===p)this.running.delete(d.projectId)}),p}async checkoutNow({projectId:d,name:u,repo:p,github:w}){let y=this.deps.state.projects.find((j)=>j.id===d);if(y&&!y.checkout)return this.ownAsCheckout(y,p);O(w?.token);let v=y?.path,S=v??(p.remotes.length?await this.clone(u,p,w):await this.restore(d,u)),x=await yu(S);if(!yp(p,x))throw new c("conflict",`${S} is a checkout of another repository`);if(!v)this.deps.state.projects.push({id:d,path:S,checkout:!0}),await F(this.deps.state);return s.info(`checkouts: ${d} is checked out in ${S}`),{path:S,repo:x}}async ownAsCheckout(d,u){let p=()=>new c("conflict",`this machine has a project of its own with the id ${d.id}`);if(d.lead)throw p();let w=await yu(d.path);if(!yp(u,w))throw p();return d.checkout=!0,await F(this.deps.state),s.info(`checkouts: ${d.id} has its home elsewhere now: its folder ${d.path} is its checkout`),{path:d.path,repo:w}}async cloneNew({url:d,name:u,github:p}){O(p?.token);let w=await this.clone(u,{remotes:[d]},p);return s.info(`checkouts: cloned ${d} into ${w}`),{path:w}}async createEmpty({name:d}){let u=await ku(d);await bu(u),await iR(vu(u,"README.md"),`# ${d}
|
|
63
|
+
`),await a(u,(w)=>w.sub("init").flag("--quiet").flag("-b","main")),await this.deps.projects.init(u,d),await a(u,(w)=>w.sub("add").flag("--all"));let p=await he(u);return await a(u,(w)=>w.env(p).sub("commit").flag("--quiet").flag("--message","First commit")),s.info(`checkouts: made an empty project in ${u}`),{path:u}}async forget(d){this.deps.state.projects=this.deps.state.projects.filter((u)=>!(u.id===d&&u.checkout)),await F(this.deps.state)}async restore(d,u){let p=this.deps.link?.();if(!p)throw new c("unavailable","the project has no remote, and the server isn't reached");let w=await ku(u);await bu(w,{recursive:!0});let y=await Sk(p,d,w).catch(async(v)=>{throw await Pk(w,{recursive:!0,force:!0}),new c("unavailable",`couldn't restore the project from the server: ${v.message}`)});if(!y)throw await Pk(w,{recursive:!0,force:!0}),new c("unavailable","the project's repository has no remote, and the server holds no copy of it yet");return s.info(`checkouts: restored ${d} from the server into ${w} (${y.bundles.length} bundles)`),w}async clone(d,u,p){let w=await ku(d),y=[...u.remotes,...u.remotes.flatMap((x)=>oR(x)??[])],v=[];for(let x of y)if(await a(Ar(),(L)=>L.sub("clone").arg(x).arg(w),[],{github:p}).then(()=>!0,(L)=>(v.push(`${x}: ${aR(L)}`),!1)))return w;let S=v.some((x)=>dR.test(x))?". This machine has no access to the repository: give it a GitHub login for git, or an SSH key the repository accepts":"";throw new c("unavailable",`couldn't clone the project here: ${v.join("; ")}${S}`)}}async function ku(d){await bu(Ar(),{recursive:!0});let u=vu(Ar(),mn(d,60)||"project"),p=u;for(let w=2;nR(p);w++)p=`${u}-${w}`;return p}function aR(d){let u=d.message.split(`
|
|
64
|
+
`).map((p)=>p.trim()).filter(Boolean);return(u.find((p)=>p.startsWith("fatal:"))??u.at(-1)??"git failed").replace(/^fatal: /,"")}var dR=/could not read (Username|Password)|terminal prompts disabled|Cannot prompt because user interactivity has been disabled|Authentication failed|Repository not found|Permission denied \(publickey|returned error: 40[13]/i;var pR=l`set -eu
|
|
65
|
+
user=$1 uid=$2 gid=$3 home=$4 auid=$5 agid=$6 hide=$7
|
|
66
|
+
shift 7
|
|
67
|
+
command -v dockerd >/dev/null 2>&1 || { echo "no docker"; exit 0; }
|
|
68
|
+
lib=/usr/local/lib/superfactory
|
|
69
|
+
tools=$lib/rootless-docker
|
|
70
|
+
need=
|
|
71
|
+
command -v newuidmap >/dev/null 2>&1 || need="$need uidmap"
|
|
72
|
+
command -v rootlesskit >/dev/null 2>&1 || need="$need rootlesskit"
|
|
73
|
+
command -v slirp4netns >/dev/null 2>&1 || need="$need slirp4netns"
|
|
74
|
+
command -v ip >/dev/null 2>&1 || need="$need iproute2"
|
|
75
|
+
[ -e /usr/lib/systemd/user/dbus.socket ] || need="$need dbus-user-session"
|
|
76
|
+
if [ -n "$need" ]; then
|
|
77
|
+
export DEBIAN_FRONTEND=noninteractive
|
|
78
|
+
apt-get install -y -qq --no-install-recommends $need >&2 ||
|
|
79
|
+
{ apt-get update -qq >&2 && apt-get install -y -qq --no-install-recommends $need >&2; }
|
|
80
|
+
fi
|
|
81
|
+
touch /etc/subuid /etc/subgid
|
|
82
|
+
if ! grep -q "^$user:" /etc/subuid || ! grep -q "^$user:" /etc/subgid; then
|
|
83
|
+
first=$(awk -F: 'BEGIN { m = 100000 } { if ($2 + $3 > m) m = $2 + $3 } END { print m }' /etc/subuid /etc/subgid)
|
|
84
|
+
usermod --add-subuids "$first-$((first + 65535))" --add-subgids "$first-$((first + 65535))" "$user"
|
|
85
|
+
fi
|
|
86
|
+
version=$(dockerd --version | awk '{ sub(",", "", $3); print $3 }')
|
|
87
|
+
case $version in [0-9]*.[0-9]*) ;; *) echo "dockerd says no version: $(dockerd --version)" >&2; exit 1 ;; esac
|
|
88
|
+
if [ "$(cat "$tools/version" 2>/dev/null)" != "$version" ]; then
|
|
89
|
+
t=$(mktemp -d)
|
|
90
|
+
curl -fsSL "https://download.docker.com/linux/static/stable/$(uname -m)/docker-rootless-extras-$version.tgz" |
|
|
91
|
+
tar -xz -C "$t" docker-rootless-extras/dockerd-rootless.sh docker-rootless-extras/dockerd-rootless-setuptool.sh
|
|
92
|
+
install -d "$tools"
|
|
93
|
+
install -m 755 "$t"/docker-rootless-extras/*.sh "$tools/"
|
|
94
|
+
# The setuptool checks the daemon with the docker next to it.
|
|
95
|
+
ln -sf "$(command -v docker)" "$tools/docker"
|
|
96
|
+
echo "$version" >"$tools/version"
|
|
97
|
+
rm -rf "$t"
|
|
98
|
+
fi
|
|
99
|
+
install -d -m 700 -o "$uid" -g "$gid" "$home"
|
|
100
|
+
view=/run/superfactory-session-view
|
|
101
|
+
dirs=
|
|
102
|
+
for op in "$@"; do dirs="$dirs \${op#r?:}"; done
|
|
103
|
+
printf '%s\n' "$@" >"$lib/session-view.list.new"
|
|
104
|
+
mv "$lib/session-view.list.new" "$lib/session-view.list"
|
|
105
|
+
cat >"$lib/session-view.new" <<'EOS'
|
|
106
|
+
#!/bin/sh
|
|
107
|
+
# The agent's folders its session user's Docker sees (session-docker.ts), as session-view.list has them:
|
|
108
|
+
# each entered once, its real path its path and its owner the agent (a container writes folders around
|
|
109
|
+
# some of them, and may have put a link there), then mounted id-mapped from where it was entered; the
|
|
110
|
+
# ro: ones read-only.
|
|
111
|
+
set -eu
|
|
112
|
+
PATH=/usr/sbin:/usr/bin:/sbin:/bin
|
|
113
|
+
auid=$1 agid=$2 uid=$3 gid=$4
|
|
114
|
+
view=/run/superfactory-session-view
|
|
115
|
+
install -d -m 700 "$view"
|
|
116
|
+
for old in "$view"/*; do
|
|
117
|
+
if mountpoint -q "$old"; then umount -l "$old"; fi
|
|
118
|
+
done
|
|
119
|
+
i=0
|
|
120
|
+
while IFS= read -r op; do
|
|
121
|
+
i=$((i + 1)) dir=\${op#r?:}
|
|
122
|
+
[ -e "$dir" ] || [ -L "$dir" ] || install -d -m 700 -o "$auid" -g "$agid" "$dir"
|
|
123
|
+
cd -P "$dir" && [ "$(pwd -P)" = "$dir" ] && [ "$(stat -c %u .)" = "$auid" ] ||
|
|
124
|
+
{ echo "session view: $dir isn't a folder of the agent's own: a link is on its way" >&2; exit 1; }
|
|
125
|
+
mkdir -p "$view/$i"
|
|
126
|
+
mount --no-canonicalize --bind -o "X-mount.idmap=u:$auid:$uid:1 g:$agid:$gid:1" . "$view/$i"
|
|
127
|
+
cd /
|
|
128
|
+
case $op in ro:*) mount -o remount,bind,ro "$view/$i" ;; esac
|
|
129
|
+
done <"$(dirname "$0")/session-view.list"
|
|
130
|
+
EOS
|
|
131
|
+
chmod 755 "$lib/session-view.new"
|
|
132
|
+
mv "$lib/session-view.new" "$lib/session-view"
|
|
133
|
+
cat >/etc/systemd/system/superfactory-session-view.service <<EOT
|
|
134
|
+
[Unit]
|
|
135
|
+
Description=Superfactory: the agent's folders $user's Docker sees
|
|
136
|
+
RequiresMountsFor=$home$dirs
|
|
137
|
+
Before=user@$uid.service
|
|
138
|
+
|
|
139
|
+
[Service]
|
|
140
|
+
Type=oneshot
|
|
141
|
+
RemainAfterExit=yes
|
|
142
|
+
ExecStart=$lib/session-view $auid $agid $uid $gid
|
|
143
|
+
|
|
144
|
+
[Install]
|
|
145
|
+
WantedBy=multi-user.target
|
|
146
|
+
EOT
|
|
147
|
+
d=/etc/systemd/system/user@$uid.service.d
|
|
148
|
+
install -d "$d"
|
|
149
|
+
{
|
|
150
|
+
echo '[Unit]'
|
|
151
|
+
echo 'Requires=superfactory-session-view.service'
|
|
152
|
+
echo 'After=superfactory-session-view.service'
|
|
153
|
+
echo '[Service]'
|
|
154
|
+
echo 'Delegate=cpu cpuset io memory pids'
|
|
155
|
+
echo "TemporaryFileSystem=$hide"
|
|
156
|
+
echo "BindPaths=$home"
|
|
157
|
+
i=0
|
|
158
|
+
for op in "$@"; do i=$((i + 1)); echo "BindPaths=$view/$i:\${op#r?:}"; done
|
|
159
|
+
} >"$d/superfactory-session.conf.new"
|
|
160
|
+
changed=1
|
|
161
|
+
cmp -s "$d/superfactory-session.conf.new" "$d/superfactory-session.conf" && changed=
|
|
162
|
+
mv "$d/superfactory-session.conf.new" "$d/superfactory-session.conf"
|
|
163
|
+
systemctl daemon-reload
|
|
164
|
+
systemctl enable -q superfactory-session-view.service
|
|
165
|
+
systemctl restart superfactory-session-view.service
|
|
166
|
+
loginctl enable-linger "$user" 2>/dev/null || { mkdir -p /var/lib/systemd/linger && touch "/var/lib/systemd/linger/$user"; }
|
|
167
|
+
if [ -n "$changed" ]; then systemctl restart "user@$uid.service"; else systemctl start "user@$uid.service"; fi
|
|
168
|
+
as_user() {
|
|
169
|
+
runuser -u "$user" -- env -i HOME="$home" USER="$user" LOGNAME="$user" XDG_RUNTIME_DIR="/run/user/$uid" \
|
|
170
|
+
DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$uid/bus" PATH="$tools:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" "$@"
|
|
171
|
+
}
|
|
172
|
+
# Its home is only in its manager's world: the setuptool runs there.
|
|
173
|
+
if ! as_user systemctl --user is-active -q docker.service; then
|
|
174
|
+
as_user systemctl --user reset-failed docker.service >/dev/null 2>&1 || :
|
|
175
|
+
as_user systemd-run --user --wait --pipe --quiet --setenv=PATH="$tools:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" \
|
|
176
|
+
-- "$tools/dockerd-rootless-setuptool.sh" install >&2
|
|
177
|
+
fi
|
|
178
|
+
i=0
|
|
179
|
+
until as_user env DOCKER_CONFIG=/nonexistent docker --host "unix:///run/user/$uid/docker.sock" info >/dev/null 2>&1; do
|
|
180
|
+
i=$((i + 1))
|
|
181
|
+
[ "$i" -lt 60 ] || { echo "its Docker doesn't answer: systemctl --user status docker.service as $user" >&2; exit 1; }
|
|
182
|
+
sleep 1
|
|
183
|
+
done
|
|
184
|
+
echo ready
|
|
185
|
+
`,hR=(d)=>/^\/[A-Za-z0-9._/@+-]*$/.test(d),mR=60000,wa;async function ka(d,u=mR){if(d.group||Pe())return;let p=await fR().catch((y)=>{s.warn(`sessions: what ${d.name}'s Docker sees couldn't be listed: ${y.message}`);return});if(!p)return;let w=wa;if(w?.view!==p.join(`
|
|
186
|
+
`)){let v=(w?.result??Promise.resolve("")).then(()=>gR(d,p)).catch((x)=>`it couldn't be set up: ${x.message}`),S={view:p.join(`
|
|
187
|
+
`),result:v};w=wa=S,v.then((x)=>{if(x==="ready")s.info(`sessions: ${d.name} has its own Docker (${$l(d)})`);else if(x==="no docker"){if(wa===S)wa=void 0}else s.warn(`sessions: ${d.name} has no Docker of its own: ${x}`)})}await Promise.race([w.result,Bun.sleep(u)])}async function fR(){let d=Ar();for(let p of[d,ns.root])await $k(p,{recursive:!0,mode:448});let u=[];for(let p of(await cR(d)).sort()){let w=Ik(d,p);if(!xm(w))continue;await $k(Ik(w,".superfactory","worktrees"),{recursive:!0}),u.push(...await Sl(w))}return[`ro:${d}`,`rw:${ns.root}`,...u.map((p)=>`rw:${p}`)]}async function gR(d,u){let p=Qn([uR(),U()]),y=[...p,...u.map((j)=>j.slice(3)),d.home].filter((j)=>!hR(j));if(y.length)return`a folder's name it can't put in a unit file: ${y.join(", ")}`;let v=lR(),S=await g(r(A).flag("-n").wrap(r(Yd).script("-c",pR).argsOf(["session-docker",d.name,d.uid,d.gid,d.home,v.uid,v.gid,p.join(" "),...u]).build()).by("session user's Docker").timeoutMs(600000).build()),x=S.stdout.trim().split(`
|
|
188
|
+
`).at(-1)??"";if(S.exitCode===0&&(x==="ready"||x==="no docker"))return x;return(S.stderr.trim()||x).split(`
|
|
189
|
+
`).slice(-5).join(" ").slice(0,500)}import{existsSync as Ak}from"fs";import{join as Ek}from"path";var wR="https://github.com",Tk=()=>k("SUPERFACTORY_GITHUB_TICK_MS",60000);class va{deps;renewals=new Map;due=new Map;written=new Map;hosts=new Map;awaited=new Set;sent=new Map;renewing=new Set;checks;ensuring;constructor(d){this.deps=d}get source(){return this.deps.source??Jm}async forSession(d){let u;try{u=await this.source.known(d)}catch(p){if(s.info(`github: no token for ${d} yet (${p.message}): asking again shortly`),this.awaited.add(d),!this.renewals.has(d))this.renewIn(d,ta());return}return await this.keep(d,u),u}env(d,u,p){if(u)return this.deps.files.env(d,u,p,this.deps.pushGateway?.(d));if(!this.awaited.has(d))return p;return this.deps.files.gitEnv(d,{host:this.hosts.get(d)??wR},p)}async changed(d){if(this.source.forget(d),!this.deps.inUse(d)&&!this.written.has(d))return;await this.renew(d)}async taken(d,u){if(!u||this.renewing.has(d)||!this.written.has(d))return;if(this.written.get(d)===u.token)return;await this.keep(d,u).catch((p)=>{s.info(`github: couldn't write ${d}'s token: ${p.message}`)})}async renew(d){if(this.stopRenewing(d),!this.deps.inUse(d)){await this.keep(d,void 0);return}this.renewing.add(d);try{await this.keep(d,await this.source.fresh(d))}catch(u){s.info(`github: couldn't renew ${d}'s token: ${u.message}`),this.renewIn(d,ta())}finally{this.renewing.delete(d)}}async keep(d,u){if(this.stopRenewing(d),this.awaited.delete(d),u){if(this.hosts.set(d,u.host),await this.deps.files.write(d,u),this.written.set(d,u.token),u.expiresAt)this.renewIn(d,Ll(u))}else await this.deps.files.remove(d),this.written.delete(d);if(this.sent.has(d)&&this.sent.get(d)===u?.token)return;this.sent.set(d,u?.token),await this.deps.toSandboxes(d,u).catch((p)=>{if(s.warn(`github: ${d}'s sandboxes didn't get its new token: ${p.message}`),this.sent.delete(d),u?.expiresAt)this.renewIn(d,ta())})}renewIn(d,u){this.stopRenewing(d),this.due.set(d,Date.now()+u),this.tick(d)}tick(d){let u=this.due.get(d);if(u===void 0)return;let p=u-Date.now();if(p<=0){this.renew(d);return}let w=setTimeout(()=>this.tick(d),Math.min(p,Tk()));w.unref?.(),this.renewals.set(d,w)}stopRenewing(d){clearTimeout(this.renewals.get(d)),this.renewals.delete(d),this.due.delete(d)}start(){if(this.checks)return;this.checks=setInterval(()=>void this.ensure(),Tk()),this.checks.unref?.(),this.ensure()}ensure(){return this.ensuring??=this.ensureNow().finally(()=>{this.ensuring=void 0}),this.ensuring}async ensureNow(){for(let d of new Set(this.deps.used())){if(this.renewing.has(d)||this.awaited.has(d))continue;let u=await this.deps.files.has(d).catch(()=>!0);if(u&&this.written.has(d))continue;let p=await this.source.known(d).catch(()=>{return});if(!p)continue;if(u)s.info(`github: ${d}'s token files from the agent before: renewed from now on`);else s.warn(`github: ${d}'s credential file was missing: written again`);await this.keep(d,p).catch((w)=>{s.info(`github: couldn't write ${d}'s token: ${w.message}`)})}}stop(){clearInterval(this.checks),this.checks=void 0;for(let d of[...this.renewals.keys()])this.stopRenewing(d)}clear(){return this.stop(),this.written.clear(),this.sent.clear(),this.deps.files.clear(new Set(this.deps.used()))}}class $u{calls=new Map;answer(d,u,p){if(!u)return p(new AbortController().signal);let w=`${d}:${u}`,y=this.calls.get(w);if(y)return y.result;let v=new AbortController,S=p(v.signal).finally(()=>{setTimeout(()=>{if(this.calls.get(w)?.result===S)this.calls.delete(w)},600000).unref()});return this.calls.set(w,{result:S,gaveUp:v}),S}gaveUp(d,u){this.calls.get(`${d}:${u}`)?.gaveUp.abort()}}import{chmod as yR,mkdir as kR,readdir as bR,readFile as vR,rename as SR,rm as PR,stat as Rk,writeFile as $R}from"fs/promises";import{join as IR}from"path";var TR=t({session:te.optional(),origin:$o.optional(),resume:t({state:Vt}).optional(),left:o(nk).max(200).optional()});class Ru{cache=new Map;async read(d){if(!f.safeParse(d).success)return;let u=Iu(d),p=await Rk(u).catch(()=>{return});if(!p)return;let w=this.cache.get(d);if(w?.mtimeMs!==p.mtimeMs||w.size!==p.size){let y=TR.safeParse(AR(await vR(u,"utf8").catch(()=>"")));if(!y.success||y.data.session&&y.data.session.id!==d){s.warn(`sessions: ${u} isn't a session record: ignored`);return}w={mtimeMs:p.mtimeMs,size:p.size,record:y.data},this.cache.set(d,w)}return structuredClone(w.record)}async sessions(){let u=(await bR(m().sessionRecords).catch(()=>[])).filter((w)=>w.endsWith(".json")).map((w)=>w.slice(0,-5));return(await Promise.all(u.map((w)=>this.read(w)))).flatMap((w)=>w?.session?[{session:w.session,record:w}]:[])}async write(d,u){if(!f.safeParse(d).success)throw Error(`not a session id: ${d}`);await kR(m().sessionRecords,{recursive:!0,mode:448});let p=Iu(d),w=`${p}.${process.pid}.${++RR}.tmp`;await $R(w,`${JSON.stringify(u,null,2)}
|
|
190
|
+
`,{mode:384}),await yR(w,384),await SR(w,p);let{mtimeMs:y,size:v}=await Rk(p);this.cache.set(d,{mtimeMs:y,size:v,record:structuredClone(u)})}async change(d,u){await this.write(d,u(await this.read(d)??{}))}async remove(d){this.cache.delete(d),await PR(Iu(d),{force:!0})}}var RR=0,Iu=(d)=>IR(m().sessionRecords,`${d}.json`);function AR(d){try{return JSON.parse(d)}catch{return}}class Au{deps;live=new Map;records=new Ru;recovering=Promise.resolve();recordsMoved=!1;recovered=!1;taskTurns=new Map;ensuring=new Map;loading=new Map;shuttingDown=!1;freshNext=new Set;startFailures=new Map;remote=new Map;reserved=new Set;holding=new Map;preparing=new Map;forwarded=new $u;movedAway=new Set;movingOut=new Set;commandCache=new Map;github=new va({files:new Hn(m().github),inUse:(d)=>[...this.live.values()].some((u)=>u.session.projectId===d&&u.process?.alive)||[...this.remote.values()].some((u)=>u.session.projectId===d),used:()=>[...[...this.live.values()].flatMap((d)=>d.process?.alive&&d.session.projectId||[]),...[...this.remote.values()].flatMap((d)=>d.session.projectId??[])],toSandboxes:(d,u)=>this.githubToSandboxes(d,u)});taskGithub=new va({files:new Hn(m().githubTasks),inUse:(d)=>[...this.live.values()].some((u)=>u.session.projectId===d&&u.session.kind!=="coordinator"&&u.process?.alive),used:()=>[...this.live.values()].flatMap((d)=>d.process?.alive&&d.session.kind!=="coordinator"&&d.session.projectId||[]),toSandboxes:async()=>{},source:Zm,pushGateway:(d)=>ww(Number(new URL(this.deps.mcpUrl()).port),d)});stalls;constructor(d){this.deps=d;this.stalls=new au({activity:d.activity,inTurn:(u)=>{let p=this.live.get(u);return p?.session.state==="running"&&!!p.process?.alive&&!Ft(p.phase,"compact")},stalled:(u,p)=>this.onStall(u,p)}),d.ownLogin?.onSignedIn(()=>void this.ownLoginBack())}turnKey(d){if(d.kind==="coordinator"){let y=this.managerOf(d);return y&&`manager:${y.id}`}let{projectId:u,taskId:p,teammate:w}=d;return u&&p&&!w?`${u}/${p}`:void 0}oneAtATime(d,u){let w=(this.taskTurns.get(d)??Promise.resolve()).catch(()=>{return}).then(u),y=w.catch(()=>{return});return this.taskTurns.set(d,y),y.then(()=>{if(this.taskTurns.get(d)===y)this.taskTurns.delete(d)}),w}projectOf(d){if(!d.projectId)return Promise.resolve(void 0);return this.deps.projects.get(d.projectId).catch(()=>{return})}coordinator(d,u){let p=d.kind==="project"?d.projectId:void 0,w=this.deps.managers.resolve(d,u).id;return[...this.live.values()].find((y)=>y.session.kind==="coordinator"&&y.session.projectId===p&&this.managerOf(y.session)?.id===w&&Ir(y))}strayProjectLead(d){if(d.kind!=="coordinator"||!d.projectId)return!1;let{projects:u,managers:p,nodeId:w}=this.deps;if(u.isLead(d.projectId))return!1;let y=d.managerId??`p-${d.projectId}`,v=p.list().find((S)=>S.id===y);if(v)return v.nodeId!==w();return!u.ownIds().includes(d.projectId)}otherCoordinator(d){let{session:u}=d;if(u.kind!=="coordinator")return;let p=this.managerOf(u)?.id;return[...this.live.values()].find((w)=>w!==d&&w.session.kind==="coordinator"&&w.session.projectId===u.projectId&&this.managerOf(w.session)?.id===p&&Ir(w))}addressOf(d){let u=this.managerOf(d);return vp({kind:d.kind,projectId:d.projectId,taskId:d.taskId,key:d.projectId?this.deps.projects.keys(d.projectId).key:void 0,teammate:d.teammate,machine:d.teammate?this.deps.machineName?.():void 0,manager:u&&{name:u.name,main:u.main,machine:u.type==="machine"},mainLead:bt(d)&&this.deps.projects.holdsLead()})}addressed(){let d=this.deps.projects.holdsLead(),u=[...this.live.values()].map((G)=>({session:G.session})),p=[...this.remote.values()].map((G)=>({session:G.session})),w=new Map,y=(G,V)=>{let Y=$s(G).toLowerCase();w.set(Y,(w.get(Y)??new Set).add(V))},v=(G)=>G.kind==="coordinator"?`lead:${this.managerOf(G)?.id??G.id}`:"task",S=(G)=>!Jy.has(G.state),x=[...u,...p].flatMap((G)=>{let V=(p.includes(G)?void 0:G.session.address)??this.addressOf(G.session);if(!V)return[];return y(V,v(G.session)),[{...G,address:V}]}).sort((G,V)=>Number(S(G.session))-Number(S(V.session))||V.session.startedAt.localeCompare(G.session.startedAt)).filter((G,V,Y)=>Y.findIndex((ne)=>st(ne.address,G.address))===V),j=(G)=>x.some((V)=>st(V.address,G)),L=[...this.deps.projects.ownIds().map((G)=>this.deps.managers.main({kind:"project",projectId:G})),...d?[this.deps.managers.main({kind:"global"})]:[]],B=[...this.deps.managers.list(),...L].filter((G,V,Y)=>Y.findIndex((ne)=>ne.id===G.id)===V).flatMap((G)=>{let V=G.main&&G.scope.kind==="global"&&d;if(G.main&&G.scope.kind==="global"&&!V)return[];let Y=Ia(G);if(G.mergedInto||G.type==="machine"||!Y)return[];if(y(Y,`lead:${G.id}`),j(Y))return[];let ne=G.scope.kind==="project"?G.scope.projectId:void 0,ie=G.scope.kind==="global"&&!G.main;return[{address:Y,lead:{id:G.id,projectId:ne,bossId:G.bossId,mainLead:V,allProjects:ie}}]});return[...x,...B].map((G)=>(w.get($s(G.address).toLowerCase())?.size??0)>1?{...G,ambiguous:!0}:G)}managerOf(d){if(d.kind!=="coordinator")return;let u=d.projectId?{kind:"project",projectId:d.projectId}:{kind:"global"};return d.managerId&&this.deps.managers.get(d.managerId)||this.deps.managers.main(u)}ofManager(d){let u=this.deps.managers.get(d);return u?this.coordinator(u.scope,u.id):void 0}settingsOf(d){let{projectId:u}=d.session;return u?this.deps.projects.settings(u,d.userLayer):this.deps.projects.globalSettings(d.userLayer)}outboxOf(d){return this.live.get(d)?.outbox??this.remote.get(d)?.outbox}sessionForTask(d,u){let p=(y)=>y.projectId===d&&y.taskId===u&&!y.teammate;return[...this.live.values()].find((y)=>p(y.session)&&y.process?.alive)?.session.id??[...this.remote.values()].find((y)=>p(y.session))?.session.id}async taskOf({projectId:d,taskId:u}){if(!d||!u)return;return this.deps.tasks.get({projectId:d,taskId:u}).catch(()=>{return})}wentElsewhere(d){if(this.movingOut.has(d))return"moving";return this.movedAway.has(d)?"moved":void 0}backHere(d){this.movedAway.delete(d)}runsGoingOn(){let d=new Map,u=(p)=>p.state!=="exited"&&p.state!=="failed";for(let{session:p}of[...this.live.values(),...this.remote.values()])if(u(p))d.set(p.id,p.startedAt);for(let p of this.preparing.values())d.set(p.id,p.startedAt);return d}get stopping(){return this.shuttingDown}ranHere(d){return this.remote.has(d)||this.hasHistory(d)}sandboxNodes(){return new Set([...this.remote.values()].map((d)=>d.childId))}readTask(d){return this.deps.tasks.get(d).catch((u)=>{if(u instanceof c&&u.code==="not_found")return;throw u})}async everRan(d){let{cwd:u,claudeSessionId:p,id:w}=d.session;if(Ak(qe(u,p??w)))return!0;return(await Ms(Ek(m().sessionLogs,`${d.session.id}.jsonl`))).some((v)=>v.type==="init")}ours(d){return d.nodeId===this.deps.nodeId()}async list(d){let u=new Set(this.deps.projects.ids());return(await this.records.sessions()).flatMap(({session:p})=>{if(!this.ours(p))return[];return(d?p.projectId===d:!p.projectId||u.has(p.projectId))?[this.live.get(p.id)?.session??p]:[]})}history(d,u,p,w){return $i(m().sessionLogs,d,u,p,w)}async cwdOf(d){let u=this.live.get(d);if(u)return u.session.cwd;let p=await this.savedOne(d);if(!p)throw new c("not_found",`no session ${d} on this node`);return p.cwd}replyTarget(d,u,p){let w=d?this.live.get(d):void 0;if(!w?.process?.alive||w.session.kind!=="coordinator")return;let{projectId:y}=w.session;return y===u||y===void 0&&p?w.session.id:void 0}processes(){return[...this.live.values()].flatMap((d)=>d.process?.pid?[{session:d.session,pid:d.process.pid}]:[])}find(d){return this.live.get(d)?.session??this.remote.get(d)?.session}forTask(d,u){return[...this.live.values()].find((p)=>p.session.projectId===d&&p.session.taskId===u&&!p.session.teammate&&p.process?.alive)}leadOf(d,u){return[...this.live.values()].find((p)=>p.session.projectId===d&&p.session.taskId===u&&!p.session.teammate&&Ss(p))}otherLead(d){let{projectId:u,taskId:p,teammate:w}=d.session;if(!u||!p||w)return;let y=this.leadOf(u,p);return y&&y!==d?y:void 0}busy(){return[...this.live.values()].filter((d)=>Qy.includes(d.session.state)).map((d)=>d.session)}inTurn(){return this.withClaude(zo)}cutByRestart(){return[...this.live.values()].filter((d)=>d.process?.alive&&zo.includes(d.session.state)&&(!d.process.handsOver||this.deps.mcp.busy(d.token))).map((d)=>d.session)}inTool(){return this.withClaude(zo).filter((d)=>this.stalls.runsTool(d.id))}withClaude(d){return[...this.live.values()].filter((u)=>u.process?.alive&&d.includes(u.session.state)).map((u)=>u.session)}isLive(d){return this.live.has(d)}claudeRunsHere(){return[...this.live.values()].some((d)=>d.process?.alive&&!d.place?.sandbox)}isRunning(d){return this.live.get(d)?.process?.alive??!1}reconcileWaiting(d){let u=this.live.get(d);if(u)u.reconcileWaiting(this.waitsForUser(u))}waitsForUser(d){return this.deps.waitsForUser?.(d.session.id)??!0}switching=new Map;localHandle(d){let u=d.session.id;return{session:d.session,outbox:d.outbox,get place(){return d.place},get origin(){return d.origin},get account(){return d.account},send:(p,w,y)=>this.sendHere(u,p,w,y),stop:(p,w)=>this.stopHere(d,p,w),wrapUp:(p,w)=>this.wrapUpHere(d,p,w),interrupt:async()=>d.interrupt(),nudge:()=>this.nudgeHere(d),restartClaude:(p)=>this.restartHere(d,p),boundary:(p)=>{if(d.newPart(p))this.compactIfDue(d,p)},jobOutput:(p)=>d.jobOutput(p),stopJob:(p)=>d.stopJob(p),secrets:async(p,w,y)=>{d.secretEnv=p,d.leadEnv=w,await this.deps.secretEnvs.update(u,ts(p),y)},note:async(p)=>{if(p)d.record({type:"claude_account",...p});await this.save(d)},restartOn:async(p,w)=>{d.nextLogin=p,await this.respawn(d,w)},idle:()=>d.betweenTurns()&&d.restartAfterTurn===void 0,waiting:()=>d.outbox.unread().length>0}}handleOf(d){return this.remote.get(d)??this.live.get(d)?.handle}requireHandle(d){let u=this.handleOf(d);if(!u)throw new c("not_found",`session ${d} isn't running on this node`);return u}handles(){return[...[...this.live.values()].map((d)=>d.handle),...this.remote.values()]}mayMove(d){return d.idle()&&!tn(d.session)&&!this.switching.has(d.session.id)}recordEvent(d,u){let p=this.live.get(d);if(p)p.record(u)}async recordInHistory(d,u){if(this.live.has(d))return this.recordEvent(d,u);if(!this.hasHistory(d))return;let p=(await js.open(m().sessionLogs,d)).append(u);this.deps.push({type:"session.event",event:p})}managersChat(d){let u=this.find(d),p=u&&this.managerOf(u);if(!u||!p)return d;let w=u.projectId?{kind:"project",projectId:u.projectId}:{kind:"global"};return this.coordinator(w,p.id)?.session.id??d}failures(d){return this.live.get(d)?.failures??0}wake(d,u=!1){return this.resumeSession(d,{reason:"message",byPerson:u})}async resumeSession(d,u){let p=this.live.get(d);if(p&&Ss(p))return p;let w=p??await this.revivable(d),y=this.otherLead(w)??this.otherCoordinator(w);if(y)return y;return await this.ensureRunning(w,{...u,resume:!0}),w}revivable(d){let u=this.live.get(d);if(u)return Promise.resolve(u);let p=this.loading.get(d);if(!p)p=this.load(d).finally(()=>this.loading.delete(d)),this.loading.set(d,p);return p}async load(d){let u=await this.records.read(d),p=u?.session;if(!u||!p)throw new c("not_found",`no session ${d} on this node`);let w=await this.newLive(p,{level:(await this.taskOf(p))?.level??"normal",secretEnv:{},origin:u.origin,userLayer:{},place:void 0},void 0,oc(p.state));w.resumeOnStart=u.resume,w.leftRunning=u.left;let y=this.live.get(d);if(y)return y;return this.live.set(d,w),w}recorded(d,u,p){this.deps.activity.onEvent(d.session.id,p),this.stalls.onEvent(d.session.id,p),this.deps.push({type:"session.event",event:u}),this.deps.hooks.onEvent?.(d.session,u)}shown(d,u,p){if(u!==d.session.state&&this.holding.has(d.session.id))this.heldWoke(d);if(this.save(d),p)this.deps.hooks.onStateChange?.(d.session)}async showApplied(d){let u=d.process,p=await u?.applied().catch(()=>{return});if(!p||d.process!==u)return;let w=p.model??d.session.model,y=p.effort??void 0;if(w===d.session.model&&y===d.session.effort)return;d.session.model=w,d.session.effort=y,await this.save(d)}async checkPlugins(d){let u=d.process;for(let p=0;p<Jc;p+=1){if(await Bun.sleep(Wy),d.process!==u||!u?.alive)return;let w=await u.mcpStatus().catch(()=>{return});if(!w)return;if(w.some((y)=>y.status==="pending")&&p<Jc-1)continue;cm(w);return}}onStall(d,u){let p=this.live.get(d);if(!p)return;let w=p.session.stalledSince;if(p.session.stalledSince=u,u)s.warn(`sessions: ${d} stalled: no progress since ${u}, no tool running`),p.record({type:"notice",level:"warning",kind:iu,text:`${fa(u)}: Claude may hang. Nudge starts it again where it was.`});else if(w)s.info(`sessions: ${d} moves again`);if(u||w)this.save(p)}save(d){let u={...d.session},p={session:u,origin:d.origin,resume:d.resumeOnStart,...d.leftRunning?.length?{left:d.leftRunning}:{}},w=(d.saving??Promise.resolve()).then(async()=>{if(this.movedAway.has(u.id))return;await this.records.write(u.id,p),this.deps.push({type:"session.updated",session:u})});return d.saving=w.catch(()=>{return}),w}async savedOne(d){return(await this.records.read(d))?.session}get(d){let u=this.live.get(d);if(!u)throw new c("not_found",`session ${d} isn't running on this node`);return u}otherProjects(d){let{projects:u}=this.deps;return u.ids().filter((p)=>p!==d).map((p)=>u.path(p)).filter((p)=>!p.includes(","))}saveTranscript(d){return this.deps.transcripts?.save({sessionId:d.id,cwd:d.cwd,conversationId:d.claudeSessionId??d.id,memory:!d.teammate&&(process.platform==="linux"||d.kind==="coordinator")})??Promise.resolve()}hasHistory(d){return Ak(Ek(m().sessionLogs,`${d}.jsonl`))}}class Eu extends Au{async switchAccount(d,u){let{id:p}=d.session,w=this.switching.get(p),y=u.reason==="limit"||u.reason==="signed_out";if(w&&!y)return;let v=d.account?.id,S=(w??Promise.resolve()).catch(()=>{return}).then(async()=>{if(w&&d.account?.id!==v)return;await this.switchNow(d,u)});this.switching.set(p,S);try{await S}catch(x){s.warn(`sessions: ${p} couldn't switch its Claude account (${u.reason})`,x)}finally{if(this.switching.get(p)===S)this.switching.delete(p)}}async switchNow(d,u){let{session:p}=d,w=d.account;if(u.reason==="rebalance"&&!w)return;if(u.reason==="resume"&&!p.pausedUntil)return;if(Yc(u)){if(p.state!=="idle"||tn(p))return;let S=this.live.get(p.id);if(S?.handle===d&&await this.restNow(S,Uy(u,w),`(${u.reason})`))return}let y=await this.deps.claudeLogin(p,{origin:d.origin,...Ny(u,w?.id)}).catch((S)=>{s.warn(`sessions: no next Claude login for ${p.id}`,S);return});if(u.reason==="resume")return this.carryOn(d,u.due,y);let v=!!y?.token&&!y.waitUntil&&y.accountId!==w?.id;if(!y||!v)return this.stay(d,u,y);if(Yc(u)&&(p.state!=="idle"||tn(p)))return;await d.note(Dy(u,y,w)),s.info(`sessions: ${p.id} moves to another Claude account (${u.reason})`),await d.restartOn(y,Fy(u))}async stay(d,u,p){let{session:w}=d;if(u.reason==="limit"){let x=Kc(u,p);return this.pause(d,p?.waitUntil??x,p?.signedOut?"signed_out":"limit")}if(u.reason!=="signed_out"||await this.retryLogin(d))return;let y=d.account?.name??Mi,v=p?.waitUntil??new Date(vs()+Ko).toISOString();s.info(`sessions: ${w.id} waits for a signed-in Claude account: ${y} is signed out`);let S=p?.noAccount;await this.pause(d,v,"signed_out",{change:"signed_out",from:y,until:v,noAccount:S}),this.deps.hooks.onSignedOut?.(w,{from:y,noAccount:S,machineLogin:!d.account})}async retryLogin(d){let{session:u}=d;if(this.loginRetried.has(u.id))return!1;let p=await this.deps.claudeLogin(u,{origin:d.origin}).catch(()=>{return});if(!p||p.signedOut||p.waitUntil&&Date.parse(p.waitUntil)>vs())return!1;if(!p.token&&await this.ownLoginOut(d))return!1;return this.loginRetried.add(u.id),s.info(`sessions: ${u.id} runs again once on the Claude login it gets now`),await d.restartOn(p),!0}async ownLoginOut(d){return!d.place?.sandbox&&(await this.deps.ownLogin?.signedOut()??!1)}async ownLoginBack(){let d=this.paused().filter((u)=>u.session.pausedFor==="signed_out"&&!u.place?.sandbox);await Promise.all(d.map((u)=>this.switchAccount(u,{reason:"resume",due:!0})))}async waitForOwnLogin(d,u){let p=new Date(vs()+Ko).toISOString();s.info(`sessions: ${d.session.id} waits: this machine's own Claude login is signed out`),await this.pause(d.handle,p,"signed_out",{change:"signed_out",from:Mi,until:p,noAccount:u}),this.deps.hooks.onSignedOut?.(d.session,{from:Mi,noAccount:u,machineLogin:!0})}loginRetried=new Set;loginWorked(d){this.loginRetried.delete(d.id)}async accountLimited(d,u){let p=this.handles().filter((w)=>w.account?.id===d&&this.mayMove(w));await Promise.all(p.map((w)=>this.switchAccount(w,{reason:"limited_elsewhere",until:u})))}async rebalance(d){let u=new Set(d);for(let p of this.handles())if(u.has(p.session.id)&&p.account&&this.mayMove(p))await this.switchAccount(p,{reason:"rebalance"})}async pause(d,u,p="limit",w={change:"paused",limited:d.account?.name,until:u}){d.session.pausedUntil=u,d.session.pausedFor=p,await d.note(w),s.info(`sessions: ${d.session.id} waits for a Claude account (${p}) until ${u}`),this.watchPauses()}unpause(d){d.pausedUntil=void 0,d.pausedFor=void 0}paused(){return this.handles().filter((d)=>d.session.pausedUntil)}pauseTimer;watchPauses(){if(this.pauseTimer)return;this.pauseTimer=setInterval(()=>{let d=this.paused();if(!d.length)clearInterval(this.pauseTimer),this.pauseTimer=void 0;for(let u of d)if(Date.parse(u.session.pausedUntil??"")<=vs())this.switchAccount(u,{reason:"resume",due:!0})},Ey),this.pauseTimer.unref?.()}async signInAgain(d,u,p,w){let{session:y}=d;if(u)d.startTicket=u,d.origin=void 0;if(this.unpause(y),await this.save(d),s.info(`sessions: ${y.id} runs again on the Claude login its start gets`),p)d.enqueue(p,"user",void 0,w);await this.respawn(d,d.outbox.unread().length?void 0:qc)}async resumePaused(){await Promise.all(this.paused().map((d)=>this.switchAccount(d,Qo)))}async carryOn(d,u,p){let{session:w}=d;if(!p||!w.pausedUntil)return;let y=!!p.waitUntil&&Date.parse(p.waitUntil)>vs();if(!u&&(!p.token||y))return;let S=p.noAccount==="owner_only"&&!!d.place?.sandbox||await this.ownLoginOut(d);if(!p.token&&S&&w.pausedFor==="signed_out"){w.pausedUntil=p.waitUntil??new Date(vs()+Ko).toISOString(),await d.note();return}if(y){w.pausedUntil=p.waitUntil,w.pausedFor=p.signedOut?"signed_out":"limit",await d.note();return}let x=w.pausedFor==="signed_out";if(w.pausedUntil=void 0,w.pausedFor=void 0,await d.note({change:"resumed",account:p.account}),s.info(`sessions: ${w.id} carries on after waiting for a Claude account`),d.waiting())return d.restartOn(p);await d.restartOn(p,x?qc:_y)}async originOf(d,u){if(d.startTicket)return;if(d.origin||!u)return d.origin;return this.live.get(u)?.origin??(await this.records.read(u))?.origin}async claudeLogin(d,u){try{let p=u.startTicket;u.startTicket=void 0;let w=u.nextLogin;u.nextLogin=void 0,u.account=void 0;let y=()=>this.deps.claudeLogin(d,{startTicket:p,origin:u.origin}),v=w??await y().catch(async(Y)=>(s.warn(`sessions: asking the server for ${d.id}'s Claude login again`,Y),await Bun.sleep(jy()),y())),{token:S,note:x,instructions:j,machine:L,machines:N,author:B,noAccount:G}=v;if(x)s.info(`sessions: ${d.id} runs on Claude's own login here: ${x}`);u.account=qo(v),Vo(d,u.account);let V={instructions:j,machine:L,machines:N,author:B,noAccount:G};if(!S)return{env:{},...V};return O(S),{env:{CLAUDE_CODE_OAUTH_TOKEN:S},...V}}catch(p){return s.warn(`sessions: no Claude account from the server for ${d.id}; Claude's own login here`,p),{env:{}}}}}class Cu extends Eu{leadSecretsFrom(d,u){let p=this.live.get(d);if(!p||!bt(p.session)||!this.deps.projects.isLead(u))return;let w=Object.keys(p.leadEnv??{});if(!w.length)return;return s.info(`sessions: the main Lead hands ${w.join(", ")} to its task in ${u}`),{...p.leadEnv}}async mayRelease(d){let u=this.live.get(d)?.session;if(!u)return!1;let p=await this.projectOf(u);return ba(u,p)}async keepLeadSecrets(d,u,p){if(!Object.keys(p).length)return;let w=Li(d.session,u,p);if(!Object.keys(w).length)return;let y=Object.fromEntries(Object.entries(d.secretEnv).filter(([v])=>!(v in(d.leadEnv??{}))));await this.updateSecrets({sessionId:d.session.id,env:y,leadEnv:w,changed:[]})}async stackBase(d,u){if(!u.buildsOn&&!u.epic)return;let{parent:p}=await Gr(u,(w)=>this.deps.tasks.get({projectId:d.id,taskId:w}).catch(()=>{return}));return jf(d.path,p)}async spawnClaude(d,u){let{session:p}=d;d.startStep="its outbox",await this.checkOutbox(d);let{projects:w,tasks:y}=this.deps,v=p.projectId?await w.get(p.projectId):void 0,S=await this.settingsOf(d),x=v&&p.taskId?await y.get({projectId:v.id,taskId:p.taskId}):void 0,{kind:j}=p;if(!d.place&&v&&x&&p.runner==="host")d.place=await this.placeAgain(d,v,x,S);await _k(Er(m().attachments,p.id),{recursive:!0,mode:448}),d.startStep="its Claude account, from the server";let L=await this.claudeLogin(p,d),N=!L.env.CLAUDE_CODE_OAUTH_TOKEN&&await this.ownLoginOut(d);d.startStep="its run files";let B=await Gc(Yo(S,{lead:j==="coordinator"})),G=await this.marketplacePlugins(p,S,d.secretEnv);await Ri().catch((bs)=>s.warn("plugins: couldn't write out the built-in plugins",bs));let V=[...ml(S),...B?[B]:[],...G.dirs],Y=wk(S,{lead:j==="coordinator",secretNames:Object.keys(ts(d.secretEnv))}),ne=await this.deps.systemPrompt(j,v,x,p,L),{mcpConfig:ie,hooks:ye,promptFile:ve}=await Si(d.runDir,{mcpUrl:this.deps.mcpUrl(),token:d.token,waitMs:eu(S),systemPrompt:[ne,Y.prompt,G.prompt].filter(Boolean).join(`
|
|
191
|
+
|
|
192
|
+
`),servers:{...lt()?Oi(V,Object.keys(G.env)):{},...Y.servers}});if(d.startStep="its conversation, from the server",u)await this.deps.transcripts?.restore({sessionId:p.id,cwd:p.cwd,conversationId:p.claudeSessionId??p.id});let Qe=this.managerOf(p),ht=Qe?.type==="machine",et=oa(ht?"task":j,d.level,S,Qe);this.registerTools(d,v?.id,et.permissionMode);let _t=j!=="coordinator"&&v?.lead?this.otherProjects(v.id):[],Gn=u&&await this.noConversationToResume(d);if(Gn)this.startAfresh(d,x),u=!1;let ft={cwd:p.cwd,sessionId:u||Gn?p.claudeSessionId??p.id:p.id,resume:u&&(!p.claudeSessionId||Ck(qe(p.cwd,p.claudeSessionId))),mcpConfig:ie,settings:ye,permissionPromptTool:ki,...et,appendSystemPromptFile:ve,allowedTools:[`mcp__${Me}`,...Y.tools,...j==="coordinator"&&!ht?Zy(d):[]],disallowedTools:[...tk(),...j==="coordinator"?[]:ek(_t),...la(p,v)],systemPromptSnapshot:j==="coordinator"?"off":void 0,addDirs:[Xs(p.id),...v&&p.taskId?[Jn({projectId:v.id,taskId:p.taskId})]:[],..._t],pluginDirs:V,...lt()?Wi:{},name:p.address??this.addressOf(p),bin:process.env.SUPERFACTORY_CLAUDE_BIN,noNewPrivileges:Fi(j,S)};p.model=ft.model,p.effort=ft.effort,d.cacheTtl=S["agents.longCache"]?"1h":"5m";let Ws=ts(d.secretEnv);this.deps.secretEnvs.started(p.id,Ws,d.runDir);let wt=j!=="coordinator"&&!d.place?.sandbox?await ce():void 0,_e=d.place?.sandbox?{}:await ns.env(p.projectId,p.taskId),Eo={...G.env,...Zo(d.place?.env),..._e,...d.place?.sandbox?{}:dn(Bt(S),wt?{...process.env,SUPERFACTORY_LIBRARIES_DIR:Er(wt.home,"libraries")}:void 0),...d.place?.sandbox?{}:ji(),...ra(S,p),...d.place?.sandbox?{}:await he(p.cwd,L.author),...d.place?.display?{DISPLAY:d.place.display,...await this.displayAuthority(d)}:{},...d.place?.previewPort?nf(d.place.previewPort):{},...Ws,...await Gi(d.runDir),...L.env};if(d.startStep="Claude Code on this machine",!d.place?.sandbox)await this.deps.claudeCurrent?.().catch(()=>{return}),await this.claudeHere(d);let As=qe(p.cwd,p.claudeSessionId??p.id),Co=await CR(As).then((bs)=>bs.size,()=>0);d.runFrom={path:As,offset:Co},d.facts=Jr();let Gs=!d.place?.sandbox&&(Zn()||wt?.sid)?await vm():void 0;if(j==="coordinator"&&!d.place?.sandbox)Object.assign(Eo,await Pm(p.cwd,Eo));d.startStep="its GitHub token";let br=await this.withGitHub(p.projectId,Eo,j);if(d.startStep="its world as the session user",wt&&Gs)await ka(wt);let it=wt&&Gs?await this.worldOf(d,wt,v?.path,ft.pluginDirs??[],_e.TMPDIR):void 0;if(!Oe(d.phase))throw await it?.release(),Error(`its start was given up at: ${d.startStep}`);if(d.world=it,d.startStep="its process",d.startedBy=H,d.process=new qt({...ft,env:it?{...br,...io(it.user,{...process.env,...br})}:br,...it?.claudeBin?{bin:it.claudeBin}:{},...Gs?{spawn:(bs)=>Te.start(bs,it?.host?it.host:it?{socketIn:d.runDir,program:(b$)=>it.program(Vi(b$)),pidOf:it.pidOf,log:Er(d.runDir,"host.log"),socketMode:z(384)}:{socketIn:Gs,program:Vi})}:{}},this.claudeHandlers(d)),p.claudeVersion=this.deps.installedClaude?.(),p.newerClaude=void 0,p.restartPending=void 0,this.save(d),await d.process.spawned,!d.process.ran)return this.notStarted(d,d.process);if(s.info(`sessions: started ${p.kind} ${p.id} in ${p.cwd} (pid ${d.process.pid})`),d.outbox.newRun(),N){if(Oe(d.phase))d.transition({kind:"idle"});return this.waitForOwnLogin(d,L.noAccount)}let Mt=d.drain();if(d.process.alive&&Oe(d.phase))d.transition(Mt?{kind:"turn",turn:{kind:"work"}}:{kind:"idle"});if(!Object.keys(d.secretEnv).filter((bs)=>!(bs in(d.leadEnv??{}))).length&&p.projectId)this.fetchSecrets(d)}async placeAgain(d,u,p,w){let y=await this.deps.places.forTask(u,p,w,await this.stackBase(u,p),{setUp:!1}).catch((v)=>s.warn(`sessions: ${d.session.id}'s place couldn't be found again`,v));return y?.runner==="host"&&y.cwd===d.session.cwd?y:void 0}async worldOf(d,u,p,w,y){let{session:v}=d,S=v.kind==="coordinator"?m().github:m().githubTasks,x=v.projectId?Er(S,v.projectId):void 0;if(x)await _k(x,{recursive:!0,mode:448});return Im(u,{runDir:d.runDir,cwd:v.cwd,projects:p?[p]:[],tmp:y,attachments:[Xs(v.id),...v.projectId&&v.taskId?[Jn({projectId:v.projectId,taskId:v.taskId})]:[]],github:x,plugins:w,task:v.projectId&&v.taskId?ns.taskData(v.projectId,v.taskId):void 0})}async displayAuthority(d){let u=d.place?await this.deps.places.displayAuthority(d.place.cwd):void 0;if(!u)return{};let p=Er(d.runDir,"Xauthority");return await de(p,u,z(384)),{XAUTHORITY:p}}claudeHandlers(d){return d.handlers({heard:(u)=>this.onEvent(d,u),line:(u)=>this.deps.hooks.onLine?.(d.session,u),exited:(u,p)=>void this.onExit(d,u,p)})}registerTools(d,u,p){let{session:w}=d;d.permissionMode=p,this.deps.mcp.register(d.token,{projectId:u,sessionId:w.id,kind:w.kind,taskId:w.taskId,managerId:w.managerId,cwd:w.cwd,signal:d.abort.signal,permissionMode:p})}async noConversationToResume(d){if(this.freshNext.has(d.session.id))return!0;if(d.session.claudeSessionId)return!1;return!await this.everRan(d)}startAfresh(d,u){let{session:p}=d,w=this.freshNext.delete(p.id),y=p.claudeSessionId??p.id;if(Ck(qe(p.cwd,y)))p.claudeSessionId=ER();let v=u&&p.taskId?Qr(u,p.teammate):void 0;if(v&&!d.outbox.unread().some((S)=>S.text===v))d.outbox.add(v,at,{first:!0});if(s.info(`sessions: ${p.id} has no conversation to resume: it starts a new one`),!w)return;d.record({type:"notice",level:"info",kind:of,text:"Its earlier conversation can't go on (Claude couldn't open it): it starts a new one, with its task's brief."})}async claudeHere(d){d.claudeRepair=void 0;let u=this.deps.claude;if(!u||u.found())return;if(d.record({type:"notice",level:"warning",kind:qu,text:"Claude Code is missing on this machine: this session starts once it is back (an update under way puts it back, else it is installed again)."}),d.claudeRepair=await u.repair().catch((p)=>p.message),!d.claudeRepair)d.record({type:"notice",level:"info",kind:qu,text:"Claude Code is back: the session starts."})}async notStarted(d,u){throw await u.ended,new c("unavailable",d.session.error??Ln(u.startError,d.claudeRepair))}async fetchSecrets(d){await d.saving;let u;for(let p=1;!u&&p<=4&&d.process?.alive;p++)if(u=await this.deps.secretsNow?.(d.session.id).catch((w)=>{if(p===4)s.warn(`sessions: ${d.session.id}'s secrets`,w instanceof Error?w.message:w);return}),!u&&p<4)await new Promise((w)=>setTimeout(w,p*2000));if(u&&Object.keys({...u.env,...u.leadEnv}).length)await this.updateSecrets({sessionId:d.session.id,env:u.env,leadEnv:u.leadEnv,changed:[]})}async updateSecrets({sessionId:d,env:u,leadEnv:p,changed:w}){let y=this.handleOf(d);if(!y)return!1;let{session:v}=y,S=await this.projectOf(v),x=Li(v,S,ua(p)),j=this.live.get(d)?.leadEnv??{},L=bt(v)||Object.keys(x).length?x:j,N={...Tr(u),...L};for(let B of Object.values(N))O(B);if(await y.secrets(N,L,w),w.length&&v.previews?.length&&v.state!=="exited"&&v.state!=="failed")await this.send(d,`Secrets changed: ${w.join(", ")}. New commands get them as they are now; restart the servers you run (${v.previews.map((B)=>B.name).join(", ")}) if they read them.`,at).catch(()=>{return});return!0}async withGitHub(d,u,p){if(!d)return u;let w=p==="coordinator"?this.github:this.taskGithub;return w.env(d,await w.forSession(d),u)}async marketplacePlugins(d,u,p){let{projectId:w}=d;return Sy(u,{lead:d.kind==="coordinator",secretEnv:ts(p),projectId:w,github:w?await this.github.forSession(w):void 0})}}class _u extends Cu{async askSlot(d,u){return await Promise.all([...this.live.values()].map((p)=>p.saving)),Hr(this.deps.askSlot,d,u)}queue(d,u,p){if(d.session.slotAsked={at:new Date().toISOString(),for:"start"},u)d.record({type:"notice",level:"info",kind:Ut,text:He(u)}),s.info(`sessions: ${d.session.id} queued: ${He(u)}`);else s.info(`sessions: ${d.session.id} queued until the server grants it a slot`);d.transition({kind:"queued",resume:p,full:u})}async held(d,u,p){if(!Za(u,p)||!d.betweenTurns())return!1;let{id:w}=d.session;if(this.holding.has(w))return!0;let y=await this.askSlot(d.session,"message");if(!y||!d.betweenTurns()||this.holding.has(w))return!!y&&this.holding.has(w);if(this.holding.set(w,{said:!!y.full}),d.session.slotAsked={at:new Date().toISOString(),for:"message"},this.save(d),y.full)d.record({type:"notice",level:"info",kind:Ut,text:on(y.full)});return s.info(`sessions: ${w}'s message waits for a slot${y.full?`: ${on(y.full)}`:""}`),!0}heldWoke(d){if(d.betweenTurns()&&d.outbox.unread().length)return;if(this.unhold(d),d.process?.alive&&d.outbox.unread().length)this.give(d)}unhold(d){if(this.holding.delete(d.session.id),d.session.slotAsked?.for!=="message")return;d.session.slotAsked=void 0,this.save(d)}slots(d,u){if(this.shuttingDown)return;for(let p of d){let w=this.live.get(p);if(!w)continue;if(this.holding.has(p)){if(this.unhold(w),s.info(`sessions: ${p} takes the slot the server granted for the message that waited`),w.process?.alive&&w.outbox.unread().length)this.give(w);continue}let{phase:y}=w;if(y.kind!=="queued"&&w.session.slotAsked)w.session.slotAsked=void 0,this.save(w);if(y.kind!=="queued"||this.ensuring.has(p))continue;this.reserved.add(p),s.info(`sessions: ${p} takes the slot the server granted`),this.ensureRunning(w,{resume:y.resume,reason:"queue",wait:!0}).catch((v)=>s.warn(`sessions: ${p} couldn't start in the slot it was granted`,v)).finally(()=>this.reserved.delete(p))}for(let[p,w]of Object.entries(u)){let y=this.live.get(p),v=this.holding.get(p);if(v&&y&&!v.said)v.said=!0,y.record({type:"notice",level:"info",kind:Ut,text:on(w)});if(y?.phase.kind!=="queued")continue;let S=y.phase.full;if(!S)y.record({type:"notice",level:"info",kind:Ut,text:He(w)});if(S&&Object.entries(w).every(([x,j])=>S[x]===j))continue;y.transition({...y.phase,full:w})}}give(d){if(d.startedBy===H||!d.betweenTurns()||!d.outbox.unread().length)return void d.give();s.info(`sessions: ${d.session.id}'s Claude was started by ${d.startedBy?`agent ${d.startedBy}`:"an agent before"}: it starts again on its conversation for its next turn`),this.restartNow(d).catch((u)=>s.warn(`sessions: ${d.session.id} couldn't start again on this agent's arguments`,u))}async superseded(d,u){let{id:p}=d.session;s.info(`sessions: ${p} stops: ${u.id} went on in session ${u.sessionId}`),this.recordEvent(p,{type:"notice",level:"warning",kind:Vu,text:Qa(u)}),await d.stop(!1,"asked")}async refuseSuperseded(d,u){s.info(`sessions: ${d.session.id} not started: ${u.id} went on in session ${u.sessionId}`),this.unpause(d.session),await this.refuseStart(d,{level:"warning",kind:Vu,text:Qa(u)})}async closedTask(d){let u=await this.taskOf(d);return pe(u)?u:void 0}async refuseClosed(d,u){s.info(`sessions: ${d.session.id} not started: ${u.id} is ${u.status}`),await this.refuseStart(d,{level:"info",kind:Br,text:mi(u)})}async refuseStart(d,u){if(d.outbox.clear(),d.record({type:"notice",...u}),d.phase.kind==="ended"||d.phase.kind==="respawning"&&!d.process)d.transition({kind:"ended",failed:d.session.state==="failed"}),await this.save(d);else await this.finish(d,{kind:"ended",failed:!1})}ensureRunning(d,u){if(u.message)d.enqueue(u.message.text,u.message.author,void 0,u.message.relay);if(u.byPerson)d.startedClosed=!0;let{id:p}=d.session,w=this.ensuring.get(p);if(!w){let y=this.startRun(d,u);w=y,this.ensuring.set(p,y),y.running.catch(()=>{return}).finally(()=>{if(this.ensuring.get(p)===y)this.ensuring.delete(p)})}return u.wait?w.running:w.decided}startRun(d,u){let p=Promise.withResolvers(),w=(async()=>{let y=(await this.decideRun(d,u))?.spawning;if(!y)return p.resolve();y.then(p.resolve,(v)=>{if(p.reject(v),!u.wait)this.couldNotStart(d,v)})})();return w.catch(p.reject),{decided:w,running:p.promise}}async decideRun(d,u){let{session:p}=d;if(d.process?.alive){this.give(d);return}if(Oe(d.phase)||aa(d)&&u.reason!=="queue")return;if(u.reason==="queue"&&this.shuttingDown)return;let y=d.startedClosed||p.kind==="coordinator"?void 0:await this.closedTask(p);if(y)throw await this.refuseClosed(d,y),new c("conflict",mi(y));let v=p.kind==="coordinator"?void 0:await this.taskOf(p);if(v&&da(p,v))throw await this.refuseSuperseded(d,v),new c("conflict",Qa(v));if(v?.parked&&!u.byPerson&&u.reason!=="start")throw s.info(`sessions: ${p.id} not woken: ${v.id} is parked`),this.unpause(p),await this.refuseStart(d,{level:"info",kind:Br,text:Ku(v)}),new c("conflict",Ku(v));p.endedAt=void 0;let S=["start","message","queue"].includes(u.reason)||u.reason==="restart"&&!u.resume,x=u.reason==="queue"&&this.reserved.has(p.id),j=S&&!x?await this.askSlot(p,"start"):void 0;if(j){if(d.phase.kind!=="queued")this.queue(d,j.full,u.resume);await d.saving;return}if(Oe(d.phase)||d.process?.alive)return;return await this.endOtherCoordinators(d),p.error=void 0,d.transition({kind:"starting"}),{spawning:Xy(d,this.spawnClaude(d,u.resume)).catch((N)=>this.startFailed(d,N))}}startFailed(d,u){if(Oe(d.phase)&&!d.process){let p=vt(`Couldn't start: ${u.message}`,Object.values(d.secretEnv)).slice(0,4000);d.session.error=p,d.transition({kind:"ended",failed:!0})}throw u}async endOtherCoordinators(d){for(let u=this.otherCoordinator(d);u;u=this.otherCoordinator(d))s.warn(`sessions: ${u.session.id} ends: ${d.session.id} is its manager's session now`),await this.stopAndWait(u)}couldNotStart(d,u){if(s.warn(`sessions: ${d.session.id} couldn't start again`,u),u.message!==d.session.error)d.record({type:"notice",level:"error",kind:Br,text:`Couldn't start again: ${u.message}`})}}class Ou extends _u{async nudge(d){await this.requireHandle(d).nudge()}async nudgeHere(d){if(!d.process?.alive||d.phase.kind==="respawning"||d.phase.kind==="stopping")return;let u=d.session.stalledSince,p=u?` (${fa(u).toLowerCase()})`:"";s.warn(`sessions: nudging ${d.session.id}${p}: its Claude restarts on the same conversation`),await this.respawn(d,Pi(p))}async interrupt(d){await this.requireHandle(d).interrupt()}jobOutput(d,u){return this.requireHandle(d).jobOutput(u)}stopJob(d,u){return this.requireHandle(d).stopJob(u)}async rest(d,u){let p=this.live.get(d);if(!p||this.switching.has(d))return!1;return this.restNow(p,u,"while its task waits for a person's merge")}async restNow(d,u,p){let w=d.session.id;if(!d.betweenTurns()||d.outbox.unread().length)return!1;if(d.record({type:"notice",level:"info",kind:af,text:u}),s.info(`sessions: ${w} rests ${p}`),await this.stop(w,!0),await d.finishing,d.outbox.unread().length)await this.resumeSession(w,{reason:"message"});return!0}async stop(d,u=!1,p="asked"){for(let[w,y]of this.preparing)if(y.id===d){this.preparing.delete(w),this.deps.push({type:"session.updated",session:{...y,state:"exited",waitingFor:void 0,endedAt:new Date().toISOString()}});return}await this.requireHandle(d).stop(u,p)}async stopHere(d,u,p){if(Oe(d.phase))await this.ensuring.get(d.session.id)?.running.catch(()=>{return});if(!u)d.outbox.clear(),this.unpause(d.session);if(!d.process?.alive)return this.finish(d,{kind:"ended",failed:!1,stopped:!0});this.noteStarted(d),await d.stopNow(p)}async escalate(d){let u=this.get(d),p=Xc[Xc.indexOf(u.level)+1];if(!p)return;return u.level=p,u.failures=0,await this.respawn(u,`Your earlier attempts at this failed. You now run with a stronger setup (${p} level). Look at what went wrong and continue.`),p}async restart(d,u){let p=this.live.get(d);if(!p?.process?.alive||p.phase.kind==="stopping")return;if(p.phase.kind==="respawning"){if(u)p.enqueue(u,at);return}if(p.session.state==="idle")await this.respawn(p,u);else p.restartAfterTurn=u??""}async restartClaude(d,u){return this.requireHandle(d).restartClaude(u)}async restartHere(d,u){let{phase:p}=d;if(!d.process?.alive||p.kind==="respawning")throw new c("conflict","its Claude isn't running: your next message starts it on the Claude Code installed now");if(p.kind==="stopping"||Ft(p,"wrap_up"))throw new c("conflict","the session is stopping: your next message starts it again");if(p.kind==="idle"&&!p.waiting)return await this.restartNow(d),"done";if(u==="now")return await this.restartNow(d,Hy),"done";return d.restartAfterTurn??="",d.session.restartPending=!0,d.record({type:"notice",level:"info",kind:"restart_pending",text:"Claude restarts on this conversation once this turn ends."}),await this.save(d),"after_turn"}async restartNow(d,u){let p=d.session.claudeVersion;d.restartAfterTurn=void 0,s.info(`sessions: restarting ${d.session.id}'s Claude on its conversation, by hand`);let w=await this.respawn(d,u),y=d.session.claudeVersion;if(!w)return;let v=y&&p&&y!==p?`, now on Claude Code ${y} (was ${p})`:y?` (Claude Code ${y})`:"";d.record({type:"notice",level:"info",kind:"restarted",text:`Claude restarted on this conversation${v}.`})}claudeInstalled(){for(let d of this.live.values())if(d.process?.alive&&this.markNewerClaude(d))this.save(d)}markNewerClaude(d){let u=this.deps.installedClaude?.(),p=d.session.claudeVersion,w=u&&p&&nt(p,u)?u:void 0;if(w===d.session.newerClaude)return!1;return d.session.newerClaude=w,!0}async respawn(d,u){let p=u?{text:u,author:at}:void 0;if(d.phase.kind==="queued"){if(p)d.enqueue(p.text,p.author);return!1}if(d.phase.kind==="starting")await this.ensuring.get(d.session.id)?.running.catch(()=>{return});if(d.phase.kind==="stopping")return!1;if(d.phase.kind!=="respawning")d.transition({kind:"respawning",shows:d.session.state});try{if(this.noteStarted(d),await d.process?.stop(),await d.finishing,d.phase.kind!=="respawning")return!1;return await this.ensureRunning(d,{resume:!0,reason:"respawn",message:p,wait:!0}),!!d.process}finally{if(d.phase.kind==="respawning"&&!d.process)d.transition({kind:"ended",failed:d.session.state==="failed"})}}async checkOutbox(d){let{session:u,runFrom:p}=d;if(!p)return;d.runFrom=void 0;let w=qe(u.cwd,u.claudeSessionId??u.id),y=await Wl(w,w===p.path?p.offset:0).catch(()=>[]);d.outbox.takenBack(y)}async wrapUp(d,u,p=xi(u)){await this.requireHandle(d).wrapUp(u,p)}async wrapUpHere(d,u,p){if(!d.process?.alive)return;let{id:w}=d.session;await this.send(w,p,at),d.lastTurn(u,()=>void this.stop(w,!1,"wrap_up_timeout"))}onEvent(d,{body:u,jobs:p,end:w}){if(u.type==="init"){if(this.startFailures.delete(d.session.id),u.claudeVersion&&u.claudeVersion!==d.session.claudeVersion)d.session.claudeVersion=u.claudeVersion,this.markNewerClaude(d),this.save(d);if(this.showApplied(d),d.process&&d.pluginsChecked!==d.process)d.pluginsChecked=d.process,this.checkPlugins(d)}if(u.type==="session_reset"||p)this.save(d);if(p||w&&w.kind!=="before_begin")this.noteStarted(d);if(!w||w.kind==="before_begin")return;if(this.saveTranscript(d.session),w.kind==="compacted")return;let{limit:y,loginFailed:v}=w.login;if(d.failures=w.outcome==="error"&&!y&&!v?d.failures+1:0,w.kind==="stopping")return;if(w.kind==="wrapped_up"){(d.place?.sandbox?.pull().catch(()=>{return})??Promise.resolve()).then(()=>this.stop(d.session.id));return}if((d.place?.sandbox?.pull()??Promise.resolve()).catch((x)=>s.warn(`sessions: pull from ${d.session.id} failed`,x)).then(()=>this.deps.hooks.onTurnSynced?.(d.session)),this.deps.hooks.onTurnEnd?.(d.session,w.outcome),!v)this.loginWorked(d.session);let S;if(!d.account&&!d.place?.sandbox){if(v)S=this.deps.ownLogin?.refused(v).catch(()=>{return});else if(w.outcome==="success")this.deps.ownLogin?.worked()}if(v){d.restartAfterTurn=void 0;let x={reason:"signed_out",why:v,answering:w.answering};Promise.resolve(S).then(()=>this.switchAccount(d.handle,x))}else if(y)d.restartAfterTurn=void 0,this.switchAccount(d.handle,{reason:"limit",...y});else if(d.restartAfterTurn!==void 0){let x=d.restartAfterTurn||void 0;d.restartAfterTurn=void 0,(d.session.restartPending?this.restartNow(d,x):this.respawn(d,x)).catch((j)=>s.warn(`sessions: ${d.session.id} couldn't restart after its turn`,j))}else if(w.outcome!=="interrupted")this.compactIfDue(d,w.boundary)}noteStarted(d){let u=d.process?.alive?d.process.pid:void 0;if(!u||d.place?.sandbox)return Promise.resolve();let p=this.noteNow(d,u),w=d.noting;return d.noting=Promise.all([w?.catch(()=>{return}),p]).then(()=>{return}),p}async noteNow(d,u){let p=await rk(u).catch(()=>[]);if(!p.length)return;let w=d.leftRunning?.length??0;if(d.leftRunning=ok(d.leftRunning,p),d.leftRunning.length!==w)await this.save(d)}async endLeftRunning(d,u){if(!u?.length)return;let p=await ha(u).catch((w)=>(s.warn(`sessions: couldn't end what ${d.session.id}'s Claude left running`,w),[]));if(p.length)s.info(`sessions: ${d.session.id}'s Claude left ${p.join(", ")} running: ended`)}async onExit(d,u,p=null){let w=d.world;if(d.world=void 0,w)w.release().catch((_t)=>s.warn(`sessions: couldn't give ${d.session.id}'s session user back`,_t));let y=d.process?.startError;if(y!==void 0)d.session.error=Ln(y,d.claudeRepair),d.record({type:"notice",level:"error",kind:Br,text:d.session.error});let{phase:v,facts:S}=d,x=v.kind==="stopping"||v.kind==="respawning",j=!x&&u!==0,L=j&&!this.shuttingDown&&y===void 0?await this.deps.memory?.ranOut().catch(()=>{return}):void 0,N=j&&!this.shuttingDown&&(p!==null||Gy.has(u??-1)||!!L),B=d.session.state,G=j&&!N&&y===void 0;if(j&&y===void 0)this.sayWhyExited(d,{code:u,signal:p},N,L);let V=G&&!S.began,Y=(this.startFailures.get(d.session.id)??0)+(V?1:0);if(V)this.startFailures.set(d.session.id,Y);else if(j&&!N)d.failures+=1;let ne=V&&Y>=Ja,ie=`${u}${p?`, ${p}`:""}`;s.info(`sessions: ${d.session.id} exited (${ie})${L?`: ${L}`:N?`: ended from outside the agent, while ${B}`:""}`);let ye=v.kind==="stopping"&&v.why==="wrap_up_timeout",ve=!!S.noConversation&&!x&&!this.shuttingDown&&!N&&!ne;S.noConversation=void 0;let Qe=v.kind==="respawning"?{kind:"respawning",shows:"exited"}:{kind:"ended",failed:j&&!ve,stopped:v.kind==="stopping"||void 0,killed:N?{at:Date.now(),state:B}:void 0};if(d.finishing=this.finish(d,Qe).then(async()=>{await d.noting?.catch(()=>{return});let _t=d.leftRunning;d.leftRunning=void 0,await this.endLeftRunning(d,_t)}),await d.finishing,ve){this.freshNext.add(d.session.id),this.ensureRunning(d,{resume:!0,reason:"fresh",wait:!0}).catch((_t)=>s.warn(`sessions: ${d.session.id} couldn't start a new conversation`,_t));return}if(ne&&!this.shuttingDown)this.freshNext.add(d.session.id);let ht=N&&this.carryOnAfterKill(d,B,!!L);if(j&&!N&&!V)this.deps.hooks.onTurnEnd?.(d.session,"error");let et=y!==void 0&&!x?"not_started":ne?"start_failing":this.endedWhy({timedOut:ye,killed:N,resumes:ht,stopping:x,code:u});if(et&&!Ss(d))this.deps.hooks.onEnded?.(d.session,et)}sayWhyExited(d,u,p,w){let{facts:y}=d,v=vt(y.failedToBegin??y.lastWords.join(`
|
|
193
|
+
`),Object.values(d.secretEnv));if(d.session.error=w?uf(u,w,v):p?df(u,v):fi(u,v,y.began),p)return;d.record({type:"notice",level:"error",kind:pi,text:d.session.error})}endedWhy(d){if(this.shuttingDown)return;if(d.timedOut)return"wrap_up_timeout";if(d.killed)return d.resumes?void 0:"killed";if(d.stopping)return;return d.code===0?"ended":"crashed"}carryOnAfterKill(d,u,p=!1){let w=d.session.id,y=Date.now(),v=(x)=>y-x<3600000;if(d.killedResumes=(d.killedResumes??[]).filter(v),d.memoryResumes=(d.memoryResumes??[]).filter(v),d.killedResumes.length>=zc)return s.warn(`sessions: ${w} was ended from outside ${zc} times this hour: left ended`),!1;if(p&&d.memoryResumes.length)return s.warn(`sessions: ${w} ran out of memory again this hour: left ended`),!1;if(d.killedResumes.push(y),p)d.memoryResumes.push(y);return setTimeout(async()=>{let x=()=>this.shuttingDown||d.phase.kind!=="ended"||!!d.phase.stopped||!!d.process?.alive;if(x())return;if(p&&!await this.roomAgain(w,x))return;let j=u==="idle"&&!d.outbox.unread().length,L=d.session.kind==="task"||d.session.kind==="epic";if(j&&L&&await this.closedTask(d.session)){s.info(`sessions: not resuming ${w}: it was idle in ${d.session.taskId}, which ended`);return}if(x())return;if(d.session.endedAt=void 0,d.session.pausedUntil)return this.watchPauses();s.info(`sessions: resuming ${w}: its Claude was ended from outside the agent`),await this.ensureRunning(d,{resume:!0,reason:"killed",message:u!=="idle"?{text:Jf,author:at}:void 0,wait:!0}).catch((N)=>s.warn(`sessions: couldn't resume ${w}`,N))},qy()).unref?.(),!0}async roomAgain(d,u){let p=Date.now()+Vy();while(!this.deps.memory?.hasRoom()&&Date.now()<p)if(await Bun.sleep(Yy),u())return!1;if(!this.deps.memory?.hasRoom())s.warn(`sessions: resuming ${d} while the machine is still short of memory`);return!u()}async finish(d,u){await d.end(u,(v)=>{this.deps.mcp.unregister(v),this.deps.secretEnvs.ended(d.session.id),d.abort.abort(),d.abort=new AbortController,d.session.claudeVersion=void 0,d.session.newerClaude=void 0,d.session.restartPending=void 0}),this.saveTranscript(d.session);let{projectId:p,taskId:w,id:y}=d.session;if(p&&w&&!this.movedAway.has(y)&&!this.movingOut.has(y))await this.deps.tasks.cancelOpenPrompts({projectId:p,taskId:w},y).catch(()=>{return})}}class ju extends Ou{async elsewhere(d){if(this.remote.has(d))return;let u=this.live.get(d),p=u?.session??await this.savedOne(d);if(!p)return;if(s.info(`sessions: ${d} goes on on another machine: this one forgets it`),this.movedAway.add(d),u)await this.stopAndWait(u),this.live.delete(d);await this.records.remove(d),await q.forget(d),this.deps.hooks.onMovedAway?.(p)}async moveOut(d,u,p){if(this.remote.has(d))throw new c("conflict","it runs in a sandbox: only a session on its machine moves");let w=this.live.get(d);if(!w){let y=await this.savedOne(d);if(y&&xu(y))return y;throw new c("not_found",`no session ${d} here`)}if(!xu(w.session)){if(u==="after_turn")for(let y=Date.now()+p;Date.now()<y&&OR(w);)await Bun.sleep(250);s.info(`sessions: ${d} moves to another machine: its Claude here stops`)}this.movingOut.add(d);try{if(!xu(w.session))await this.stopAndWait(w);await this.saveTranscript(w.session)}finally{this.movingOut.delete(d)}return{...w.session}}async endStrayLeads(){let d=[...this.live.values()].filter(({session:u})=>(su(u,this.deps.projects.holdsLead())||this.strayProjectLead(u))&&u.state!=="exited"&&u.state!=="failed");for(let u of d)s.info(`sessions: ending ${u.session.id}, a lead's session off its lead's machine`),await this.stop(u.session.id).catch((p)=>s.warn(`sessions: couldn't end the stray lead ${u.session.id}`,p))}async stopProject(d){return(await this.stopGoing((u)=>u.projectId===d)).length}stopTask({projectId:d,taskId:u}){return this.stopGoing((p)=>p.projectId===d&&p.taskId===u)}async stopGoing(d){let u=(w)=>d(w)&&w.state!=="exited"&&w.state!=="failed",p=new Set([...[...this.preparing.values()].filter(u).map((w)=>w.id),...[...this.live.values()].filter((w)=>u(w.session)).map((w)=>w.session.id),...[...this.remote.values()].filter((w)=>u(w.session)).map((w)=>w.session.id)]);for(let w of p)await this.stop(w).catch((y)=>s.warn(`sessions: couldn't stop ${w}`,y)),await this.live.get(w)?.finishing;return[...p]}async stopAndWait(d){await this.stop(d.session.id),await d.finishing}async stopAll(){this.shuttingDown=!0,this.github.stop(),this.taskGithub.stop();let d=[...this.live.values()].filter((p)=>p.process?.alive&&p.phase.kind!=="stopping"&&p.phase.kind!=="respawning"),u=[...this.live.values()].flatMap((p)=>{let w=p.phase.kind==="ended"?p.phase.killed:void 0;return!p.process?.alive&&w&&Date.now()-w.at<Ky?[{l:p,was:w.state}]:[]});for(let p of d)p.resumeOnStart={state:tn(p.session)?"running":p.session.state};for(let{l:p,was:w}of u)p.resumeOnStart={state:w};await Promise.all([...d,...u.map(({l:p})=>p)].map((p)=>this.save(p).catch((w)=>s.warn(`sessions: couldn't note ${p.session.id} to resume`,w)))),await Promise.all(d.map((p)=>this.stop(p.session.id,!0).catch(async(w)=>{s.warn(`sessions: stopping ${p.session.id} failed; its Claude stops all the same`,w),await p.process?.stop()}))),await Promise.all(d.map((p)=>this.checkOutbox(p).catch(()=>{return}))),await q.flushAll()}recover(){return this.recovered=!0,this.recovering=this.recovering.then(()=>this.recoverNow()).catch((d)=>s.warn("sessions: couldn't settle the sessions the agent before left",d)),this.recovering}linked(){if(this.recovered&&!this.recordsMoved)this.recover()}async recoverNow(){await this.deps.linkedSoon?.(),this.recordsMoved||=await ck({records:this.records,projects:this.deps.projects,task:(p)=>this.readTask(p)});let d=new Set(this.deps.projects.ids()),u=[];for(let{session:p,record:w}of await this.records.sessions()){if(this.live.has(p.id)||!this.ours(p))continue;if(p.projectId&&!d.has(p.projectId))continue;let{left:y,...v}=w;if(y?.length){let L=await ha(y).catch(()=>[]);if(L.length)s.info(`sessions: ${p.id}'s Claude left ${L.join(", ")} running: ended`)}let S=p.state==="exited"||p.state==="failed";if(S&&!v.resume){if(y?.length)await this.records.write(p.id,v);continue}let x=v.resume??(!S&&!p.sandbox?{state:p.state}:void 0),j={...p,stalledSince:void 0,jobs:void 0,subagents:void 0,state:"exited",phase:"ended",queued:void 0,endedAt:p.endedAt??new Date().toISOString()};if(await this.records.write(p.id,{...v,session:j,resume:x}),this.deps.push({type:"session.updated",session:j}),this.deps.hooks.onStateChange?.(j),x)u.push(await this.revivable(p.id))}u.sort((p,w)=>w.session.startedAt.localeCompare(p.session.startedAt));for(let p of u)await this.resumeAfterRestart(p).catch((w)=>s.warn(`sessions: couldn't resume ${p.session.id} after the restart`,w));this.deps.hooks.onOrphansSettled?.()}async resumeAfterRestart(d){let{id:u}=d.session,p=this.turnKey(d.session),w=()=>this.resumeNow(this.live.get(u)??d);await(p?this.oneAtATime(p,w):w())}async resumeNow(d){let{id:u}=d.session,p=d.resumeOnStart?.state;if(d.resumeOnStart=void 0,!p||Ss(d))return this.save(d);let w=await this.notResumedWhy(d,p);if(w)return s.info(`sessions: not resuming ${u}: ${w}`),this.save(d);if(d.session.pausedUntil)return await this.save(d),this.watchPauses();if(p==="starting"&&!await this.everRan(d))return this.startAgain(d);let y=p==="waiting_input"&&(await this.deps.asksUser?.(d.session)??!1);s.info(`sessions: resuming ${u} after the restart${y?": its question waits for you":""}`),await this.ensureRunning(d,{resume:!0,reason:"restart",message:p!=="idle"&&!y?{text:ol,author:at}:void 0,wait:!0})}async notResumedWhy(d,u){let{session:p}=d,w=this.otherLead(d)??this.otherCoordinator(d);if(w)return`${w.session.id} goes on for the same ${w.session.taskId??"manager"}`;if(su(p,this.deps.projects.holdsLead()))return"the main lead runs on another machine";if(this.strayProjectLead(p))return`${p.projectId}'s lead runs on another machine`;let{projectId:y,taskId:v,teammate:S}=p;if(!y||!v)return;let x=p.kind==="task"||p.kind==="epic",j=u==="idle"&&!d.outbox.unread().length&&x,L=await this.readTask({projectId:y,taskId:v}).then((G)=>({task:G}),()=>{return});if(!L)return j?`it was idle, and ${v} can't be read now`:void 0;let{task:N}=L;if(j&&pe(N))return`it was idle in ${v}, which ended`;if(j&&N&&Ly.includes(N.status))return`it was idle in ${v}, ${N.status==="in_review"?"in review":"which waits for an answer"}: its next message resumes it`;if(!N)return;if(N.parked)return`${v} is parked: it waits for someone to start it`;if(x&&(N.status==="todo"||N.status==="backlog"))return`${v} is in ${N.status}: it starts again when it is started`;if(S)return;let B=this.deps.nodeId();if(N.sessionId===p.id&&N.node&&N.node!==B&&N.node!==p.nodeId)return"it went on on another machine while this one was away";if(x&&N.sessionId&&N.sessionId!==p.id)return"its task went on in another session";return}async startAgain(d){if(!d.outbox.unread().length){let p=(await Ms(_R(m().sessionLogs,`${d.session.id}.jsonl`))).flatMap((w)=>w.type==="user_message"&&w.text!==ol?[w.text]:[]);for(let w of new Set(p))d.outbox.add(w,at)}s.info(`sessions: starting ${d.session.id} again after the restart`),await this.ensureRunning(d,{resume:!1,reason:"restart",wait:!0})}async handOver(){let d=[];for(let u of[...this.live.values()]){if(!is(u.phase)||this.deps.mcp.busy(u.token))continue;if(u.world?.endsWithAgent)continue;let p=u.process?.handOver();if(!p)continue;d.push({id:u.session.id,projectId:u.session.projectId,state:u.session.state,token:u.token,permissionMode:u.permissionMode,host:p,sessionUser:u.world?.held,startedBy:u.startedBy,jobLogs:u.jobs.runningLogs()}),this.live.delete(u.session.id),await u.saving}if(await q.flushAll(),!d.length)return;await Sm(d),s.info(`sessions: ${d.length} handed to the next agent, their Claude going on: ${d.map((u)=>u.id).join(", ")}`)}async takeHandedBack(d){await pk(this.records).catch((p)=>s.warn("sessions: couldn't move the notes an agent before T-326 kept",p));let u=await $m();if(u.length)s.info(`sessions: taking back ${u.length} the agent before handed over`);for(let p of u)await(d?Promise.reject(Error(d)):this.adopt(p)).catch(async(w)=>{this.live.delete(p.id),await Te.adopt(p.host).then((y)=>y.kill("SIGKILL")).catch(()=>{return}),s.warn(`sessions: couldn't take ${p.id} back from the agent before: it resumes`,w)});await Am(await ce().catch(()=>{return})).catch((p)=>s.warn("sessions: couldn't end what the session users of the agent before left",p))}async adopt(d){let u=await this.records.read(d.id),p=u?.session??await lk(this.deps.projects,d.id,d.projectId),w=p.jobs,y=await Te.adopt(d.host),v=await this.newLive(p,{level:"normal",secretEnv:{},origin:u?.origin,userLayer:{},place:void 0},void 0,oc(p.state));v.jobs.restore(w,d.jobLogs,p.subagents),v.session.jobs=w?.length?w:void 0;let S=v.jobs.subagents();v.session.subagents=S.length?S:void 0,v.token=d.token,v.startedBy=d.startedBy;let{session:x}=v;this.registerTools(v,x.projectId,d.permissionMode),this.deps.secretEnvs.started(x.id,{},v.runDir),v.facts={began:!0,lastWords:[]},this.live.set(x.id,v);let j=d.sessionUser?await ce():void 0;if(j&&d.sessionUser)v.world=await Em(j,d.sessionUser);if(v.process=new qt({adopt:y},this.claudeHandlers(v)),x.endedAt=void 0,x.address=this.addressOf(x),v.transition(Wf(d.state)),await v.saving,s.info(`sessions: took ${x.id} back from the agent before, its Claude still going (pid ${y.pid})`),this.fetchSecrets(v),p.projectId&&p.taskId)this.deps.tasks.get({projectId:p.projectId,taskId:p.taskId}).then((L)=>{if(L.level&&this.live.get(x.id)===v&&v.level==="normal")v.level=L.level}).catch(()=>{return})}}var xu=(d)=>d.state==="exited"||d.state==="failed",OR=(d)=>{let u=d.phase;return u.kind==="turn"&&!u.waiting||Oe(u)||u.kind==="respawning"};import{randomUUID as xR}from"crypto";import{readFile as MR}from"fs/promises";import{join as jR}from"path";var LR=86400000,Ok=()=>jR(m().home,"slash-probe.json");async function xk(d,u){let p=u?await NR():{},w=p[d];if(w&&w.version===u&&Date.now()-w.at<LR)return w.info;let y=await DR(d);if(u){p[d]={version:u,at:Date.now(),info:y};let v=Object.fromEntries(Object.entries(p).filter(([,S])=>S.version===u));await Ce(Ok(),JSON.stringify(v)).catch((S)=>s.warn("slash: couldn't keep the commands Claude listed",S))}return y}async function NR(){let d=await MR(Ok(),"utf8").catch(()=>"{}");try{return JSON.parse(d)}catch{return{}}}async function DR(d){let u=new qt({cwd:d,sessionId:xR(),settingSources:["user"],strictMcpConfig:!0,bin:process.env.SUPERFACTORY_CLAUDE_BIN},{onEvent:()=>{return},onExit:()=>{return}});try{return await u.initialize()}finally{await u.stop(1000)}}async function Mk(d,u){let p=Ti(d);if(!p)return;let{name:w,args:y}=p;if(il(p)){if(!u.owner)return{output:`/${w} ${y} changes this machine's Claude Code setup for every session: only the server owner can do that from a chat.`};u.audit(`/${w} ${y}`)}let v=_i(w)&&UR[w];return v?{output:await v(u)}:void 0}var UR={away:async(d)=>(await d.away(),"Away: the screens are off, and this Mac stays awake so its sessions keep working. Press any key or move the mouse to come back."),login:async()=>"Sign in to Claude in Superfactory: Settings \u203A Claude accounts \u203A Add an account (typing /login in the app's chat opens it too). Sessions move to the new account when theirs hits its usage limit."};class cl extends ju{async attach(d,u,p,w){if(!this.live.has(d)&&!await this.savedOne(d))throw new c("not_found",`no session ${d} on this node`);return Bo(Xs(d),u,p,w)}async send(d,u,p,w={}){let{attachments:y=[],...v}=w;await(this.remote.get(d)??(await this.revivable(d)).handle).send(Pr(d,u,y),p,v)}async sendHere(d,u,p,w){let{callerIsOwner:y=!1,byPerson:v=!1,reply:S,relay:x}=w;if(await this.slash(d,u,p,y))return;let j=this.live.get(d);if(j?.phase.kind==="respawning")return void j.enqueue(u,p,S,x);let L=this.timeAway(d),N=await this.wake(d,v);if(N.enqueue(u,p,S,x),!N.process?.alive)return;if(N.session.pausedUntil){if(p!==at)this.switchAccount(N.handle,Qo);return}if(await this.held(N,p,w))return;if((N.session.state==="idle"||L>0)&&!Ft(N.phase,"compact")&&p!==at&&!u.startsWith("/")){let G=L>Gf?{kind:"resumed",hours:Math.round(L/3600000)}:{kind:"reply",text:u};await this.compactIfDue(N,G,L>0)}this.give(N)}async answering(d,u,p,w){(this.outboxOf(d)??await q.open(d)).answering(u,p,w)}timeAway(d){let u=this.live.get(d);if(!u||u.process?.alive||!u.session.endedAt)return 0;return Date.now()-Date.parse(u.session.endedAt)}markBoundary(d,u){this.handleOf(d)?.boundary(u)}onTaskChange({task:d,previous:u}){if(pe(d)&&!pe(u))for(let p of this.live.values()){if(p.session.projectId!==d.projectId||p.session.taskId!==d.id)continue;if(p.startedClosed=void 0,aa(p))this.refuseClosed(p,d).catch((w)=>s.warn(`sessions: ${p.session.id}'s queued start`,w))}if(d.pr&&!u?.pr){let p=this.sessionForTask(d.projectId,d.id);if(p)this.markBoundary(p,{kind:"pr",url:d.pr.url})}if(d.epic&&d.status==="done"&&u&&u.status!=="done"){let p=this.sessionForTask(d.projectId,d.epic);if(p)this.markBoundary(p,{kind:"subtask",title:d.title})}if(d.sessionId&&d.sessionId!==u?.sessionId){for(let p of this.handles())if(da(p.session,d)&&zy(p.session))this.superseded(p,d).catch((w)=>s.warn(`sessions: couldn't stop ${p.session.id}, whose task went on elsewhere`,w))}}async compactIfDue(d,u,p=!1){let w=rc(await this.settingsOf(d));await d.compactIfDue(w,()=>this.taskOf(d.session),u,p)}async commands(d){let u=this.live.get(d);if(u?.process?.alive){let{process:x}=u,j=await Uc(u.session.cwd),L=eo(await x.initialize(),x.lastInit,j);return this.commandCache.set(d,{at:Date.now(),commands:L}),L}let p=this.commandCache.get(d);if(p&&Date.now()-p.at<By)return p.commands;let w=u?.session??await this.savedOne(d);if(!w)throw new c("not_found",`no session ${d} on this node`);if(w.runner!=="host")throw new c("conflict","a sandboxed session lists its commands while it runs: send it a message first");let y=await Uc(w.cwd),v=await xk(w.cwd,this.deps.installedClaude?.()),S=eo(v,void 0,y);return this.commandCache.set(d,{at:Date.now(),commands:S}),S}async slash(d,u,p,w){let y=Ti(u);if(!y)return!1;let v=this.live.get(d)??await this.revivable(d);if(v.session.runner!=="host"&&!_i(y.name))return!1;let S={away:this.deps.away,owner:w,audit:(j)=>s.info(`audit: ${p} (server owner) ran ${j} in session ${d}`)},x;try{x=await Mk(u,S)}catch(j){x={output:`${u.split(/\s/)[0]}: ${j.message}`}}if(!x)return!1;return v.record({type:"user_message",text:u,author:p}),v.record({type:"command_output",text:x.output}),!0}}class hl extends cl{sandboxGone(d){for(let[u,p]of this.remote){if(p.place.sandboxName!==d)continue;if(this.remote.delete(u),!p.sandboxGone())continue;s.info(`sessions: ${u} ended with its sandbox ${d}`),this.deps.push({type:"session.updated",session:{...p.session}}),this.deps.hooks.onStateChange?.(p.session)}}async portAddress(d,u){let p=this.live.get(d),w=this.remote.get(d),y=p?p.session.ports.find((x)=>x.port===u):w?.session.ports.find((x)=>x.port===u&&x.relay==="machine"),v=p?.place?.sandbox??w?.place.sandbox;if(p&&!v&&y){let x=p.place?.display?p.place.cwd:p.place?void 0:p.session.cwd,j=y.kind==="vnc"?await this.deps.places.hostScreenAt(x,u):void 0;if(j)return{screen:j};return await this.ownListener(p,u),{host:"127.0.0.1",port:u}}if(!y||!v)throw new c("not_found",`session ${d} doesn't expose port ${u}`);if(y.kind==="vnc")return{screen:await v.openVnc()};let S=new URL(await v.url(u));return{host:S.hostname,port:Number(S.port)}}async screenOf(d){let u=this.live.get(d),w=(u?u.session.ports:this.remote.get(d)?.session.ports.filter((y)=>y.relay==="machine")??[]).find((y)=>y.kind==="vnc");if(!w)throw new c("not_found","your session has no screen of its own here (this machine shares none with its sessions); a task's platform's screen: screen_view with platform");return this.portAddress(d,w.port)}async setPreviews(d,u){let p=this.remote.get(d),w=this.live.get(d),y=p?.session??w?.session;if(!y?.projectId||!y.taskId)throw new c("bad_request","only a task's session has previews");let v=p?.place.ports??(w?.place?.sandbox?y.ports:void 0);if(ri(u,v?{sandboxPorts:v}:{host:{reserved:this.deps.reservedPorts()}}),!v)await oi(u);if(!v&&w)for(let S of new Set(u.map((x)=>x.port)))await this.ownListener(w,S);if(y.previews=u,w){if(!w.place?.sandbox)y.ports=qp(y.ports,u);await this.save(w)}return await this.deps.tasks.update({projectId:y.projectId,taskId:y.taskId},{previews:u}),u}async checkPreview(d,u,p,w){let y=this.live.get(d);if(y)await this.ownListener(y,u);return ii(u,p,w)}async ownListener(d,u){let p=await this.sessionUid(d);if(p===void 0)return;let w=await mc(u).catch(()=>{return});if(w?.everyone&&w.uids.length&&w.uids.every((y)=>y===p))return;throw new c("forbidden",`port ${u} isn't held by this session's own server (another user's process listens on it, or none): serve the page yourself, on one of your own ports`)}async sessionUid(d){if(d.session.kind==="coordinator"||d.place?.sandbox)return;let u=d.world?.user;if(u)return u.sid?void 0:u.uid;let p=Zn()?await ce().catch(()=>{return}):void 0;if(!p||p.sid)return;if(!p.group&&!p.pool)return p.uid;throw new c("unavailable","this session's own user isn't known here: restart the session")}sandboxFor(d){return this.live.get(d)?.place?.sandbox??this.remote.get(d)?.place.sandbox}sandboxPlaceOf(d,u){let p=(w)=>w.projectId===d&&w.taskId===u&&w.state!=="exited"&&w.state!=="failed";for(let w of this.remote.values())if(p(w.session)&&w.place.sandbox)return w.place;for(let w of this.live.values())if(p(w.session)&&w.place?.sandbox)return w.place;return}async githubToSandboxes(d,u){let p=new Map;for(let w of this.remote.values()){if(w.session.projectId!==d)continue;let y=w.githubChanged(u);if(y)p.set(w.childId,y)}await Promise.all([...p.values()].map((w)=>w.call("github.credential",{projectId:d,credential:u})))}async startInChild(d,u,p,w,y,v){let S=u.sandbox;if(!S)throw new c("internal","no sandbox");let x=await this.deps.children.for(S,u.runner,p.id);await this.deps.children.handOver(x.nodeId,d);let{kind:j}=d,L=oa(j,w.level??"normal",y),N={...d,address:this.addressOf(d),nodeId:x.nodeId,cwd:S.workdir,model:L.model,effort:L.effort},B=new Nc(x,u,N,v.origin,this.childDeps());this.remote.set(d.id,B);let G=rc(y),V={startTicket:v.startTicket,origin:v.origin},Y=await this.claudeLogin(N,V),ne=await this.marketplacePlugins(N,y,v.secretEnv??{}),ie={session:N,waitForSlot:!0,messages:[v.prompt??(v.resume?Xr:Qr(w,d.teammate))],systemPrompt:[await this.deps.systemPrompt(j,p,w,d,Y),ne.prompt].filter(Boolean).join(`
|
|
194
|
+
|
|
195
|
+
`),model:L.model,effort:L.effort,allowedTools:[`mcp__${Me}`],disallowedTools:la(N,p),permissionMode:L.permissionMode,resume:Boolean(v.resume),eventSeq:v.eventSeq,env:{...ne.env,...Zo(u.env),...ra(y,N),...v.secretEnv??{},...Y.env},secretNames:[...Object.keys(ts(v.secretEnv??{})),...Object.keys(ne.env)],pluginDirs:[...await dm(y,S),...await Ay(Yo(y,{lead:j==="coordinator"}),S),...await Py(ne.dirs,S)],compaction:G&&{rule:G,task:w},github:await this.github.forSession(p.id),author:Y.author},ye=await B.start(ie,V.account);if(d.teammate)return ye;let ve={projectId:p.id,taskId:w.id},Qe={sessionId:d.id,node:x.nodeId,runner:u.runner,status:["backlog","todo","in_review"].includes(w.status)?"in_progress":w.status,...w.parked?{parked:null}:{},via:"session start (sandbox)"};return await this.deps.tasks.update(ve,Qe),zr({audit:(ht)=>this.deps.push({type:"mcp.audited",entry:ht})},d.id,ve,w,Qe),ye}async mcpCall(d,u,p,w,y){let v=this.remote.get(u);if(!v||v.childId!==d)throw new c("forbidden",`session ${u} isn't one of ${d}'s`);let{session:S}=v;if(p==="task_attach_media"){let L=sl.safeParse(w);if(!L.success)return Un("task_attach_media from a sandbox sends the file's bytes");let N=L.data.taskId??S.taskId;if(!N||!S.projectId)return Un("taskId is required: this session has no task of its own");let B=await this.deps.tasks.get({projectId:S.projectId,taskId:N}).catch(()=>{return});if(!(N===S.taskId||S.kind==="epic"&&B?.epic===S.taskId||S.kind==="task"&&!!B?.bundle?.tasks.includes(S.taskId??"")))return Un(nl({kind:S.kind,role:"task",sandboxed:!0},S.taskId));let V=Buffer.from(L.data.data,"base64"),Y=await Lf(L.data.name,V,L.data.clip).then(()=>{return},(ie)=>ie.message);if(Y)return Un(Y);let ne=await this.deps.attachMedia({projectId:S.projectId,taskId:N},L.data.name,V,L.data.clip?"clip":"video");return{content:[{type:"text",text:JSON.stringify(ne)}]}}if(!wy.has(p))return Un(`${p} isn't available to a session in a sandbox`);let x;if(p==="task_ask"){let L=sk(S,w);if("error"in L)return Un(L.error);w=L.args,x=L.video}let j={projectId:S.projectId,sessionId:u,kind:S.kind,taskId:S.taskId,cwd:v.place.cwd,signal:v.abort.signal,sandboxVideo:x,sandboxed:!0,permissionMode:v.permissionMode};return this.forwarded.answer(u,y,(L)=>this.deps.mcp.callTool(p,w,j,L))}childDeps(){return{children:this.deps.children,tasks:this.deps.tasks,github:this.github,activity:this.deps.activity,heard:(d,u)=>this.deps.hooks.onEvent?.(d,u),synced:(d)=>this.deps.hooks.onTurnSynced?.(d),switchAccount:(d,u)=>void this.switchAccount(d,u),loginWorked:(d)=>this.loginWorked(d),gaveUp:(d,u)=>this.forwarded.gaveUp(d,u)}}}class vl extends hl{async start(d){let u=this.startKey(d);return u?this.oneAtATime(u,()=>this.startNow(d)):this.startNow(d)}startKey({projectId:d,taskId:u,teammate:p,kind:w,managerId:y}){if(w!=="coordinator")return d&&u&&!p?`${d}/${u}`:void 0;let v=d?{kind:"project",projectId:d}:{kind:"global"};try{return`manager:${this.deps.managers.resolve(v,y).id}`}catch{return}}async startNow(d){let{leadSecretEnv:u,...p}=d,w={...p,secretEnv:Tr(d.secretEnv)},y=ua(u);if(!w.projectId)return this.startGlobalCoordinator(w,y);let{projects:v,tasks:S}=this.deps,x=await v.get(w.projectId),j=x.lead&&w.kind!=="coordinator"&&!w.teammate?y:pa(y),L=w.settings?.user??{},N=await v.settings(x.id,L);if(!N["project.enabled"])throw new c("conflict",`${x.id} is turned off`);let B=w.taskId?await S.get({projectId:x.id,taskId:w.taskId}):void 0,G=B?.kind==="epic"?"epic":w.kind;if(G!=="coordinator"&&!B)throw new c("bad_request",`a ${G} session needs a taskId`);if(G!=="coordinator"&&B?.status==="cancelled")throw new c("conflict",mi(B));let V=w.teammate&&Kt.parse(w.teammate);if(V&&(G!=="task"||!B))throw new c("bad_request","a teammate joins a task's session: a task, not an epic");let Y=!V&&!w.ownSession&&B&&await this.routeToEpic(B,w.prompt);if(Y)return Y;let ne=!V&&B?Ee(await S.list(x.id),B):void 0;if(ne&&B)return this.startNow({...d,taskId:ne.id,prompt:w.prompt??`Work on ${B.id} (${B.title}) of your bundle now.`});let ie=!V&&B&&this.preparing.get(`${x.id}/${B.id}`);if(ie)return ie;let ye=!V&&B&&this.leadOf(x.id,B.id);if(ye&&w.fresh)await this.stopAndWait(ye);else if(ye&&ye.session.pausedFor==="signed_out")return await this.keepLeadSecrets(ye,x,j),await this.signInAgain(ye,w.startTicket,w.prompt,w.relay),this.deps.hooks.onTaskSession?.(ye.session),ye.session;else if(ye){if(await this.keepLeadSecrets(ye,x,j),w.prompt)await this.send(ye.session.id,w.prompt,"user",{relay:w.relay});if(w.restart)await this.restartClaude(ye.session.id,"after_turn").catch((_e)=>s.info(`sessions: ${ye.session.id} not restarted: ${_e instanceof Error?_e.message:String(_e)}`));return this.deps.hooks.onTaskSession?.(ye.session),ye.session}let ve=G==="coordinator"?this.deps.managers.resolve({kind:"project",projectId:x.id},w.managerId):void 0;if(ve&&this.strayProjectLead({kind:G,projectId:x.id,managerId:ve.id}))throw new c("conflict",`${x.name}'s lead runs on its own machine, not on this one: write to it there (SendMessage \`LEAD ${x.id}\`)`);if(ve){let _e=this.coordinator(ve.scope,ve.id);if(_e){if(w.prompt)await this.send(_e.session.id,w.prompt,"user",{relay:w.relay});return _e.session}}let Qe=!V&&!w.fresh&&!w.resume&&B?.sessionId&&!this.hasHistory(B.sessionId)?await this.deps.transcripts?.kept(B.sessionId):void 0,ht=!V&&!w.fresh&&B?.sessionId&&(this.hasHistory(B.sessionId)||Qe)?B.sessionId:void 0,et=w.fresh?void 0:w.resume??ht,_t=w.eventSeq??Qe?.lastSeq,Gn=et?w.conversationId??Qe?.conversationId:void 0,ft=et??w.id??jk(),Ws=await this.originOf(w,et);if(Ws||w.startTicket)await this.records.change(ft,(_e)=>({..._e,origin:Ws}));let wt=B&&{projectId:x.id,taskId:B.id};if(wt)await this.deps.removals.starting(wt);try{let _e=B?await this.deps.places.forTask(x,B,N,await this.stackBase(x,B),{retrySetup:w.retrySetup,head:V?void 0:w.head}).catch((Mt)=>{if(Mt instanceof xe&&!V)return Mt;throw Mt}):{runner:"host",cwd:x.path,ports:[],seconds:0};if(_e instanceof xe&&B)return this.waitForSetup(_e,{...w,leadSecretEnv:j},{id:ft,projectId:x.id,taskId:B.id,nodeId:this.deps.nodeId(),runner:N["runner.kind"],kind:G,state:"starting",waitingFor:"setup",title:`${B.id} ${B.title}`,cwd:_e.place?.cwd??x.path,branch:_e.place?.branch,sandbox:_e.place?.sandboxName,startedAt:_e.state.startedAt??new Date().toISOString(),ports:[],previews:[]});if(_e instanceof xe)throw new c("unavailable",_e.message);let As={...et?await this.spentSoFar(et):void 0,id:ft,projectId:x.id,taskId:B?.id,nodeId:this.deps.nodeId(),runner:_e.runner,kind:G,managerId:ve?.id,state:"starting",title:B?`${B.id} ${B.title}${V?` \xB7 ${V.name}`:""}`:ve?.main?`${x.name} manager`:`${ve?.name} (${x.name})`,cwd:_e.cwd,branch:_e.branch,startedAt:w.startedAt??new Date().toISOString(),ports:_e.ports,previews:[],sandbox:_e.sandboxName,..._e.sandboxName?{sandboxSpec:gy(N)}:{},teammate:V,...Gn&&Gn!==ft?{claudeSessionId:Gn}:{}};if(_e.sandbox&&B){if(!this.deps.children.available())throw new c("unavailable","a task in a sandbox needs this machine linked to its server");pa(j);let Mt=await this.startInChild(As,_e,x,B,N,{...w,resume:et,eventSeq:_t,origin:Ws});return this.deps.hooks.onTaskSession?.(Mt),Mt}if(w.memory?.length&&!V)await this.carryMemory(_e.cwd,ft,w.memory);let Co=Li(As,x,j),Gs=await this.newLive(As,{level:B?.level??"normal",secretEnv:{...w.secretEnv??{},...Co},leadEnv:Co,startTicket:w.startTicket,origin:Ws,userLayer:L,place:_e},_t);if(pe(B))Gs.startedClosed=!0;if(B&&!V){let Mt={projectId:x.id,taskId:B.id},qd={sessionId:ft,node:As.nodeId,runner:_e.runner,status:["backlog","todo","in_review"].includes(B.status)?"in_progress":B.status,...B.parked?{parked:null}:{},via:et?"session wake":"session start"};await S.update(Mt,qd),zr({audit:(bs)=>this.deps.push({type:"mcp.audited",entry:bs})},ft,Mt,B,qd),await this.holdBundle(B,As.nodeId)}let br=w.prompt??(et?Xr:B?Qr(B,V):""),it=await this.launch(Gs,Boolean(et),w.prompt?"user":"superfactory",br,w.prompt?w.relay:void 0);if(B)this.deps.hooks.onTaskSession?.(it.session);return it.session}finally{if(wt)this.deps.removals.started(wt)}}async holdBundle(d,u){if(!d.bundle)return;let p=await this.deps.tasks.list(d.projectId);for(let w of Ct(p,d.bundle.id))if(w.id!==d.id&&Ps(w)&&w.node!==u)await this.deps.tasks.update({projectId:w.projectId,taskId:w.id},{node:u,via:"bundle session start"}).catch((y)=>s.warn(`sessions: ${w.id} of ${d.id}'s bundle`,y))}async carryMemory(d,u,p){let w=await zf(d,u,p).catch((y)=>(s.warn(`sessions: ${u}'s memory not written here: ${y.message}`),0));s.info(`sessions: ${u}'s memory came along: ${w} of ${p.length} file(s) written`)}async spentSoFar(d){let u=this.live.get(d)?.session??await this.savedOne(d);if(!u)return{};let{costUsd:p,usage:w,context:y,lastTurn:v}=u;return{costUsd:p,usage:w,context:y,lastTurn:v}}async startGlobalCoordinator(d,u){let p=this.deps.managers.resolve({kind:"global"},d.managerId),w=this.coordinator(p.scope,p.id);if(w){if(d.prompt)await this.send(w.session.id,d.prompt,"user",{relay:d.relay});return w.session}let y=d.settings?.user??{},v=p.type==="machine",S=v?p.cwd??WR():p.main?m().coordinator:Lk(m().managers,p.id);if(v&&!FR(S))throw new c("bad_request",`${S} isn't a folder on this machine`);await BR(S,{recursive:!0});let x=d.resume??jk();if(d.memory?.length)await this.carryMemory(S,x,d.memory);let j=d.resume?d.conversationId:void 0,N={...d.resume?await this.spentSoFar(d.resume):void 0,id:x,nodeId:this.deps.nodeId(),runner:"host",kind:"coordinator",managerId:p.id,state:"starting",title:p.main?xn({kind:"global"}):p.name,cwd:S,startedAt:new Date().toISOString(),ports:[],previews:[],...j&&j!==x?{claudeSessionId:j}:{}},B=Li(N,void 0,u),G=await this.newLive(N,{level:"normal",secretEnv:{...d.secretEnv,...B},leadEnv:B,startTicket:d.startTicket,userLayer:y},d.resume?d.eventSeq:void 0);return(await this.launch(G,Boolean(d.resume),"user",d.prompt,d.relay)).session}async newLive(d,u,p,w={kind:"starting",deciding:!0}){for(let j of Object.values(u.secretEnv))O(j);let y=await q.open(d.id),v=await js.open(m().sessionLogs,d.id,p),S={recorded:(j,L)=>this.recorded(x,j,L),shown:(j,L)=>this.shown(x,j,L),waitsForUser:()=>this.waitsForUser(x)},x=new Qc([d,v,y,Lk(m().run,d.id),S,w],u);return x.handle=this.localHandle(x),x}async launch(d,u,p,w,y){let v=w?{text:w,author:p,relay:y}:void 0,S=this.live.get(d.session.id);if(S&&S!==d&&(Ss(S)||Ir(S)||this.ensuring.has(S.session.id)))return S.startedClosed||=d.startedClosed,await this.ensureRunning(S,{resume:!0,reason:"start",message:v,wait:!0}),S;return d.session.address=this.addressOf(d.session),this.live.set(d.session.id,d),await this.save(d),await this.ensureRunning(d,{resume:u,reason:"start",message:v,wait:!0}),d}waitForSetup(d,u,p){let w=`${p.projectId}/${p.taskId}`;this.preparing.set(w,p);let y=(v,S)=>this.deps.push({type:"session.updated",session:{...p,state:v,waitingFor:void 0,error:S,endedAt:new Date().toISOString()}});return(async()=>{let v=await d.done;if(this.preparing.get(w)!==p)return;if(this.preparing.delete(w),v.state!=="ready")return y("failed",`The project's setup failed: ${v.error??"it ended badly"}`);try{let S=await this.start({...u,id:p.id,retrySetup:!1,startedAt:p.startedAt});if(this.deps.push({type:"session.updated",session:S}),S.id!==p.id)y("exited")}catch(S){y("failed",S.message.slice(0,4000))}})().catch((v)=>s.warn(`sessions: ${w}'s start after its setup`,v)),s.info(`sessions: ${w} waits for its project's setup (${d.state.step??"setup"})`),p}async routeToEpic(d,u){if(!d.epic)return;let p=this.forTask(d.projectId,d.epic);if(!p)return;if(d.sessionId&&d.sessionId!==p.session.id)return;if(this.leadOf(d.projectId,d.id))return;return await this.send(p.session.id,u??`Work on ${d.id} (${d.title}) of your epic next.`,"superfactory"),p.session}}class Cl extends vl{}import{existsSync as Dk,realpathSync as HR}from"fs";import{chmod as GR,mkdtemp as qR,writeFile as VR}from"fs/promises";import{tmpdir as YR}from"os";import{join as Nk}from"path";var KR=1000,QR="/etc/systemd/system/superfactory-agent.service";async function Ta(){let d=JR();if(d)throw new c("unavailable",d);let u=process.platform==="win32",p=await qR(Nk(YR(),"superfactory-uninstall-"));await GR(p,448);let w=Nk(p,u?"uninstall.ps1":"uninstall.sh");return await VR(w,u?ZR(p):XR(p),{mode:448,flag:"wx"}),s.info("uninstall: this machine was removed; the agent takes itself off it"),setTimeout(()=>e0(w),KR),{ok:!0}}function JR(){if(process.env.SUPERFACTORY_SANDBOX)return"a sandbox's agent goes with its sandbox";if(/\.app\/Contents\//.test(process.execPath))return"it is the desktop app's: quit the app and remove it";if(Ze()==="systemd"&&Dk(QR)&&process.getuid?.()!==0)return"its service is the system's, which only root removes";if(zR()&&!process.env.SUPERFACTORY_ADMINISTRATOR)return"an administrator installed it, and only an administrator removes it";return}function Bl(){let d=HR(process.execPath);return Dk(`${d}.sha256`)?d:void 0}var zR=()=>process.platform==="win32"&&!!Bl()?.toLowerCase().startsWith("c:\\superfactory\\"),Ul=(d)=>`'${d.replaceAll("'","'\\''")}'`,Pa=(d)=>`'${d.replaceAll("'","''")}'`;function XR(d){let u=Ze();return[`SF_UNINSTALL_PID=${process.pid}`,`SF_UNINSTALL_HOME=${Ul(U())}`,`SF_UNINSTALL_SERVICE=${u==="launchd"||u==="systemd"?u:"none"}`,`SF_UNINSTALL_BIN=${Ul(u?Bl()??"":"")}`,jg,`rm -rf ${Ul(d)}`,""].join(`
|
|
196
|
+
`)}function ZR(d){let u=Ze()?Bl():void 0;return["$FromAgent = $true",`$AgentPid = ${process.pid}`,`$AgentHome = ${Pa(U())}`,`$Bin = ${u?Pa(u):"$null"}`,Mg,`Remove-Item ${Pa(d)} -Recurse -Force -ErrorAction SilentlyContinue`,""].join(`\r
|
|
197
|
+
`)}function e0(d){try{let u=_(t0(d),{stdin:"ignore",stdout:"ignore",stderr:"ignore",detached:!0});u.once("error",(p)=>s.warn("uninstall: the script didn't start",p)),u.unref()}catch(u){s.warn("uninstall: the script didn't start",u)}}function t0(d){if(process.platform==="win32"){let u=`powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File "${d}"`;return r(wu).flag("-NoProfile").flag("-NonInteractive").flag("-Command",`Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = ${Pa(u)} } | Out-Null`).build()}if(Ze()==="systemd")return r(hu).flag("--user").flag("--collect").flag("--quiet").arg("sh").arg(d).build();return r(mu).arg(d).build()}var Ra=new Map,n0=3600000,Je={ok:!0},Be=(d)=>async(u)=>(await d(u),Je);function Aa(d,u,p){let w=p.map((y)=>[`${d}.${y}`,u[y].bind(u)]);return Object.fromEntries(w)}function ss(d){if(process.platform!=="darwin"&&process.env.SUPERFACTORY_TART_ANYWHERE!=="1")return Promise.reject(new c("unavailable","this machine isn't a Mac: Tart runs VMs on Macs only"));return d()}var i0=(d)=>d?{ip:d}:{},Uk=()=>{throw new c("conflict","this machine's Superfactory no longer hands sessions to Claude")};function Fk(d){let u=async(S,x)=>{let j=await d.tasks.get(S);if(!x.askedBy||x.askedBy!==j.sessionId||d.sessions.isRunning(x.askedBy))return!1;return!!await d.placed.start({...S,prompt:ni(x)}).catch((N)=>s.warn(`questions: couldn't start ${S.taskId}'s agent where it moved`,N))},p=async(S,x)=>{let j=await d.tasks.get(S);return((await d.sessions.list(S.projectId)).find((N)=>N.id===x.askedBy)?.runner??j.runner??"host")==="host"},w=async(S,x,j,L)=>{let N=d.questions.pending(S,x);if((N??(await d.tasks.get(S)).questions.find((G)=>G.id===x))?.kind!=="permission"){if(j.remember)throw new c("bad_request",`${x} isn't a permission prompt`);return}if(j.dismissed)return;if(!N)throw new c("conflict","Claude no longer waits for this: the call it asked about has ended");if(j.decision==="allow"&&!L&&await p(S,N))throw new c("forbidden","only the server owner allows a tool for a session on this machine");if(j.remember&&(j.decision!=="allow"||!N.permission?.canRemember))throw new c("forbidden","this call can't be always allowed: allow it once instead")},y=async(S)=>{let x=await d.tasks.get(S);return await(x.sessionId?d.sessions.sandboxFor(x.sessionId):void 0)?.pull(),ee(d.projects.path(S.projectId),S.taskId)},v=async(S,x)=>({projectPath:d.projects.path(S.projectId),task:await d.tasks.get(S),base:x??ut(await d.projects.settings(S.projectId))});return{"link.moving":Be(({reason:S})=>d.moveLink(S)),"projects.identity":({projectId:S})=>d.checkouts.identity(S),"projects.checkout":async(S)=>{let x=await d.checkouts.checkout(S);return d.watchProject(S.projectId),d.setup.run().then(()=>d.setUpProject(S.projectId).catch(()=>{return})),x},"projects.clone":(S)=>d.checkouts.cloneNew(S),"projects.createEmpty":(S)=>d.checkouts.createEmpty(S),"projects.remote.attach":({projectId:S,url:x})=>Gw(d.projects.path(S),x),"projects.remote.detach":Be(({projectId:S,url:x})=>qw(d.projects.path(S),x)),"projects.remote.sync":async({projectId:S})=>{let x=await d.projects.settings(S);return Vw(d.projects.path(S),{settings:x,createTask:(j)=>d.tasks.create({...j,projectId:S},x),openTask:async(j)=>(await d.tasks.list(S)).find((L)=>L.title===j&&!["done","cancelled"].includes(L.status))})},"projects.forget":Be(({projectId:S})=>d.checkouts.forget(S)),"github.changed":Be(async({projectId:S})=>{await d.sessions.github.changed(S),await d.sessions.taskGithub.changed(S)}),"projects.init":async({path:S,name:x,settings:j})=>{let L=await d.projects.init(S,x,j);return d.watchProject(L.id),L},"projects.config.patch":async({projectId:S,patch:x})=>{let j=await d.projects.patchConfig(S,x);return await d.projectChanged(S),j},"projects.icon.set":async({projectId:S,icon:x})=>{let j=await d.projects.setIcon(S,x);return await d.projectChanged(S),j},"projects.icon.read":({projectId:S})=>d.projects.iconImage(S),"projects.name.set":async({projectId:S,name:x})=>{let j=await d.projects.setName(S,x);return await d.projectChanged(S),j},"projects.delete":async({projectId:S,removeFolder:x})=>{if(!d.projects.ids().includes(S))return{known:!1,sessionsStopped:0};let j=await d.sessions.stopProject(S);d.tasks.forget(S);let L=await d.projects.forget(S);if(!L||!x||!await d.projects.removeFolder(L))return{known:!0,sessionsStopped:j};return{known:!0,sessionsStopped:j,folderRemoved:L}},"projects.lead.forget":async({projectId:S})=>{if(!await d.projects.forgetLead(S))throw new c("not_found",`${S} isn't this machine's lead project`);return{ok:!0}},"projects.backupCode":({projectId:S,uploadId:x})=>Bw(d.projects.path(S),(j)=>d.uploadBackup({projectId:S,uploadId:x},j)),"machine.config.patch":async({patch:S})=>{let x=await Jp(S);return d.machineSettingsChanged(),x},"machine.displays":()=>_l(),"machine.identity":async({challenge:S})=>{let x=await fn();return{publicKey:x.publicKey,signature:x.prove("link",S)}},"machine.openTask":Be(({event:S,path:x})=>Dw(S,x,d.serverUrl())),"machine.away":({on:S})=>d.away(S),"machine.setup":()=>d.setUpAgain(),"machine.projectSetup":({projectId:S})=>d.setUpProject(S,!0),"machine.growDisks":async()=>({disks:await Sc()}),"claude.signIn.start":({flowId:S})=>d.claudeSignIns.start(S),"claude.signIn.code":({flowId:S,code:x})=>d.claudeSignIns.code(S,x),"claude.signIn.cancel":Be(({flowId:S})=>d.claudeSignIns.cancel(S)),"claude.ping":({token:S})=>ac(S),"fs.listDirs":({path:S,filter:x})=>Nw(S,x),"settings.sync":async({server:S,projects:x,managers:j,keys:L,holdsLead:N,leadProject:B,disabled:G,pause:V,homeOf:Y,machineName:ne})=>{if(ne)d.machineNamed(ne);if(await d.projects.setServerSettings(S,x,L),await d.projects.setDisabled(G,V),Y)await d.projects.setHomes(Y);return await d.managers.set(j),await d.leadSynced(N,B),d.settingsChanged(),Je},"ports.open":async(S)=>{if("sessionId"in S)await d.ports.open(S.channel,S.sessionId,S.port);else await d.ports.openAt(S.channel,await d.platformPlaces.address(S.place,S.port));return Je},...Aa("platforms",d.platformPlaces,["run","read","expose","view","send","receive"]),"platforms.end":Be((S)=>d.platformPlaces.end(S)),"coordinator.stop":async({scope:S,managerId:x,mode:j,timeoutSeconds:L})=>{let N=d.sessions.coordinator(S,x);if(!N)throw new c("not_found","this manager isn't running");if(j==="force")await d.sessions.stop(N.session.id);else await d.sessions.wrapUp(N.session.id,L*1000);return Je},...Aa("coordinator.instructions",d.instructions,["get"]),"coordinator.instructions.set":({scope:S,managerId:x,text:j,baseRevision:L,by:N,userId:B})=>d.instructions.set({scope:S,managerId:x},j,L,{by:N,userId:B}),"macos.queue":async()=>d.macos.queue(),"macos.golden.get":({projectId:S})=>d.macos.golden(S),"macos.golden.rebuild":({projectId:S})=>d.macos.rebuild(S),"macos.screen.open":Be(async({channel:S})=>d.ports.openScreen(S,await d.macos.screen())),"macos.passwords.rotate":Be(({vm:S})=>d.macos.rotate(S)),"tart.info":({image:S})=>ss(()=>d.tartVms.info(S)),"tart.install":()=>ss(()=>d.tartVms.install()),"tart.vms":({names:S})=>ss(()=>d.tartVms.vms(S)),"tart.create":(S)=>ss(()=>d.tartVms.create(S).then(()=>Je)),"tart.seed":({name:S,userData:x,networkData:j})=>ss(()=>d.tartVms.seed(S,x,j).then(()=>Je)),"tart.start":({name:S})=>ss(()=>d.tartVms.start(S).then(()=>Je)),"tart.stop":({name:S})=>ss(()=>d.tartVms.stop(S).then(()=>Je)),"tart.set":({name:S,...x})=>ss(()=>d.tartVms.set(S,x).then(()=>Je)),"tart.delete":({name:S})=>ss(()=>d.tartVms.delete(S).then(()=>Je)),"tart.ip":async({name:S})=>ss(async()=>({...await i0(await d.tartVms.ip(S))})),"machine.screen.open":async({channel:S})=>(await d.ports.openScreen(S,await Di(d.displays,d.serverUrl())),d.screenOpened(),Je),"machine.run":async(S)=>_w(d.commandRuns,{...S,runId:S.runId??d.newRunId(),timeoutSeconds:S.timeoutSeconds??await d.commandTimeoutSeconds()}),"machine.unlock":async()=>gm(bl(),()=>Di(d.displays,d.serverUrl())),"machine.restart":async({what:S})=>Tc(S,d.stopToRestart),"machine.uptime":async()=>Pl(),"machine.wakeOnLan":({mac:S,broadcast:x})=>Nm(S,x),"machine.shutdown":async()=>(await Lm(),Je),"commands.wait":({runId:S,scope:x,waitMs:j})=>d.commandRuns.wait(S,j,x),"commands.stop":({runId:S,scope:x})=>d.commandRuns.stop(S,x),"commands.output":async({runId:S,scope:x,...j})=>d.commandRuns.output(S,x,j),"commands.list":async({scope:S})=>d.commandRuns.list(S),"machine.screenshot":({screen:S})=>Ow(d.displays,d.serverUrl(),S),"agent.uninstall":()=>Ta(),"node.key.rotate":Be(({key:S})=>d.rekey(S)),"managers.wakeCost":async({managerId:S})=>{if(!d.managers.get(S))throw new c("not_found","no such manager here");return d.wakeCost(S)},"managers.wake":async({managerId:S,text:x})=>{if(!d.managers.get(S))throw new c("not_found","no such manager here");return{sessionId:await d.wakeManager(S,x)}},"retention.sweep":({dryRun:S})=>my(d,S),"tasks.list":({projectId:S})=>d.tasks.list(S),...Aa("tasks",d.tasks,["get"]),"tasks.create":async(S)=>d.tasks.create(S,await d.projects.settings(S.projectId)),"tasks.update":({patch:S,...x})=>d.tasks.update(x,S),"tasks.changed":Be(({stored:S})=>d.tasks.received(S)),"sprints.changed":Be(({projectId:S,sprints:x})=>d.tasks.sprintsChanged(S,x)),"tasks.messages":async(S)=>(await d.tasks.get(S),d.talk.messages(S)),"tasks.messagesPage":async({before:S,limit:x,...j})=>(await d.tasks.get(j),d.talk.messagesPage(j,{before:S,limit:x})),"tasks.recordMessage":async({message:S,...x})=>(await d.tasks.get(x),await d.talk.recordMessage(x,S),Je),"tasks.reply":async({text:S,author:x,callerIsOwner:j,fromAgent:L,...N})=>{let B=L?void 0:(await d.messageAnswers.onTask(N,S,x,j))?.question.askedBy,G=B||L?void 0:await d.merges.answerWithMessage(N,S,x);if(G?.sentTo)return{sessionId:G.sentTo,to:"task"};let V=await d.replies.send(N,S,x,j,B);if(!V)throw new c("not_found","nobody to reply to yet: start the task or its coordinator");return V},"tasks.attach":async({name:S,contentType:x,data:j,...L})=>(await d.tasks.get(L),Bo(Jn(L),S,x,Buffer.from(j,"base64"))),"comments.add":async({author:S,body:x,callerIsOwner:j,fromAgent:L,attachments:N,...B})=>{let G=Wo(Jn(B),x,N),V=await d.tasks.addComment(B,S,G);if(S.kind!=="user")return V;let Y=L?void 0:(await d.messageAnswers.onTask(B,G,S.handle,j))?.question.askedBy,ne=Y||L?void 0:await d.merges.answerWithMessage(B,G,S.handle);if(ne?.sentTo)return d.replies.answering(B,V,ne.sentTo);return d.replies.deliver(B,V,j,Y).catch(async(ie)=>(s.warn(`comments: couldn't deliver ${V.id} on ${B.taskId}`,ie),d.tasks.setReply(B,V.id,{state:"waiting"})))},"comments.edit":({commentId:S,body:x,by:j,...L})=>d.tasks.editComment(L,S,j,x),"comments.remove":Be(({commentId:S,by:x,...j})=>d.tasks.removeComment(j,S,x)),"questions.answer":async({questionId:S,answer:x,callerIsOwner:j,...L})=>{let N=async(ve)=>(await d.tasks.get(L)).questions.find((Qe)=>Qe.id===ve.id)??ve;await w(L,S,x,j);let{questions:B}=await d.tasks.get(L),G=B.find((ve)=>ve.id===S),V=G?.purpose==="merge"&&G.status!=="open"&&x.choiceIds?.includes(Yt)?B.find((ve)=>ve.purpose==="merge"&&ve.status==="open"):void 0;if(G&&V){let ve=await d.merges.refusedForOld(L,G,V,x);if(ve)return ve;let{question:Qe}=await d.questions.answer(L,V.id,x,j);return await d.merges.answered(L,{...Qe,head:G?.head??Qe.head}),N(Qe)}let{question:Y,delivered:ne}=await d.questions.answer(L,S,x,j);if(Y.purpose==="merge"&&Y.status==="dismissed")return Y;if(Y.purpose==="merge")return await d.merges.answered(L,Y),N(Y);if(Y.purpose==="continue")return d.continues.answered(L,Y),Y;if(Y.purpose==="sign_in")return Y;if(Y.purpose==="system_permission")return d.systemPermissions.answered(L,Y,j).catch((ve)=>s.warn(`questions: couldn't act on ${S}'s system prompt`,ve)),Y;let ie=!ne&&Y.kind!=="permission";if(ie&&await u(L,Y))return Y;let ye=ie?await d.replies.asker(L,Y.askedBy):void 0;if(ye)d.sessions.send(ye,ni(Y),x.by).catch((ve)=>s.warn(`questions: couldn't deliver ${S} to ${Y.askedBy}`,ve));return Y},"questions.reopen":({questionId:S,...x})=>d.questions.reopen(x,S),"reviewComments.add":({comment:S,...x})=>Hl(d.tasks,d.sessions,x,S),"files.list":({path:S,...x})=>d.files.list(x,S),"files.read":({path:S,...x})=>d.files.read(x,S),"files.find":({query:S,limit:x,...j})=>d.files.find(j,S,x),"files.grep":({query:S,limit:x,...j})=>d.files.grep(j,S,x),"git.diff":async({base:S,...x})=>{let j=await d.tasks.get(x),L=await ia(d.projects.path(x.projectId),x.taskId);if(!L)return{files:[]};let N=j.sessionId?d.sessions.sandboxFor(j.sessionId):void 0;if(!N)return{files:await Fl(L,S)};return await N.pull(),{files:await Fl(N.workdir,await Us(L,S),ih(N))}},"git.commits":async({base:S,limit:x,...j})=>rh(await y(j),S,x),"git.commitDiff":async({sha:S,base:x,...j})=>oh(await y(j),S,x),"worktree.get":async({base:S,...x})=>{await d.removals.settled(x);let j=await v(x,S);return{...await Ya(j),videoOutdated:await Nf(d.projects,j.task)}},"worktree.remove":async({deleteBranch:S,base:x,...j})=>{Hu(await d.sessions.list(j.projectId),j.taskId),await d.removals.settled(j);let L=await tf(await v(j,x),S);return d.worktreeChanged(j),L},"worktree.recreate":async({from:S,base:x,branch:j,stop:L,...N})=>{let B=L?await d.sessions.stopTask(N):[];Hu(await d.sessions.list(N.projectId),N.taskId),await d.removals.settled(N);let G=await v(N,x),V=await sf(G,S,j),Y=G.task.pr;if(Y?.branch&&Y.branch!==V.branch)await d.tasks.forgetPr(N),await d.tasks.appendNote(N,`Its worktree is on ${V.branch} now: PR #${Y.number} on ${Y.branch} is no longer its PR.`);d.worktreeChanged(N);let ne=G.task.sessionId;if(ne&&B.includes(ne))await d.sessions.send(ne,Xp(V.branch,B.length-1),Ve).catch((ie)=>s.warn(`worktree: couldn't resume ${ne} after remaking it`,ie));return{...V,stopped:B}},"sessions.list":({projectId:S})=>d.sessions.list(S),"sessions.slots":async({grant:S,waiting:x})=>(d.sessions.slots(S,x),Je),"sessions.start":async(S)=>{if(S.resume)d.sessions.backHere(S.resume);let x=d.sessions.runsGoingOn(),j=await d.teams.start(S,S.addedBy);return{...j,joined:x.get(j.id)===j.startedAt}},"team.get":(S)=>d.teams.team(S),"team.watch":({sessionId:S,watch:x,...j})=>d.teams.setWatch(j,S,x),"team.remove":({sessionId:S,...x})=>d.teams.remove(x,S),...Aa("team",d.teams,["describe","publish"]),"team.send":Be(({to:S,text:x,manager:j,from:L,by:N,depth:B,...G})=>d.teams.send(G,void 0,S,x,{manager:j,from:L,by:N},B)),"sessions.deliver":async(S)=>{let{sessionId:x,managerId:j}=S;if(!(x?!!d.sessions.find(x)||(await d.sessions.list()).some((N)=>N.id===x):!!j&&!!d.managers.get(j)))throw new c("not_found",`no session ${x??j} on this machine`);return await d.sessionMessages.deliver(S),Je},"team.joined":({projectId:S,taskId:x,...j})=>d.teams.joined({projectId:S,taskId:x},j),"team.awayChanged":({projectId:S,taskId:x,nodeId:j,members:L})=>d.teams.awayChanged({projectId:S,taskId:x},j,L),"team.awayEvent":Be(({projectId:S,taskId:x,...j})=>d.teams.awayEvent({projectId:S,taskId:x},j)),"sessions.send":async({sessionId:S,text:x,author:j,attachments:L,callerIsOwner:N,taskRefs:B,fromAgent:G})=>{let V=Pr(S,x,L),Y=G?void 0:await d.messageAnswers.inChat(S,V,j,N),ne=d.sessions.find(S);if(!G&&!Y&&ne?.projectId&&ne.taskId&&ne.kind!=="coordinator"){let ie={projectId:ne.projectId,taskId:ne.taskId};if((await d.merges.answerWithMessage(ie,V,j))?.sentTo===S)return Je}return d.talk.expect(S,x,B),await d.sessions.send(S,x,j,{attachments:L,callerIsOwner:N,byPerson:!0}),Je},"sessions.attach":({sessionId:S,name:x,contentType:j,data:L})=>d.sessions.attach(S,x,j,Buffer.from(L,"base64")),"sessions.commands":({sessionId:S})=>d.sessions.commands(S),"sessions.handoff":Uk,"sessions.takeBack":Uk,"sessions.answer":({sessionId:S,questionId:x,answer:j})=>d.chatQuestions.answer(S,x,j),"sessions.reopenQuestion":({sessionId:S,questionId:x})=>d.chatQuestions.reopen(S,x),"questions.show":({question:S,...x})=>d.questions.post(x,S),"sessions.show":({sessionId:S,question:{text:x,details:j,choices:L,multiSelect:N,asker:B,shown:G}})=>d.chatQuestions.post(S,{text:x,details:j,choices:L,multiSelect:N,asker:B,shown:G}),"sessions.interrupt":Be(({sessionId:S})=>d.sessions.interrupt(S)),"sessions.jobOutput":({sessionId:S,jobId:x})=>d.sessions.jobOutput(S,x),"sessions.stopJob":Be(({sessionId:S,jobId:x})=>d.sessions.stopJob(S,x)),"sessions.nudge":Be(({sessionId:S})=>d.sessions.nudge(S)),"sessions.restart":async({sessionId:S,when:x})=>({restart:await d.sessions.restartClaude(S,x)}),"sessions.wrapUp":Be(({sessionId:S,timeoutSeconds:x})=>d.sessions.wrapUp(S,x*1000)),"sessions.stop":Be(({sessionId:S})=>d.sessions.stop(S)),"sessions.elsewhere":Be(({sessionId:S})=>d.sessions.elsewhere(S)),"sessions.moveOut":async({sessionId:S,to:x,when:j,waitSeconds:L})=>{let N=await d.sessions.moveOut(S,j,L*1000),B=N.teammate?[]:await nc(N.cwd,N.id).catch((Y)=>(s.warn(`sessions: ${S}'s memory not read for its move: ${Y.message}`),[])),G=B.length?{memory:B}:{},V=N.kind!=="coordinator"&&!N.teammate&&N.projectId&&N.taskId?{projectId:N.projectId,taskId:N.taskId}:void 0;try{let Y=V?await d.workBackup.handOff(V,x):void 0,ne=Ra.get(S),ie=Y&&ne&&ne.work.head===Y.head?ne.work:Y;for(let[ye,ve]of Ra)if(Date.now()-ve.at>n0)Ra.delete(ye);if(ie)Ra.set(S,{at:Date.now(),work:ie});return{session:N,...G,...ie?{work:ie}:{}}}catch(Y){return{session:N,...G,workFailed:Y.message.slice(0,2000)}}},"sessions.resumePaused":Be(()=>d.sessions.resumePaused()),"sessions.accountLimited":Be(({accountId:S,until:x})=>void d.sessions.accountLimited(S,x)),"sessions.rebalance":Be(({sessionIds:S})=>void d.sessions.rebalance(S)),"sessions.history":async({sessionId:S,afterSeq:x,limit:j,before:L})=>{let N=await d.sessions.history(S,x,j,L);return{...N,events:await d.talk.decorate(S,N.events)}},"terminals.open":async({target:S,callerIsOwner:x,...j})=>{try{if(S.kind==="sandbox")return await d.openSandboxTerminal(j);if(S.kind==="task")return await d.openTaskTerminal(j,S.taskId,x);if(S.kind==="machine")throw new c("bad_request","a shell for no project opens with terminals.openMachine");if(!x)throw new c("forbidden","only the server owner opens a shell on this machine");return d.terminals.start({...j,target:S,cwd:d.projects.path(j.projectId)})}catch(L){throw s.warn(`terminals: couldn't open one in ${j.projectId}'s ${S.kind}: ${L}`),L}},"terminals.start":()=>{throw new c("forbidden","this machine opens its own terminals: terminals.open")},"terminals.list":async({projectId:S})=>[...d.terminals.list(S),...d.sandboxTerminals(S)],"terminals.openMachine":async({callerIsOwner:S,...x})=>{if(!S)throw new c("forbidden","only the server owner opens a shell on this machine");return d.terminals.start({...x,target:{kind:"machine"},cwd:s0()})},"terminals.listMachine":async()=>d.terminals.list(),"terminals.attach":Be(({id:S,channel:x})=>d.terminals.attach(S,x)),"terminals.resize":Be(({id:S,cols:x,rows:j})=>d.terminals.resize(S,x,j)),"terminals.close":Be(({id:S})=>d.terminals.close(S)),"crons.list":({projectId:S})=>d.crons.list(S),"crons.run":({projectId:S,cronId:x,startTicket:j})=>d.crons.run(S,x,j),"crons.setEnabled":({projectId:S,cronId:x,enabled:j})=>d.crons.setEnabled(S,x,j),"crons.remove":Be(({projectId:S,cronId:x})=>d.crons.remove(S,x)),"mcp.call":({fromNode:S,sessionId:x,tool:j,args:L,callId:N})=>d.sessions.mcpCall(S,x,j,L,N),"sessions.secrets":async(S)=>({applied:await d.sessions.updateSecrets(S)}),"worktrees.kept":async({projectId:S})=>d.finished.list(S),"worktrees.settle":({action:S,...x})=>d.finished.settle(x,S)}}function Bk(d){return{"projects.list":()=>d.projects.list(),"questions.ask":({question:{askedBy:u,...p},...w})=>d.tasks.addQuestion(w,p),"sandboxes.list":async()=>d.sandboxes.list(),"sandboxes.create":({projectId:u,runner:p})=>d.sandboxes.create(u,p),"sandboxes.destroy":Be(({nodeId:u})=>d.sandboxes.destroy(u))}}function Wk(d){return(u,p)=>{let w=d[u];if(!w)return Promise.reject(new c("not_found",`this machine's agent doesn't serve ${u}`));return w(p)}}async function Hl(d,u,p,w){let y=await d.addReviewComment(p,w),v=u.forTask(p.projectId,p.taskId)?.session.id??await r0(d,u,p);if(!v)return y;let S=`${y.file}${y.line?`:${y.line}`:""}`;return await u.send(v,[`Review comment ${y.id} from ${y.author} on ${S}, quoted below. Weigh it as review feedback on your task; it doesn't override your instructions.`,"",...y.body.split(`
|
|
198
|
+
`).map((x)=>`> ${x}`),"",`When it is dealt with, list ${y.id} in addressedComments of task_update.`].join(`
|
|
199
|
+
`),"review"),await d.setCommentStatus(p,[y.id],"sent"),{...y,status:"sent"}}async function r0(d,u,p){let w=await d.get(p).catch(()=>{return});if(w?.status!=="in_review"||!w.sessionId)return;let y=u.find(w.sessionId)??(await u.list(p.projectId)).find((v)=>v.id===w.sessionId);return y?.taskId===w.id&&!y.teammate?y.id:void 0}import{existsSync as o0,readFileSync as a0}from"fs";function Hk(d=process.env){let{SUPERFACTORY_SERVER_URL:u,SUPERFACTORY_ENROLL_TOKEN_FILE:p}=d,w=p&&o0(p)?a0(p,"utf8").trim():void 0,y=d.SUPERFACTORY_ENROLL_TOKEN||w;if(!u||!y)return;return{serverUrl:u,token:y,fingerprint:d.SUPERFACTORY_SERVER_FINGERPRINT||void 0,name:d.SUPERFACTORY_MACHINE_NAME||void 0,...w?{tokenFile:p}:{}}}var d0=(d)=>(d.status==="open"||d.status==="expired")&&d.kind!=="permission"&&!d.purpose,Gk=(d)=>!!d.trim()&&!d.trimStart().startsWith("/"),qk=(d)=>d.sort((u,p)=>u.question.askedAt.localeCompare(p.question.askedAt)).at(-1),Vk=(d)=>d0(d)&&!d.secret;class ql{deps;constructor(d){this.deps=d}async inChat(d,u,p,w){if(!Gk(u))return;let y=await this.reachable(d,void 0,w);if(!y)return;let v=qk([...await this.onOwnTask(y),...await this.inOwnChat(y)].filter((S)=>Vk(S.question)));return v&&this.answer(d,v,u,p)}async onTask(d,u,p,w){if(!Gk(u))return;let y=await this.deps.tasks.get(d),v=qk(y.questions.filter(Vk).map((x)=>({question:x,ref:d}))),S=v?.question.askedBy;if(!v||!S||!await this.reachable(S,d.projectId,w))return;return this.answer(S,v,u,p)}async reachable(d,u,p){let w=await this.deps.session(d);if(!w)return;return(w.projectId?w.projectId===(u??w.projectId):p)?w:void 0}async answer(d,u,p,w){let y={text:p,by:w,viaMessage:!0};return(u.ref?this.deps.questions.answer(u.ref,u.question.id,y):this.deps.chatQuestions.answerWithMessage(d,u.question.id,y)).then(()=>u,(S)=>{s.warn(`questions: a message couldn't answer ${u.question.id} of ${d}`,S);return})}async onOwnTask(d){if(d.kind==="coordinator"||!d.projectId||!d.taskId)return[];let u={projectId:d.projectId,taskId:d.taskId};return((await this.deps.tasks.get(u).catch(()=>{return}))?.questions??[]).filter((w)=>w.askedBy===d.id).map((w)=>({question:w,ref:u}))}async inOwnChat(d){if(d.kind!=="coordinator")return[];let u=await this.deps.chatQuestions.latestWaiting(d.id);return u?[{question:u}]:[]}}var Yk=process.env.SUPERFACTORY_E2E_METHODS==="1",l0=30000;function Qk(d){if(d.link?.connected)return Promise.resolve();return new Promise((u)=>d.linkWaiters.push(u))}async function Jk(d){if(d.link&&!d.link.connected){let u;await Promise.race([d.linked(),new Promise((p)=>u=setTimeout(p,l0))]),clearTimeout(u)}return d.link?.connected?d.link:void 0}function zk(d){for(let u of d.linkWaiters.splice(0))u();d.tunnel.linked().catch((u)=>s.warn("tunnel:",u)),d.vmVault.sync().catch((u)=>s.warn("macos: couldn't sync the VMs' passwords",u)),d.tasks.resync().finally(()=>d.sessions.linked()),d.selfUpdate?.check(),d.sessions.github.ensure(),d.sessions.taskGithub.ensure(),d.recheckMonitors(),d.learnServerVersion(),Pf({projects:d.projects,upload:(u,p,w)=>d.uploadMedia(u,p,w)}).catch((u)=>s.warn("media: couldn't send the unsent files again",u))}async function Xk(d){let u=d.httpLink();if(!u)return;d.serverVersion=await uh(u).catch((p)=>(s.info(`agent: couldn't ask the server's version: ${p.message}`),d.serverVersion))}function Zk(d,u){let p=d.serverVersion;if(!p||p===H)return;let w=Gt(),y=w.updates?"it updates itself to the server's version, and restarting Superfactory on this machine updates it now":`update Superfactory on this machine (it doesn't update itself: ${w.why})`;return`this machine runs Superfactory ${H} and the server ${p}, so it can't read the server's ${u} answer: ${y}`}function eb(d){if(!d.link?.connected)throw Error("not connected to the server: try again in a moment");return d.link}function tb(d){let{serverUrl:u,nodeKey:p,certSpkiSha256:w}=d.state;if(!u||!p)return;let{url:y,pin:v,headers:S}=d.tunnel.routed(u,w);return{serverUrl:y,key:p,pin:v,headers:S}}function sb(d){let{serverUrl:u,nodeKey:p,certSpkiSha256:w}=d.state;return u&&p?{serverUrl:u,key:p,pin:w}:void 0}async function nb(d){let{serverUrl:u,certSpkiSha256:p}=d.state;if(!u||p)return p;let w=await Wt(u);if(!w)return;return d.state.certSpkiSha256=w,await F(d.state),s.info(`agent: pinned the local server ${u} (${w})`),w}var Kk=Number(process.env.SUPERFACTORY_UNINSTALL_GRACE_MS)||300000;function p0(d){if(d.uninstalling)return;s.warn(`agent: its owner removed this machine while it was offline: taking itself off in ${Math.round(Kk/1000)} s unless connected again`),d.uninstalling=setTimeout(()=>{d.uninstalling=void 0,Ta().catch((u)=>s.warn(`uninstall: removed while offline, but ${u.message}`))},Kk)}async function ib(d){let{serverUrl:u,nodeId:p,nodeKey:w}=d.state;if(!u||!p||!w){s.info("agent: not enrolled; working locally");return}d.link=new gn({serverUrl:u,route:(y)=>d.tunnel.routed(u,y),ready:()=>d.tunnel.settled(),failed:(y)=>d.tunnel.failed(y),silent:(y)=>d.tunnel.silent(y),moving:(y)=>d.tunnel.renew(y),removed:(y,v)=>{if(d.removedFrom=u,v)p0(d)},key:()=>d.state.nodeKey??w,pin:()=>d.serverPin(),...d.linkOptions()}),d.link.versionMismatch=(y)=>d.versionMismatch(y);for(let y of d.early.splice(0))d.link.push(y);d.link.start(),d.applyNetwork()}function rb(d){return{handle:Wk({...Fk({checkouts:d.checkouts,workBackup:d.workBackup,projects:d.projects,files:new cc(d.projects),tasks:d.tasks,questions:d.questions,chatQuestions:d.chatQuestions,messageAnswers:new ql({tasks:d.tasks,questions:d.questions,chatQuestions:d.chatQuestions,session:async(u)=>d.sessions.find(u)??(await d.sessions.list()).find((p)=>p.id===u)}),sessions:d.sessions,teams:d.teams,crons:d.crons,macos:d.macos,tartVms:d.tartVms,sandboxes:d.sandboxes,ports:d.ports,displays:d.places.displays,platformPlaces:d.platformPlaces,commandRuns:d.commandRuns,newRunId:()=>Sr.newId(d.nodeId??"here"),commandTimeoutSeconds:async()=>(await d.projects.globalSettings())["agents.commandTimeoutSeconds"],stopToRestart:(u)=>d.restartForLead(u),claudeSignIns:d.claudeSignIns,terminals:d.terminals,openSandboxTerminal:(u)=>d.openSandboxTerminal(u),openTaskTerminal:(u,p,w)=>d.openTaskTerminal(u,p,w),sandboxTerminals:(u)=>[...d.sandboxTerminals.values()].filter((p)=>p.projectId===u),instructions:d.instructions,managers:d.managers,wakeCost:(u)=>d.wakeCosts.estimate(u),wakeManager:(u,p)=>d.wakeManagerWith(u,p),replies:d.replies,placed:d.placed,talk:d.talk,sessionMessages:d.sessionMessages,merges:d.merges,continues:d.continues,systemPermissions:d.systemPermissions,watchProject:(u)=>d.watch(u),uploadBackup:async(u,p)=>{let w=d.httpLink();if(!w)throw Error("not linked to a server");await wh(w,u,p)},worktreeChanged:(u)=>d.workPulse.touch(u),removals:d.removals,finished:d.finishedTasks,serverUrl:()=>d.state.serverUrl,screenOpened:()=>void d.recheckMonitors(),projectChanged:async(u)=>{d.push({type:"project.updated",project:await d.projects.get(u)}),d.tasks.resyncRepo(u)},setup:d.setup,setUpAgain:async()=>d.setUpAgain(),setUpProject:(u,p)=>d.setUpProject(u,p),rekey:(u)=>h0(d,u),moveLink:(u)=>d.link instanceof gn?d.link.move(u):void 0,away:async(u)=>{let p=await d.setAway(u);if(!p)throw new c("unavailable","the agent hasn't said hello yet");return p},leadSynced:(u,p)=>d.ensureLeadProject(u,p).catch((w)=>s.warn("projects: couldn't make the Superfactory lead project",w)),machineNamed:(u)=>{d.serverName=u},settingsChanged:()=>{d.automation.sweep(),d.tasks.resyncRepo(),d.applyNetwork(),d.claudeUpdates.allowed()},machineSettingsChanged:()=>{d.pushNode(!0),d.claudeUpdates.allowed()}}),...Yk?Bk({projects:d.projects,tasks:d.tasks,sessions:d.sessions,sandboxes:d.sandboxes}):{}}),channels:Xo(d.terminals,d.ports),connected:()=>d.onLinked(),hello:async()=>(d.networkSaid="",d.applyNetwork(),d.node=d.withMonitors({...await uo(d.nodeId,d.state.name),away:d.away.state,setup:d.setup.state,claudeUpdate:d.claudeUpdates.state,selfUpdate:d.selfUpdate?.state,sessionsAsAgent:$c(),projectSetups:d.places.setups.list(),usage:d.usage}),{type:"hello",node:d.node,projects:await d.projects.list(),methods:[...Object.keys(re),...Yk?Object.keys(rd):[]],run:tr})}}async function ob(d,{serverUrl:u,token:p,fingerprint:w}){O(p);let y=await wo(u,p,w);return d.linkTo({serverUrl:u,nodeId:y.nodeId,key:y.key,fingerprint:w})}async function ab(d){let u=Hk();if(!u||d.state.serverUrl===u.serverUrl&&d.state.nodeKey)return;let{serverUrl:p,token:w,fingerprint:y,name:v=d.state.name,tokenFile:S}=u;O(w);for(let x=1000;!d.stopping;x=Math.min(x*2,60000))try{let j=await wo(p,w,y,v);if(d.state.name=v,await d.linkTo({serverUrl:p,nodeId:j.nodeId,key:j.key,fingerprint:y}),s.info(`agent: enrolled with ${p} as ${j.nodeId}`),S&&w.startsWith("sfe_"))await u0(S,{force:!0}).catch(()=>{return});return}catch(j){s.warn(`agent: couldn't enroll with ${p}: ${j.message}; again in ${x} ms`),await Bun.sleep(x)}}async function h0(d,u){O(u);let p=c0(24).toString("hex");O(p),Object.assign(d.state,{nodeKey:u,controlToken:p}),await F(d.state),s.info("agent: the server rotated this machine's key; its control token is new too")}async function db(d,{serverUrl:u,nodeId:p,key:w,fingerprint:y}){if(O(w),d.state.serverUrl&&d.state.serverUrl!==u)await d.children.stopAll();return await d.tunnel.forget(),Object.assign(d.state,{serverUrl:u,nodeId:p,nodeKey:w,certSpkiSha256:y}),await F(d.state),d.removedFrom=void 0,clearTimeout(d.uninstalling),d.uninstalling=void 0,d.link?.stop(),await d.connect(),d.status()}import{watch as R0}from"fs";import{basename as A0}from"path";import{readdir as f0,readFile as g0}from"fs/promises";import{availableParallelism as w0,cpus as y0,freemem as k0,loadavg as b0,totalmem as _a}from"os";import{join as v0}from"path";function cb(){let d=0,u=0;for(let{times:p}of y0()){let w=p.user+p.nice+p.sys+p.idle+p.irq;d+=w-p.idle,u+=w}return{busy:d,total:u}}var Oa=(d,u)=>u>0?Math.min(100,Math.max(0,Math.round(d/u*100))):0;function Ca(d,u){let p=d.split(`
|
|
200
|
+
`).find((w)=>w.startsWith(`${u}:`));return Number(p?.split(":")[1]?.trim().replace(/\.$/,""))||0}function S0(d,u){let p=Number(d.match(/page size of (\d+) bytes/)?.[1])||4096,w=Ca(d,"Anonymous pages")-Ca(d,"Pages purgeable")+Ca(d,"Pages wired down")+Ca(d,"Pages occupied by compressor");return Oa(w*p,u)}function P0(d){let u=(w)=>Number(d.match(new RegExp(`^${w}:\\s+(\\d+)`,"m"))?.[1])||0,p=u("MemTotal");return Oa(p-u("MemAvailable"),p)}var ub=()=>Oa(_a()-k0(),_a());async function $0(){if(process.platform==="darwin")return S0(await T(r(Bd).timeoutMs(1e4).by("machine.usage").build()),_a());if(process.platform==="linux")return P0(await g0("/proc/meminfo","utf8"));return ub()}async function I0(d){return(await Promise.all(d.map((p)=>f0(v0(E(p).root,"worktrees"),{withFileTypes:!0}).then((w)=>w.filter((y)=>y.isDirectory()).length,()=>0)))).reduce((p,w)=>p+w,0)}function T0(){let[d=0]=b0(),u=process.platform==="win32"?void 0:Math.round(d*10)/10;return{cores:w0(),memoryGb:Math.round(_a()/1073741824*10)/10,...u===void 0?{}:{load:u}}}function lb(d){let u=cb();return async()=>{let p=cb(),w=Oa(p.busy-u.busy,p.total-u.total);u=p;let[y,v]=await Promise.all([$0().catch(ub),I0(d())]);return{cpuPct:w,memoryPct:y,worktrees:v,at:new Date().toISOString(),...T0()}}}function pb(d,u,p){if(!d)return!0;return Math.abs(d.cpuPct-u.cpuPct)>=3||Math.abs(d.memoryPct-u.memoryPct)>=2||Math.abs((d.load??0)-(u.load??0))>=Math.max(1,(u.cores??10)/10)||d.worktrees!==u.worktrees||Date.parse(u.at)-Date.parse(d.at)>=p}var E0=300000;function hb(d,u=!1){if(!d.node)return Promise.resolve();let p={away:d.away.state,setup:d.setup.state,claudeUpdate:d.claudeUpdates.state,selfUpdate:d.selfUpdate?.state,sessionsAsAgent:$c(),projectSetups:d.places.setups.list(),usage:d.usage,disk:C0(d.diskCleanup.state,d.serverVersion)},w=u?Ic(d.state.name):Promise.resolve({});w.catch(()=>{return});let y=d.nodePushes.then(async()=>{let v=await w;if(!d.node)return;d.node=d.withMonitors({...d.node,...v,...p,lastSeenAt:new Date().toISOString()}),d.push({type:"node.updated",node:d.node})});return d.nodePushes=y.catch(()=>{return}),y}function C0(d,u){let p=d?.lastCleanup;if(!d||!p||u&&!nt(u,H))return d;let w=p.steps.filter((y)=>qh.includes(y.step));return{...d,lastCleanup:{...p,steps:w}}}async function mb(d){try{let u=await d.measureUsage();if(!pb(d.usage,u,E0))return;d.usage=u,await d.pushNode()}catch(u){s.warn("machine: couldn't measure its usage",u)}}function fb(d,u){let{monitors:p,...w}=u.capabilities;return{...u,capabilities:{...w,...d.monitors?.length?{monitors:d.monitors}:{}}}}function gb(d){return d.monitorsCheck??=(async()=>{if(!d.node||d.node.kind==="sandbox")return;let u=d.node.capabilities.screen?await Fo().catch((p)=>(s.warn("screen: couldn't list the monitors",p),d.monitors)):void 0;if(JSON.stringify(u)===JSON.stringify(d.monitors))return;d.monitors=u,await d.pushNode()})().finally(()=>{d.monitorsCheck=void 0}),d.monitorsCheck}async function wb(d){if(!d.node||d.node.kind==="sandbox")return;if(await gc().catch(()=>d.node?.capabilities.screen)===d.node.capabilities.screen)return;await d.pushNode(!0),await d.recheckMonitors()}function yb(d){let{home:u,screen:p}=m();try{d.screenWatch=R0(u,(w,y)=>{if(y?.toString()===A0(p))d.recheckScreen()}),d.screenWatch.unref()}catch(w){s.warn("screen: couldn't watch screen.json",w)}}async function kb(d){if(!await d.gate.apply(await d.projects.globalSettings()).catch((y)=>s.warn("network: couldn't apply the server's network settings",y)))return;let p={localName:await Tu(),addresses:await Pu()},w=JSON.stringify(p);if(w===d.networkSaid)return;d.networkSaid=w,d.push({type:"machine.network",network:p})}async function bb(d){return d.virtualMachine??=_c(),pc(await fc(),await d.virtualMachine)}import{writeFileSync as O0}from"fs";import{tmpdir as x0}from"os";import{join as M0}from"path";var j0=1e4,L0=900000,N0=3000,vb=Number.NEGATIVE_INFINITY;async function $b(d=F0){let u=await d.probe();if(u.probe==="ok")return{state:"ok"};if(u.probe==="failed")return{state:"no-audio",detail:u.detail??""};if(d.now()-vb<L0)return s.warn("coreaudio: the audio server still hangs; it was restarted a few minutes ago"),{state:"hung",restarted:!1,reason:"restarted recently"};let p=await d.pid();if(p===void 0)return s.warn("coreaudio: the audio server hangs, and no coreaudiod is running to restart"),{state:"hung",restarted:!1,reason:"no coreaudiod"};if(vb=d.now(),!await d.restart(p))return s.warn(`coreaudio: the audio server hangs, and coreaudiod (pid ${p}) couldn't be ended`),{state:"hung",restarted:!1,reason:"kill failed"};await d.settle();let w=(await d.probe()).probe==="ok";if(w)s.warn(`coreaudio: the audio server hung; restarted coreaudiod (pid ${p}), it plays again`);else s.warn(`coreaudio: the audio server hung; restarted coreaudiod (pid ${p}), it still doesn't play`);return{state:"hung",restarted:!0,pid:p,recovered:w}}function D0(){let p=new DataView(new ArrayBuffer(1644)),w=(y,v)=>{for(let S=0;S<v.length;S++)p.setUint8(y+S,v.charCodeAt(S))};return w(0,"RIFF"),p.setUint32(4,1636,!0),w(8,"WAVE"),w(12,"fmt "),p.setUint32(16,16,!0),p.setUint16(20,1,!0),p.setUint16(22,1,!0),p.setUint32(24,8000,!0),p.setUint32(28,16000,!0),p.setUint16(32,2,!0),p.setUint16(34,16,!0),w(36,"data"),p.setUint32(40,1600,!0),new Uint8Array(p.buffer)}async function U0(d=j0){let u=M0(x0(),"superfactory-audio-probe.wav");O0(u,D0());let p=await g(r(Qd).flag("-v","0").arg(u).timeoutMs(d).by("coreaudio.probe").build());if(p.timedOut)return{probe:"hung"};if(p.exitCode!==0)return{probe:"failed",detail:`afplay exited ${p.exitCode}: ${p.stderr.trim().slice(0,300)}`};return{probe:"ok"}}async function Sb(){let d=await g(r($r).flag("-x").arg("coreaudiod").timeoutMs(1e4).build()),u=Number(d.stdout.trim().split(`
|
|
201
|
+
`)[0]);return d.exitCode===0&&Number.isInteger(u)&&u>1?u:void 0}async function Pb(d,u){return(await g(r(A).flag("-n").wrap(r(Js).flag("-s",u).arg(String(d)).build()).timeoutMs(1e4).by("coreaudio.restart").build())).exitCode===0}var F0={probe:()=>U0(),pid:Sb,restart:async(d)=>{if(!await Pb(d,"TERM"))return!1;for(let u=0;u<20;u++){if(await Sb()!==d)return!0;await Bun.sleep(100)}return Pb(d,"KILL")},settle:()=>Bun.sleep(N0),now:()=>Date.now()};import{homedir as B0}from"os";import{join as W0}from"path";var Ib=".simruntime/Contents/Resources/RuntimeRoot/",Ql="[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}",H0=new RegExp(`/${Ql}/data/Containers/Bundle/Application/`),G0=new RegExp(`(?:^|\\s)SIMULATOR_UDID=(${Ql})(?=\\s|$)`),q0=new RegExp(`^launchd_sim (\\S.*?)/(${Ql})/data/`),Tb=3000,V0=60000,Y0=180000,K0=1800000;function Q0(d){let[u,p]=d.includes("-")?d.split("-"):["0",d],w=(p??"").split(":").map(Number);while(w.length<3)w.unshift(0);let[y=0,v=0,S=0]=w;return(((Number(u)*24+y)*60+v)*60+S)*1000}function J0(d){return(d.split(Ib)[1]??d.split("/Containers/Bundle/Application/")[1]??d).split(" ")[0]?.split("/").pop()||"?"}function z0(d,u){return d.split(`
|
|
202
|
+
`).flatMap((p)=>{let w=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+([\d.,]+)\s+(\S+)\s+(.*)$/.exec(p);if(!w)return[];let[,y,v,S,x,j,L=""]=w,N=q0.exec(L);return[{pid:Number(y),ppid:Number(v),uid:Number(S),cpu:Number((x??"0").replace(",",".")),startedAt:u-Q0(j??""),name:J0(L),simulator:L.includes(Ib)||H0.test(L),udid:G0.exec(L)?.[1],launchd:N?.[1]&&N[2]?{set:N[1],udid:N[2]}:void 0}]})}function X0(d){let u=d.flatMap((w)=>w.launchd?[{pid:w.pid,uid:w.uid,...w.launchd,bootedAt:w.startedAt}]:[]);return{orphans:d.filter((w)=>{if(w.ppid!==1||w.launchd||!(w.simulator||w.udid))return!1;let y=w.udid&&u.find((v)=>v.udid===w.udid);return!y||w.startedAt<y.bootedAt-Tb}),devices:u}}var Z0=(d)=>d.cpu>=1?`${d.name} ${Math.round(d.cpu)}%`:d.name;class Jl{deps;suspects=new Map;constructor(d){this.deps=d}async check(){let d=this.deps.now(),{orphans:u,devices:p}=X0(z0(await this.deps.ps(),d)),w={ended:[],shutDown:[]},y=u.filter((v)=>Math.abs((this.suspects.get(v.pid)??Number.NaN)-v.startedAt)<=Tb);this.suspects=new Map(u.map((v)=>[v.pid,v.startedAt]));for(let v of new Set(y.map((S)=>S.uid))){let S=y.filter((N)=>N.uid===v),x=v!==this.deps.uid;if(x&&!this.deps.root)continue;let j=S.map((N)=>N.pid);if(!await this.deps.kill(j,x)){s.warn(`simulators: couldn't end ${j.length} orphaned simulator processes of uid ${v}`);continue}for(let N of j)this.suspects.delete(N);let L=[...S].sort((N,B)=>B.cpu-N.cpu).slice(0,3).map(Z0);w.ended.push({uid:v,pids:j,top:L}),this.deps.note(`simulators: ended ${j.length} orphaned iOS simulator processes of uid ${v} (their launchd_sim gone, PPID 1; busiest: ${L.join(", ")})`)}if(p.length&&await this.deps.shutsDown())w.shutDown=await this.shutDownLeftovers(p,d);return w}async shutDownLeftovers(d,u){let w=(await this.deps.work()).filter((v)=>v.endedAt===void 0||u-v.endedAt<K0),y=[];for(let v of d){if(v.uid!==this.deps.uid||v.set!==this.deps.deviceSet)continue;if(u-v.bootedAt<Y0)continue;if(w.some((x)=>x.startedAt<=v.bootedAt+V0))continue;if(!await this.deps.shutdown(v.udid)){s.warn(`simulators: couldn't shut down ${v.udid}, left booted`);continue}y.push(v.udid);let S=Math.round((u-v.bootedAt)/360000)/10;this.deps.note(`simulators: shut down ${v.udid}, booted ${S} h ago by work that has ended (launchd_sim ${v.pid})`)}return y}}var eA=()=>W0(B0(),"Library","Developer","CoreSimulator","Devices");function Rb(d){return{...d,ps:async()=>(await g(r(oe).flag("-E").flag("-axww").flag("-o","pid=,ppid=,uid=,pcpu=,etime=,command=").timeoutMs(15000).maxOutputBytes(67108864).build())).stdout,uid:process.getuid?.()??-1,kill:async(u,p)=>{let w=r(Js).flag("-s","KILL").argsOf(u.map(String)).timeoutMs(15000).build();return(await g(p?r(A).flag("-n").wrap(w).timeoutMs(15000).by("simulators.orphans").build():w)).exitCode===0},shutdown:async(u)=>(await g(r(es).sub("simctl shutdown").arg(u).timeoutMs(60000).by("simulators.shutdown").build())).exitCode===0,deviceSet:eA(),now:()=>Date.now()}}import{existsSync as Cb,readFileSync as Ab,statSync as tA,watch as sA}from"fs";import{isAbsolute as Eb,join as ln}from"path";var nA=500;class zl{moved;watched=new Map;due=new Map;constructor(d){this.moved=d}sync(d){let u=new Set(d.map((p)=>p.id));for(let[p,w]of this.watched)if(!u.has(p)||d.find((y)=>y.id===p)?.path!==w.path)this.unwatch(p);for(let{id:p,path:w}of d)if(!this.watched.has(p))this.watch(p,w)}close(){for(let d of[...this.watched.keys()])this.unwatch(d)}watch(d,u){let p=iA(u),w=[];if(this.watched.set(d,{path:u,watchers:w}),!p)return;let y=(S)=>{let x=S?.replaceAll("\\","/")??"";if(!x.endsWith(".lock")&&!/(^|\/)sf\//.test(x))this.soon(d)},v=(S,x,j)=>{try{let L=sA(S,{recursive:x},(N,B)=>{if(!j||B&&j.includes(B))y(B)});L.on("error",()=>L.close()),L.unref(),w.push(L)}catch(L){s.warn(`repo watch: couldn't watch ${S}`,L)}};if(Cb(ln(p,"refs")))v(ln(p,"refs"),!0);v(p,!1,["packed-refs","HEAD"])}unwatch(d){for(let u of this.watched.get(d)?.watchers??[])u.close();this.watched.delete(d),clearTimeout(this.due.get(d)),this.due.delete(d)}soon(d){if(this.due.has(d))return;let u=setTimeout(()=>{this.due.delete(d),this.moved(d)},nA);u.unref?.(),this.due.set(d,u)}}function iA(d){let u=ln(d,".git");try{if(tA(u).isDirectory())return u;let p=Ab(u,"utf8").match(/^gitdir: (.+)$/m)?.[1]?.trim();if(!p)return;let w=Eb(p)?p:ln(d,p),y=Cb(ln(w,"commondir"))?Ab(ln(w,"commondir"),"utf8").trim():".";return Eb(y)?y:ln(w,y)}catch{return}}var as=60000;function _b(d){let u=d.periodic;u.every("places: sandboxes left behind",k("SUPERFACTORY_SANDBOX_SWEEP_MS",10*as),()=>d.removeOrphanSandboxes(),{firstAfterMs:0}),d.finishedTasks.sweep(),u.every("finished tasks: sweep",k("SUPERFACTORY_FINISHED_SWEEP_MS",5*as),()=>Promise.all([d.finishedTasks.sweep(),d.macos.sweep()]));let p=process.env.SUPERFACTORY_PREPARE_SANDBOX_IMAGE;if(p)rf(p).catch((y)=>s.warn("sandboxes: couldn't prepare the image",y));d.setup.run().then(()=>d.setUpProjects()),Sc().catch((y)=>s.warn("disks: couldn't grow",y));let w=lc();if(w.dir||process.env.SUPERFACTORY_KEEP_USER_STORES!=="1")u.every("libraries: sweep",1440*as,()=>d.prepareLibraries().then(()=>om(w)),{firstAfterMs:0});if(u.every("libraries: package caches",k("SUPERFACTORY_MIRROR_CHECK_MS",5*as),()=>d.projects.globalSettings().then(nm).then(()=>d.prepareLibraries()),{firstAfterMs:0}),!process.env.SUPERFACTORY_SANDBOX){let y=k("SUPERFACTORY_DISK_CHECK_MS",5*as);if(process.env.SUPERFACTORY_KEEP_DISK!=="1")u.every("disk: cleanup",y,()=>d.diskCleanup.check(),{firstAfterMs:Math.min(as,y)});let v=k("SUPERFACTORY_USAGE_CHECK_MS",as);u.every("usage",v,()=>d.checkUsage(),{firstAfterMs:Math.min(5000,v)})}if(process.platform==="darwin"||process.env.SUPERFACTORY_TART_ANYWHERE==="1")u.every("tart: the server's VMs keep running",k("SUPERFACTORY_TART_KEEP_MS",as),()=>d.tartVms.keepRunning(),{firstAfterMs:0});if(process.platform==="darwin"&&!X())u.every("coreaudio",k("SUPERFACTORY_COREAUDIO_CHECK_MS",3*as),async()=>{if(await d.dedicated())await $b()},{firstAfterMs:30000});if(process.platform==="darwin"){let y=new Jl(Rb({root:!X(),shutsDown:async()=>!X()&&await d.dedicated(),work:async()=>[...(await d.sessions.list()).filter((v)=>v.state!=="exited"&&v.state!=="failed").map((v)=>({startedAt:Date.parse(v.startedAt)})),...d.commandRuns.spans()],note:Ol}));u.every("simulators",k("SUPERFACTORY_SIMULATOR_CHECK_MS",20000),()=>y.check(),{firstAfterMs:1e4})}u.every("network",30000,()=>Promise.all([d.applyNetwork(),d.recheckScreen()])),d.watchScreenFile(),d.repoWatch=new zl((y)=>void d.checkRepoConfigs([y]).catch((v)=>s.warn(`repo config: couldn't check ${y}'s default branch`,v))),xa(d),u.every("repo config",k("SUPERFACTORY_REPO_CONFIG_CHECK_MS",10*as),()=>(xa(d),d.checkRepoConfigs()))}function Ob(d){d.periodic.stopAll(),d.repoWatch?.close(),d.screenWatch?.close()}function xa(d){d.repoWatch?.sync(d.projects.ids().map((u)=>({id:u,path:d.projects.path(u)})))}async function xb(d){await d.places.removeEnded().catch((p)=>s.warn("places: checking for stopped sandboxes failed",p));let u=(await d.sessions.list()).filter((p)=>p.state!=="exited"&&p.state!=="failed").map((p)=>p.cwd);await d.places.displays.closeIdle(new Set([...u,gl])).catch((p)=>s.warn("displays: closing idle ones failed",p));for(let p of d.projects.ids()){let w=await(async()=>{let y=await d.projects.get(p),v=(await d.tasks.list(p)).filter((N)=>!pe(N)).map((N)=>N.id),S=(await d.sessions.list(p)).filter((N)=>N.state!=="exited"&&N.state!=="failed").map((N)=>N.runner),x=await d.projects.settings(p),j=(await d.sessions.list(p)).filter((N)=>N.state!=="exited"&&N.state!=="failed"&&N.taskId).map((N)=>N.taskId),L=await ns.sweep(p,new Set([...v,...j]));if(L.length)s.info(`session temp: removed ${L.join(", ")}`);return[...await d.places.removeUnused(p,new Set(S)),...await d.places.reconcile(y,x,new Set(v))]})().catch((y)=>(s.warn(`places: checking ${p}'s sandboxes failed`,y),[]));if(w.length)s.info(`places: removed sandboxes left behind: ${w.join(", ")}`)}}async function Mb(d,u=d.projects.ids()){let p=await d.sessionsConfined().catch(()=>!0);for(let w of u){let y=d.projects.path(w),v=(await d.projects.settings(w).catch(()=>{return}))?.["git.baseBranch"],S=!1;if(p)S=await rA(d,w,y,v);else S=!!await Yp(y,v).catch((L)=>{s.warn(`repo config: couldn't catch ${w}'s default branch up with its remote`,L);return});let x=await d.projects.repoConfigs.seen(w,y,v).catch(()=>{return}),j=d.repoTips.has(w)?d.repoTips.get(w):d.projects.repoConfigs.lastRead(w);if(d.repoTips.set(w,x),j===x)continue;if(d.push({type:"project.updated",project:await d.projects.get(w)}),S)d.setUpProject(w).catch((L)=>s.warn(`project setup: ${w} after its default branch moved`,L))}}var Zl=new Map;async function rA(d,u,p,w){let y=(w||await ge(p)).replace(/^origin\//,""),[v,S]=await Promise.all([dt(p,`refs/heads/${y}`),dt(p,`refs/remotes/origin/${y}`)]);if(!S||S===v)return d.projects.repoConfigs.setRemote(u,y,void 0),Zl.delete(u),!1;if(Zl.get(u)===S)return!1;Zl.set(u,S);let x=await wm(u,p,w).catch((L)=>{s.warn(`repo config: couldn't read ${u}'s default branch from its remote: ${L.message}`);return});if(!x||x.commit===v)return d.projects.repoConfigs.setRemote(u,y,void 0),!1;let j=await x.files.read(me);return d.projects.repoConfigs.setRemote(u,y,{commit:x.commit,bytes:j}),!0}import{hostname as aA}from"os";function jb(d){return async(u,p,w,y,v)=>{if(v?.machine?.name)d.serverName=v.machine.name;if(u==="coordinator")await Kf();let S=y&&d.sessions.managerOf(y),x=p&&await d.projects.settings(p.id),j=(x??await d.projects.globalSettings())["instructions.platform"];return Yf(u,p,w,{platformInstructions:j,userInstructions:v?.instructions,machine:v?.machine,machines:v?.machines,machineNote:[Tl(),!y||y.runner==="host"?u!=="coordinator"&&_m(await ce())||mm(u,x??await d.projects.globalSettings()):""].filter(Boolean).join(`
|
|
203
|
+
|
|
204
|
+
`),manager:S&&{...S,...d.managers.team(S),instructions:await d.instructions.text({scope:S.scope,managerId:S.id})},projects:p?void 0:await d.projects.list(),machineSession:S?.type==="machine"&&y?{machine:v?.machine?.name??d.node?.name??aA(),cwd:y.cwd}:void 0,informed:p&&u!=="coordinator"?d.managers.forProject(p.id):void 0,teammate:y?.teammate,preview:p&&w&&x?await d.previewPlanFor(p,x,y):void 0,ready:p&&x?.["github.sync"]&&x["github.draft"]&&x["git.flow"]!=="direct"?await yi(p.path):void 0,leadApproves:u==="coordinator"&&!!p&&!S?.area&&Zc(x),video:x?.["videos.beforeAfter"]===!0,videoSkill:x?im(x):void 0,dependencies:y&&d.places.dependencies.promptLine(y.cwd),parentClosed:p&&w?.buildsOn?!Dn(await d.tasks.get({projectId:p.id,taskId:w.buildsOn}).catch(()=>{return})):void 0,bundle:p&&w?.bundle?Ct(await d.tasks.list(p.id),w.bundle.id):void 0})}}import{appendFile as gA,readFile as wA}from"fs/promises";var dA=new Set(["superfactory"]),cA=3000;function uA(){return k("SUPERFACTORY_WATCH_BATCH_MS",cA)}var lA=900000;function pA(){return k("SUPERFACTORY_DIGEST_MS",lA)}var ep=30,ps=4,ip=12;class op{batchMs;now;digestEvery;sources=[];batches=new Map;digests=new Map;chain=new Map;told=new Set;sent=new Map;changesOf;constructor(d=uA(),u=()=>Date.now(),p=pA()){this.batchMs=d;this.now=u;this.digestEvery=p}useChanges(d){this.changesOf=d}addSource(d){this.sources.push(d)}emit(d){this.deliver(d).catch((u)=>s.warn(`watch: ${d.type} on ${d.projectId} not delivered`,u))}woke(d,u){this.chain.set(d,u)}depthOf(d){return this.chain.get(d)??0}onEvent(d,u){if(u.type!=="user_message"||dA.has(u.author))return;this.chain.delete(d.id),this.told.delete(d.id)}async deliver(d){let u=d.depth??(d.actor?this.depthOf(d.actor):0),w=(await Promise.all(this.sources.map((v)=>v(d.projectId)))).flat().filter((v)=>v.id!==d.actor&&v.id!==d.told&&Lb(v,d));await this.addChanges(d,w);let y=w.filter((v)=>Nb(v,d));if(u>=ps){s.info(`watch: ${d.type} not sent on (${u} wake-ups in a row)`);for(let v of y)if(v.stopped&&!this.told.has(v.id))this.told.add(v.id),v.stopped(d.text);return}for(let v of y)if(d.digest)this.gather(v,d,d.digest,d.text,u+1);else this.queue(v,v.line?.(d)??d.text,u+1)}gather(d,u,p,w,y){let v=this.digests.get(d.id);if(v){v.lines.delete(p),v.lines.set(p,w),v.latest.set(u.projectId,u),v.depth=Math.max(v.depth,y),v.watcher=d;return}let S=setTimeout(()=>void this.flushDigest(d.id),this.digestEvery),x=new Map([[u.projectId,u]]);this.digests.set(d.id,{watcher:d,latest:x,lines:new Map([[p,w]]),depth:y,timer:S})}async flushDigest(d){let u=this.digests.get(d);if(this.digests.delete(d),!u)return;let p=await this.stillWatching(d,u.latest).catch(()=>{return});if(!p)return;let w=[...u.lines.values()],y=w.slice(0,ep).join(", "),v=w.length>ep?` and ${w.length-ep} more`:"",S=Na([`Tasks changed since you last looked (id and new status; task_find or task_get if one matters): ${y}${v}.`]);p.wake(S,u.depth).catch((x)=>s.warn(`watch: couldn't send ${d} its digest`,x))}async stillWatching(d,u){for(let[p,w]of u){let v=(await Promise.all(this.sources.map((S)=>S(p)))).flat().find((S)=>S.id===d&&Lb(S,w)&&Nb(S,w));if(v)return v}return}async addChanges(d,u){if(d.files||d.changes||!d.taskId||!this.changesOf)return;if(!u.some((w)=>w.area?.paths.length))return;let p={projectId:d.projectId,taskId:d.taskId};d.changes=await this.changesOf(p).catch(()=>{return})}repeated(d,u){if(!d.dedupeMs)return!1;let p=d.key??d.id,w=this.sent.get(p)??new Map;this.sent.set(p,w);let y=this.now();for(let[v,S]of w)if(y-S>(d.dedupeMs??0))w.delete(v);if(w.has(u))return!0;return w.set(u,y),!1}queue(d,u,p){if(this.repeated(d,u)){s.info(`watch: ${d.key??d.id} was already told: ${u.slice(0,80)}`);return}let w=this.batches.get(d.id);if(w){if(!w.lines.includes(u))w.lines.push(u);w.depth=Math.max(w.depth,p),w.watcher=d;return}let y=setTimeout(()=>this.flush(d.id),this.batchMs);this.batches.set(d.id,{watcher:d,lines:[u],depth:p,timer:y})}flush(d){let u=this.batches.get(d);if(this.batches.delete(d),!u)return;u.watcher.wake(Na(u.lines),u.depth).catch((p)=>s.warn(`watch: couldn't wake ${d}`,p))}stop(){for(let d of this.batches.values())clearTimeout(d.timer);this.batches.clear();for(let d of this.digests.values())clearTimeout(d.timer);this.digests.clear()}}function Na(d){let u=d.slice(0,ip).map((p)=>`- ${p}`);if(d.length>ip)u.push(`- and ${d.length-ip} more like these`);return`What happened on what you listen to:
|
|
205
|
+
${u.join(`
|
|
206
|
+
`)}
|
|
207
|
+
Look at it if it concerns your role; otherwise reply only: ok.`}var hA=(d)=>d.files??d.changes?.map((u)=>u.path),mA=(d,u)=>new Bun.Glob(d).match(u);function Lb(d,u){if(d.onlyTask&&u.taskId!==d.onlyTask)return!1;return d.subscriptions.some((p)=>fA(p,u))||!!d.alsoWhen?.(u)}function Nb(d,u){if(!d.area)return!0;let p={labels:u.labels,text:u.about??u.text,files:hA(u)};return Sa(d.area,p,mA)}function fA(d,u){if(d.event!==u.type||u.approve)return!1;if(d.taskIds.length&&(!u.taskId||!d.taskIds.includes(u.taskId)))return!1;if(d.labels.length&&!d.labels.some((p)=>u.labels?.includes(p)))return!1;if(d.filePattern&&u.files){let p=new Bun.Glob(d.filePattern);return u.files.some((w)=>p.match(w))}return!0}var Db=240,yA=(d)=>d.split(`
|
|
208
|
+
`).map((u)=>u.length>Db?`${u.slice(0,Db-3)}...`:u).join(`
|
|
209
|
+
`),kA=1800000,up=4;function bA(d,u){let w=(d.changes??d.files?.map((S)=>({path:S}))??[]).filter((S)=>u.paths.some((x)=>new Bun.Glob(x).match(S.path)));if(!w.length)return d.text;let y=w.slice(0,up).map((S)=>S.additions===void 0?S.path:`${S.path} (+${S.additions} -${S.deletions})`),v=w.length>up?` and ${w.length-up} more`:"";return`${d.text} In your area: ${y.join(", ")}${v}.`}var vA=(d)=>d.split(`
|
|
210
|
+
`).filter((u)=>u.startsWith("- ")).map((u)=>u.slice(2));function Fb(d,u,p,w,y=async()=>!1){let v=async(S,x,j)=>{if(!await p.take(S)){p.hold(S.id,x,(B)=>{let G=d.get(S.id);if(G)v(G,B,j).catch((V)=>s.warn("watch: held events lost",V))});return}let L=Na([...p.takeHeld(S.id),...x]),N=await kn(u(),S,Wp(yA(L))).catch((B)=>{throw p.giveBack(S.id),B});w.woke(N,j),p.expect(N,S,L,!0)};return async(S)=>{let x=d.forProject(S),j=await y(S).catch(()=>!1),L=x.find((N)=>N.main&&N.scope.kind==="project")??x.find((N)=>N.main);return x.filter((N)=>ed(N.events).length||N===L).map((N)=>({id:u().ofManager(N.id)?.session.id??`manager:${N.id}`,key:`manager:${N.id}`,subscriptions:ed(N.events),area:N.area,line:(B)=>N===L&&B.approve&&!j&&B.userApproves?B.userApproves:N.area?.paths.length?bA(B,N.area):B.text,dedupeMs:kA,...N===L?{alsoWhen:(B)=>SA(B)||j&&!!B.approve}:{},wake:(B,G)=>v(N,vA(B),G),stopped:(B)=>{let G=u().ofManager(N.id);if(G)u().recordEvent(G.session.id,PA(B))}}))}}var SA=(d)=>(d.type==="task_ready"||d.type==="task_done")&&!!d.waiting?.length||d.type==="task_stuck"&&!!d.ownAgent,PA=(d)=>({type:"notice",level:"info",kind:"wake_chain_stopped",text:`Not woken: ${ps} wake-ups in a row with no person between them (last: ${d.slice(0,120)}).`});async function kn(d,u,p,w){let y=d.ofManager(u.id);if(y)return await d.send(y.session.id,p,"superfactory",{relay:w}),y.session.id;return(await d.start({kind:"coordinator",projectId:u.scope.kind==="project"?u.scope.projectId:void 0,managerId:u.id,prompt:p,relay:w,settings:{server:{},user:{}}})).id}var Ub=86400000;class pp{waiting=new Map;days=new Map;held=new Map;file=()=>m().wakeCosts;expect(d,u,p,w=!1){let y=p.split(`
|
|
211
|
+
`).filter((S)=>S.startsWith("- ")).length,v=this.waiting.get(d)?.events??0;if(this.waiting.set(d,{manager:u,events:v+y}),!w)this.counted(u)}counted(d){let u=this.days.get(d.id);if(u?.day===Da(Date.now()))u.count++}async today(d){let u=Da(Date.now()),p=this.days.get(d);if(p?.day===u)return p.count;let w=(await this.wakes()).filter((v)=>v.managerId===d&&Da(Date.parse(v.at))===u).length,y=this.days.get(d);if(y?.day===u)return y.count;return this.days.set(d,{day:u,count:w}),w}async take(d){await this.today(d.id);let u=this.days.get(d.id)?.count??0;if(d.wakeBudget!==void 0&&u>=d.wakeBudget)return!1;return this.counted(d),!0}giveBack(d){let u=this.days.get(d);if(u?.day===Da(Date.now())&&u.count>0)u.count--}hold(d,u,p){let w=this.held.get(d);if(w){w.lines=[...new Set([...w.lines,...u])].slice(-50);return}let y=new Date;y.setHours(24,0,1,0);let v=setTimeout(()=>{let S=this.takeHeld(d);if(S.length)p(S)},y.getTime()-Date.now());this.held.set(d,{lines:[...u],timer:v}),s.info(`watch: ${d}'s wake budget is spent: events wait for tomorrow`)}takeHeld(d){let u=this.held.get(d);if(!u)return[];return clearTimeout(u.timer),this.held.delete(d),u.lines}stop(){for(let d of this.held.values())clearTimeout(d.timer);this.held.clear()}onEvent(d,u){if(u.type!=="result")return;let p=this.waiting.get(d.id);if(!p)return;this.waiting.delete(d.id);let w=u.usage;s.info(`watch: ${p.manager.name} read ${p.events} event(s): ${w?`${w.outputTokens} output tokens, ${w.inputTokens} input, ${w.cacheReadTokens} cache read, ${w.cacheCreationTokens} cache write`:"no usage reported"}${u.costUsd===void 0?"":`, $${u.costUsd.toFixed(4)}`}`);let y={managerId:p.manager.id,at:u.ts,events:p.events,outputTokens:w?.outputTokens,costUsd:u.costUsd};gA(this.file(),`${JSON.stringify(y)}
|
|
212
|
+
`).catch((v)=>s.warn("watch: wake cost not kept",v))}async wakes(){return(await wA(this.file(),"utf8").catch(()=>"")).split(`
|
|
213
|
+
`).filter(Boolean).flatMap((u)=>{try{return[JSON.parse(u)]}catch{return[]}})}async estimate(d,u=Date.now()){let p=u-7*Ub,w=(await this.wakes()).filter((x)=>x.managerId===d&&Date.parse(x.at)>=p),y=Math.min(...w.map((x)=>Date.parse(x.at)),u),v=Math.min(7,Math.max(1,Math.ceil((u-y)/Ub))),S=w.reduce((x,j)=>x+(j.costUsd??0),0);return{wakeUpsPerDay:w.length/v,usdPerDay:S/v,days:v,today:await this.today(d),held:this.held.get(d)?.lines.length??0}}}var Da=(d)=>new Date(d).toLocaleDateString("sv");var $A=15000;function IA(){return k("SUPERFACTORY_PLATFORM_STEP_MS",$A)}class mp{deps;constructor(d){this.deps=d}mayRelease(d){return this.deps.mayRelease(d)}async use(d,{ref:u,lead:p},w,y,v){let S=this.withCode(d,{ref:u,lead:p},w,y);if(!v||w.op==="list")return S;let x,j=setInterval(()=>{this.deps.use({sessionId:d,...p?{task:u}:{},target:y,request:{op:"list"}}).then(({platforms:L})=>{let N=L.find((G)=>G.step&&$a(G,y));x=N?.step??x;let B=Math.round((Date.now()-Date.parse(N?.stepAt??""))/1000)||0;if(N?.step)v(N.step,B,N.setup)}).catch(()=>{return})},IA());try{return await S}catch(L){if(x!=="running"||!(L instanceof c)||L.code!=="unavailable")throw L;throw new c("unavailable",`${L.message} (while running the command: it may still run there, command_list shows it)`)}finally{clearInterval(j)}}async withCode(d,{ref:u,lead:p},w,y){if(p)return this.deps.use({sessionId:d,task:u,target:y,request:w});let v=await this.deps.use({sessionId:d,target:y,request:{op:"list"}});if(w.op==="list")return v;let S=v.platforms.flatMap((j)=>j.code?[j.code.commit]:[]),x=w.op==="screen"||w.op==="view"||w.op==="copy"?void 0:await this.code(d,u,S,!1);try{return await this.deps.use({sessionId:d,target:y,request:w,code:x})}catch(j){if(!x||!/needs a full bundle/.test(String(j)))throw j;return this.deps.use({sessionId:d,target:y,request:w,code:await this.code(d,u,S,!0)})}}async code(d,u,p,w){let{cwd:y,sandbox:v}=this.deps.placeOf(d,u),S=u.taskId,{commit:x,uncommitted:j}=await Rm(y,S,v),L=p.includes(x)&&!w?void 0:await Om(y,S,p,w);if(L)await this.deps.uploadBundle(u,x,L);return{commit:x,uncommitted:j,bundle:L!==void 0}}}function Bb(d,u){return{projects:d.projects,tasks:d.tasks,questions:d.questions,chatQuestions:d.chatQuestions,uploadMedia:(p,w,y)=>d.uploadMedia(p,w,y),serverMedia:{list:async(p)=>{let w=d.httpLink();return w?ch(w,p):void 0},download:async(p,w,y)=>{let v=d.httpLink();if(!v)throw Error("this machine isn't linked to a server");await dh(v,p,w,y)}},recordTest:(p,w,y)=>d.recordTest(p,w,y),readyRuns:d.readyRuns,offPr:(p)=>d.github.offPrForReview(p),withLivePr:(p)=>d.github.withLivePr(p),markPrReady:(p,w)=>d.github.markReady(p,w),startTask:async(p,w,y,v,S,x)=>await d.placed.start({by:y,projectId:p,taskId:w,ownSession:v,retrySetup:S,restart:x})??d.sessions.start({projectId:p,taskId:w,kind:"task",ownSession:v,retrySetup:S,restart:x,origin:{kind:"session",sessionId:y},leadSecretEnv:d.sessions.leadSecretsFrom(y,p)}),placed:d.placed,setPreviews:async(p,w)=>{let y=await d.sessions.setPreviews(p,w);return d.previewsChanged(p,y),y},checkPreview:(p,w,y,v)=>d.sessions.checkPreview(p,w,y,v),instructions:d.instructions,managers:d.managers,notifyUser:(p)=>{u({type:"manager.notified",notification:p}),d.sessions.recordEvent(p.sessionId,{type:"notice",level:"warning",kind:"important",text:p.text})},tellManager:async(p,w,y,v)=>{let S=d.watchers.depthOf(y)+1;if(S>ps*2)throw Error(`stopped: ${S-1} messages in a row with no person between them`);if(v&&!await d.wakeCosts.take(p))throw Error(`${p.name}'s wake budget for today is spent (${p.wakeBudget}): put it in your task's conversation with task_comment, or tell them tomorrow`);let x=await kn(d.sessions,p,w).catch((j)=>{if(v)d.wakeCosts.giveBack(p.id);throw j});if(d.watchers.woke(x,S),v)d.wakeCosts.expect(x,p,"",!0)},taskCoordinators:d.taskCoordinators,replies:d.replies,talk:d.talk,taskCreated:(p,w)=>d.sessions.recordEvent(p,{type:"task_created",projectId:w.projectId,taskId:w.id,title:w.title,kind:w.kind,status:w.status}),teams:d.teams,createProject:(p)=>d.serverLink().request("projects.create",p),platforms:new mp({use:(p)=>{if(p.request.op==="copy")je(d,"platform_copy needs","move the file with platform_run meanwhile");return d.serverLink().request("platforms.use",{...p,target:void 0,...ug(p.target)},p.request.op==="list"?void 0:((p.request.op==="run"?p.request.timeoutSeconds??bn:p.request.op==="copy"?fg:0)+1200)*1000)},uploadBundle:async(p,w,y)=>{let v=d.httpLink();if(!v)throw Error("not linked to a server");await ph(v,p,w,y)},placeOf:(p,w)=>({cwd:ee(d.projects.path(w.projectId),w.taskId),sandbox:d.sessions.sandboxFor(p)}),mayRelease:(p)=>d.sessions.mayRelease(p)}),screens:{screenOf:(p)=>d.sessions.screenOf(p),recordings:d.recordings},permissionRules:d.permissionRules,leadJoin:Df(async(p,w)=>(je(d,"Adding machines from a lead needs"),d.serverLink().request(p,w))),leads:{taskUpdate:(p)=>d.serverLink().request("leads.taskUpdate",p),bundle:async(p)=>(je(d,"Bundles need","start the tasks one by one (task_start)"),d.serverLink().request("leads.bundle",p)),unbundle:async(p)=>(je(d,"Bundles need","start the tasks one by one (task_start)"),d.serverLink().request("leads.unbundle",p)),settings:(p)=>d.serverLink().request("leads.settings",p),machines:(p)=>d.serverLink().request("leads.machines",p),machineRun:async(p)=>{if(p.root)je(d,"machine_run root needs");return d.serverLink().request("leads.machineRun",p,((p.timeoutSeconds??bn)+60)*1000)},machineScreen:(p)=>d.serverLink().request("leads.machineScreen",p,90000),machineUnlock:async(p)=>(je(d,"machine_unlock needs"),d.serverLink().request("leads.machineUnlock",p,120000)),machineRestart:async(p)=>(je(d,"machine_restart needs"),d.serverLink().request("leads.machineRestart",p,((p.waitSeconds??900)+900)*1000)),machinePower:async(p)=>(je(d,"machine_power needs"),d.serverLink().request("leads.machinePower",p,((p.waitSeconds??900)+300)*1000)),vm:async(p)=>{if(p.hypervisor)je(d,"vm_control's hypervisor needs");return d.serverLink().request("leads.vm",p,600000)},serverSettings:(p)=>d.serverLink().request("leads.serverSettings",p),dbQuery:async(p)=>(je(d,"sf db query needs"),d.serverLink().request("leads.dbQuery",p)),serverLog:async(p)=>(je(d,"server_log needs"),d.serverLink().request("leads.serverLog",p,120000)),auditLog:async(p)=>(je(d,"audit_log needs"),d.serverLink().request("leads.auditLog",p)),vmEvents:async(p)=>(je(d,"vm_events needs"),d.serverLink().request("leads.vmEvents",p,90000)),superfactoryTask:(p)=>d.serverLink().request("leads.superfactoryTask",p),taskRead:async(p)=>(je(d,"reading another machine's project's task needs","task_find shows it meanwhile"),d.serverLink().request("leads.taskRead",p)),taskList:async(p)=>(je(d,"listing another machine's project's tasks needs","task_find shows them meanwhile"),d.serverLink().request("leads.taskList",p,60000)),githubRead:async(p)=>(je(d,"github_read needs"),d.serverLink().request("leads.githubRead",p,60000)),deployRecord:async(p)=>(je(d,"`sf deploy record` needs"),d.serverLink().request("leads.deployRecord",p)),...Uf((p,w,y)=>(je(d,`${p} needs`),d.serverLink().request(p,w,y))),...Ff((p,w,y)=>d.serverLink().request(p,w,y),(p)=>je(d,p))},leadRequest:(p,w,y)=>(je(d,`${p} needs`),d.serverLink().request(p,w,y)),leadMachines:{projects:async(p)=>(je(d,"machine_projects needs"),d.serverLink().request("leads.machineProjects",p,300000)),update:async(p)=>(je(d,"machine_update needs"),d.serverLink().request("leads.machineUpdate",p,300000)),settings:async(p)=>(je(d,"machine settings need"),d.serverLink().request("leads.machineSettings",p,60000)),setup:async(p)=>(je(d,"machine_setup needs"),d.serverLink().request("leads.machineSetup",p,300000)),remove:async(p)=>(je(d,"machine_remove needs"),d.serverLink().request("leads.machineRemove",p,120000))},commands:{wait:(p)=>d.serverLink().request("runs.wait",p,(p.extendSeconds+60)*1000),stop:(p)=>d.serverLink().request("runs.stop",p,60000),output:(p)=>d.serverLink().request("runs.output",p,60000),list:(p)=>d.serverLink().request("runs.list",p,60000)},sessionSearch:{search:(p)=>d.serverLink().request("sessions.search",p)},taskFind:{find:(p)=>d.serverLink().request("tasks.find",p),similar:(p)=>d.serverLink().request("tasks.similar",p),why:async(p)=>(je(d,"task_why needs","task_find and session_search say much of it meanwhile"),d.serverLink().request("tasks.why",p))},moveSession:async(p)=>(je(d,"session_move needs"),d.serverLink().request("sessions.move",p,60000)),githubDispatch:async(p)=>(je(d,"workflow_dispatch needs"),d.serverLink().request("github.dispatch",p,60000)),secrets:{list:(p)=>d.serverLink().request("secrets.list",p),set:(p)=>d.serverLink().request("secrets.set",p),remove:(p)=>d.serverLink().request("secrets.remove",p),promote:(p)=>d.serverLink().request("secrets.promote",p)},shown:{show:async(p)=>(je(d,"secret_show and command_for_user need"),d.serverLink().request("secrets.show",p))},projectCards:{local:async(p)=>{let w=await d.projects.get(p);return{id:w.id,name:w.name,key:w.key,repoConfig:w.repoConfig}},all:async(p)=>(await d.serverLink().request("projects.configs",{sessionId:p})).projects},audit:(p)=>u({type:"mcp.audited",entry:p}),sessionMessages:d.sessionMessages,reports:d.reports,systemPermissions:d.systemPermissions}}async function Wb(d,u){return je(d,"`sf deploy exec` needs"),(await d.serverLink().request("leads.deployCredentials",{by:u})).env}function je(d,u,p){let w=d.serverVersion;if(w&&!nt(w,H))return;throw new c("conflict",`${u} the server at Superfactory ${H} or newer; it runs ${w??"a version not known yet"}${p?`: ${p}`:""}`)}import{appendFile as TA,realpath as RA}from"fs/promises";import{relative as AA}from"path";var Hb=(d=new Date)=>d.toLocaleDateString("sv-SE");var Gb=60000;class fp{projects;tasks;sessions;placed;projectChanged;mergeLocal;caffeinate;timer;sprints;repaired=new Set;constructor(d,u,p,w,y,v=async()=>{return}){this.projects=d;this.tasks=u;this.sessions=p;this.placed=w;this.projectChanged=y;this.mergeLocal=v;this.sprints=new Uu(d,u)}start(){this.repairApproved().then(()=>this.sweep()),this.timer=setInterval(()=>{this.sweep()},Gb)}async sweep(){for(let d of this.projects.ownIds())try{if(await this.sprints.rollOver(d))await this.projectChanged(d);await this.archiveApproved(d)}catch(u){s.warn(`automation: sweeping ${d} failed`,u)}}async archiveApproved(d){let u=await this.projects.settings(d);if(!u["tasks.autoArchive"])return;let p=Date.now()-u["tasks.archiveAfterHours"]*60*Gb,w=(y)=>y.status==="done"&&!y.archived&&!At(y)&&Date.parse(y.updatedAt)<=p;for(let y of await this.tasks.list(d))if(w(y))await this.tasks.updateIf({projectId:d,taskId:y.id},w,{archived:!0})}async repairApproved(){for(let d of this.projects.ownIds()){await this.tasks.caughtUp(d).catch(()=>{return});let u=await this.tasks.list(d).catch(()=>[]);for(let p of u){if(!p.archived||Ne.includes(p.status)||!ya(p))continue;let w=`${d}/${p.id}`;this.repaired.add(w);try{await this.tasks.update({projectId:d,taskId:p.id},{status:"done",archived:!0}),s.info(`automation: ${w} was approved but ${p.status}: done again`)}catch(y){this.repaired.delete(w),s.warn(`automation: couldn't repair ${w}`,y)}}}}stop(){clearInterval(this.timer),this.caffeinate?.kill()}async onTaskChange(d){let{task:u,previous:p}=d;if(await this.followEpic(d).catch((w)=>s.warn(`automation: ${u.epic}'s progress`,w)),p&&At(p)&&!At(u)&&u.status==="done")await this.archiveDone(u);if(!p||u.status===p.status)return;if(this.repaired.delete(`${u.projectId}/${u.id}`))return;if(u.status==="done")await this.mergeLocal(u).catch((w)=>s.warn(`automation: merging ${u.id} here failed`,w)),await this.finished(u),await this.mergeStacked(u);if(u.status==="done"||u.status==="cancelled")await this.startUnblocked(u)}async onTurnEnd(d,u){let{projectId:p,taskId:w}=d;if(u!=="error"||!p||!w)return;if(!(await this.projects.settings(p))["agents.escalate"]||this.sessions().failures(d.id)<2)return;let v=await this.sessions().escalate(d.id);if(v)await this.tasks.update({projectId:p,taskId:w},{level:v}),await this.tasks.appendNote({projectId:p,taskId:w},`Failed twice; moved up to the ${v} level.`)}async onSessionState(){if(process.platform!=="darwin")return;let d=this.sessions().busy().length>0&&await EA();if(d&&!this.caffeinate)this.caffeinate=_(r(Ks).flag("-i").flag("-w",process.pid).by("automation").build(),{stdin:"ignore",stdout:"ignore",stderr:"ignore"}),this.caffeinate.on("exit",()=>{this.caffeinate=void 0});else if(!d&&this.caffeinate)this.caffeinate.kill(),this.caffeinate=void 0}async followEpic({task:d,previous:u}){if(!d.epic||u?.status===d.status&&u.progress===d.progress)return;let p=(await this.tasks.list(d.projectId)).filter((x)=>x.epic===d.epic&&x.status!=="cancelled");if(!p.length)return;let w=p.reduce((x,j)=>x+(j.status==="done"?100:j.progress),0),y=Math.round(w/p.length),v={projectId:d.projectId,taskId:d.epic},S=await this.tasks.get(v).catch(()=>{return});if(S&&S.progress!==y)await this.tasks.update(v,{progress:y})}async finished(d){let p=(await this.projects.settings(d.projectId))["tasks.logFile"];if(p){let w=`- ${Hb()} ${d.id} ${d.title}${d.pr?` (${d.pr.url})`:""}
|
|
214
|
+
`,y=await RA(this.projects.path(d.projectId)),v=Oo.safeParse(p).success?await ae(y,p).catch(()=>{return}):void 0;if(v&&Oo.safeParse(AA(y,v)).success)await TA(v,w);else s.warn(`automation: tasks.logFile ${p} isn't a text file inside the project; not logging ${d.id}`)}await this.archiveDone(d)}async archiveDone(d){let u={projectId:d.projectId,taskId:d.id},p=await this.projects.settings(d.projectId);if(!p["tasks.autoArchive"]||p["tasks.archiveAfterHours"]||d.archived)return;let w=await this.tasks.get(u);if(w.status==="done"&&!w.archived&&!At(w))await this.tasks.update(u,{archived:!0})}async mergeStacked(d){if(!d.buildsOn&&!d.epic)return;let u=await this.projects.settings(d.projectId);if(d.pr&&u["github.sync"]&&u["git.flow"]!=="direct")return;let{parent:p}=await Gr(d,(S)=>this.tasks.get({projectId:d.projectId,taskId:S}).catch(()=>{return}));if(!Dn(p))return;let w=this.projects.path(d.projectId),y=ee(w,d.id);if(y===w)return;let v={projectId:d.projectId,taskId:d.id};try{let S=await Mf(w,y,d,p);if(S.merged)await this.mergedInto(d,p,S.into);else await this.tasks.appendNote(v,`Couldn't merge into ${p.id}'s branch ${S.into}: ${S.reason}. Merge it by hand.`)}catch(S){s.warn(`automation: merging ${d.id} into ${p.id} failed`,S),await this.tasks.appendNote(v,`Couldn't merge into ${p.id}'s branch: ${S.message.split(`
|
|
215
|
+
`)[0]}`)}}async mergedInto(d,u,p){await this.tasks.appendNote({projectId:d.projectId,taskId:d.id},`Merged into ${u.id}'s branch ${p}.`),await this.tasks.appendNote({projectId:u.projectId,taskId:u.id},`${d.id} ${d.title} was merged into this branch.`);let w=this.sessions().forTask(u.projectId,u.id);if(w)await this.sessions().send(w.session.id,`Superfactory merged task ${d.id} (${d.title}) into your branch ${p}: it builds on your work. Look at what it changed before you go on.`,"superfactory")}async startUnblocked(d){if(!this.projects.ownIds().includes(d.projectId))return;let u=await this.tasks.list(d.projectId),p=new Set(u.filter((y)=>y.status==="done").map((y)=>y.id)),w=new Set(u.filter((y)=>Le.includes(y.status)).map((y)=>y.id));for(let y of u){if(y.archived||!y.dependsOn.includes(d.id))continue;if(y.status==="in_progress"&&!y.parked&&!y.dependsOn.some((v)=>w.has(v))){await this.wakeUnblocked(y,d);continue}if(y.status!=="todo"||y.parked)continue;if(!y.dependsOn.every((v)=>p.has(v)))continue;s.info(`automation: ${y.id} is unblocked; starting it`),await this.startPlaced(y).catch((v)=>s.warn(`automation: couldn't start ${y.id}`,v))}}async wakeUnblocked(d,u){let p=this.sessions().forTask(d.projectId,d.id);if(!p)return;s.info(`automation: ${d.id} is unblocked; waking its session`);let w=u.status==="done"?"is done":"was cancelled";await this.sessions().send(p.session.id,`Superfactory: ${u.id} (${u.title}), which ${d.id} depends on, ${w}; nothing in its dependsOn is open now. Take in what it landed and go on with ${d.id}.`,"superfactory").catch((y)=>s.warn(`automation: couldn't wake ${d.id}`,y))}async startPlaced({projectId:d,id:u}){if(await this.placed.start({projectId:d,taskId:u}))return;await this.sessions().start({projectId:d,taskId:u,kind:"task",origin:{kind:"task",taskId:u}})}}async function EA(){return De("machine",await Cs()).values["machine.keepAwake"]??!0}import{mkdtempSync as CA,rmSync as _A}from"fs";import{tmpdir as OA}from"os";import{join as xA}from"path";var qb=900000,MA=30000,jA=60000,LA=2000,NA=65536,DA=4;class wp{flows=new Map;async start(d){if(this.flows.has(d))throw new c("conflict","this sign-in has started");if(this.flows.size>=DA)throw new c("conflict","too many Claude sign-ins at once: finish or cancel one first");let u=CA(xA(OA(),"sf-claude-sign-in-")),p={screen:"",changed:()=>{return}},w=Jo(r(St).programPath(process.env.SUPERFACTORY_CLAUDE_BIN).sub("setup-token").in(u).env({BROWSER:"true",TERM:"xterm-256color",COLORTERM:"truecolor"}).timeoutMs(qb).by("claude-sign-in").build(),{cols:LA,rows:50,onData:(S)=>{p.screen=(p.screen+Buffer.from(S).toString("utf8")).slice(-NA),p.changed()}}),y=Object.assign(p,{pty:w,dir:u,ends:setTimeout(()=>this.end(d),qb)});w.exited.then(()=>y.changed()),this.flows.set(d,y);let v=await this.waitFor(y,MA,()=>UA(gp(y.screen)));if(!v){let S=this.exitedWhy(y)??"Claude didn't show its sign-in link";throw this.end(d),new c("unavailable",S)}return{url:v}}async code(d,u){let p=this.flows.get(d);if(!p)throw new c("not_found","this sign-in ended: start again");let w=p.screen.length;p.pty.terminal?.write(u),await Bun.sleep(300),p.pty.terminal?.write("\r");let y=await this.waitFor(p,jA,()=>FA(gp(p.screen.slice(w)))),v=y?void 0:BA(gp(p.screen.slice(w)))??this.exitedWhy(p);if(this.end(d),!y)throw new c("bad_request",v??"Claude didn't accept the code: start again");return O(y),{token:y}}cancel(d){this.end(d)}end(d){let u=this.flows.get(d);if(!u)return;if(this.flows.delete(d),clearTimeout(u.ends),u.pty.exitCode===null)u.pty.kill("SIGKILL");u.screen="",_A(u.dir,{recursive:!0,force:!0})}exitedWhy(d){if(d.pty.exitCode===null)return;return s.warn(`claude sign-in: claude setup-token ended (${d.pty.exitCode})`),`Claude stopped (exit ${d.pty.exitCode}): is Claude Code installed and up to date on this machine?`}waitFor(d,u,p){return new Promise((w)=>{let y=(S)=>{clearTimeout(v),d.changed=()=>{return},w(S)},v=setTimeout(()=>y(p()),u);d.changed=()=>{let S=p();if(S!==void 0||d.pty.exitCode!==null)y(S)},d.changed()})}}function gp(d){return d.replace(/\x1b\][^\x07\x1b]*(\x07|\x1b\\)/g,"").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g,"").replace(/\x1b[@-_]/g,"")}function UA(d){let u=[...d.matchAll(/https:\/\/[^\s"'<>]+\/oauth\/authorize\?[^\s"'<>]+/g)].map((p)=>p[0]).filter(xh);return u.find((p)=>!/redirect_uri=http(%3A|:)\/\/localhost/i.test(p))??u[0]}function FA(d){return d.match(/sk-ant-[a-z]+\d*-[A-Za-z0-9_-]{20,}/)?.[0]}function BA(d){let u=d.split(/\r?\n/).map((p)=>p.trim()).find((p)=>/error|invalid|failed|expired/i.test(p));return u&&!/sk-ant-/.test(u)?`Claude said: ${u.slice(0,200)}`:void 0}import{createHash as WA}from"crypto";import{constants as Ua,watch as HA}from"fs";import{appendFile as GA}from"fs/promises";import{join as Fa}from"path";var Vb=({managerId:d})=>d&&!jo(d)?d:void 0,kp=(d)=>`${d.scope.kind==="global"?"global":`project:${d.scope.projectId}`}/${Vb(d)??"main"}`,Pp=(d)=>WA("sha256").update(d).digest("hex").slice(0,16),qA=50,VA=Ua.O_WRONLY|Ua.O_APPEND|Ua.O_CREAT|(Ua.O_NOFOLLOW??0);class Ip{projects;onChange;watchers=new Map;known=new Map;constructor(d,u){this.projects=d;this.onChange=u}async get(d){let u=this.files(d),p=await this.read(d),w=(await sn(u.root,u.history)??"").split(`
|
|
216
|
+
`).filter(Boolean).map((y)=>JSON.parse(y));return{text:p,revision:Pp(p),updatedAt:w.at(-1)?.at,history:w.slice(-qA)}}async set(d,u,p,w){let y=this.files(d),v=await this.read(d);if(p!==Pp(v))throw new c("conflict","the instructions changed since you read them; reload and edit again");if(v!==u)this.known.set(kp(d),u),await be(y.root,y.dir,!0,(S)=>de(S.at("CLAUDE.md"),u,438)),await this.record(d,v,u,w);return this.get(d)}async text(d){return(await this.get(d)).text}watch(d){let u=kp(d);if(this.watchers.has(u))return;let p=this.files(d);be(p.root,p.dir,!0,async()=>{return}).then(async()=>{this.known.set(u,await this.read(d));let w;try{let y=HA(p.dir,(v,S)=>{if(S!=="CLAUDE.md")return;clearTimeout(w),w=setTimeout(()=>void this.rescan(d),200)});this.watchers.set(u,y)}catch(y){s.warn(`coordinator: can't watch ${p.dir}`,y)}},(w)=>s.warn(`coordinator: can't watch ${p.dir}`,w))}close(){for(let d of this.watchers.values())d.close()}async rescan(d){let u=kp(d),p=await this.read(d),w=this.known.get(u)??"";if(p===w)return;this.known.set(u,p),await this.record(d,w,p,{by:"user"})}async record(d,u,p,w){let y={...w,at:new Date().toISOString(),diff:YA(u,p)},v=this.files(d);await be(v.root,v.dir,!0,(S)=>GA(S.at("history.jsonl"),`${JSON.stringify(y)}
|
|
217
|
+
`,{flag:VA})),this.onChange(d,p,Pp(p),y)}async read(d){let u=this.files(d);return await sn(u.root,u.text)??""}files(d){let{scope:u}=d,p=Vb(d),w=u.kind==="global"?m().home:this.projects.path(u.projectId),y=u.kind==="global"?void 0:E(w).root,v=y?Fa(y,p?`managers/${p}`:"coordinator"):p?Fa(m().managers,p):m().coordinator;return{root:w,dir:v,text:Fa(v,"CLAUDE.md"),history:Fa(v,"history.jsonl")}}}function YA(d,u){let p=d?d.split(`
|
|
218
|
+
`):[],w=u?u.split(`
|
|
219
|
+
`):[],y=w.length+1,v=Array((p.length+1)*y).fill(0),S=(N,B)=>v[N*y+B]??0;for(let N=p.length-1;N>=0;N--)for(let B=w.length-1;B>=0;B--)v[N*y+B]=p[N]===w[B]?S(N+1,B+1)+1:Math.max(S(N+1,B),S(N,B+1));let x=[],j=0,L=0;while(j<p.length||L<w.length)if(j<p.length&&L<w.length&&p[j]===w[L])x.push(` ${p[j]}`),j++,L++;else if(L<w.length&&(j>=p.length||S(j,L+1)>=S(j+1,L)))x.push(`+${w[L++]}`);else x.push(`-${p[j++]}`);return x.join(`
|
|
220
|
+
`)}import{mkdir as KA}from"fs/promises";import{dirname as QA,join as JA}from"path";var Yb=(d)=>`${d.projectId}/${d.taskId}`;class Tp{links;file=JA(m().coordinator,"tasks.json");async get(d){return(await this.load())[Yb(d)]}async set(d,u){let p=await this.load();p[Yb(d)]=u,await KA(QA(this.file),{recursive:!0,mode:448}),await $e(this.file,p,384)}async load(){return this.links??=await Ge(this.file,{}).catch((d)=>(s.warn("coordinators: starting with no task links",d),{})),this.links}}import{createHash as zA}from"crypto";import{join as Kb}from"path";var XA=t({cron:e(),prompt:e(),recurring:n().default(!0),durable:n().default(!1)}),ZA=t({id:e(),durable:n().optional()}),eE=t({id:e()}),Jb=Vl({id:e().optional(),cron:e().optional(),schedule:e().optional(),prompt:e().default(""),recurring:n().optional(),createdAt:M([e(),b()]).optional()});class Ap{projects;push;sessions;tracked={};state={};calls=new Map;constructor(d,u,p){this.projects=d;this.push=u;this.sessions=p}async load(){let d=(u)=>Ge(u,{}).catch((p)=>(s.warn("crons: starting empty",p),{}));this.tracked=await d(m().crons),this.state=await d(m().cronState)}async list(d){let u=this.stateOf(d).lastRunAt,p=(this.tracked[d]??[]).map(({durable:y,...v})=>v),w=this.stateOf(d).paused.flatMap(({id:y,row:v})=>Qb(d,v,y,!1));return[...p,...await this.scheduledTasks(d),...w].map((y)=>({...y,lastRunAt:u[y.id]??y.lastRunAt}))}async run(d,u,p){let w=await this.find(d,u),y=this.sessions(),v;if(w.sessionId&&y.running(w.sessionId))await y.send(w.sessionId,w.prompt),v=w.sessionId;else v=await y.toCoordinator(d,w.prompt,p);return this.stateOf(d).lastRunAt[u]=new Date().toISOString(),await this.saved(d),{cron:await this.find(d,u),sessionId:v}}async setEnabled(d,u,p){let w=await this.find(d,u);if(w.enabled===p)return w;if(w.source!=="scheduled_tasks")throw new c("conflict","a cron made in a session can't be paused: remove it instead");let y=this.stateOf(d),v=await this.readScheduled(d);if(p){let S=y.paused.find((x)=>x.id===u);y.paused=y.paused.filter((x)=>x.id!==u),await this.writeScheduled(d,{...v,rows:[...v.rows,S?.row]})}else{let S=v.rows.findIndex((x,j)=>Rp(x,j)===u);y.paused.push({id:u,row:v.rows[S]}),await this.writeScheduled(d,{...v,rows:v.rows.filter((x,j)=>j!==S)})}return await this.saved(d),this.find(d,u)}async remove(d,u){let p=await this.find(d,u),w=this.stateOf(d);if(p.source==="scheduled_tasks"){w.paused=w.paused.filter((v)=>v.id!==u);let y=await this.readScheduled(d);await this.writeScheduled(d,{...y,rows:y.rows.filter((v,S)=>Rp(v,S)!==u)})}else{if(p.sessionId&&this.sessions().running(p.sessionId))await this.sessions().send(p.sessionId,`The user removed your scheduled prompt ${u}: delete it now with CronDelete (id ${u}) and reply only: ok.`);this.tracked[d]=(this.tracked[d]??[]).filter((y)=>y.id!==u),await $e(m().crons,this.tracked)}delete w.lastRunAt[u],await this.saved(d)}async find(d,u){let p=(await this.list(d)).find((w)=>w.id===u);if(!p)throw new c("not_found",`no scheduled prompt ${u} in ${d}`);if(p.source!=="cron_tool"&&p.source!=="scheduled_tasks")throw new c("conflict",`a ${p.source} scheduled prompt can't be changed from here`);return p}stateOf(d){return this.state[d]??={lastRunAt:{},paused:[]},this.state[d]}async saved(d){await $e(m().cronState,this.state),this.push({type:"crons.changed",projectId:d,crons:await this.list(d)})}onLine(d,u){if(!d.projectId)return;if(u.type==="assistant"){for(let y of u.message.content)if(y.type==="tool_use"&&(y.name==="CronCreate"||y.name==="CronDelete"))this.calls.set(y.id,{name:y.name,input:y.input});return}if(u.type!=="user")return;let p=u,w=Array.isArray(p.message.content)?p.message.content:[];for(let y of w){if(y.type!=="tool_result")continue;let v=this.calls.get(y.tool_use_id);if(!v)continue;if(this.calls.delete(y.tool_use_id),y.is_error)continue;if(v.name==="CronCreate")this.created(d,v.input,p.tool_use_result);else this.deleted(d,v.input)}}sessionEnded(d){let{projectId:u}=d;if(!u)return;let p=this.tracked[u]??[],w=p.filter((y)=>y.sessionId!==d.id||y.durable);if(w.length!==p.length)this.changed(u,w)}created(d,u,p){let{projectId:w}=d;if(!w)return;let y=XA.safeParse(u),v=ZA.safeParse(p);if(!y.success||!v.success)return;let S={...Ot.parse({id:v.data.id,projectId:w,nodeId:d.nodeId,sessionId:d.id,source:"cron_tool",schedule:y.data.cron,prompt:y.data.prompt,recurring:y.data.recurring,createdAt:new Date().toISOString()}),durable:v.data.durable??y.data.durable},x=(this.tracked[w]??[]).filter((j)=>j.id!==S.id);this.changed(w,[...x,S])}deleted(d,u){let{projectId:p}=d;if(!p)return;let w=eE.safeParse(u);if(!w.success)return;let y=this.tracked[p]??[];this.changed(p,y.filter((v)=>v.id!==w.data.id))}async changed(d,u){this.tracked[d]=u,await $e(m().crons,this.tracked),this.push({type:"crons.changed",projectId:d,crons:await this.list(d)})}async scheduledTasks(d){let{rows:u}=await this.readScheduled(d);return u.flatMap((p,w)=>Qb(d,p,Rp(p,w),!0))}scheduledFile(d){let u=this.projects.path(d),p=Kb(u,".claude");return{root:u,dir:p,name:"scheduled_tasks.json",path:Kb(p,"scheduled_tasks.json")}}async readScheduled(d){let u=this.scheduledFile(d),p=await sn(u.root,u.path);if(!p)return{rows:[],wrapped:!1};try{let w=JSON.parse(p);if(Array.isArray(w))return{rows:w,wrapped:!1};return{rows:w.tasks??[],wrapped:!0}}catch{return{rows:[],wrapped:!1}}}async writeScheduled(d,{rows:u,wrapped:p}){let w=this.scheduledFile(d),y=await sn(w.root,w.path)??"{}",v=p?{...JSON.parse(y),tasks:u}:u;await be(w.root,w.dir,!0,(S)=>de(S.at(w.name),`${JSON.stringify(v,null,2)}
|
|
221
|
+
`,438))}}function Rp(d,u){let p=Jb.safeParse(d);if(!p.success)return`scheduled-${u+1}`;if(p.data.id)return p.data.id;let w=`${p.data.cron??p.data.schedule??""}
|
|
222
|
+
${p.data.prompt}`;return`scheduled-${zA("sha256").update(w).digest("hex").slice(0,8)}`}function Qb(d,u,p,w){let y=Jb.safeParse(u),v=y.success?y.data.cron??y.data.schedule:void 0;if(!y.success||!v)return[];let S=y.data.createdAt;return[{id:p,projectId:d,source:"scheduled_tasks",schedule:v,prompt:y.data.prompt,recurring:y.data.recurring??!0,enabled:w,createdAt:S===void 0?void 0:new Date(S).toISOString()}]}import{join as gE}from"path";class Cr{timers=new Set;every(d,u,p,{firstAfterMs:w}={}){let y=!1,v=async()=>{if(y)return;y=!0;try{await p()}catch(S){s.warn(`${d}: failed`,S)}finally{y=!1}};if(this.keep(setInterval(()=>void v(),u)),w===0)v();else if(w!==void 0)this.keep(setTimeout(()=>void v(),w))}stopAll(){for(let d of this.timers)clearInterval(d);this.timers.clear()}keep(d){d.unref?.(),this.timers.add(d)}}var tE=2000;async function vn(d,u,p){let w=await zb(d,u);if(!w||!await Ep(d,w.remote,w.head)||!await Xb(d,w))return;let y=await sE(d,w);if(!y)return;return{commit:y,pr:await nE(d,y,p)}}async function Pn(d,u){let p=await zb(d,u);if(!p)return!1;return!await Xb(d,p)||await Ep(d,p.remote,p.head)}async function zb(d,u){let p=`origin/${u}`;await a(d,(v)=>v.sub("fetch").flag("--quiet").arg("origin").arg(`${u}:refs/remotes/origin/${u}`)).catch(()=>{return});let w=await Ba(d,"HEAD");if(!w||!await Ba(d,p))return;let y=(await a(d,(v)=>v.sub("merge-base").arg(p).arg(w)).catch(()=>"")).trim();return y?{remote:p,head:w,since:y}:void 0}function Yi(d,u){let p=d.commit.slice(0,8);return d.pr?`Its work is already on ${u}: PR #${d.pr} carried it (${p}).`:`Its work is already on ${u}: commit ${p} carried it.`}async function Ba(d,u){return(await a(d,(w)=>w.sub("rev-parse").flag("--verify").flag("--quiet").arg(u)).catch(()=>{return}))?.trim()||void 0}async function Ep(d,u,p){let w=await a(d,(y)=>y.sub("merge-tree").flag("--write-tree").arg(u).arg(p),[1]).then((y)=>y.split(`
|
|
223
|
+
`)[0]?.trim()).catch(()=>{return});return!!w&&w===await Ba(d,`${u}^{tree}`)}async function Xb(d,{remote:u,head:p,since:w}){if(w!==p)return(await a(d,(x)=>x.sub("log").flag("--format","%P").arg(`${u}..${p}`)).catch(()=>"")).split(`
|
|
224
|
+
`).some((x)=>x.trim()&&!x.trim().includes(" "));let v=(await a(d,(S)=>S.sub("rev-list").flag("--first-parent").flag("--reverse").arg(`${w}..${u}`)).catch(()=>"")).split(`
|
|
225
|
+
`).find(Boolean);return!!v&&await Ba(d,`${v}^1`)!==p}async function sE(d,{remote:u,head:p,since:w}){let v=(await a(d,(L)=>L.sub("rev-list").flag("--first-parent").flag("--reverse").arg(`${w}..${u}`)).catch(()=>"")).split(`
|
|
226
|
+
`).filter(Boolean).slice(-tE),S=0,x=v.length-1,j;while(S<=x){let L=S+x>>1,N=v[L];if(await Ep(d,N,p))j=N,x=L-1;else S=L+1}return j??v.at(-1)}async function nE(d,u,p){let w=await a(d,(x)=>x.sub("log").flag("-1").flag("--format","%s").arg(u)).catch(()=>""),y=w.match(/\(#(\d+)\)\s*$/)??w.match(/^Merge pull request #(\d+)\b/);if(y)return Number(y[1]);if(!p)return;let v=await Q(d,(x)=>x.sub("api").arg(`repos/${p}/commits/${u}/pulls`).flag("--jq",".[0].number // empty")).catch(()=>""),S=Number.parseInt(v.trim(),10);return Number.isInteger(S)?S:void 0}import{openAsBlob as iE}from"fs";import{readdir as rE,readFile as oE,stat as aE}from"fs/promises";import{extname as nv,join as dE}from"path";var Cp="<!-- superfactory -->",_p="<!-- /superfactory -->",iv="<!-- superfactory:task -->",rv="<!-- /superfactory:task -->",Op="<!-- summary -->",xp="<!-- /summary -->",Zb=3,ev=500,cE=new Set([".mp4",".m4v",".mov",".webm"]),uE=[".github/pull_request_template.md",".github/PULL_REQUEST_TEMPLATE.md","pull_request_template.md","docs/pull_request_template.md"];async function ov(d){let u=(await rE(d).catch(()=>[])).filter((w)=>cE.has(nv(w).toLowerCase()));return(await Promise.all(u.map(async(w)=>{let y=dE(d,w),v=await aE(y),{durationSeconds:S,chapters:x}=await iE(y).then(qm).catch(()=>({}));return{video:{name:w,...S?{durationSeconds:S}:{},...x?{chapters:x}:{}},at:v.mtimeMs}}))).sort((w,y)=>y.at-w.at||w.video.name.localeCompare(y.video.name)).map((w)=>w.video)}async function av(d){let u=await hE(d.cwd,d.template);return[cv(d),u,uv(d.task)].filter(Boolean).join(`
|
|
227
|
+
|
|
228
|
+
`)}function dv(d,u){let p=Mp(d,Cp,_p)??"",w=Mp(p,Op,xp)?.slice(Op.length,-xp.length).trim(),y=tv(tv(d,Cp,_p),iv,rv).trim();return[cv(u,w),y,uv(u.task)].filter(Boolean).join(`
|
|
229
|
+
|
|
230
|
+
`)}function jp(d){let p=d.comments.filter((v)=>v.author.kind==="claude"&&v.author.role!=="coordinator"&&!v.important).at(-1)?.body.trim();if(!p)return;let w=(p.split(/\n\s*\n/)[0]??"").split(`
|
|
231
|
+
`).filter((v)=>v.trim()),y=w.slice(0,Zb).join(`
|
|
232
|
+
`);if(y.length>ev)return`${y.slice(0,ev).trimEnd()}\u2026`;return w.length>Zb?`${y}\u2026`:y}function cv(d,u){let p=[Cp];for(let v of d.videos)p.push(...lE(v,d),"");let w=d.summary??u;if(w)p.push(Op,w,xp,"");let y=d.testsUrl?` \xB7 [every test run](${d.testsUrl})`:"";return p.push(`**Local checks:** ${Ha(d.checks)}${y}`,_p),p.join(`
|
|
233
|
+
`)}function lE(d,u){let p=u.mediaUrl(d.name),w=u.github?.get(d.name),y=d.name.slice(0,d.name.length-nv(d.name).length)||d.name,v=[];if(w&&"url"in w&&w.preview)v.push(`[](${w.url})`,"");let S=[w&&("url"in w?`[download](${w.url})`:`not on GitHub: ${w.failed.short}`),p&&`[watch in Superfactory](${p})`],x=[`**Video: ${y}**`,d.durationSeconds?sv(d.durationSeconds):""];if(v.push([...x,...S].filter(Boolean).join(" \xB7 ")),d.chapters?.length)v.push(`<br>Chapters: ${d.chapters.map((j)=>`${sv(j.startSeconds)} ${j.title}`).join(" \xB7 ")}`);return v}function uv(d){let u=d.description.trim(),p=[iv];if(u)p.push(`<details><summary>${pE(`${d.id} ${d.title}`)}</summary>`,"",u,"","</details>","");return p.push("_Synced by Superfactory._",rv),p.join(`
|
|
234
|
+
`)}function Ha(d){if(!d.ran)return`not run: ${d.reason}`;let u=Math.round((d.finishedAt.getTime()-d.startedAt.getTime())/1000),p=u>=60?`${Math.round(u/60)} min`:`${u} s`;return`\`${d.command.join(" ")}\` ${d.passed?"passed":"failed"} in ${p}`}function Mp(d,u,p){let w=d.indexOf(u),y=w>=0?d.indexOf(p,w):-1;return y>=0?d.slice(w,y+p.length):void 0}function tv(d,u,p){let w=Mp(d,u,p);return w?d.replace(w,""):d}function sv(d){let u=Math.floor(d),[p,w,y]=[Math.floor(u/3600),Math.floor(u%3600/60),u%60],v=(S)=>String(S).padStart(2,"0");return p?`${p}:${v(w)}:${v(y)}`:`${w}:${v(y)}`}var pE=(d)=>d.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");async function hE(d,u){for(let p of u?[u]:uE){let w=await ae(d,p).catch(()=>{return}),y=w&&await oE(w,"utf8").catch(()=>{return});if(y?.trim())return y.trim()}return""}async function za(d,u){let p=lv(u.statusCheckRollup??[]);if(p!=="failing"&&p!=="pending")return p;let w=await fE(d,u.number).catch((y)=>(s.warn(`github: couldn't read which checks PR #${u.number}'s base requires`,y),[]));return w.length?lv(w)??p:p}function lv(d){if(!d.length)return;let u=(w)=>(w.conclusion||w.state||w.status||"").toUpperCase(),p=d.map(u);if(p.some((w)=>["FAILURE","ERROR","CANCELLED","TIMED_OUT","ACTION_REQUIRED"].includes(w)))return"failing";if(p.every((w)=>["SUCCESS","NEUTRAL","SKIPPED"].includes(w)))return"passing";return"pending"}var mE=`query($owner: String!, $name: String!, $number: Int!) {
|
|
235
|
+
repository(owner: $owner, name: $name) {
|
|
236
|
+
pullRequest(number: $number) {
|
|
237
|
+
commits(last: 1) { nodes { commit { statusCheckRollup { contexts(first: 100) { nodes {
|
|
238
|
+
... on CheckRun { status conclusion isRequired(pullRequestNumber: $number) }
|
|
239
|
+
... on StatusContext { state isRequired(pullRequestNumber: $number) }
|
|
240
|
+
} } } } } }
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}`.replace(/\s+/g," ");async function fE(d,u){return((await fe(d,(y)=>y.sub("api").arg("graphql").flag("-f",`query=${mE}`).flag("-F","owner={owner}").flag("-F","name={repo}").flag("-F",`number=${u}`))).data?.repository?.pullRequest?.commits?.nodes?.[0]?.commit?.statusCheckRollup?.contexts?.nodes??[]).filter((y)=>y.isRequired)}var wE=k("SUPERFACTORY_GITHUB_POLL_MS",60000),yE=k("SUPERFACTORY_MERGE_RETRY_MS",300000),kE=600000,pv=600000,bE=30000,hv=600000,vE=["admin","maintain","write"],SE={squash:"--squash",merge:"--merge",rebase:"--rebase"},PE="nothing says which commit the person's Merge was for, so it wasn't merged",$E="neither a merge question nor GitHub names the commit it was approved at, so it wasn't merged",IE="its PR was only just opened, so nobody had reviewed the commit it merges: Merge again to merge it",kt=["draft","open"],td=["in_progress","needs_input","in_review"],TE={APPROVED:"approved",CHANGES_REQUESTED:"changes",REVIEW_REQUIRED:"required","":"none"};class kh{deps;polling=new Cr;running=new Map;permissions=new Map;reopened=new Set;checkedHeads=new Map;caughtUp=new Set;nothingYet=new Map;swept=new Map;resumed=new Set;repos=new Map;unlisted=new Map;shareChecked=new Set;looked=new Map;relinkLooked=new Map;baseChecked=new Set;constructor(d){this.deps=d}start(){this.polling.every("github: poll",wE,()=>this.poll())}stop(){this.polling.stopAll()}onTaskChange({task:d,previous:u}){if(!u||!this.worksHere(d))return Promise.resolve();if((d.epic!==u.epic||d.buildsOn!==u.buildsOn)&&d.status===u.status&&d.pr&&kt.includes(d.pr.state))return this.serial(d,()=>this.repairBase(d));if(Et(d)&&!Et(u))return this.serial(d,()=>this.approve(d));if(d.status===u.status)return Promise.resolve();if(d.status==="in_review"&&this.reopened.delete(Ye(d)))return Promise.resolve();if(d.status==="in_review")return this.serial(d,()=>this.publish(d));if(d.status==="done")return this.serial(d,()=>this.approve(d));if(d.status==="cancelled")return this.serial(d,()=>this.close(d));return Promise.resolve()}async poll(){for(let d of this.deps.projects.ids()){if(!await this.syncOn(d))continue;let u=(await this.deps.tasks.list(d).catch(()=>[])).filter((y)=>this.worksHere(y)),p=(y)=>!!y.pr&&kt.includes(y.pr.state),w=u.some(p)?await this.openPrs(d):void 0;for(let y of u){let v=y;if(p(v)&&v.pr?.branch)await this.serial(v,()=>this.unshareWrong(y)),v=await this.deps.tasks.get(le(v)).catch(()=>y);let S=this.swept.get(Ye(v)),x=S===void 0||Date.now()-S>=yE;if(p(v)&&(v.status==="done"||Et(v))&&!v.archived&&x)this.swept.set(Ye(v),Date.now()),await this.serial(v,()=>this.approve(v));else if(p(v)&&v.status==="in_review"&&!this.resumed.has(Ye(v))&&EE(v))this.resumed.add(Ye(v)),await this.serial(v,()=>this.deps.resumeMerge(le(v)).then(()=>{return}));else if(p(v))await this.serial(v,()=>this.mirror(v,w));else if(v.pr?.state==="closed"&&td.includes(v.status)&&this.relinkDue(v))await this.serial(v,()=>this.replaceClosed(v).then(()=>{return}));else if(!v.pr&&td.includes(v.status)&&!this.caughtUp.has(Ye(v)))await this.serial(v,()=>this.catchUp(v))}}}async catchUp(d){let u=await this.deps.tasks.get(le(d));if(u.pr||!td.includes(u.status))return;if(await this.bundleLeadOf(u)){this.caughtUp.add(Ye(u));return}let p=this.deps.projects.path(u.projectId),w=ee(p,u.id);if(w===p||!await Ae(p))return;if(!await id(w,await ge(w)))return;let y=await this.place(u,{quiet:!0});if(!y||!await id(w,y.base))return;if(u.status==="in_review")return this.caughtUp.add(Ye(u)),this.publish(u);let v=await $n(w);if(this.nothingYet.get(Ye(u))===v)return;if(await Pn(w,y.base)){this.nothingYet.set(Ye(u),v);return}this.caughtUp.add(Ye(u));let S=await vn(y.cwd,y.base,y.slug);if(S){await this.deps.tasks.appendCountedNote(le(u),`No PR opened: ${sd(Yi(S,y.base))}`);return}await th(y.cwd,y.branch,!!u.runner&&u.runner!=="host");let x={ran:!1,reason:"the agent is still at work"},j=await this.openOrUpdate(u,y,x,!0).catch((G)=>{if(Lp(G))return;throw G});if(!j){this.caughtUp.delete(Ye(u)),this.nothingYet.set(Ye(u),v);return}let{pr:L,opened:N,carrier:B}=j;if(await this.deps.tasks.update(le(u),{pr:L}),B)await this.deps.tasks.appendNote(le(u),await this.sharedNote(u,B));else if(N)await this.deps.tasks.appendNote(le(u),`Opened draft PR #${L.number} ${L.url}: it shows the work as it goes, and is updated when the task is ready for review.`)}worksHere(d){let u=!d.runner||d.runner==="host";if(d.node&&u)return d.node===this.deps.nodeId();if(this.deps.projects.ownIds().includes(d.projectId))return!0;let p=this.projectPath(d.projectId);return!!p&&ee(p,d.id)!==p}projectPath(d){try{return this.deps.projects.path(d)}catch{return}}serial(d,u){let p=Ye(d),w=le(d),y=(this.running.get(p)??Promise.resolve()).then(u).catch(async(v)=>{s.warn(`github: ${d.id}`,v),await this.deps.tasks.appendCountedNote(w,`GitHub: ${v.message.split(`
|
|
244
|
+
`)[0]}`).catch(()=>{return})});return this.running.set(p,y),y}async publish(d){let u=le(d),p=await this.deps.tasks.get(u),w=await this.bundleLeadOf(p);if(w)return this.shipWithLead(p,w);let y=await this.place(p);if(!y)return;let v=!!p.runner&&p.runner!=="host";await this.commitLeftovers(p,y);let S=v?this.deps.sandboxFor(p)??"none":void 0,x=await ec(y.cwd,sh(y.settings),S);if(x.ran)await this.recordChecks(u,x,y.cwd,v?p.runner:void 0);if(x.ran&&!x.passed){if(await this.deps.tasks.appendNote(u,`Local checks failed, so nothing was pushed:
|
|
245
|
+
|
|
246
|
+
${eh(x.tail)}`),p.pr)await this.deps.tasks.update(u,{pr:{...p.pr,checks:"failing"}});return}if(x.ran)this.checkedHeads.set(Ye(p),await $n(y.cwd));if(await th(y.cwd,y.branch,v),!await In(y.cwd,y.branch)){let G=await vn(y.cwd,y.base,y.slug);if(G){await this.deps.tasks.appendNote(u,`No PR opened: ${sd(Yi(G,y.base))}`);return}if(!await id(y.cwd,y.base)||await Pn(y.cwd,y.base)){await this.deps.tasks.appendNote(u,"No PR opened: its branch has no commits of its own yet.");return}}let j=await this.openOrUpdate(p,y,x,!1,{summary:jp(p)}).catch((G)=>{if(Lp(G))return;throw G});if(!j){await this.deps.tasks.appendNote(u,"No PR opened: its branch has no commits of its own yet.");return}let{pr:L,opened:N,carrier:B}=j;await this.deps.tasks.update(u,{pr:L}),await this.deps.tasks.appendNote(u,B?await this.sharedNote(p,B):`${N?"Opened":"Pushed to"} ${L.state==="draft"?"draft ":""}PR #${L.number} ${L.url} (local checks: ${Ha(x)})`)}async recordChecks(d,u,p,w){await this.deps.recordTest(d,{command:u.command.join(" "),suite:"Pre-push checks",by:{kind:"pre-push"},startedAt:u.startedAt,finishedAt:u.finishedAt,exitCode:u.exitCode,timedOut:u.timedOut,log:u.output,...w?{sandbox:w}:{}},p).catch((y)=>s.warn(`github: ${d.taskId}: the checks' run wasn't kept`,y))}async openOrUpdate(d,u,p,w,{summary:y}={}){let v=await In(u.cwd,u.branch),S=await this.carrierOf(d,u,v);if(S){if(v)await Q(u.cwd,(G)=>G.sub("pr close").arg(v).flag("--comment",`PR #${S.pr.number} holds all of this branch's work: closed, so one PR carries it.`)),S.closed=v;if(S.pr.state!=="draft"||w)return{pr:S.pr,opened:!1,carrier:S};return await Q(u.cwd,(G)=>G.sub("pr ready").arg(String(S.pr.number))),{pr:{...S.pr,state:"open"},opened:!1,carrier:S}}let x=v?await jE(u.cwd,v):"",j=!!v&&!!(await this.openPrs(d.projectId))?.get(Number(v))?.isCrossRepository,L=await this.bodyInput(d,u,{checks:p,summary:y,fork:j});if(v)await Tf(u.cwd,u.slug,v,dv(x,L));else{if(u.parent)await $v(u);else await DE(u);let G=await av(L);await Q(u.cwd,(V)=>(V.sub("pr create").flag("--head",u.branch).flag("--base",u.base).flag("--title",`${d.id} ${d.title}`).flag("--body-file","-"),w?V.flag("--draft"):V),G)}let N=v??u.branch,B=await this.view(u.cwd,N,_E(p));if(B.state!=="draft"||w)return{pr:B,opened:!v};return await Q(u.cwd,(G)=>G.sub("pr ready").arg(String(B.number))),{pr:{...B,state:"open"},opened:!v}}async carrierOf(d,u,p){let y=[...(await this.openPrs(d.projectId))?.values()??[]].filter((N)=>N.isCrossRepository===!1&&N.headRefName!==u.branch&&N.baseRefName===u.base&&N.headRefOid);if(!y.length)return;let v=await this.deps.tasks.list(d.projectId).catch(()=>[]),S=y.filter((N)=>vv(d,N.number,N.headRefName,v)).sort((N,B)=>N.number-B.number);if(!S.length)return;if(await Pn(u.cwd,u.base))return;let x=[];for(let N of S)if(!await fv(u.cwd,N.headRefOid??""))x.push(N.headRefName);let j=(N)=>a(u.cwd,(B)=>B.sub("fetch").flag("--quiet").arg("origin").argsOf(N.map((G)=>`refs/heads/${G}`))).then(()=>!0,()=>!1);if(x.length&&!await j(x))for(let N of x)await j([N]);let L=await $n(u.cwd);for(let N of S){let B=N.headRefOid??"";if(p&&B===L&&N.number>Number(p))continue;if(await a(u.cwd,(V)=>V.sub("merge-base").flag("--is-ancestor").arg(L).arg(B)).then(()=>!0,()=>!1))return{pr:await this.view(u.cwd,String(N.number),"none")}}return}async unshareWrong(d){let u=await this.deps.tasks.get(le(d)),p=u.pr;if(!p?.branch||!kt.includes(p.state))return;let w=`${Ye(u)}#${p.number}`;if(this.shareChecked.has(w))return;let y=await this.place(u,{quiet:!0});if(!y)return;if(this.shareChecked.add(w),p.branch===y.branch)return;let v=await this.deps.tasks.list(u.projectId).catch(()=>{return});if(!v){this.shareChecked.delete(w);return}let S=await Pn(y.cwd,y.base)?"its branch has no commits of its own":!vv(u,p.number,p.branch,v)?"no task of its epic or of the tasks it builds on has that PR":void 0;if(!S)return;await this.deps.tasks.forgetPr(le(u)),await this.deps.tasks.appendNote(le(u),`PR #${p.number} (${p.branch}) isn't this task's work: ${S}, so it no longer shares it. Its own PR opens from its branch ${y.branch}.`)}async bundleLeadOf(d){if(!d.bundle)return;return Ee(await this.deps.tasks.list(d.projectId).catch(()=>[]),d)}async shipWithLead(d,u){let p=le(d),w=this.deps.projects.path(d.projectId),y=ee(w,d.id),v=y===w?"":await a(y,(G)=>G.sub("branch").flag("--show-current")).then((G)=>G.trim(),()=>""),S=v?await In(y,v).catch(()=>{return}):void 0,x=d.pr&&kt.includes(d.pr.state)?String(d.pr.number):void 0,j=u.pr&&kt.includes(u.pr.state)?u.pr:void 0,L=[...new Set([x,S])].filter((G)=>!!G&&G!==String(j?.number??""));for(let G of L)await Q(y,(V)=>V.sub("pr close").arg(G).flag("--comment",`${u.id}'s PR carries the bundle ${d.id} is in: closed, so one PR carries its work.`)).catch((V)=>s.warn(`github: ${d.id}'s PR #${G} wasn't closed`,V));if(d.pr)await this.deps.tasks.forgetPr(p);let N=j?`${u.id}'s PR #${j.number} ${j.url}`:`${u.id}'s PR, once it opens`,B=L.length?` Its own PR ${L.map((G)=>`#${G}`).join(", ")} was closed as the same work.`:"";await this.deps.tasks.appendNote(p,`No PR of its own: its work ships in ${N}, its bundle's one PR, and ${u.id}'s Merge closes it too.${B}`)}async sharedNote(d,{pr:u,closed:p}){let y=(await this.deps.tasks.list(d.projectId).catch(()=>[])).find((x)=>x.id!==d.id&&x.pr?.number===u.number&&(!x.pr.branch||x.pr.branch===u.branch)),v=y?`, ${y.id}'s`:"",S=p?` Its own PR #${p}, the same work, was closed.`:"";return`Its work is all in PR #${u.number} (${u.branch}${v}), so it shares that PR rather than opening another.${S} Merge on any task that shares it merges it.`}async commitLeftovers(d,u){let p=await LE(u.cwd);if(!p.length)return;let w=new Set(await NE(u.cwd,u.base)),y=(L)=>L.status==="??"||!" ?".includes(L.status[0]??" ")||w.has(L.path),v=p.filter(y).map((L)=>L.path),S=p.filter((L)=>!y(L)).map((L)=>L.path);if(v.length)await We(u.cwd,async()=>{await a(u.cwd,(N)=>N.sub("add").flag("--all").endOptions().argsOf(v));let L=await he(u.cwd);await a(u.cwd,(N)=>N.env(L).sub("commit").flag("--quiet").flag("--message",`${d.id} ${d.title}`))});if(!S.length)return;let x=S.slice(0,10).join(", "),j=S.length>10?` and ${S.length-10} more`:"";await this.deps.tasks.appendNote(le(d),`Left out of the PR, uncommitted: ${x}${j}. No commit of the task's changes ${S.length>1?"them":"it"}, so ${S.length>1?"they look":"it looks"} like a build's output; commit ${S.length>1?"them":"it"} if ${S.length>1?"they are":"it is"} the task's.`)}async bodyInput(d,u,{checks:p,summary:w,fork:y=!1}){let v=le(d),S=E(this.deps.projects.path(d.projectId)).taskMedia(d.id),x=await ov(S),j=u.settings["github.uploadVideos"]&&!y;return{task:d,cwd:u.cwd,template:u.settings["github.prTemplate"],videos:x,mediaUrl:(L)=>this.deps.mediaUrl(v,L),...j?{github:await this.uploadVideos(d,u,S,x)}:{},checks:p,testsUrl:this.deps.testsUrl(v),summary:w}}async uploadVideos(d,u,p,w){let y=new Set(d.questions.flatMap((j)=>j.video?[j.video.media]:[])),v=[];for(let j of w)if(!await Xa(p,j.name,y.has(j.name)))v.push({name:j.name,path:gE(p,j.name),durationSeconds:j.durationSeconds});if(!v.length)return;let S=await sy(u.cwd,u.slug,d.id,v),x=[...S.values()].find((j)=>("failed"in j));if(x&&"failed"in x){let j=`GitHub: the task's video wasn't uploaded to ${u.slug} (${x.failed.reason}), so its PR links it in Superfactory only.`;if(!(await this.deps.tasks.get(le(d)).catch(()=>d)).notes.includes(j))await this.deps.tasks.appendNote(le(d),j)}return S}async approve(d,u=!1){let p=await this.deps.tasks.get(le(d));if(p.status!=="done"&&!Et(p))return;if(p.pr&&!kt.includes(p.pr.state))return;if(!p.pr&&(!ya(p)||p.epic))return;let w=await this.place(p);if(!w)return;if(!p.pr){let N=await this.publishForMerge(p,w);if(N)return this.unpublished(p,N);if(p=await this.deps.tasks.get(le(p)),!p.pr){await this.deps.tasks.appendNote(le(p),`Nothing to merge: the work is on ${w.base}.`);return}return this.refused(p,w,String(p.pr.number),IE)}let y=await this.ownPr(p,w,{shared:!0}).catch(async(N)=>{if(!gh(Xe(N))||!p.mergeApproval)throw N;await this.wait(p,String(p.pr?.number),p.mergeApproval.head,`GitHub: ${Xe(N)}`);return});if(!y)return;if(y.state==="merged")return this.settled(p,w,y,`PR #${y.number} was already merged on GitHub.`);if(y.state==="closed")return this.closedOnApprove(p,w,y);let v=String(p.pr.number),S=SE[w.settings["github.mergeMethod"]],x=p.mergeApproval,j=ya(p)||!!x?.verifiedHead,L=j?x?.verifiedHead??x?.head:UE(p)??await wi(w.cwd,v);if(!L)return this.refused(p,w,v,j?PE:$E);if(L&&y.checks==="pending")return await this.deps.tasks.update(le(p),{pr:y}),this.wait(p,v,L,`its checks are still running on ${L.slice(0,8)}`);if(L&&y.checks==="failing")return this.refused(p,w,v,`its checks fail on ${L.slice(0,8)}`);try{if(y.state==="draft")await Q(w.cwd,(B)=>B.sub("pr ready").arg(v));let N=await this.retarget(p,w,y,v,x?.into);if(N)return this.refused(p,w,v,N);await mv(()=>Q(w.cwd,(B)=>(B.sub("pr merge").arg(v).flag(S),B.flag("--match-head-commit",L))))}catch(N){let B=await vn(w.cwd,w.base,w.slug);if(B){let Y=Yi(B,w.base);return await Q(w.cwd,(ne)=>ne.sub("pr close").arg(v).flag("--comment",Y)).catch(()=>{return}),this.settled(p,w,{...y,state:"closed"},`PR #${v} didn't need merging. ${Y}`)}if(gh(Xe(N))||Sv(Xe(N)))return this.wait(p,v,L,`GitHub: ${Xe(N)}`);let G=await If(w.cwd,v);if(G?.mergeable==="UNKNOWN")return this.wait(p,v,L,"GitHub is still working out whether it can merge");if(G?.mergeStateStatus==="BLOCKED"||yt(Xe(N)).kind==="protected")return this.mergeProtected(p,w,{number:v,method:S,at:L,state:G});let V=RE(Xe(N),G,w.base);if(!u&&zs(yt(V,w.base))){let Y=await this.updatedForMerge(p,w,L);if(Y===!0)return this.approve(p,!0);if(Y)return await this.deps.tasks.appendNote(le(p),`PR #${v}: what changed since ${_r(L)}: ${Y}`),this.refused(p,w,v,`its branch changed since ${_r(L)}, the commit ${Np(p)} chose to merge, beyond what ${w.base} brought in. Nothing was merged; it's asked again`)}return this.refused(p,w,v,V)}return this.merged(p,w,v)}async updatedForMerge(d,u,p){if(d.runner&&d.runner!=="host"||u.parent)return!1;if(d.pr?.branch&&d.pr.branch!==u.branch)return!1;let w=await this.baseMergedIn(d,u,{checks:!0,approved:p}).catch((j)=>{s.warn(`github: ${d.id}: couldn't bring its branch up to date`,j);return});if(w?.kind==="changed")return w.what;if(w?.kind!=="updated")return!1;let y=d.mergeApproval??{by:Np(d),at:new Date().toISOString(),head:p},{waiting:v,conflict:S,...x}=y;return await this.deps.tasks.setMergeApproval(le(d),{...x,verifiedHead:w.head}),await this.deps.tasks.appendNote(le(d),`GitHub refused to merge PR #${d.pr?.number}: it was behind ${u.base} or conflicted with it. ${u.base} (${w.count} commit${w.count===1?"":"s"}) merged into its branch cleanly here, its checks passed, and it's merging at ${_r(w.head)} with ${y.by}'s approval; nobody needs to approve it again.`),await this.prHeadOf(await this.deps.tasks.get(le(d))).catch(()=>{return}),!0}async wait(d,u,p,w){let y=d.mergeApproval??{by:Np(d),at:new Date().toISOString(),head:p};if(y.waiting!==w)await this.deps.tasks.setMergeApproval(le(d),{...y,waiting:w});await this.deps.tasks.appendCountedNote(le(d),`Waiting to merge PR #${u}: ${w}. It merges by itself once that clears; nobody needs to approve it again.`)}async merged(d,u,p,w){let y=d.mergeApproval,v=await this.view(u.cwd,p,d.pr?.checks??"none");if(await this.deps.tasks.update(le(d),{pr:v,...v.state==="merged"?{status:"done"}:{}}),v.state==="merged"&&y)await this.deps.tasks.setMergeApproval(le(d),void 0);if(v.state==="merged"&&w)await this.deps.tasks.appendNote(le(d),w);if(v.state==="merged"&&y?.verifiedHead)await this.carriedThrough(d,u,y);else await this.deps.tasks.appendNote(le(d),`PR #${v.number} ${v.state==="merged"?`merged${u.parent?` into ${u.parent.id}'s branch ${u.base}`:""}`:"is ready for review"}.`);if(u.parent&&v.state==="merged")await this.pullIntoParent(d,u.parent,u.base)}async mergeProtected(d,u,{number:p,method:w,at:y,state:v}){let S=(ye)=>mv(()=>Q(u.cwd,(ve)=>(ve.sub("pr merge").arg(p).flag(w),ve.flag("--match-head-commit",y).flag(ye)))),x=await Ef(u.cwd,u.slug,u.base),j=new Set((v?.statusCheckRollup??[]).map((ye)=>ye.name||ye.context)),L=x.checks.filter((ye)=>!j.has(ye)),N=v?.reviewDecision==="REVIEW_REQUIRED"||x.reviews>0,B=v?.reviewDecision==="APPROVED"?[]:x.approvals,G=[...L.length?[`${u.base} requires ${Qi(L.map((ye)=>`'${ye}'`))}, which ${L.length>1?"don't":"doesn't"} run on PRs (nothing by that name reported on this one)`]:[],...N?[`it needs ${x.reviews>1?`${x.reviews} approving reviews`:"an approving review"} on GitHub, which Superfactory's GitHub App can't give`]:[],...B.length?[`its pull request rule sets ${Qi(B)}, which wants an approving review of the app's pushes`]:[]],V=G.length?G.join("; "):"GitHub says its rules aren't met, though git merges it cleanly";try{return await S("--admin"),this.merged(d,u,p,`PR #${p} merged as an admin: ${sd(V)}, and Superfactory's GitHub App may bypass ${u.base}'s rules.`)}catch(ye){if(yt(Xe(ye)).kind==="moved")return this.refused(d,u,p,Xe(ye))}let Y;if(!L.length)try{if(!v?.autoMergeRequest)await S("--auto");return await this.deps.tasks.update(le(d),{pr:await this.view(u.cwd,p,d.pr?.checks??"none")}),this.wait(d,p,y,`${u.base}'s branch protection holds it back: ${sd(V)}, and Superfactory's GitHub App may not bypass it. Its auto-merge is on, so GitHub merges it once the rules are met. To merge at once, add the Superfactory app to the bypass list of ${u.base}'s ruleset or branch rule`)}catch(ye){Y=Xe(ye)}let ne=[`add the Superfactory app to the bypass list of ${u.base}'s ruleset or branch rule (Settings \u2192 Rules \u2192 Rulesets, or Settings \u2192 Branches)`,...L.length?[`drop ${Qi(L.map((ye)=>`'${ye}'`))} from its required checks, or run ${L.length>1?"them":"it"} on pull requests`]:[],...N?["drop its required review"]:[],...B.length?[`turn off ${Qi(B)}`]:[]];if(!G.length)ne.push("drop the rule that blocks it");if(Y)ne.push("turn on Allow auto-merge (Settings \u2192 General), so it merges once the rules are met");let ie=`${V}, and Superfactory's GitHub App may not bypass it${Y?` (auto-merge: ${Y})`:""}`;return this.wait(d,p,y,np(u.base,ie,ne).replace(/\.$/,""))}async closedOnApprove(d,u,p){let w=await vn(u.cwd,u.base,u.slug);if(w)return this.settled(d,u,p,`PR #${p.number} was closed on GitHub. ${Yi(w,u.base)}`);let y=await In(u.cwd,u.branch);if(y){let S=await this.view(u.cwd,y,p.checks);return await this.deps.tasks.update(le(d),{pr:S}),await this.deps.tasks.appendNote(le(d),`PR #${p.number} was closed on GitHub: PR #${y} from its branch merges instead.`),this.approve(d)}let v=(await Pv(u.cwd,u.branch,"merged"))[0];if(v)return this.settled(d,u,p,`PR #${p.number} was closed on GitHub: PR #${v} from its branch merged its work.`);return this.settled(d,u,p,`PR #${p.number} was closed on GitHub without merging, and its work isn't on ${u.base}: the task is done, with nothing merged.`)}async settled(d,u,p,w){if(await this.deps.tasks.update(le(d),{pr:p,status:"done"}),d.mergeApproval?.waiting)await this.deps.tasks.setMergeApproval(le(d),void 0);if(await this.deps.tasks.appendNote(le(d),w),u.parent&&p.state==="merged")await this.pullIntoParent(d,u.parent,u.base)}async refused(d,u,p,w){let y=yt(w,u.base);if(await this.deps.tasks.appendNote(le(d),`PR #${p} couldn't merge: ${w}`),!zs(y)&&y.kind!=="checks"&&d.status==="done")this.reopened.add(Ye(d));await this.deps.mergeFailed(le(d),y,await wi(u.cwd,p))}async publishForMerge(d,u){let p=le(d),w=!!d.runner&&d.runner!=="host";if(await this.commitLeftovers(d,u),!await this.notOnPr(d,u))return;let y=w?this.deps.sandboxFor(d)??"none":void 0,v=await ec(u.cwd,sh(u.settings),y);if(v.ran&&!v.passed)return await this.deps.tasks.appendNote(p,`Local checks failed, so nothing was pushed:
|
|
247
|
+
|
|
248
|
+
${eh(v.tail)}`),"its local checks fail, so its branch can't be pushed";try{await th(u.cwd,u.branch,w)}catch(S){return`pushing its branch failed: ${Xe(S)}`}try{let{pr:S,opened:x,carrier:j}=await this.openOrUpdate(d,u,v,!1,{summary:jp(d)});await this.deps.tasks.update(p,{pr:S}),await this.deps.tasks.appendNote(p,j?await this.sharedNote(d,j):`${x?"Opened":"Pushed to"} PR #${S.number} ${S.url} to merge it (local checks: ${Ha(v)})`)}catch(S){if(Lp(S))return;return`GitHub didn't open its PR: ${Xe(S)}`}return}async notOnPr(d,u){return(await this.offPr(d,u))?.reason}async offPr(d,u){if(d.pr&&!kt.includes(d.pr.state))return;let{task:p,unasked:w}=d.pr?{task:d,unasked:void 0}:await this.adoptOpenPr(d,u);if(!p.pr){if(await Pn(u.cwd,u.base))return;if(!await id(u.cwd,u.base))return;if(await vn(u.cwd,u.base,u.slug))return;let G=await a(u.cwd,(Y)=>Y.sub("ls-remote").flag("--heads").arg("origin").arg(`refs/heads/${u.branch}`)).catch(()=>""),V={branch:u.branch,base:u.base};if(!G.trim())return{kind:"unpushed",reason:"its branch isn't on GitHub, and it has no PR",...V};return w?{kind:"unknown",reason:`GitHub couldn't list its branch's PRs: ${w}`,...V}:{kind:"no-pr",reason:"its branch has no PR",...V}}let y=await wi(u.cwd,p.pr.number);if(!y)return;let v=await $n(u.cwd);if(y===v)return;let S=p.pr.branch||u.branch,x=await yh(u.cwd,S);if(x===v)return;await a(u.cwd,(G)=>G.sub("fetch").flag("--quiet").arg("origin").arg(`refs/heads/${S}`)).catch(()=>{return});let j=[];for(let G of new Set([y,x].filter((V)=>!!V)))if(await fv(u.cwd,G))j.push(G);if(!j.length)return;let L=(await a(u.cwd,(G)=>G.sub("rev-list").arg("HEAD").argsOf(j.map((V)=>`^${V}`))).catch(()=>"")).split(`
|
|
249
|
+
`).map((G)=>G.trim()).filter(Boolean);if(!L.length)return;let N=L.slice(0,3).map(_r).join(", "),B=L.length>3?` and ${L.length-3} more`:"";return{kind:"behind",reason:`${L.length} commit${L.length===1?"":"s"} not pushed to its PR (${N}${B}; its PR is at ${_r(y)})`,branch:S,base:u.base}}async adoptOpenPr(d,u){let p,w=await In(u.cwd,u.branch).catch((S)=>{p=Xe(S);return});if(!w)return{task:d,unasked:p};let y=await this.view(u.cwd,w,"none").catch(()=>{return});if(!y||y.branch!==u.branch)return{task:d};let v=le(d);return await this.deps.tasks.update(v,{pr:y}),await this.deps.tasks.appendNote(v,`GitHub: PR #${y.number} ${y.url} is open on its branch, so it's the task's PR.`),{task:await this.deps.tasks.get(v)}}async unmergeable(d){if(d.epic&&!d.pr)return;let u=await this.place(d,{quiet:!0});return u?this.notOnPr(d,u):void 0}async offPrForReview(d){if(d.epic&&!d.pr)return;let u=await this.place(d,{quiet:!0}),p=u?await this.offPr(d,u):void 0;return p?.kind==="unknown"?void 0:p}async nothingToMerge(d){if(d.pr)return!1;let u=await this.place(d,{quiet:!0});return!!u&&await Pn(u.cwd,u.base)}async unpublished(d,u){let p=Io(u);await this.deps.tasks.appendNote(le(d),p.message),this.reopened.add(Ye(d)),await this.deps.mergeFailed(le(d),p,void 0)}upToDate(d){let u={kind:"current"};return this.serial(d,async()=>{u=await this.mergeBaseIn(d)}).then(()=>u)}async mergeBaseIn(d){let u=await this.deps.tasks.get(le(d)),p=!!u.runner&&u.runner!=="host";if(u.pr?.state!=="open"||p||u.status!=="in_review")return{kind:"current"};let w=await this.place(u,{quiet:!0});if(!w||w.parent)return{kind:"current"};if(u.pr.branch&&u.pr.branch!==w.branch)return{kind:"current"};let y=await this.baseMergedIn(u,w);if(y.kind==="updated")await this.deps.tasks.appendNote(le(u),`Brought PR #${u.pr?.number} up to date with ${w.base} (${y.count} commit${y.count===1?"":"s"}) before asking to merge it, so the commit you approve is one GitHub can merge.`);if(y.kind==="updated")return{kind:"updated"};return y.kind==="conflict"?y:{kind:"current"}}async baseMergedIn(d,u,{checks:p=!1,approved:w}={}){let y=`origin/${u.base}`;return We(u.cwd,async()=>{await a(u.cwd,(B)=>B.sub("fetch").flag("--quiet").arg("origin").arg(`${u.base}:refs/remotes/${y}`));let v=await a(u.cwd,(B)=>B.sub("rev-list").flag("--count").arg(`HEAD..${y}`)),S=Number(v.trim())||0;if(!S)return{kind:"current"};let x=await $n(u.cwd),j=await he(u.cwd);if(!await a(u.cwd,(B)=>B.env(j).sub("merge").flag("--quiet").flag("--message",`Merge ${y} into ${u.branch}`).arg(y)).then(()=>!0,()=>!1))return await a(u.cwd,(B)=>B.sub("merge").flag("--abort")).catch(()=>{return}),{kind:"conflict",raw:`the branch conflicts with ${u.base}: merging it in by code failed`};let N=await $n(u.cwd);if(w){let B=await sc(u.cwd,w,N,u.base);if(B.kind!=="base")return await a(u.cwd,(G)=>G.sub("reset").flag("--keep").flag("--quiet").arg(x)).catch(()=>{return}),{kind:"changed",what:B.kind==="changed"?B.what:"nothing of its base came in"}}if(p){let B=await ec(u.cwd,sh(u.settings));if(B.ran)await this.recordChecks(le(d),B,u.cwd);if(B.ran&&!B.passed)return await a(u.cwd,(G)=>G.sub("reset").flag("--keep").flag("--quiet").arg(x)).catch(()=>{return}),{kind:"failing"};if(w&&await $n(u.cwd)!==N)return await a(u.cwd,(G)=>G.sub("reset").flag("--keep").flag("--quiet").arg(x)).catch(()=>{return}),{kind:"changed",what:"its branch moved here while its checks ran"};if(B.ran)this.checkedHeads.set(Ye(d),N)}try{await Nn(u.cwd,u.branch,{src:N})}catch(B){return await a(u.cwd,(G)=>G.sub("reset").flag("--keep").flag("--quiet").arg(x)).catch(()=>{return}),await this.deps.tasks.appendNote(le(d),`Couldn't bring PR #${d.pr?.number} up to date with ${u.base}: pushing the merge failed, so it was undone and the PR is asked about as it is.
|
|
250
|
+
|
|
251
|
+
${eh(CE(B))}`),{kind:"current"}}if(w){let B=await tc(this.approvalProject(d),w,N,u.base);if(B.kind==="base"&&B.resolved.length)return{kind:"changed",what:`${Qi(B.resolved)} differ from a clean merge`};if(B.kind!=="base")return{kind:"changed",what:B.kind==="changed"?B.what:"nothing of its base came in"}}return{kind:"updated",head:N,count:S}})}idle(d){return this.running.get(Ye(d))??Promise.resolve()}async prHeadOf(d){let u=d.pr&&await this.place(d,{quiet:!0});if(!u||!d.pr)return;let p=await yh(u.cwd,d.pr.branch||u.branch);for(let w=Date.now()+bE;;await Bun.sleep(250)){let y=await wi(u.cwd,d.pr.number);if(!y||!p||y===p||Date.now()>=w)return y&&p?p:y}}async markReady(d,u){let p={refused:"GitHub didn't answer"};return await this.serial(d,async()=>{try{p=await this.readyOwn(d,u)}catch(w){p={refused:`GitHub: ${w.message.split(`
|
|
252
|
+
`)[0]}`}}}),p}async readyOwn(d,u){let p=await this.place(d,{quiet:!0});if(!p)return{notHere:`this machine doesn't push ${d.id}'s branch or open its PR`};let w=u??Number(await In(p.cwd,p.branch));if(!w)return{refused:`${p.branch} has no open PR`};let y=await this.view(p.cwd,String(w),d.pr?.checks??"none");if(y.branch!==p.branch)return{refused:`PR #${w} is from ${y.branch}, not ${d.id}'s branch ${p.branch}`};if(y.state!=="draft"&&y.state!=="open")return{refused:`PR #${w} is ${y.state}`};if(y.state==="draft")await Q(p.cwd,(S)=>S.sub("pr ready").arg(String(w)));let v={...y,state:"open"};if(!d.pr||d.pr.number===w)await this.deps.tasks.update(le(d),{pr:v});return{pr:v}}async sinceAsked(d,u,p){let w=await this.place(d,{quiet:!0});if(!w)return{kind:"changed",what:"its worktree isn't on this machine"};return tc(this.approvalProject(d),u,p,w.base)}async sinceApproval(d,u){let p=d.pr?.number,w=p?await this.place(d,{quiet:!0}):void 0,y=w?await fe(w.cwd,(L)=>L.sub("pr view").arg(String(p)).flag("--json","headRefOid,statusCheckRollup")).catch(()=>{return}):void 0,v=y?.headRefOid;if(!w||!v)return{since:{kind:"changed",what:"GitHub didn't say where its PR is now"},checks:"none"};let S=await za(w.cwd,{number:p??0,statusCheckRollup:y?.statusCheckRollup??[]}),x=this.checkedHeads.get(Ye(d))===v?"passing":void 0,j=S==="failing"||S==="pending"?S:S??x??"none";return{since:await tc(this.approvalProject(d),u,v,w.base),head:v,checks:j}}approvalProject(d){return{projectId:d.projectId,projectPath:this.deps.projects.path(d.projectId)}}async carriedThrough(d,u,p){let w=d.pr?.number,y=`${bi(p)}; the branch was brought up to date with ${u.base}.`;if(w)await _f(u.cwd,u.slug,w,`Merged ${y}`).catch((v)=>s.warn(`github: couldn't comment on ${d.id}'s PR #${w}`,v));await this.deps.tasks.appendNote(le(d),`PR #${w} merged ${y}`)}async pullIntoParent(d,u,p){let w=this.deps.projects.path(d.projectId);await a(w,(S)=>S.sub("fetch").flag("--quiet").arg("origin").arg(`${p}:refs/remotes/origin/${p}`));let y=await el(w,u,`origin/${p}`,`Merge ${d.id} into ${u.id}`,!1),v=le(u);await this.deps.tasks.appendNote(v,y.merged?`${d.id} ${d.title} was merged into this branch (PR #${d.pr?.number}).`:`${d.id} was merged into this branch on GitHub, but pulling it here failed: ${y.reason}.`)}relinkDue(d){let u=this.relinkLooked.get(Ye(d));if(u!==void 0&&Date.now()-u<hv)return!1;return this.relinkLooked.set(Ye(d),Date.now()),!0}async relink(d,u,p){let w=p.branch||d.pr?.branch;if(!w)return!1;let y=await In(u,w).catch(()=>{return});if(!y||y===String(p.number))return!1;let v=await this.view(u,y,"none").catch(()=>{return});if(!v||v.branch!==w||!kt.includes(v.state))return!1;return await this.deps.tasks.update(le(d),{pr:v}),await this.deps.tasks.appendNote(le(d),`PR #${p.number} was closed on GitHub; PR #${v.number} ${v.url}, open from its branch ${w}, is the task's PR now.`),!0}async replaceClosed(d){let u=await this.deps.tasks.get(le(d));if(!u.pr||u.pr.state==="merged"||!td.includes(u.status))return u;let p=await this.place(u,{quiet:!0});if(!p||u.pr.branch&&u.pr.branch!==p.branch)return u;let w=u.pr.state==="closed"?u.pr:await this.view(p.cwd,String(u.pr.number),u.pr.checks).catch(()=>{return});if(w?.state!=="closed"||w.branch!==p.branch)return u;if(!await this.relink(u,p.cwd,w))await this.deps.tasks.forgetPr(le(u)),await this.deps.tasks.appendNote(le(u),`PR #${w.number} was closed on GitHub and its branch ${p.branch} has no open PR: the task has none now, and its next one opens from its branch.`);return this.deps.tasks.get(le(u))}async withLivePr(d){if(!d.pr||!this.worksHere(d)||!await this.syncOn(d.projectId))return d;let u=d;return await this.serial(d,async()=>{u=await this.replaceClosed(d)}),u}async close(d){let u=await this.deps.tasks.get(le(d));if(!u.pr||!kt.includes(u.pr.state))return;let p=await this.place(u);if(!p||!await this.ownPr(u,p))return;let w=u.pr.number;await Q(p.cwd,(y)=>y.sub("pr close").arg(w).flag("--comment","The task was cancelled in Superfactory.")),await this.deps.tasks.update(le(u),{pr:{...u.pr,state:"closed"}}),await this.deps.tasks.appendNote(le(u),`Closed PR #${u.pr.number}.`)}async mirror(d,u){let p=le(d),w=await this.deps.tasks.get(p);if(!w.pr||!kt.includes(w.pr.state))return;let y=this.deps.projects.path(w.projectId),v=ee(y,w.id),S=await this.repoOf(y,v);if(!S)return;let x=u?.get(w.pr.number)??await wv(v,String(w.pr.number)),j=xE(x),L=this.looked.get(Ye(w)),N=!!j&&L?.marks===j&&Date.now()-L.at<hv,B=x.state!=="OPEN"?void 0:N?w.pr.behind:await kv(v,x.baseRefName,x.headRefName),G=yv(x,await za(v,x)??w.pr.checks,B),V=w.questions.find((ie)=>ie.purpose==="merge"&&ie.status==="open");if(w.status==="in_review"&&V?.head&&x.headRefOid&&x.headRefOid!==V.head)this.deps.prMoved(p).catch((ie)=>s.warn(`github: ${w.id}: its moved PR wasn't looked at`,ie));let Y,ne=N?[]:await Of(v,S.slug,G.number).catch((ie)=>(Y=ie,[]));if(!N&&!Y&&j)this.looked.set(Ye(w),{marks:j,at:Date.now()});for(let ie of ME(w.reviewComments,ne))if(await this.trusted(v,S.slug,ie.author))await this.deps.deliverComment(p,ie);else await this.keepUntrusted(p,ie);if(G.state==="merged"&&w.status!=="done"){await this.deps.tasks.update(p,{pr:G,status:"done"}),await this.deps.tasks.appendNote(p,`PR #${G.number} was merged on GitHub.`);let ie=w.buildsOn||w.epic?await this.place(w,{quiet:!0}):void 0;if(ie?.parent&&G.base===ie.base)await this.pullIntoParent(w,ie.parent,ie.base)}else if(G.state==="closed"&&w.status!=="done"&&w.status!=="cancelled"){let ie=await this.bundleLeadOf(w);if(ie){if(await this.deps.tasks.forgetPr(p),await this.deps.tasks.appendNote(p,`PR #${G.number} was closed on GitHub. ${w.id}'s work ships in ${ie.id}'s PR, its bundle's one PR, so it stays open.`),Y)throw Y;return}if(await this.relink(w,v,G)){if(Y)throw Y;return}let ye=G.base??S.defaultBranch,ve=await vn(v,ye,S.slug);await this.deps.tasks.update(p,{pr:G,status:ve?"done":"cancelled"}),await this.deps.tasks.appendNote(p,`PR #${G.number} was closed on GitHub.${ve?` ${Yi(ve,ye)}`:""}`)}else if(!OE(G,w.pr)){if(await this.deps.tasks.update(p,{pr:G}),w.pr.state==="draft"&&G.state==="open")Wr({projects:this.deps.projects,tasks:this.deps.tasks,offPr:(ie)=>this.offPrForReview(ie),withLivePr:async(ie)=>ie},p);if(G.base!==w.pr.base&&w.status!=="done")this.baseChecked.add(Ye(w)),await this.repairBase(w);if(G.state==="merged"&&w.mergeApproval)await this.deps.tasks.setMergeApproval(p,void 0),await this.deps.tasks.appendNote(p,`PR #${G.number} merged on GitHub.`);if(At(w)&&w.pr.checks==="pending"&&G.checks!=="pending")await this.approve(w)}if(!this.baseChecked.has(Ye(w))&&kt.includes(G.state)&&w.status!=="done")this.baseChecked.add(Ye(w)),await this.repairBase(w);if(Y)throw Y}async trusted(d,u,p){let w=p.replace(/^github:/,""),y=`${u}/${w}`,v=this.permissions.get(y);if(v&&v.until>Date.now())return v.trusted;let S=await Q(d,(j)=>j.sub("api").arg(`repos/${u}/collaborators/${encodeURIComponent(w)}/permission`).flag("--jq",".permission")).catch(()=>"none"),x=vE.includes(S.trim());return this.permissions.set(y,{trusted:x,until:Date.now()+kE}),x}async keepUntrusted(d,u){await this.deps.tasks.addReviewComment(d,u),await this.deps.tasks.appendNote(d,`GitHub comment by ${u.author} on ${u.file} kept on the task but not sent to the agent: they don't have write access to the repository.`)}async retarget(d,u,p,w,y){if(!p.base||p.base===u.base||p.branch!==u.branch)return;let v=await gv(u,p.base);if(v.length&&y!==u.base)return rp(u.base,v).raw;if(!await bv(u))return`its work lands on ${u.base}, which is neither on GitHub nor on this machine, so its PR can't target it`;await Q(u.cwd,(S)=>S.sub("pr edit").arg(w).flag("--base",u.base)),await this.deps.tasks.appendNote(le(d),`GitHub: PR #${w} targeted ${p.base}, where it no longer lands: retargeted to ${u.base} before merging${v.length?`, with ${Qi(v)}'s work, as ${d.mergeApproval?.by??"the person"} chose`:""}.`);return}async repairBase(d){let u=await this.deps.tasks.get(le(d));if(!u.pr||!kt.includes(u.pr.state)||u.status==="done")return;let p=await this.place(u,{quiet:!0}),w=u.pr.base;if(!p||!w||w===p.base)return;if((await gv(p,w)).length||!await bv(p,!1))return;if(!await this.ownPr(u,p))return;let y=String(u.pr.number);await Q(p.cwd,(v)=>v.sub("pr edit").arg(y).flag("--base",p.base)),await this.deps.tasks.update(le(u),{pr:{...u.pr,base:p.base}}),await this.deps.tasks.appendCountedNote(le(u),`GitHub: PR #${y} targeted ${w}, but ${u.id}'s work lands on ${p.base}${p.parent?` (${p.parent.kind==="epic"?"its epic":"the task it builds on"} ${D(p.parent.id,this.deps.projects.keys(u.projectId).key)}'s branch)`:""}: retargeted.`)}async ownPr(d,u,{shared:p=!1}={}){if(!d.pr)return;let w=await this.view(u.cwd,String(d.pr.number),d.pr.checks);if(w.branch===u.branch||p&&!!d.pr.branch&&w.branch===d.pr.branch)return w;await this.deps.tasks.appendNote(le(d),`GitHub: PR #${w.number} is from ${w.branch}, not this task's branch ${u.branch}, so it was left alone.`);return}async view(d,u,p){let w=await wv(d,u),y=w.state==="OPEN"?await kv(d,w.baseRefName,w.headRefName):void 0;return yv(w,await za(d,w)??p,y)}async repoOf(d,u){let p=this.repos.get(d);if(p&&p.until>Date.now())return p.repo;let w=await Xu(u);if(w)this.repos.set(d,{repo:w,until:Date.now()+pv});else this.repos.delete(d);return w}async openPrs(d){let u=this.deps.projects.path(d),p=await this.repoOf(u,u);if(!p||(this.unlisted.get(p.slug)??0)>Date.now())return;return Rf(u,p.slug).catch((w)=>{s.warn(`github: couldn't list ${p.slug}'s open PRs; looking at each for a while`,w),this.unlisted.set(p.slug,Date.now()+pv);return})}async syncOn(d){let u=await this.deps.projects.settings(d).catch(()=>{return});return!!u?.["github.sync"]&&u["git.flow"]!=="direct"}async place(d,{quiet:u=!1}={}){let p=await this.deps.projects.settings(d.projectId);if(!p["github.sync"]||p["git.flow"]==="direct")return;let w=this.deps.projects.path(d.projectId);if(!await Ae(w))return;let y=async(G)=>{if(!u)await this.deps.tasks.appendNote(le(d),G)},v=ee(w,d.id),S=v===w?"":(await a(v,(G)=>G.sub("branch").flag("--show-current"))).trim();if(!S){if(!await this.deps.runsElsewhere(d))await y("GitHub: the task has no branch of its own, so no PR.");return}if(!Jt(d.id,S)){await y(`GitHub: its worktree is on ${S}, not its own branch (sf/${d.id}-\u2026), so nothing is pushed and no PR opened: a task pushes its own branch only.`);return}let x=await this.repoOf(w,v);if(!x){await y("GitHub: gh can't see the project's GitHub repository, so no PR: sign the project in to GitHub (Project settings \u203A Git and GitHub), or run `gh auth login` on this machine.");return}let j=p["git.flow"]==="dev-prs"?p["git.devBranch"]:p["git.baseBranch"]||x.defaultBranch,{parent:L,unmerged:N}=await Gr(d,(G)=>this.deps.tasks.get({projectId:d.projectId,taskId:G}).catch(()=>{return})),B=N.map((G)=>D(G,this.deps.projects.keys(d.projectId).key));if(L){let G=await Cf(w,L);return{cwd:v,branch:S,slug:x.slug,base:G,home:j,settings:p,parent:L,unmerged:B}}return{cwd:v,branch:S,slug:x.slug,base:j,home:j,settings:p,unmerged:B}}}var le=(d)=>({projectId:d.projectId,taskId:d.id}),Ye=(d)=>`${d.projectId}/${d.id}`;function Lp(d){return/\bNo commits between\b/.test(Xe(d))}function Xe(d){return((d instanceof xt?d.result.stderr||d.result.stdout:String(d)).split(`
|
|
253
|
+
`).find((w)=>w.trim())??"GitHub refused it.").replace(/^\s*X\s+/,"").trim()}function RE(d,u,p){if(u?.mergeable==="CONFLICTING"&&yt(d).kind!=="conflicts")return`the branch conflicts with ${p}: ${d}`;if(u?.mergeable==="MERGEABLE"&&yt(d).kind==="conflicts")return`GitHub refused the merge (merge state ${u.mergeStateStatus??"unknown"}), though git merges the branch cleanly: ${d.replace(/\b(?:not mergeable|unmergeable)\b/gi,"refused")}`;return d}var Sv=(d)=>/\bbase branch was modified\b/i.test(d),AE=3;async function mv(d){for(let u=1;;u++)try{await d();return}catch(p){if(u>=AE||!Sv(Xe(p)))throw p;await Bun.sleep(k("SUPERFACTORY_BASE_MOVED_RETRY_MS",3000)*u)}}function gh(d){if(Qu(d))return!0;if(yt(d).kind!=="other")return!1;return/\b50[0234]\b|bad gateway|service unavailable|timed? ?out|ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|ENOTFOUND|network|rate limit|try again|something went wrong|temporarily/i.test(d)}function EE(d){let u=d.questions.filter((v)=>v.purpose==="merge"),p=u.findLast((v)=>v.status==="open");if(!p?.error||d.pr?.state!=="open")return!1;let w=p.error.raw??p.error.message;if(yt(w).kind!=="protected"&&!gh(w))return!1;let y=u.findLast((v)=>v.status==="answered");return!!y?.answer?.choiceIds?.includes(Yt)&&!!y.head&&y.head===p.head}var Np=(d)=>d.questions.findLast((u)=>u.purpose==="merge"&&u.answer?.choiceIds?.includes(Yt))?.answer?.by??"superfactory",Qi=(d)=>d.length>1?`${d.slice(0,-1).join(", ")} and ${d.at(-1)}`:d[0]??"";async function $n(d){return(await a(d,(u)=>u.sub("rev-parse").arg("HEAD"))).trim()}async function fv(d,u){return a(d,(p)=>p.sub("rev-parse").flag("--verify").flag("--quiet").arg(`${u}^{commit}`)).then(()=>!0,()=>!1)}var _r=(d)=>d.slice(0,8);function CE(d){return d instanceof Va?d.message:Xe(d)}var sd=(d)=>d.charAt(0).toLowerCase()+d.slice(1),eh=(d)=>`\`\`\`
|
|
254
|
+
${d}
|
|
255
|
+
\`\`\``;async function th(d,u,p){if(!p)return Nn(d,u,{upstream:!0});await a(d,(w)=>w.sub("push").flag("--set-upstream").arg("origin").arg(`HEAD:refs/heads/${u}`))}function sh(d){let u=d["git.checkCommand"];return Array.isArray(u)?u.map(String):[]}function _E(d){return d.ran?d.passed?"passing":"failing":"none"}var OE=(d,u)=>d.state===u.state&&d.checks===u.checks&&d.review===u.review&&d.behind===u.behind&&d.url===u.url&&d.branch===u.branch&&d.base===u.base;async function yh(d,u){return(await a(d,(w)=>w.sub("ls-remote").flag("--heads").arg("origin").arg(`refs/heads/${u}`)).catch(()=>"")).split("\t")[0]?.trim()||void 0}async function id(d,u){for(let p of[u,`origin/${u}`]){let w=await a(d,(y)=>y.sub("rev-list").flag("--count").arg(`${p}..HEAD`)).catch(()=>{return});if(w!==void 0)return Number(w.trim())||0}return 0}async function gv(d,u){if(!d.unmerged.length)return[];if(!await a(d.cwd,(v)=>v.sub("fetch").flag("--quiet").arg("origin").argsOf([...new Set([u,d.base,d.home])].map((S)=>`+refs/heads/${S}:refs/remotes/origin/${S}`))).then(()=>!0,()=>!1))return d.unmerged;let w=await a(d.cwd,(v)=>v.sub("merge-base").arg("HEAD").arg(`origin/${u}`)).catch(()=>"");if(!w.trim())return[];let y=await a(d.cwd,(v)=>v.sub("rev-list").flag("--count").arg(w.trim()).arg(`^origin/${d.base}`).arg(`^origin/${d.home}`)).catch(()=>"");if(!y.trim())return d.unmerged;return Number(y.trim())>0?d.unmerged:[]}async function wv(d,u){return fe(d,(p)=>p.sub("pr view").arg(u).flag("--json",Af))}function xE(d){return d.headRefOid&&d.updatedAt?`${d.headRefOid} ${d.updatedAt} ${d.baseRefOid??""}`:void 0}function yv(d,u,p){return{number:d.number,url:d.url,state:d.state==="MERGED"?"merged":d.state==="CLOSED"?"closed":d.isDraft?"draft":"open",checks:u,review:TE[d.reviewDecision]??"none",branch:d.headRefName,base:d.baseRefName,behind:p}}async function kv(d,u,p){let w=await Q(d,(v)=>v.sub("api").arg(`repos/{owner}/{repo}/compare/${u}...${p}`).flag("--jq",".behind_by")).catch(()=>""),y=Number.parseInt(w.trim(),10);return Number.isInteger(y)&&y>=0?y:void 0}function ME(d,u){let p=(y)=>`${y.author}
|
|
256
|
+
${y.file}
|
|
257
|
+
${y.line??""}
|
|
258
|
+
${y.body}`,w=new Set(d.map(p));return u.filter((y)=>y.line!==null&&y.body.trim()).map((y)=>({file:y.path,line:y.start_line??y.line??void 0,endLine:y.start_line?y.line??void 0:void 0,side:y.side==="LEFT"?"old":"new",commit:y.commit_id,author:`github:${y.user.login}`,body:y.body})).filter((y)=>!w.has(p(y)))}async function jE(d,u){return(await fe(d,(p)=>p.sub("pr view").arg(u).flag("--json","body"))).body}async function In(d,u){return(await Pv(d,u,"open"))[0]}async function Pv(d,u,p){return(await fe(d,(y)=>y.sub("pr list").flag("--head",u).flag("--state",p).flag("--json","number"))).map((y)=>String(y.number))}async function LE(d){return(await a(d,(p)=>p.sub("status").flag("--porcelain")).catch(()=>"")).split(`
|
|
259
|
+
`).filter((p)=>p.trim()).map((p)=>({status:p.slice(0,2),path:p.slice(3).replace(/^.* -> /,"").replace(/^"(.*)"$/,"$1")}))}async function NE(d,u){for(let p of[u,`origin/${u}`]){let w=await a(d,(y)=>y.sub("diff").flag("--name-only").arg(`${p}...HEAD`)).catch(()=>{return});if(w!==void 0)return w.split(`
|
|
260
|
+
`).filter(Boolean)}return[]}async function bv(d,u=!0){if(!d.parent)return!0;if(!u)return!!await yh(d.cwd,d.base);return $v(d).then(()=>!0,()=>!1)}async function $v(d){await Iv(d.cwd,d.slug,d.base,d.home,`refs/heads/${d.base}`)}async function DE(d){if(d.settings["git.flow"]!=="dev-prs")return;let u=await Xu(d.cwd);if(!u)return;await Iv(d.cwd,d.slug,d.base,u.defaultBranch)}async function Iv(d,u,p,w,y){let v=(j)=>fe(d,(L)=>L.sub("api").arg(`repos/${u}/git/ref/heads/${j}`)).then((L)=>L.object?.sha,()=>{return});if(await v(p))return;let S=await v(w);if(!S)throw Error(`${w} isn't on GitHub: ${p} can't be made from it`);let x=y?(await a(d,(j)=>j.sub("merge-base").arg(y).arg(S)).catch(()=>"")).trim():"";await Q(d,(j)=>j.sub("api").flag("--method","POST").arg(`repos/${u}/git/refs`).flag("-f",`ref=refs/heads/${p}`).flag("-f",`sha=${/^[0-9a-f]{40,64}$/.test(x)?x:S}`))}function UE(d){return d.questions.findLast((u)=>u.purpose==="merge"&&u.head)?.head}function vv(d,u,p,w){let y=new Map(w.map((x)=>[x.id,x])),v=(x)=>{let j=new Set;for(let L=x;L&&!j.has(L.id);L=L.buildsOn?y.get(L.buildsOn):void 0)if(j.add(L.id),L.buildsOn&&!y.has(L.buildsOn))j.add(L.buildsOn);return j},S=v(d);return w.some((x)=>x.id!==d.id&&x.pr?.number===u&&(!x.pr.branch||x.pr.branch===p)&&(!!d.epic&&(x.epic===d.epic||x.id===d.epic)||!!x.epic&&x.epic===d.id||wr(d,x)||[...v(x)].some((j)=>S.has(j))))}var Tv=1000,Rv=()=>k("SUPERFACTORY_STALL_MS",5000);class bh{stalled;timer;wall=0;mono=0;cpu=0;constructor(d){this.stalled=d}start(){this.mark(),this.timer=setInterval(()=>this.tick(),Tv),this.timer.unref?.()}stop(){clearInterval(this.timer)}mark(){this.wall=Date.now(),this.mono=performance.now();let{user:d,system:u}=process.cpuUsage();this.cpu=(d+u)/1000}tick(){let{wall:d,mono:u,cpu:p}=this;this.mark();let w=this.wall-d,y=this.mono-u,v=Math.max(w,y);if(v-Tv<Rv())return;let S=y>0?(this.cpu-p)/y*100:0,x=w-y>Rv()/2?"slept":S>=50?"busy":"held";this.stalled({ms:Math.round(v),at:new Date(this.wall).toISOString(),why:x,cpuPct:S})}}import{appendFile as FE,readFile as BE}from"fs/promises";import{join as Ev}from"path";var WE=k("SUPERFACTORY_AWAY_WATCH_MS",2000),Av=3,Ji=process.env.SUPERFACTORY_AWAY_FAKE;class Sh{changed;since;keepAwake;watch;constructor(d){this.changed=d}get state(){return this.since?{since:this.since}:void 0}async set(d){if(d)await this.start();else this.end("turned off")}async start(){if(!Ji&&(process.platform!=="darwin"||process.env.SUPERFACTORY_SANDBOX))throw new c("conflict","Away needs a Mac: it turns a Mac's screens off.");if(!this.since){let d=Date.now();this.since=new Date(d).toISOString(),this.keepAwake=await HE(),this.watch=setInterval(()=>void this.lookForUser(d),WE),this.changed(),s.info("away: on")}await qE(r(bd).sub("displaysleepnow").by("away").timeoutMs(1e4).build()).catch((d)=>{throw this.end("the screens didn't turn off"),new c("internal",`Couldn't turn the screens off: ${d.message}`)})}async lookForUser(d){let u=await GE().catch(()=>{return}),p=(Date.now()-d)/1000;if(this.since!==new Date(d).toISOString())return;if(u!==void 0&&p>Av&&u<p-Av)this.end("you're back")}end(d){if(!this.since)return;clearInterval(this.watch),this.keepAwake?.kill(),this.keepAwake=void 0,this.since=void 0,this.changed(),s.info(`away: off, ${d}`)}}async function HE(){let d=r(Ks).flag("-i").flag("-w",process.pid).by("away").build();if(Ji)return await vh(d),{kill:()=>vh({...d,argv:["(stopped)"]})};return _(d,{stdin:"ignore",stdout:"ignore",stderr:"ignore"})}async function GE(){if(Ji){let p=await BE(Ev(Ji,"idle"),"utf8").catch(()=>"");return p.trim()?Number(p):void 0}let u=(await T(r(kd).flag("-r").flag("-c","IOHIDSystem").flag("-k","HIDIdleTime").flag("-d","1").by("away").timeoutMs(1e4).build())).match(/"HIDIdleTime" = (\d+)/)?.[1];return u?Number(u)/1e9:void 0}async function qE(d){if(Ji)await vh(d);else await T(d)}function vh(d){return FE(Ev(Ji??"","commands"),`${[d.program,...d.argv].join(" ")}
|
|
261
|
+
`)}import{existsSync as Cv}from"fs";import{lstat as jv,readdir as xr,readFile as VE,rm as Rh,stat as YE,statfs as KE}from"fs/promises";import{homedir as QE}from"os";import{join as Lt,relative as JE,sep as zE}from"path";var Or=1e9,od=3600000,XE=10*Or,ZE=30*Or,eC=5,tC=1,sC=2,nC=0.75,iC=2,rC=4,po=1800000,oC="/ holds root's Docker too, with the server's images: each deploy prunes them to the live one and the rollback's (as root: /opt/superfactory/bin/superfactory-vm prune)";function aC(d){return{on:d["machine.diskCleanup"],lowFreePct:d["machine.diskLowFreePct"],buildCacheHours:d["machine.diskBuildCacheHours"],buildCacheGb:d["machine.diskBuildCacheGb"],imageHours:d["machine.diskImageHours"],buildOutputDays:d["machine.diskBuildOutputDays"]}}var cd=(d)=>d.totalBytes?d.freeBytes/d.totalBytes*100:100,ad=(d,u)=>d.freeBytes<XE||cd(d)<u&&d.freeBytes<ZE;async function dC(d){let u=process.env.SUPERFACTORY_E2E_METHODS==="1"?process.env.SUPERFACTORY_FAKE_DF:void 0;if(u){let w=JSON.parse(await VE(u,"utf8"));return{path:d,...w}}let p=await KE(d).catch(()=>{return});if(!p)return;return{path:d,totalBytes:p.blocks*p.bsize,freeBytes:p.bavail*p.bsize}}var cC={B:1,KB:1000,MB:1e6,GB:1e9,TB:1000000000000};function Lv(d){let u=d.match(/Total(?: reclaimed space)?:\s*([\d.]+)\s*([kKMGT]?)i?B/);if(!u)return 0;return Math.round(Number(u[1])*(cC[`${(u[2]??"").toUpperCase()}B`]??1))}var uC=(d)=>d.state!=="exited"&&d.state!=="failed";class Ch{deps;state;lastRun;lastFreed=Number.POSITIVE_INFINITY;wasLow=!1;lastAlert;running;told;constructor(d){this.deps=d}check(d=Date.now()){return this.running??=this.checkNow(d).finally(()=>{this.running=void 0}),this.running}async checkNow(d){let u=aC(await this.deps.settings()),p=await this.disks();if(!p.length)return;let w=_v(p),y=p.some((B)=>ad(B,u.lowFreePct));if(this.update(w,y,d),!u.on)return this.state=this.state&&{...this.state,alertedAt:void 0,biggest:void 0},this.say();this.lastRun??=d;let v=y&&!this.wasLow;this.wasLow=y;let S=d-this.lastRun,x=k("SUPERFACTORY_DISK_CLEANUP_MS",od),j=this.lastFreed>=Or/10,L=j?k("SUPERFACTORY_DISK_LOW_RETRY_MS",600000):x;if(!(S>=x||y&&(v&&j||S>=L)))return this.say();await this.cleanUp(y?"low":"schedule",u,d)}async cleanUp(d,u,p=Date.now()){this.lastRun=p;let w=[],y=await bC();if(y)w.push(await $h({hours:u.imageHours})),w.push(await dd({hours:u.buildCacheHours})),Xi(w,await dd({maxBytes:u.buildCacheGb*Or}));w.push(await this.buildOutputs(u.buildOutputDays,p));let v=await this.disks();if(y&&v.some((L)=>ad(L,u.lowFreePct)))s.warn("disk: still low after cleaning up: older images of each name, older build cache, unnamed volumes"),Xi(w,await $C(sC)),Xi(w,await dd({hours:Math.min(tC,u.buildCacheHours)})),Xi(w,await IC()),v=await this.disks();if(vC()&&v.some((L)=>ad(L,u.lowFreePct)))w.push(...await PC()),v=await this.disks();if(y&&v.some((L)=>cd(L)<eC))s.warn("disk: still under 5% free: every image and all the build cache nothing uses"),Xi(w,await $h({})),Xi(w,await dd({})),v=await this.disks();let S=w.reduce((L,N)=>L+N.freedBytes,0);this.lastFreed=S;let x=v.length?_v(v):void 0,j=v.some((L)=>ad(L,u.lowFreePct));if(s.info(`disk: cleaned up (${d==="low"?"free space low":"hourly"}): freed ${ur(S)}; ${w.map(lC).join("; ")}${x?`; now ${sp(x)} on ${x.path}`:""}`),!x)return;if(this.update(x,j,p),this.state)this.state.lastCleanup={at:new Date(p).toISOString(),why:d,freedBytes:S,steps:w};if(j)await this.alertIfDue(x,p);this.say(!0)}update(d,u,p){if(this.state={...this.state,path:d.path,totalBytes:d.totalBytes,freeBytes:d.freeBytes,low:u,at:new Date(p).toISOString()},!u)delete this.state.alertedAt,delete this.state.biggest;if(this.lastAlert&&d.freeBytes>this.lastAlert.freeBytes*iC)this.lastAlert=void 0}async alertIfDue(d,u){let p=this.state;if(!p)return;let w=this.lastAlert;if(!(!w||u-w.at>=k("SUPERFACTORY_DISK_ALERT_AGAIN_MS",24*od)||d.freeBytes<w.freeBytes*nC))return;p.alertedAt=new Date(u).toISOString(),p.biggest=await this.biggest(),this.lastAlert={at:u,freeBytes:d.freeBytes},s.warn(`disk: still low after cleaning up (${sp(d)} on ${d.path}); its leads are told. Biggest: ${p.biggest.join(", ")||"unknown"}`)}say(d=!1){let u=this.state;if(!u)return;let p=this.told,w=!p||p.low!==u.low||Math.abs(p.freeBytes-u.freeBytes)>=u.totalBytes/100||Date.parse(u.at)-Date.parse(p.at)>=od;if(!d&&!w)return;this.told={low:u.low,freeBytes:u.freeBytes,at:u.at},this.deps.changed()}async disks(){let d=this.deps.projects.ids().map((y)=>this.deps.projects.path(y)),u=await Dv();if(u&&Cv(u))d.push(u);if(process.env[ls])d.push("/");let p=new Set,w=[];for(let y of d){let v=(await YE(y).catch(()=>{return}))?.dev;if(v===void 0||p.has(v))continue;p.add(v);let S=await dC(y);if(S)w.push(S)}return w}async buildOutputs(d,u){let p={step:"build_outputs",freedBytes:0,items:0};if(d<=0)return p;let w=u-d*24*od;for(let y of this.deps.projects.ids())try{await this.projectBuildOutputs(y,w,p)}catch(v){s.warn(`disk: build outputs of ${y}`,v),p.error=String(v).slice(0,500)}return p}async projectBuildOutputs(d,u,p){let w=Lt(E(this.deps.projects.path(d)).root,"worktrees"),y=await xr(w).catch(()=>[]);if(!y.length)return;let v=await this.deps.tasks.list(d),S=await this.deps.sessions().list(d);for(let x of y){let j=pC(v,x);if(!j)continue;let L={projectId:d,taskId:j.id},N=this.deps.removals.mark(L),B=Lt(w,x),G=await wC(B);if(!G.length)continue;let V=await mC(B,S.filter((Y)=>Y.taskId===j.id),u);if(V){s.info(`disk: kept the build outputs of ${x}: ${V}`);continue}await this.deps.removals.remove(L,N,async()=>{let Y=!1;for(let ne of G){let ie=await Zi(ne);if(await Rh(ne,{recursive:!0,force:!0,maxRetries:3}),p.freedBytes+=ie,p.items+=1,ne.endsWith("node_modules"))Y=!0;s.info(`disk: removed ${ne} (${ur(ie)}): ${j.id} untouched since before the cutoff`)}if(Y)await kC(B)})}}async biggest(){let d=[...await Uv()];for(let u of this.deps.projects.ids()){let p=Lt(E(this.deps.projects.path(u)).root,"worktrees");if(Cv(p))d.push({what:`${u}'s worktrees`,bytes:await Zi(p)})}return d.filter((u)=>u.bytes>=Or/10).sort((u,p)=>p.bytes-u.bytes).slice(0,5).map((u)=>`${u.what}: ${ur(u.bytes)}`).concat(process.env[ls]?[oC]:[])}}function _v(d){return d.reduce((u,p)=>cd(p)<cd(u)?p:u)}function Xi(d,u){let p=d.find((w)=>w.step===u.step);if(!p)return void d.push(u);if(p.freedBytes+=u.freedBytes,p.items+=u.items,u.error)p.error=u.error}var Nv={docker_build_cache:"Docker build cache",docker_images:"unused Docker images",docker_volumes:"unnamed Docker volumes nothing has",simulators:"iOS simulators' content",xcode_derived_data:"Xcode's DerivedData",build_outputs:"idle tasks' build outputs"},lC=(d)=>`${Nv[d.step]} ${ur(d.freedBytes)} (${d.items})${d.error?` [failed: ${d.error}]`:""}`;function pC(d,u){return d.find((p)=>u===p.id||u.startsWith(`${p.id}-`))}function hC(d){let u=0;for(let p of d)for(let w of[p.startedAt,p.endedAt,p.lastTurn?.endedAt])if(w)u=Math.max(u,Date.parse(w)||0);return u}async function mC(d,u,p){if(u.some(uC))return"a session works there";let w=(x)=>new Date(x).toISOString(),y=hC(u);if(y>=p)return`a session there at ${w(y)}`;let v=await fC(d);if(v>=p)return`committed at ${w(v)}`;let S=await gC(d);if(S>=p)return`a changed or new file written at ${w(S)}`;return}async function fC(d){let u=await a(d,(w)=>w.sub("log").flag("-1").flag("--format","%ct")).catch(()=>""),p=Number(u.trim());return p>0?p*1000:Date.now()}async function gC(d){let u=await a(d,(w)=>w.sub("ls-files").flag("--modified").flag("--others").flag("--exclude-standard").flag("-z")).catch(()=>{return});if(u===void 0)return Date.now();let p=0;for(let w of u.split("\x00").filter(Boolean)){let y=await jv(Lt(d,w)).catch(()=>{return});if(y)p=Math.max(p,y.mtimeMs)}return p}async function wC(d){let u=[],p=async(w,y)=>{let v=await xr(w,{withFileTypes:!0}).catch(()=>[]),S=new Set(v.map((x)=>x.name));for(let x of v){if(!x.isDirectory()||x.name===".git")continue;let j=Lt(w,x.name);if(x.name==="node_modules"||x.name==="target"&&S.has("Cargo.toml")){if(await yC(d,j))u.push(j);continue}if(y<rC&&!x.name.startsWith("."))await p(j,y+1)}};return await p(d,1),u}var yC=(d,u)=>a(d,(p)=>p.sub("check-ignore").flag("-q").endOptions().arg(JE(d,u).split(zE).join("/"))).then(()=>!0,()=>!1);async function kC(d){let u=(await a(d,(p)=>p.sub("rev-parse").flag("--absolute-git-dir")).catch(()=>"")).trim();if(u)await Rh(Lt(u,"superfactory-install"),{force:!0})}async function Zi(d){let u=await jv(d).catch(()=>{return});if(!u||u.isSymbolicLink())return 0;if(!u.isDirectory())return u.nlink<=1?u.size:0;let p=0;for(let w of await xr(d).catch(()=>[]))p+=await Zi(Lt(d,w));return p}async function Dv(){let d=await g(r(Ue).sub("info").flag("--format","{{.DockerRootDir}}").timeoutMs(15000).build()).catch(()=>{return});return(d?.exitCode===0?d.stdout.trim():"")||void 0}async function bC(){return await Dv()!==void 0}var vC=()=>process.platform==="darwin"||process.env.SUPERFACTORY_E2E_METHODS==="1"&&process.env.SUPERFACTORY_XCODE_CLEANUP_ANYWHERE==="1";function Ov(){return(process.env.SUPERFACTORY_E2E_METHODS==="1"?process.env.SUPERFACTORY_FAKE_DEVELOPER_DIR:"")||Lt(QE(),"Library","Developer")}async function SC(){let d=await g(r(es).sub("simctl list").flag("-j").arg("devices").arg("booted").timeoutMs(60000).build()).catch((p)=>({exitCode:1,stdout:"",stderr:String(p)}));if(d.exitCode!==0)return`simctl can't say which simulators are booted: ${d.stderr.trim().slice(0,200)}`;try{let p=JSON.parse(d.stdout).devices,w=Object.values(p??{}).flat().find((y)=>y.state==="Booted");if(w)return`the simulator ${w.name??""} is booted`.replace(" "," ")}catch{return"simctl's list of booted simulators didn't read"}let u=await g(r(oe).flag("-axww").flag("-o","command=").timeoutMs(30000).build()).catch(()=>{return});if(!u||u.exitCode!==0)return"ps can't say what runs";for(let p of u.stdout.split(`
|
|
262
|
+
`)){let w=p.trim().split(/\s+/)[0]??"";if(w.endsWith("/launchd_sim")||w==="launchd_sim")return"a simulator runs (launchd_sim)";if(w.endsWith("/xcodebuild")||w==="xcodebuild")return"xcodebuild runs"}return}async function PC(){let d={step:"simulators",freedBytes:0,items:0},u={step:"xcode_derived_data",freedBytes:0,items:0},p=await SC();if(p)return s.info(`disk: kept the simulators and Xcode's DerivedData: ${p}`),[d,u];let w=Lt(Ov(),"CoreSimulator","Devices"),y=await Zi(w),v=(await xr(w,{withFileTypes:!0}).catch(()=>[])).filter((x)=>x.isDirectory()).length;for(let[x,j]of[["simctl erase","all"],["simctl delete","unavailable"]]){let L=await g(r(es).sub(x).arg(j).timeoutMs(po).build()).catch((N)=>({exitCode:1,stdout:"",stderr:String(N)}));if(L.exitCode===0)d.items=v;else d.error=(L.stderr.trim()||`exit ${L.exitCode}`).slice(0,500),s.warn(`disk: xcrun ${x} ${j} failed: ${d.error}`)}d.freedBytes=Math.max(0,y-await Zi(w));let S=Lt(Ov(),"Xcode","DerivedData");for(let x of await xr(S).catch(()=>[])){let j=Lt(S,x),L=await Zi(j);try{await Rh(j,{recursive:!0,force:!0,maxRetries:3}),u.freedBytes+=L,u.items+=1}catch(N){u.error=String(N).slice(0,500)}}return[d,u]}async function er(d){return g(d).catch((u)=>({exitCode:1,stdout:"",stderr:String(u)}))}async function dd(d){let u=(y)=>{let v=r(Ue).sub("builder prune").flag("--all").flag("--force");if(d.hours!==void 0)v.flag("--filter",`until=${d.hours}h`);if(y&&d.maxBytes!==void 0)v.flag(y,String(Math.round(d.maxBytes)));return er(v.timeoutMs(po).build())},p=await u(d.maxBytes===void 0?void 0:"--max-used-space");if(d.maxBytes!==void 0&&/unknown flag/.test(p.stderr))p=await u("--keep-storage");let w=p.stdout.split(`
|
|
263
|
+
`).filter((y)=>/^\S+\s+(true|false)\s/.test(y)).length;return ud("docker_build_cache",p,w)}async function $h(d){let u=r(Ue).sub("image prune").flag("--force");if(!d.dangling)u.flag("--all");if(d.hours!==void 0)u.flag("--filter",`until=${d.hours}h`);let p=await er(u.timeoutMs(po).build()),w=p.stdout.split(`
|
|
264
|
+
`).filter((y)=>y.startsWith("deleted: ")).length;return ud("docker_images",p,w)}async function $C(d){let u=await er(r(Ue).sub("image ls").flag("--format","{{json .}}").timeoutMs(60000).build());if(u.exitCode!==0)return ud("docker_images",u,0);let p=new Map;for(let j of u.stdout.split(`
|
|
265
|
+
`)){let L;try{L=JSON.parse(j)}catch{continue}if(!L.Repository||L.Repository==="<none>"||!L.Tag||L.Tag==="<none>")continue;p.set(L.Repository,[...p.get(L.Repository)??[],L])}let w=await Mv("Images"),y=0;for(let j of p.values()){j.sort((L,N)=>xv(N)-xv(L));for(let L of j.slice(d)){let N=`${L.Repository}:${L.Tag}`;if((await er(r(Ue).sub("image rm").arg(N).timeoutMs(po).build())).exitCode===0)y+=1,s.info(`disk: removed the image ${N}: ${d} newer of ${L.Repository} kept`)}}let v=await $h({dangling:!0}),S=await Mv("Images"),x=w!==void 0&&S!==void 0?Math.max(0,w-S):v.freedBytes;return{...v,freedBytes:x,items:y+v.items}}function xv(d){let u=/^(\S+) (\S+) ([+-]\d\d)(\d\d)/.exec(d.CreatedAt??"");return u&&Date.parse(`${u[1]}T${u[2]}${u[3]}:${u[4]}`)||0}async function IC(){let d=await er(r(Ue).sub("volume prune").flag("--force").flag("--filter","all=false").timeoutMs(po).build()),u=d.stdout.split(`
|
|
266
|
+
`).filter((p)=>/^[0-9a-f]{64}$/.test(p.trim())).length;return ud("docker_volumes",d,u)}function ud(d,u,p){if(u.exitCode!==0){let w=(u.stderr.trim()||`exit ${u.exitCode}`).slice(0,500);return s.warn(`disk: ${Nv[d]}: docker failed: ${w}`),{step:d,freedBytes:0,items:0,error:w}}return{step:d,freedBytes:Lv(u.stdout),items:p}}async function Mv(d){let u=`Docker ${d.toLowerCase()}`;return(await Uv()).find((p)=>p.what===u)?.bytes}async function Uv(){let d=await er(r(Ue).sub("system df").flag("--format","{{json .}}").timeoutMs(60000).build());if(d.exitCode!==0)return[];return d.stdout.split(`
|
|
267
|
+
`).flatMap((u)=>{try{let p=JSON.parse(u);if(!p.Type||!p.Size)return[];return[{what:`Docker ${p.Type.toLowerCase()}`,bytes:Lv(`Total: ${p.Size}`)}]}catch{return[]}})}import{readFileSync as TC}from"fs";import{readdir as RC,readFile as Wv}from"fs/promises";import{freemem as Fv,totalmem as AC}from"os";import{join as EC}from"path";var Hv=1073741824,Bv=30000,CC=6,_C=0.15,OC=2,Gv=3,xC=8000,MC=()=>process.env.SUPERFACTORY_TEST_VMSTAT||"/proc/vmstat",qv=(d)=>`${(d/Hv).toFixed(1)} GB`;function jC(d){let u=/^oom_kill (\d+)$/m.exec(d)?.[1];return u===void 0?void 0:Number(u)}function LC(d){let u=[...d.matchAll(/([^\s,:]+) \(\d+\) consumed (\d+) bytes/g)].map(([,p,w])=>({name:p??"",bytes:Number(w)}));if(!u.length)return;return u.sort((p,w)=>w.bytes-p.bytes).slice(0,Gv).map((p)=>`${p.name} ${qv(p.bytes)}`).join(", ")}var Vv=(d,u=!1)=>`the machine ran out of memory${d?` (${u?"the most now":"top"}: ${d})`:""}`;async function NC(){let d=(await RC("/proc").catch(()=>[])).filter((w)=>/^\d+$/.test(w)),p=(await Promise.all(d.map(async(w)=>{let y=await Wv(EC("/proc",w,"status"),"utf8").catch(()=>""),v=/^Name:\s+(.+)$/m.exec(y)?.[1]??"",S=Number(/^VmRSS:\s+(\d+) kB$/m.exec(y)?.[1]??0);return{name:v,bytes:S*1024}}))).filter((w)=>w.bytes>0).sort((w,y)=>y.bytes-w.bytes).slice(0,Gv);return p.length?p.map((w)=>`${w.name} ${qv(w.bytes)}`).join(", "):void 0}var DC=l`Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = 2004; StartTime = (Get-Date).AddMinutes(-3) } -MaxEvents 1 -ErrorAction SilentlyContinue | ForEach-Object { $_.Message }`;async function UC(){let u=(await g(r(Ke).flag("-NoProfile").flag("-NonInteractive").script("-Command",DC).timeoutMs(xC).build())).stdout.trim();return u?Vv(LC(u)):void 0}function FC(d){if(d!=="linux")return Fv();try{let u=/^MemAvailable:\s+(\d+) kB$/m.exec(TC("/proc/meminfo","utf8"))?.[1];if(u)return Number(u)*1024}catch{}return Fv()}function Yv(d=process.env.SUPERFACTORY_TEST_VMSTAT?"linux":process.platform){let u=[],p=async()=>{let w=jC(await Wv(MC(),"utf8").catch(()=>""));if(w===void 0)return;if(u.push({at:Date.now(),kills:w}),u.length>CC)u.shift();return w};if(d==="linux")p(),setInterval(()=>void p(),Bv).unref?.();return{ranOut:async()=>{if(d==="win32")return UC().catch(()=>{return});if(d!=="linux")return;let w=Date.now(),y=u.filter((S)=>w-S.at>=Bv*2-1000).at(-1)??u[0],v=await p();if(y===void 0||v===void 0||v<=y.kills)return;return Vv(await NC().catch(()=>{return}),!0)},hasRoom:()=>FC(d)>=Math.max(OC*Hv,AC()*_C)}}import{createHash as wd}from"crypto";import{existsSync as Nt,readlinkSync as BC,realpathSync as WC}from"fs";import{appendFile as Zv,mkdir as jh,mkdtemp as yd,open as HC,readdir as eS,readFile as Es,rename as GC,rm as Tn,stat as tS,symlink as sS,unlink as Kv,utimes as qC,writeFile as mo}from"fs/promises";import{homedir as VC,tmpdir as vd}from"os";import{dirname as Lh,join as Se,relative as YC,resolve as KC,sep as QC}from"path";var JC=4,Ie=process.env.SUPERFACTORY_MACHINE_SETUP_FAKE,ir=Ie??Se(VC(),".superfactory","machine"),ar="superfactory-npm-global.lock",Nh="superfactory-claude-updated",ld={command:"claude"},md=Ie?Se(Ie,"claude-code"):process.env.SUPERFACTORY_CLAUDE_VERSIONS||us,Dh=/^\d+\.\d+\.\d+$/,ho={command:"gh"},nS="2.103.3",Qv="/usr/local/rustup",Jv="/usr/local/cargo",zC=["cargo","rustc","rustdoc","rustfmt","cargo-fmt","cargo-clippy","clippy-driver"];class Os{deps;current;running;again=!1;constructor(d){this.deps=d}get state(){return this.current}static applies(){if(Ie)return!0;if(X())return!1;return process.platform==="linux"&&!process.env.SUPERFACTORY_SANDBOX&&!n_()&&Nt("/usr/bin/apt-get")}run(){if(this.running)return this.again=!0,this.running;return this.running=this.once().finally(()=>{if(this.running=void 0,!this.again)return;this.again=!1,this.run()}),this.running}async settled(){while(this.running)await this.running.catch(()=>{return})}rerun(){if(!Os.applies())return;this.set({state:"running",step:"checking what's missing"}),this.run()}async once(){if(!Os.applies()||!await this.deps.enabled()){if(this.current)this.set(void 0);return}let d=[...lo,ho,...await this.projectTools(),ld],u=[];for(let S of d)if(!await i_(S))u.push(S);let p=!await iS("node");if(!u.length&&!p)return this.set({state:"ready"});let w=[...new Set(u.flatMap((S)=>S.apt??[]))],y=u.flatMap((S)=>S.npm??[]),v="checking it may install";try{let S=Uh();if(S){let j=[...u.map((N)=>N.command),...p?["node"]:[]].join(", "),L=u.filter((N)=>!s_(N)).map((N)=>N.command);return this.set({state:"failed",error:L.length?`Missing ${j}. On this machine root installs the tools (superfactory host), never its agent, and ${L.join(", ")} ${L.length===1?"isn't":"aren't"} among them: install ${L.length===1?"it":"them"} as root on the VM, then set it up again.`:`Missing ${j}. On this machine root installs the tools, never its agent: run superfactory host again (its ${S} keeps them current), then set it up again.`})}if(!await rS()){let j=[...u.map((L)=>L.command),...p?["node"]:[]].join(", ");return this.set({state:"failed",error:`Missing ${j}, and this machine's agent can't use sudo without a password. Install them${w.length?` (sudo apt-get install -y ${w.join(" ")})`:""}, or give its user passwordless sudo, then set it up again.`})}if(w.length)v="installing system packages",this.set({state:"running",step:`${v}: ${w.join(", ")}`}),await a_(w),await this.installed(u.filter((j)=>j.apt));if(u.some((j)=>j.rustup))v="installing Rust (rustup, stable)",this.set({state:"running",step:v}),await T_(),await this.installed([{command:"rustup"},{command:"cargo"}]);if(u.includes(ho))v="installing the GitHub CLI (gh)",this.set({state:"running",step:v}),await A_(),await this.installed([ho]);if(p)v="installing Node.js",this.set({state:"running",step:v}),await R_(),await this.installed([{command:"node"},{command:"npm"}]);if(y.length)v=`installing ${u.filter((j)=>j.npm).map((j)=>j.command).join(", ")}`,this.set({state:"running",step:v}),await d_(y,(await this.deps.mirrors()).npm),await this.installed(u.filter((j)=>j.npm));if(u.includes(ld))v="installing Claude Code",this.set({state:"running",step:v}),await fo(ar,()=>Bh()),await Hh(Se(ir,Nh)),await this.installed([ld]);this.set({state:"ready"});let x=[...u,...p?[{command:"node"}]:[]];s.info(`machine setup: ready (${x.map((j)=>j.command).join(", ")} installed)`)}catch(S){s.warn(`machine setup: ${v} failed`,S),this.set({state:"failed",error:`While ${v}: ${S.message}`.slice(0,2000)})}}async projectTools(){let d=new Set;for(let p of this.deps.projectPaths())for(let w of await t_(p))d.add(w);let u=new Set((await this.deps.projectNeeds().catch(()=>[])).map((p)=>p.trim().toLowerCase()));return Il.filter((p)=>p.files?.some((w)=>d.has(w))||p.needs?.some((w)=>u.has(w)))}async installed(d){if(Ie)await Zv(Se(Ie,"present"),d.map((u)=>`${u.command}
|
|
268
|
+
`).join(""))}set(d){this.current=d&&{...d,version:JC,at:new Date().toISOString()},this.deps.changed()}}var XC=3,ZC=new Set(["node_modules","target","vendor","dist","build","Pods"]),e_=2000;async function t_(d){let u=new Set,p=[d],w=0;for(let y=0;y<=XC&&p.length;y++){let v=[];for(let S of p){if(++w>e_)return u;let x=await eS(S,{withFileTypes:!0}).catch(()=>[]);for(let j of x)if(j.isFile())u.add(j.name);else if(j.isDirectory()&&!j.name.startsWith(".")&&!ZC.has(j.name))v.push(Se(S,j.name))}p=v}return u}var Uh=()=>process.env[ls]||void 0,s_=(d)=>lo.includes(d)||Ki.includes(d)||d===ho||d===ld,n_=()=>Nt("/.dockerenv")||Nt("/run/.containerenv")||!!process.env.KUBERNETES_SERVICE_HOST;async function i_(d){if(d.rustup&&!Ie)return Nt("/usr/local/bin/cargo");if(!await iS(d.command))return!1;if(d!==ho)return!0;let u=await r_();return!!u&&o_(u,Dm)}async function r_(){let d=Ie?await Es(Se(Ie,"gh-version"),"utf8").catch(()=>`gh version ${nS}`):await g(r(_s).flag("--version").timeoutMs(1e4).build()).then((u)=>u.exitCode===0?u.stdout:"",()=>"");return/gh version (\d+\.\d+\.\d+)/.exec(d)?.[1]}function o_(d,u){let[p,w]=[d,u].map((y)=>y.split(".").map(Number));for(let y=0;y<3;y++)if((p?.[y]??0)!==(w?.[y]??0))return(p?.[y]??0)>(w?.[y]??0);return!0}async function iS(d){if(!Ie)return Bun.which(d)!==null;return(await Es(Se(Ie,"present"),"utf8").catch(()=>"")).split(`
|
|
269
|
+
`).includes(d)}async function rS(){if(Ie)return!Nt(Se(Ie,"no-sudo"));return T(r(A).flag("-n").wrap(r(Xt).build()).timeoutMs(1e4).build()).then(()=>!0,()=>!1)}async function a_(d){let u=(p)=>r(Ys).sub(p).flag("-q").flag("-o","DPkg::Lock::Timeout=600");await ct(u("update").build(),900000),await ct(u("install").flag("-y").flag("--no-install-recommends").argsOf(d).build(),1800000)}function d_(d,u){return fo(ar,()=>ct(c_(u).argsOf(d).build(),900000))}function c_(d){let u=r(jd).sub("install").flag("-g").flag("--no-audit").flag("--no-fund");if(d)u.flag("--registry",d);return u}async function gd(d=ir){let u=Number(await Es(Se(d,ar),"utf8").catch(()=>""));return u>0&&cS(u)}function oS(d){if(!Os.applies()||X()||Uh())return;let u=Bun.which("claude");if(!u?.startsWith("/usr/")||!v_(u))return;return async()=>{await u_(d)}}async function u_(d){let u=Se(ir,Nh),p=await fo(ar,async()=>{if(await b_(u,d/2))return!1;return await Bh(),!0});if(p)await Hh(u);return p}async function Bh(){let d=l_(),u=await p_();if(u===await mt(d))return;let p=Se(md,u),w=Se(p,"bin","claude");if(await m_(u,w).catch(async(S)=>{throw await ct(r(En).flag("-r").flag("-f").arg(p).build(),300000).catch(()=>{return}),S}),await mt(w)!==u)throw Error(`Claude Code ${u}, installed in ${p}, doesn't run`);let y=f_(d),v=`${d}.superfactory-new`;await ct(r(La).flag("-s").flag("-f").flag("-n").argsOf([w,v]).build(),60000),await ct(r(Md).flag("-f").flag("-T").argsOf([v,d]).build(),60000),s.info(`machine setup: everyone's Claude Code is ${u} now (${p})`),await g_([u,y])}function l_(){let d=process.env.SUPERFACTORY_CLAUDE_BIN;if(Ie)return d??Se(Ie,"claude");return Bun.which(d||"claude")??(d||un)}async function p_(){let u=(Ie?await Es(Se(Ie,"claude-latest"),"utf8").catch(()=>"2.1.0"):await(await ws(`${Ht}/latest`)).text()).trim();if(!Dh.test(u))throw Error(`Claude Code's releases didn't say which is the newest (${u.slice(0,200)||"nothing"})`);return u}function h_(){let d=process.arch==="arm64"?"arm64":"x64",u=Nt(`/lib/libc.musl-${d==="arm64"?"aarch64":"x86_64"}.so.1`);return`linux-${d}${u?"-musl":""}`}async function m_(d,u){let p=h_(),w=`${Ht}/${d}/${p}/claude`,y=await yd(Se(vd(),"sf-claude-"));try{let v=Se(y,"claude");if(Ie)await or(`download ${w}`);else{let x=(await(await ws(`${Ht}/${d}/manifest.json`)).json()).platforms?.[p]?.checksum;if(!x)throw Error(`Claude Code ${d} has no ${p} build`);let j=new Uint8Array(await(await ws(w)).arrayBuffer());if(wd("sha256").update(j).digest("hex")!==x)throw Error(`Claude Code ${d} doesn't match its release's checksum`);await mo(v,j)}await ct(r(vr).flag("-D").flag("-m","0755").argsOf([v,u]).build(),300000)}finally{await Tn(y,{recursive:!0,force:!0})}}function f_(d){let u;try{u=KC(Lh(d),BC(d))}catch{return}let p=YC(md,u).split(QC)[0];return p&&Dh.test(p)?p:void 0}async function g_(d){let u=await eS(md).catch(()=>[]);for(let p of u){if(!Dh.test(p)||d.includes(p))continue;let w=r(En).flag("-r").flag("-f").arg(Se(md,p)).build();await ct(w,300000).catch((y)=>s.warn(`machine setup: couldn't remove Claude Code ${p}`,y))}}function sr(d=process.env.SUPERFACTORY_CLAUDE_BIN){return Bun.which(d||"claude")!==null}var Mh;function aS(){return Mh??=w_().finally(()=>{Mh=void 0}),Mh}async function w_(){if(sr())return;if(await k_(y_),sr())return;if(!Os.applies())return"this machine doesn't install its own tools (only a Linux machine with apt does, never a test's agent)";let d=Uh();if(d)return`root installs it on this machine, never its agent: run superfactory host again (its ${d} keeps it current)`;if(!await rS())return"its agent can't use sudo without a password: install it with curl -fsSL https://claude.ai/install.sh | bash";s.warn("machine setup: Claude Code is missing here: installing it again");try{if(await fo(ar,async()=>{if(sr())return!1;return await Bh(),!0}))await Hh(Se(ir,Nh))}catch(u){return s.warn("machine setup: Claude Code's install failed",u),`installing it again failed: ${u.message}`.slice(0,500)}if(sr()){s.info("machine setup: Claude Code installed again");return}return"it was installed again, but `claude` still isn't found on the agent's PATH"}var y_=600000;async function k_(d){let u=Date.now()+d;if(await gd())s.info("machine setup: Claude Code is missing while an install runs: waiting for it");while(await gd()&&Date.now()<u)await Bun.sleep(500)}function dS(d){return fo(ar,d)}async function b_(d,u){let p=await tS(d).then((w)=>w.mtimeMs,()=>0);return Date.now()-p<u}async function Hh(d){let u=new Date;try{await qC(d,u,u)}catch{await jh(Lh(d),{recursive:!0,mode:448}).then(()=>mo(d,"")).catch((p)=>s.warn(`machine setup: couldn't note the update in ${d}`,p))}}function v_(d){let u=process.env.SUPERFACTORY_CLAUDE_BIN;if(!u)return!0;return zv(u)===zv(d)}function zv(d){try{return WC(d)}catch{return d}}var S_=1800000,P_=500;async function fo(d,u){let p=Se(ir,d),w=Date.now()+S_;await jh(ir,{recursive:!0,mode:448}).catch(()=>{return});for(;;){let y=await $_(p);if(y===!0)break;if(y==="stale"&&await Kv(p).then(()=>!0,()=>!1))continue;if(Date.now()>w)throw Error(`another install (${typeof y==="number"?`pid ${y}`:"its lock"}) still holds ${p}`);await Bun.sleep(P_)}try{return await u()}finally{await Kv(p).catch(()=>{return})}}async function $_(d){let u=await HC(d,"wx",384).catch(()=>{return});if(u){try{await u.writeFile(String(process.pid))}finally{await u.close()}return!0}let p;try{p=await Es(d,"utf8")}catch{return"held"}let w=Number(p.trim());if(w)return cS(w)?w:"stale";return await tS(d).then((v)=>Date.now()-v.mtimeMs,()=>0)>5000?"stale":"held"}function cS(d){try{return process.kill(d,0),!0}catch(u){return u.code==="EPERM"}}var I_=(d)=>d.program==="npm"?"tree":["ln","mv","rm"].includes(d.program)?"wait":"term",nr=new Map,uS=!1;async function lS(d=1e4){if(uS=!0,!nr.size)return;let u=()=>Promise.allSettled([...nr.values()].map((p)=>p.done));if(await Xv(u(),d))return;if(s.warn(`machine setup: ending ${nr.size} install(s) still running as the agent stops`),await Promise.all([...nr].map(async([p,{ending:w}])=>{if(w==="tree"){if(!await Tt(p,{asRoot:!0}))s.warn(`machine setup: an install (sudo's pid ${p}) still runs after it was ended`)}else if(w==="term")try{process.kill(p,"SIGTERM")}catch{}})),!await Xv(u(),1e4))s.warn("machine setup: an install still runs as the agent stops")}var Xv=(d,u)=>Promise.race([d.then(()=>!0),Bun.sleep(u).then(()=>!1)]);async function T_(){let u=`${process.arch==="arm64"?"aarch64":"x86_64"}-unknown-linux-gnu`,p=`https://static.rust-lang.org/rustup/dist/${u}/rustup-init`,w=(S)=>ct(r(Qt).argsOf([`RUSTUP_HOME=${Qv}`,`CARGO_HOME=${Jv}`]).wrap(r(Cd).programPath(S).flag("-y").flag("--no-modify-path").flag("--profile","default").flag("--default-toolchain","stable").build()).build(),1800000);if(Ie)await or(`download ${p}`),await w(Se(Ie,"rustup-init"));else{let S=(await(await ws(`${p}.sha256`)).text()).trim().split(/\s+/)[0],x=new Uint8Array(await(await ws(p)).arrayBuffer());if(wd("sha256").update(x).digest("hex")!==S)throw Error("rustup-init doesn't match static.rust-lang.org's checksum");let j=await yd(Se(vd(),"sf-rustup-"));try{let L=Se(j,"rustup-init");await mo(L,x,{mode:493}),await w(L)}finally{await Tn(j,{recursive:!0,force:!0})}}if(Ie?Nt(Se(Ie,"apt-cargo")):Nt("/usr/bin/cargo")||Nt("/usr/bin/rustc"))await ct(r(Ys).sub("remove").flag("-q").flag("-o","DPkg::Lock::Timeout=600").flag("-y").argsOf(["cargo","rustc"]).build(),900000);let y=Se(Qv,"toolchains",`stable-${u}`,"bin"),v=[[Se(Jv,"bin","rustup"),"/usr/local/bin/rustup"],...zC.map((S)=>[Se(y,S),`/usr/local/bin/${S}`])];for(let[S,x]of v)if(Ie)await or(`link ${x} -> ${S}`);else await ct(r(La).flag("-s").flag("-f").flag("-n").argsOf([S,x]).build(),60000)}async function R_(){let d=`https://nodejs.org/dist/${pn}`,u=process.arch==="arm64"?"arm64":"x64";if(Ie)return or(`download ${d}/node-linux-${u}.tar.xz`);let w=(await(await ws(`${d}/SHASUMS256.txt`)).text()).split(`
|
|
270
|
+
`).find((j)=>new RegExp(` node-v[\\d.]+-linux-${u}\\.tar\\.xz$`).test(j));if(!w)throw Error(`nodejs.org lists no Linux ${u} build in ${pn}`);let[y="",v=""]=w.split(/\s+/),S=new Uint8Array(await(await ws(`${d}/${v}`)).arrayBuffer());if(wd("sha256").update(S).digest("hex")!==y)throw Error(`${v} doesn't match nodejs.org's checksum`);let x=await yd(Se(vd(),"sf-node-"));try{let j=Se(x,v);await mo(j,S);let L=v.replace(/\.tar\.xz$/,"");await ct(r(ot).flag("--extract").flag("--xz").flag("--no-same-owner").flag("--file",j).flag("--directory","/usr/local").flag("--strip-components",1).argsOf(["bin","include","lib","share"].map((N)=>`${L}/${N}`)).build(),300000)}finally{await Tn(x,{recursive:!0,force:!0})}}async function A_(){let d=process.arch==="arm64"?"arm64":"amd64",u=Ie?nS:/\/tag\/v(\d+\.\d+\.\d+)$/.exec((await ws(`${zt}/latest`)).url)?.[1];if(!u)throw Error(`${zt}/latest didn't say which release is the newest`);let p=`gh_${u}_linux_${d}`,w=`${zt}/download/v${u}/${p}.tar.gz`,y=await yd(Se(vd(),"sf-gh-"));try{let v=Se(y,`${p}.tar.gz`);if(Ie)await or(`download ${w}`);else{let x=(await(await ws(`${zt}/download/v${u}/gh_${u}_checksums.txt`)).text()).split(`
|
|
271
|
+
`).find((L)=>L.endsWith(` ${p}.tar.gz`))?.split(/\s+/)[0];if(!x)throw Error(`gh ${u} has no Linux ${d} build`);let j=new Uint8Array(await(await ws(w)).arrayBuffer());if(wd("sha256").update(j).digest("hex")!==x)throw Error(`${p}.tar.gz doesn't match its release's checksum`);await mo(v,j)}await ct(r(ot).flag("--extract").flag("--gzip").flag("--no-same-owner").flag("--file",v).flag("--directory","/usr/local").flag("--strip-components",1).arg(`${p}/bin/gh`).build(),300000)}finally{await Tn(y,{recursive:!0,force:!0})}if(Ie?Nt(Se(Ie,"apt-gh")):Nt("/usr/bin/gh"))await ct(r(Ys).sub("remove").flag("-q").flag("-o","DPkg::Lock::Timeout=600").flag("-y").arg("gh").build(),900000);if(Ie)await Tn(Se(Ie,"gh-version"),{force:!0})}async function ws(d){let u=await fetch(d,{signal:AbortSignal.timeout(600000)});if(!u.ok)throw Error(`${d}: ${u.status}`);return u}async function ct(d,u){let p=I_(d);if(uS&&p!=="wait")throw Error("the agent is stopping");let w=r(A).flag("-n").wrap(d).by("machine setup").timeoutMs(u).build();if(!Ie){let L=[],N=T(w,{onStart:(B)=>L.push(B),detached:!0});for(let B of L)nr.set(B,{done:N.catch(()=>{return}),ending:p});try{await N}finally{for(let B of L)nr.delete(B)}return}let y=[w.program,...w.argv].join(" ");await or(y);let v=Number(await Es(Se(Ie,"npm-ms"),"utf8").catch(()=>""));if(v&&["npm","install"].includes(d.program))await Bun.sleep(v);let S=(await Es(Se(Ie,"fail"),"utf8").catch(()=>"")).trim();if(S&&y.includes(S))throw Error(`${d.program} failed (1): couldn't get ${S}`);if(d.program==="npm")return;if(d.program!=="install")return E_(d);let x=(await Es(Se(Ie,"claude-from"),"utf8").catch(()=>"")).trim(),j=d.argv.at(-1)??"";if(!x||!j)return;await jh(Lh(j),{recursive:!0}),await sS(x,j).catch(()=>{return})}async function E_(d){let[u="",p=""]=d.argv.filter((w)=>!w.startsWith("-"));if(d.program==="ln")await Tn(p,{force:!0}),await sS(u,p);else if(d.program==="mv")await GC(u,p);else if(d.program==="rm")await Tn(u,{recursive:!0,force:!0})}function or(d){return Zv(Se(Ie??"","commands"),`${d}
|
|
272
|
+
`)}class Gh{projects;push;builds=new Map;constructor(d,u){this.projects=d;this.push=u;al((p)=>this.push({type:"macos.queue.changed",queue:p}))}sweptAt=0;async screen(){let d=process.env.SUPERFACTORY_MACOS_VM??cs;if((await cn().catch(()=>[])).find((u)=>u.name===d)?.state!=="running")throw new c("unavailable","The macOS VM isn't running: it starts with the first macOS task.");return fl(d)}async rotate(d){if((await cn().catch(()=>[])).find((u)=>u.name===d)?.state!=="running")throw new c("unavailable",`${d} isn't running: its passwords change while it runs.`);await ul(d,Ns),s.info(`macos: new passwords for ${d}`)}async sweep(){if(Date.now()-this.sweptAt<C_||process.platform!=="darwin"||!Bun.which("tart"))return;this.sweptAt=Date.now();let d=process.env.SUPERFACTORY_MACOS_VM??cs,u=await ll(d).catch((w)=>{s.warn("macos: the VM's sweep failed",w);return});if(u?.removed.length)s.info(`macos: removed ${u.removed.length} unused caches and worktrees; caches hold ${u.cacheGb} GB`);let p=await pl([Ai]).catch(()=>[]);if(p.length)s.info(`macos: deleted golden images unused for a month: ${p.join(", ")}`)}queue(){return dc()}async golden(d){let{image:u,base:p}=await this.goldenSettings(d),w=this.builds.get(d),y=(await cn().catch(()=>[])).find((S)=>S.name===u),v={projectId:d,image:u,base:p};if(w&&w.state!=="failed")return{...v,state:w.state};if(y)return{...v,state:"ready",updatedAt:y.accessed};if(w)return{...v,state:"failed",error:w.error};return{...v,state:"missing"}}async rebuild(d){let u=this.builds.get(d);if(u?.state==="waiting"||u?.state==="building")return this.golden(d);let{image:p,base:w}=await this.goldenSettings(d),y=async(v)=>{this.builds.set(d,v),this.push({type:"macos.golden.changed",golden:await this.golden(d)})};return await y({state:"waiting"}),Ei({base:w,name:p,projectId:d,onStage:(v)=>void y({state:v})}).then(async(v)=>{s.info(`macos: ${p} ready`,v.seconds),this.builds.delete(d),this.push({type:"macos.golden.changed",golden:await this.golden(d)})}).catch((v)=>y({state:"failed",error:String(v)})),this.golden(d)}async goldenSettings(d){let u=await this.projects.settings(d).catch(()=>{throw new c("not_found",`no project ${d} on this machine`)});return{image:u["runner.macos.goldenImage"]||Ai,base:u["runner.macos.goldenBase"]}}}var C_=21600000;import{lookup as __}from"dns/promises";import{chmod as Kh,mkdir as pS,open as O_,readdir as x_,realpath as M_,rename as hS,rm as Rn,stat as $d,statfs as j_,writeFile as Qh}from"fs/promises";import{isIP as vS}from"net";import{cpus as L_,homedir as em,totalmem as N_}from"os";import{join as pr}from"path";var D_=pr(em(),".superfactory","tart-hypervisor"),go=2,U_=k("SUPERFACTORY_TART_GUEST_WAIT_MS",300000),mS=k("SUPERFACTORY_TART_BOOT_WAIT_MS",60000),fS=k("SUPERFACTORY_TART_POLL_MS",1000),F_=3600000,gS=120,_n=1073741824,B_=l`set -e
|
|
273
|
+
if id admin >/dev/null 2>&1; then
|
|
274
|
+
passwd -l admin >/dev/null
|
|
275
|
+
rm -rf ~admin/.ssh
|
|
276
|
+
fi
|
|
277
|
+
command -v cloud-init >/dev/null || { echo "the image has no cloud-init to read its seed disk" >&2; exit 1; }
|
|
278
|
+
if grep -qs 'datasource_list: *\[ *None *\]' /etc/cloud/cloud.cfg.d/*.cfg; then
|
|
279
|
+
printf 'datasource_list: [ NoCloud, None ]\nssh_pwauth: false\n' > /etc/cloud/cloud.cfg.d/99_superfactory.cfg
|
|
280
|
+
fi
|
|
281
|
+
cloud-init clean --logs
|
|
282
|
+
echo prepared`,dr="/Users/admin/projects",Id="/Users/admin/.superfactory",zh=`${Id}/screen.json`,Sd="/etc/pf.superfactory-screen.conf",wS="/Library/LaunchDaemons/com.superfactory.screen.plist",W_=l`defaults write /Library/Preferences/com.apple.RemoteManagement VNCLegacyConnectionsEnabled -bool YES
|
|
283
|
+
launchctl enable system/com.apple.screensharing
|
|
284
|
+
launchctl bootstrap system /System/Library/LaunchDaemons/com.apple.screensharing.plist 2>/dev/null || true
|
|
285
|
+
launchctl kickstart -k system/com.apple.screensharing
|
|
286
|
+
mkdir -p ${Id}
|
|
287
|
+
printf '{"url":"vnc://127.0.0.1:5900","password":"%s"}\\n' "$screen" > ${zh}
|
|
288
|
+
chown admin:staff ${Id} ${zh}
|
|
289
|
+
chmod 700 ${Id}
|
|
290
|
+
chmod 600 ${zh}
|
|
291
|
+
{
|
|
292
|
+
echo 'set skip on lo0'
|
|
293
|
+
echo 'scrub-anchor "com.apple/*"'
|
|
294
|
+
echo 'nat-anchor "com.apple/*"'
|
|
295
|
+
echo 'rdr-anchor "com.apple/*"'
|
|
296
|
+
echo 'dummynet-anchor "com.apple/*"'
|
|
297
|
+
echo 'anchor "com.apple/*"'
|
|
298
|
+
echo 'load anchor "com.apple" from "/etc/pf.anchors/com.apple"'
|
|
299
|
+
echo 'block return in quick proto { tcp udp } to any port { 5900 3283 }'
|
|
300
|
+
echo 'pass in all'
|
|
301
|
+
echo 'pass out all'
|
|
302
|
+
} > ${Sd}
|
|
303
|
+
pfctl -q -nf ${Sd}
|
|
304
|
+
pfctl -q -E -f ${Sd} 2>/dev/null
|
|
305
|
+
cat > ${wS} <<PLIST
|
|
306
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
307
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
308
|
+
<plist version="1.0"><dict>
|
|
309
|
+
<key>Label</key><string>com.superfactory.screen</string>
|
|
310
|
+
<key>ProgramArguments</key><array><string>/sbin/pfctl</string><string>-E</string><string>-f</string><string>${Sd}</string></array>
|
|
311
|
+
<key>RunAtLoad</key><true/>
|
|
312
|
+
</dict></plist>
|
|
313
|
+
PLIST
|
|
314
|
+
chmod 644 ${wS}`;function H_(d){return l`set -eu
|
|
315
|
+
launchctl disable system/com.openssh.sshd
|
|
316
|
+
launchctl bootout system/com.openssh.sshd 2>/dev/null || true
|
|
317
|
+
${Wn(!0)}
|
|
318
|
+
${W_}
|
|
319
|
+
if ! grep -qs ${` ${dr} `} /etc/fstab; then
|
|
320
|
+
disk=
|
|
321
|
+
for d in $(diskutil list physical | awk '$1 ~ "^/dev/disk" {print $1}'); do
|
|
322
|
+
[ "$(diskutil info -plist "$d" | plutil -extract TotalSize raw -)" = ${d} ] || continue
|
|
323
|
+
diskutil info "$d" | grep -q GUID_partition_scheme && continue
|
|
324
|
+
disk=$d
|
|
325
|
+
break
|
|
326
|
+
done
|
|
327
|
+
[ -n "$disk" ] || { echo "its data disk (an empty disk of ${d} bytes) isn't there" >&2; exit 1; }
|
|
328
|
+
diskutil eraseDisk APFS Superfactory GPT "$disk" >/dev/null
|
|
329
|
+
uuid=$(diskutil info -plist Superfactory | plutil -extract VolumeUUID raw -)
|
|
330
|
+
diskutil unmount Superfactory >/dev/null
|
|
331
|
+
mkdir -p ${dr}
|
|
332
|
+
echo "UUID=$uuid ${dr} apfs rw,nobrowse" >> /etc/fstab
|
|
333
|
+
diskutil mount -mountPoint ${dr} "$uuid" >/dev/null
|
|
334
|
+
diskutil enableOwnership ${dr} >/dev/null
|
|
335
|
+
chown admin:staff ${dr}
|
|
336
|
+
fi
|
|
337
|
+
echo locked`}function G_(d){let u=new URL("/join.sh",d.serverUrl).toString(),p=d.fingerprint?l`curl -fsSk --pinnedpubkey ${`sha256//${d.fingerprint}`} ${u}`:l`curl -fsSL ${u}`,w=d.fingerprint?l` --fingerprint ${d.fingerprint}`:l``;return l`set -eu
|
|
338
|
+
umask 077
|
|
339
|
+
token=$(mktemp)
|
|
340
|
+
trap 'rm -f "$token"' EXIT
|
|
341
|
+
cat > "$token"
|
|
342
|
+
i=0
|
|
343
|
+
until launchctl print "gui/$(id -u)" >/dev/null 2>&1; do
|
|
344
|
+
i=$((i + 1))
|
|
345
|
+
[ "$i" -lt 180 ] || { echo "its admin isn't logged in to its desktop, where the agent runs" >&2; exit 1; }
|
|
346
|
+
sleep 1
|
|
347
|
+
done
|
|
348
|
+
${p} | sh -s -- --token-file "$token" --name ${d.name} --project-machine${w}
|
|
349
|
+
echo joined`}class tm{dir;busy=new Map;failures=new Map;constructor(d=D_){this.dir=d}async info(d){let u=await Pd(),p=await j_(this.dir.startsWith(em())?em():this.dir).catch(()=>{return}),w={...u?{tart:u}:{},softnet:await yS(),brew:!!Bun.which("brew",{PATH:process.env.PATH??""}),cpus:L_().length,memoryGb:Cn(N_()/_n),...p?{diskGb:{free:Cn(p.bavail*p.bsize/_n),total:Cn(p.blocks*p.bsize/_n)}}:{}};if(!u)return{...w,running:{cpus:0,memoryGb:0,macos:0}};let y=await yo(),v={cpus:0,memoryGb:0,macos:0};for(let j of y.filter((L)=>L.Source==="local"&&L.State==="running")){let L=await cr(j.Name);v={cpus:v.cpus+(L?.CPU??0),memoryGb:Cn(v.memoryGb+(L?.Memory??0)/1024),macos:v.macos+(L?.OS==="darwin"?1:0)}}if(!d)return{...w,running:v};let S=y.some((j)=>j.Name===d),x=S?Zh(await cr(d)):void 0;return{...w,running:v,image:{pulled:S,...x?{os:x}:{}}}}async install(){let d=await Pd();if(d)return{tart:d};if(!Bun.which("brew",{PATH:process.env.PATH??""}))throw new c("unavailable","this Mac has no Homebrew to install Tart with");let u=await g(r($t).sub("install").arg("cirruslabs/cli/tart").timeoutMs(1200000).build());if(u.exitCode!==0)throw new c("internal",`brew install cirruslabs/cli/tart failed: ${bS(u.stderr||u.stdout)}`);let p=await Pd();if(!p)throw new c("internal","Tart installed, but `tart --version` doesn't answer");return s.info(`tart-hypervisor: installed Tart ${p}`),{tart:p}}async vms(d){let u=d??await this.recorded(),p=await yo(),w=[];for(let y of u){if(!await this.record(y))continue;let S=this.busy.get(y),x=this.failures.get(y),j=p.find((B)=>B.Name===y&&B.Source==="local");if(!j&&!S&&!x)continue;let L=j?await cr(y):void 0,N=S?S.state:x?"failed":j?.State==="running"?"running":"stopped";w.push({name:y,state:N,...x&&!S?{message:x.slice(0,500)}:{},cpus:L?.CPU??1,memoryGb:Cn((L?.Memory??0)/1024),rootDiskGb:L?.Disk??0,dataDiskGb:Cn(((await $d(this.path(y,"data.img")).catch(()=>{return}))?.size??0)/_n)})}return w}async create(d){if(await this.record(d.name))throw new c("conflict",`${d.name} is here already`);if((await yo()).some((u)=>u.Name===d.name))throw new c("conflict",`this Mac has a VM named ${d.name} that isn't Superfactory's`);if(await pS(pr(this.dir,d.name),{recursive:!0,mode:448}),await Kh(this.dir,448),await Kh(pr(this.dir,d.name),448),await this.keep(d.name,{image:d.image,...d.bridged?{bridged:d.bridged}:{},...d.join?{reach:await q_(d.join.serverUrl)}:{},wanted:"running",prepared:!1,createdAt:new Date().toISOString()}),await this.writeSeed(d.name,d.userData,d.networkData),d.join)await Qh(this.path(d.name,"join.json"),JSON.stringify(d.join),{mode:384});await kS(this.path(d.name,"data.img"),d.dataDiskGb),this.inBackground(d.name,"preparing",async()=>{await T(r(R).sub("clone").arg(d.image).arg(d.name).timeoutMs(F_).build());let u=Zh(await cr(d.name));if(await this.keep(d.name,{...await this.need(d.name),...u?{os:u}:{}}),await Rn(this.path(d.name,u==="darwin"?"seed.iso":"join.json"),{force:!0}),u==="darwin"&&!await this.join(d.name))throw Error(`${d.image} is a macOS image, and the server sent no join: it joins with none`);await T(r(R).sub("set").arg(d.name).flag("--cpu",d.cpus).flag("--memory",d.memoryGb*1024).flag("--disk-size",d.rootDiskGb).build()),await this.prepare(d.name),await this.boot(d.name)}),s.info(`tart-hypervisor: making ${d.name} from ${d.image}`)}async seed(d,u,p){if((await this.need(d)).os==="darwin")return;await this.writeSeed(d,u,p)}async start(d){let u=await this.need(d);if(this.busy.get(d)?.state==="preparing"||this.busy.get(d)?.state==="booting")return;if(await this.busy.get(d)?.work,await this.keep(d,{...u,wanted:"running"}),await An(d)==="running")return;let p=await this.info();if(Zh(await cr(d))==="darwin"&&p.running.macos>=go)throw new c("conflict",`${go} macOS VMs run on this Mac already: Apple allows no more`);this.inBackground(d,u.prepared?"booting":"preparing",async()=>{if(!u.prepared)await this.prepare(d);await this.boot(d)})}async stop(d){let u=await this.need(d);if(await this.keep(d,{...u,wanted:"stopped"}),await this.busy.get(d)?.work,await An(d)!=="running")return;this.inBackground(d,"stopping",async()=>{await T(r(R).sub("stop").arg(d).flag("--timeout",gS).timeoutMs((gS+60)*1000).build())})}async set(d,u){if(await this.need(d),this.busy.has(d)||await An(d)==="running")throw new c("conflict",`${d} is running: its size changes while it is stopped`);let p=r(R).sub("set").arg(d),w=!1;if(u.cpus)w=!!p.flag("--cpu",u.cpus);if(u.memoryGb)w=!!p.flag("--memory",u.memoryGb*1024);if(u.rootDiskGb){let y=(await cr(d))?.Disk??0;if(u.rootDiskGb<y)throw new c("bad_request",`its system disk can only grow: it has ${y} GiB`);if(u.rootDiskGb>y)w=!!p.flag("--disk-size",u.rootDiskGb)}if(w)await T(p.build());if(u.dataDiskGb){let y=this.path(d,"data.img"),v=(await $d(y)).size;if(u.dataDiskGb*_n<v)throw new c("bad_request",`its data disk can only grow: it has ${Cn(v/_n)} GiB`);await kS(y,u.dataDiskGb)}}async delete(d){let u=await this.record(d),p=(await yo()).some((w)=>w.Name===d);if(!u){if(p)throw new c("forbidden",`${d} isn't one of the VMs Superfactory made on this Mac`);return}if(await this.keep(d,{...u,wanted:"stopped"}),await this.busy.get(d)?.work.catch(()=>{return}),p){if(await An(d)==="running")await g(r(R).sub("stop").arg(d).flag("--timeout",30).build());await T(r(R).sub("delete").arg(d).build())}if(this.failures.delete(d),u.os==="darwin")await so(this.dir).remove(d).catch((w)=>s.warn(`tart-hypervisor: ${d}'s passwords weren't removed`,w));await Rn(pr(this.dir,d),{recursive:!0,force:!0}),s.info(`tart-hypervisor: deleted ${d}`)}async ip(d){await this.need(d);let u=await g(r(R).sub("ip").arg(d).flag("--wait",5).build()),p=u.stdout.trim();return u.exitCode===0&&/^[0-9a-f.:]+$/i.test(p)?p:void 0}async keepRunning(){if(!await Pd())return;for(let d of await this.recorded()){let u=await this.record(d);if(u?.wanted!=="running"||!u.prepared||this.busy.has(d))continue;if(this.failures.has(d)||await An(d)!=="stopped")continue;if(u.os==="darwin"&&(await this.info()).running.macos>=go)continue;s.info(`tart-hypervisor: ${d} stopped by itself: starting it again`),this.inBackground(d,"booting",()=>this.boot(d))}}async settled(d){await this.busy.get(d)?.work}async prepare(d){if((await this.need(d)).os==="darwin")return this.prepareMac(d);if(await this.boot(d,{seed:!1}),await this.guestAnswers(d)){if(!(await T(r(R).sub("exec").arg(d).wrap(r(A).flag("-n").wrap(r(Z).script("-c",B_).build()).build()).build())).includes("prepared"))throw Error(`readying ${d}'s cloud-init said nothing`)}else s.info(`tart-hypervisor: ${d} has no guest agent: its image reads its seed disk itself`);await T(r(R).sub("stop").arg(d).flag("--timeout",60).timeoutMs(120000).build()),await this.until(d,"stopped"),await this.keep(d,{...await this.need(d),prepared:!0})}async prepareMac(d){if(await this.boot(d),!await this.guestAnswers(d))throw Error(`${d}'s guest agent doesn't answer: a macOS VM joins through Tart's guest agent`);if(!(await this.need(d)).locked){let w=an();await so(this.dir).put(d,w);let y=(await $d(this.path(d,"data.img"))).size;if(!(await T(r(R).sub("exec").flag("-i").arg(d).wrap(r(A).flag("-n").wrap(r(Z).script("-c",H_(y)).build()).build()).timeoutMs(300000).build(),{input:`admin
|
|
350
|
+
${w.adminPassword}
|
|
351
|
+
${w.screenPassword}
|
|
352
|
+
`})).includes("locked"))throw Error(`locking ${d} down said nothing`);await this.keep(d,{...await this.need(d),locked:!0})}let u=await this.join(d);if(!u)throw Error(`${d} has no join to run: it was spent, make the VM again`);if(!(await T(r(R).sub("exec").flag("-i").arg(d).wrap(r(Z).script("-c",G_(u)).build()).timeoutMs(1200000).build(),{input:u.token})).includes("joined"))throw Error(`${d}'s join said nothing`);await Rn(this.path(d,"join.json"),{force:!0}),await this.keep(d,{...await this.need(d),prepared:!0}),s.info(`tart-hypervisor: ${d} (macOS) locked down and joined`)}async guestAnswers(d){let u=r(R).sub("exec").arg(d).wrap(r(Xt).build()).timeoutMs(30000).build(),p=Date.now()+U_;while(Date.now()<p){if((await g(u)).exitCode===0)return!0;await Bun.sleep(fS)}return!1}async join(d){let u=Bun.file(this.path(d,"join.json"));return await u.exists()?await u.json():void 0}async boot(d,{seed:u=!0}={}){if(await An(d)==="running")return;let p=await this.need(d);if(p.os==="darwin"&&(await this.info()).running.macos>=go)throw Error(`${go} macOS VMs run on this Mac already: Apple allows no more`);let w=this.path(d,"tart.log");await Rn(w,{force:!0});let y=r(R).sub("run").arg(d).flag("--no-graphics").flag("--disk",this.path(d,"data.img"));if(u&&p.os!=="darwin")y.flag("--disk",`${this.path(d,"seed.iso")}:ro`);if(p.bridged)y.flag("--net-bridged",p.bridged);else if(p.reach&&await yS()==="ready"){if(y.flag("--net-softnet"),p.reach.length)y.flag("--net-softnet-allow",p.reach.join(","))}_(y.build(),{stdin:"ignore",stdout:{file:w},stderr:{file:w},detached:!0}).unref(),await this.until(d,"running",w)}async until(d,u,p){let w=Date.now()+mS;while(await An(d)!==u){if(Date.now()>w){let y=p?bS(await Bun.file(p).text().catch(()=>"")):"";throw Error(`${d} isn't ${u} after ${Math.round(mS/1000)} s${y?`: ${y}`:""}`)}await Bun.sleep(fS)}}async writeSeed(d,u,p){let w=this.path(d,"seed");await Rn(w,{recursive:!0,force:!0}),await pS(w,{mode:448});try{let y=[["user-data",u],["meta-data",`instance-id: ${d}
|
|
353
|
+
local-hostname: ${d}
|
|
354
|
+
`],...p?[["network-config",p]]:[]];for(let[S,x]of y)await Qh(pr(w,S),x,{mode:384});let v=this.path(d,"seed.new.iso");await Rn(v,{force:!0}),await T(r(hd).sub("makehybrid").flag("-iso").flag("-joliet").flag("-default-volume-name","cidata").flag("-o",v).arg(w).build()),await Kh(v,384),await hS(v,this.path(d,"seed.iso"))}finally{await Rn(w,{recursive:!0,force:!0})}}inBackground(d,u,p){this.failures.delete(d);let w=p().then(()=>{this.busy.delete(d)},(y)=>{this.busy.delete(d),this.failures.set(d,y.message),s.warn(`tart-hypervisor: ${d}: ${u} failed`,y)});this.busy.set(d,{state:u,work:w})}path(d,u){return pr(this.dir,d,u)}async recorded(){return(await x_(this.dir).catch(()=>[])).filter((u)=>/^sf-[a-z0-9][a-z0-9-]{0,62}$/.test(u))}async record(d){let u=Bun.file(this.path(d,"vm.json"));return await u.exists()?await u.json():void 0}async need(d){let u=await this.record(d);if(!u)throw new c("not_found",`${d} isn't one of the VMs Superfactory made on this Mac`);return u}async keep(d,u){let p=this.path(d,"vm.json");await Qh(`${p}.new`,JSON.stringify(u),{mode:384}),await hS(`${p}.new`,p)}}async function yS(){let d=Bun.which("softnet",{PATH:process.env.PATH??""});if(!d)return"missing";let u=await M_(d).then((p)=>$d(p)).catch(()=>{return});return u?.isFile()&&u.uid===0&&(u.mode&2048)!==0?"ready":"not-setuid"}async function q_(d){let u=new URL(d).hostname.replace(/^\[|\]$/g,""),p=vS(u)?[u]:(await __(u,{all:!0,family:4}).catch(()=>[])).map((w)=>w.address);return[...new Set(p.filter(V_))].map((w)=>`${w}/32`)}function V_(d){if(vS(d)!==4)return!1;let[u=0,p=0]=d.split(".").map(Number);return u===10||u===172&&p>=16&&p<=31||u===192&&p===168||u===100&&p>=64&&p<=127||u===169&&p===254}async function Pd(){if(!Bun.which("tart",{PATH:process.env.PATH??""}))return;let d=await g(r(R).flag("--version").timeoutMs(30000).build());return d.exitCode===0?d.stdout.trim().slice(0,100)||"unknown":void 0}async function yo(){return JSON.parse(await T(r(R).sub("list").flag("--format","json").build()))}async function cr(d){let u=await g(r(R).sub("get").arg(d).flag("--format","json").build());return u.exitCode===0?JSON.parse(u.stdout):void 0}async function An(d){return(await yo()).find((u)=>u.Name===d&&u.Source==="local")?.State}var Zh=(d)=>d?.OS==="darwin"||d?.OS==="linux"?d.OS:void 0;async function kS(d,u){let p=await O_(d,"a",384);try{await p.truncate(u*_n)}finally{await p.close()}}var Cn=(d)=>Math.round(d*10)/10,bS=(d)=>d.trim().split(`
|
|
355
|
+
`).slice(-3).join(" ").slice(-400);import{readdir as Y_}from"fs/promises";class fm{server;nodeKey;constructor(d,u){this.server=d;this.nodeKey=u}vaultFor=(d)=>{let u=()=>to(d,this.nodeKey());return{get:async(p)=>{let w=await u().get(p);if(w)return w;let y=this.server();if(!y?.connected)throw Error(`${p}'s passwords aren't on this Mac, and the server is out of reach`);let{passwords:v}=await y.request("vm.passwords.get",{vm:p});if(v)await u().put(p,v);return v},put:async(p,w)=>{await u().put(p,w),await this.send(p,w)},remove:async(p)=>{await u().remove(p);let w=this.server();if(w?.connected)await w.request("vm.passwords.remove",{vm:p}).catch((y)=>s.warn(`macos: ${p}'s passwords stay on the server until the next link`,y))}}};async send(d,u){let p=this.server();if(!p?.connected)return;await p.request("vm.passwords.put",{vm:d,passwords:u}).catch((w)=>s.warn(`macos: ${d}'s passwords go to the server at the next link`,w))}async sync(d=Ns){if(process.platform!=="darwin"||!Bun.which("tart"))return;let u=this.server();if(!u?.connected)return;let p=to(d,this.nodeKey()),w=new Set((await cn()).map((S)=>S.name)),y=await Y_(d).catch(()=>[]);for(let S of y.filter((x)=>x.endsWith(".vault")).map((x)=>x.slice(0,-6))){if(!w.has(S)){await p.remove(S);continue}let x=await p.get(S);if(x)await this.send(S,x)}let{vms:v}=await u.request("vm.passwords.list",{});for(let S of v.filter((x)=>!w.has(x)))await u.request("vm.passwords.remove",{vm:S}).catch(()=>{return})}}class ym{state;nodeId;constructor(d,u){this.state=d;this.nodeId=u}list(){return this.state.managers}async set(d){this.state.managers=d,await F(this.state)}main(d){let u=cp(d,this.nodeId());return this.list().find((p)=>p.id===u)??Mo.parse({id:u,name:xn(d),scope:d,nodeId:this.nodeId(),main:!0,type:"general",createdAt:new Date(0).toISOString()})}resolve(d,u){if(!u||jo(u))return this.main(d);let p=this.list().find((w)=>w.id===u);if(!p||!K_(p.scope,d))throw new c("not_found","no such manager here: add it in Agents first");return p}get(d){let u=this.list().find((p)=>p.id===d);if(u)return u;if(d===cp({kind:"global"},this.nodeId()))return this.main({kind:"global"});if(d.startsWith("p-"))return this.main({kind:"project",projectId:d.slice(2)});return}team(d){return{boss:d.bossId?this.get(d.bossId):void 0,reports:this.list().filter((u)=>u.bossId===d.id),peers:d.bossId?this.list().filter((u)=>u.bossId===d.bossId&&u.id!==d.id):[]}}forProject(d){let u=this.state.holdsLead??this.state.projects.some((S)=>S.lead),p=(S)=>!(S.main&&S.scope.kind==="global")||u,w=this.list().filter((S)=>S.scope.kind==="global"?p(S):S.scope.projectId===d);return[...[...u&&this.state.projects.some((S)=>S.id===d&&S.lead)?[]:[this.main({kind:"project",projectId:d})],...u?[this.main({kind:"global"})]:[]].filter((S)=>!w.some((x)=>x.id===S.id)),...w].filter((S)=>!S.mergedInto)}}var K_=(d,u)=>d.kind===u.kind&&(d.kind==="global"||u.kind==="project"&&d.projectId===u.projectId);import{readFile as Q_}from"fs/promises";import{connect as J_,createServer as z_}from"net";import{networkInterfaces as X_}from"os";import{join as Z_}from"path";class bm{serverUrl;servers=[];open=new Set;applied="";constructor(d){this.serverUrl=d}async apply(d){let u=await nO(),p=eO(d),w=!!u&&u.mode!=="host"&&u.url===this.serverUrl(),y=u&&w&&p.open?u.port:void 0,v=y?tO(p.addresses):[],S=JSON.stringify({port:y,wanted:v,allow:p.allowClients});if(S===this.applied)return w;if(this.applied=S,await this.close(),!y)return w;for(let x of v)this.servers.push(await sO(x,y,p.allowClients,this.open));return s.info(`network: server reachable on ${v.join(", ")||"no address"} (port ${y})`),w}async close(){for(let u of this.open)u.destroy();this.open.clear();let d=this.servers.splice(0);await Promise.all(d.map((u)=>new Promise((p)=>u.close(()=>p()))))}}function eO(d){let u=d;return{open:u["server.reach"]==="network",addresses:u["server.addresses"]??[],allowClients:u["server.allowClients"]??[]}}function tO(d){if(d.length)return d;return Object.values(X_()).flat().filter((u)=>u&&!u.internal&&!u.address.startsWith("fe80:")&&!u.address.startsWith("169.254.")).map((u)=>u?.address??"").filter(Xl)}function sO(d,u,p,w){let y=z_((v)=>{let S=v.remoteAddress??"";if(!Fh(S,p))return s.info(`network: refused ${S}`),v.destroy();let x=J_(u,"127.0.0.1");w.add(v);let j=()=>{w.delete(v),v.destroy(),x.destroy()};v.on("error",j).pipe(x).on("error",j).pipe(v),v.on("close",j),x.on("close",j)});return new Promise((v)=>{y.once("error",(S)=>{s.warn(`network: can't listen on ${d}:${u}`,S),v(y)}),y.listen(u,d,()=>v(y))})}async function nO(){let d=await Q_(Z_(m().home,"local-server.json"),"utf8").catch(()=>{return});if(!d)return;let u=JSON.parse(d);return typeof u.port==="number"&&u.url?{port:u.port,url:u.url,mode:u.mode}:void 0}import{chmod as iO,mkdir as rO,readFile as oO,rename as aO,writeFile as dO}from"fs/promises";import{dirname as cO}from"path";var uO=t({toolName:e(),command:e().optional(),by:e(),at:e(),onHost:n().optional()}),lO=I(e(),o(uO));function pO(d,u,p,w){let y=new Date().toISOString();if(d!=="Bash")return{toolName:d,by:p,at:y,onHost:w};return typeof u.command==="string"?{toolName:d,command:u.command,by:p,at:y,onHost:w}:void 0}var PS=(d,u,p)=>d.toolName===u&&(u!=="Bash"||d.command===p.command),hO=(d,u,p,w)=>PS(d,u,p)&&(!w.onHost||d.onHost===!0);function SS(d,u,p,w){let y=d.find((v)=>PS(v,p,w));if(!y)return[...d,u];if(u.onHost)Object.assign(y,{onHost:!0,by:u.by,at:u.at});return d}class Tm{sessions=new Map;projects;async allows(d,u,p){if(!Lr(u,p,d.place).canRemember)return;let w=(y)=>hO(y,u,p,d.place);if(this.sessions.get(d.sessionId)?.some(w))return"session";if(!d.projectId)return;return((await this.load())[d.projectId]??[]).some(w)?"project":void 0}async remember(d,u,p,w,y){if(u.place.onHost&&!y.serverOwner)return!1;let v=pO(p,w,y.handle,y.serverOwner);if(!v||!Lr(p,w,u.place).canRemember)return!1;if(d==="session")return this.sessions.set(u.sessionId,SS(this.sessions.get(u.sessionId)??[],v,p,w)),!0;if(!u.projectId)return!1;let S=await this.load();return S[u.projectId]=SS(S[u.projectId]??[],v,p,w),await this.save(S),!0}async load(){if(this.projects)return this.projects;let d=await oO(m().permissionRules,"utf8").catch(()=>"{}"),u={};try{u=JSON.parse(d)}catch{}let p=lO.safeParse(u);return this.projects=p.success?p.data:{},this.projects}async save(d){let u=m().permissionRules;await rO(cO(u),{recursive:!0,mode:448});let p=`${u}.${process.pid}.tmp`;await dO(p,`${JSON.stringify(d,null,2)}
|
|
356
|
+
`,{mode:384}),await iO(p,384),await aO(p,u)}}import{join as mO}from"path";var $S=(d,u)=>d.findLast((p)=>p.type==="question"&&p.question.id===u)?.question;class Um{deps;lastAsked=new Map;constructor(d){this.deps=d}async post(d,u){let p=K.parse({...u,id:await this.nextId(d),kind:"choice",status:"open",askedAt:new Date().toISOString(),askedBy:d});return this.deps.record(d,{type:"question",question:p}),p}async answer(d,u,p){let w=await this.take(d,u,p);return await this.deps.send(d,ni(w),p.by),this.deps.record(d,{type:"question",question:w}),w}async answerWithMessage(d,u,p){this.deps.record(d,{type:"question",question:await this.take(d,u,p)})}async reopen(d,u){let p=$S(await this.events(d),u);if(!p)throw new c("not_found",`${d} asked no ${u}`);if(p.status!=="dismissed")throw new c("conflict",`${u} is ${p.status}`);let{answer:w,...y}=p,v={...y,status:"open"};return this.deps.record(d,{type:"question",question:v}),v}async latestWaiting(d){let u=new Map;for(let p of await this.events(d))if(p.type==="question")u.set(p.question.id,p.question);return[...u.values()].filter((p)=>p.status==="open"||p.status==="expired").sort((p,w)=>p.askedAt.localeCompare(w.askedAt)).at(-1)}async take(d,u,p){let w=$S(await this.events(d),u);if(!w)throw new c("not_found",`${d} asked no ${u}`);if(w.status!=="open"&&w.status!=="expired")throw new c("conflict",`${u} is ${w.status}`);return{...w,status:p.dismissed?"dismissed":"answered",answer:{...p,at:new Date().toISOString()}}}async nextId(d){let u=[this.lastAsked.get(d)??0];for(let w of await this.events(d))if(w.type==="question")u.push(Number(w.question.id.slice(2)));let p=Math.max(...u)+1;return this.lastAsked.set(d,p),`Q-${p}`}events(d){return this.deps.events?.(d)??Ms(mO(m().sessionLogs,`${d}.jsonl`))}}var fO="continue",IS="not_now",gO={crashed:"it crashed",ended:"it ended on its own",killed:"its Claude was ended from outside Superfactory",wrap_up_timeout:"it didn't wrap up in time",not_started:"its Claude Code couldn't start",start_failing:"it keeps failing as it starts"},wO=3600000,yO=(d)=>d.projectId&&d.taskId?{projectId:d.projectId,taskId:d.taskId}:void 0,kO=(d)=>(d.kind==="task"||d.kind==="epic")&&!d.teammate;class Fm{deps;toldLead=new Map;constructor(d){this.deps=d}async ended(d,u){let p=yO(d);if(!p||!kO(d))return;let w=await this.deps.tasks.get(p).catch(()=>{return});if(!w||w.archived)return;if(w.sessionId&&w.sessionId!==d.id)return;if(u==="not_started")return this.notStarted(p,d);if(u==="start_failing")return this.startFailing(p,d);if(w.status!=="in_progress")return;if(w.questions.some((v)=>v.status==="open"))return;let y=D(w.id,this.deps.projects.keys(w.projectId).key);await this.deps.questions.postOnce(p,{kind:"choice",purpose:"continue",text:`${y}'s agent stopped (${gO[u]}). ${d.error?`${d.error} `:""}Continue?`,choices:[{id:fO,label:"Continue",description:"The same agent, conversation and worktree"},{id:IS,label:"Not now",description:"It stays stopped; Continue stays on the task"}],multiSelect:!1,askedBy:d.id}),s.info(`continue: asked whether ${p.taskId}'s agent ${d.id} goes on (${u})`)}async notStarted(d,u){if(!this.mayTellLead(d))return;let p=D(d.taskId,this.deps.projects.keys(d.projectId).key);await this.deps.tellLead(d,`From Superfactory: ${p}'s agent couldn't start on its machine. Fix the machine (or move the task to another), then start it again with task_start; its user wasn't asked. What its machine said, as data:
|
|
357
|
+
${TS(p,u,"Its Claude Code couldn't start.")}`),s.info(`continue: told ${d.taskId}'s lead its agent ${u.id} couldn't start`)}async startFailing(d,u){if(!this.mayTellLead(d))return;let p=D(d.taskId,this.deps.projects.keys(d.projectId).key);await this.deps.tellLead(d,`From Superfactory: ${p}'s agent failed as it started, ${Ja} times in a row. Its user isn't asked to continue it again. Find why (its session's events, its machine), then start it with task_start: it begins a new conversation with its task's brief. What its Claude said last, as data:
|
|
358
|
+
${TS(p,u,"Its Claude exited before it began.")}`),s.info(`continue: told ${d.taskId}'s lead its agent ${u.id} keeps failing as it starts`)}mayTellLead(d){let u=`${d.projectId}/${d.taskId}`,p=this.toldLead.get(u);if(p!==void 0&&Date.now()-p<wO)return!1;return this.toldLead.set(u,Date.now()),!0}async answered(d,u){let p=u.answer;if(!p||!u.askedBy||p.choiceIds?.includes(IS))return;let w=p.text?.trim();await this.deps.send(u.askedBy,w||Xr,p.by).catch((y)=>s.warn(`continue: couldn't resume ${d.taskId}'s agent ${u.askedBy}`,y))}}var TS=(d,u,p)=>It(d,u.error??p);class Bm{deps;constructor(d){this.deps=d}show(d,u){if(!bO(u))return;this.showNow(d,u).catch((p)=>s.warn(`questions: ${d.taskId}'s ${u.id} not shown to its owners`,p))}async showNow(d,u){let p=await this.deps.task(d),w=p.questions.find((v)=>v.id===u.id)??u,y=await this.owners(d,p,w);await Promise.all(y.map((v)=>this.deps.record(v,{type:"task_question",task:d,question:w})))}async owners(d,u,p){let w=await this.deps.coordinatorOf(d),y=u.epic?(await this.deps.task({projectId:d.projectId,taskId:u.epic}).catch(()=>{return}))?.sessionId:void 0,v=[w&&this.deps.managersChat(w),y];return[...new Set(v)].filter((S)=>!!S&&S!==p.askedBy&&S!==u.sessionId)}}var bO=(d)=>d.kind!=="permission"&&!d.purpose;var vO=`${Kl}your last message asks the user something in plain text, but they answer only questions asked with a tool. Something you can decide: decide it by best practice, note it on the task, and go on; an infrastructure problem: tell your lead. Only what only the user can give (a credential, a physical action, a business decision with no reasonable default): ask it now with mcp__superfactory__task_ask, in a sentence or two with 2-4 short choices they tap (an action is a choice too, e.g. "Done, it's unlocked"). If you weren't asking them anything, reply only: ok`,SO=`${Kl}your last message asks the user something in plain text, but they answer only questions asked with a tool. Something you can decide: decide it by best practice and go on. Only what only the user can give (a credential, a physical action, a business decision with no reasonable default): ask it now with mcp__superfactory__chat_ask (or task_ask with the taskId, when it is about a task), in a sentence or two with 2-4 short choices they tap. If you weren't asking them anything, reply only: ok`,PO=/\?[\s*_`)"'\u201D]*$/,$O=[/\b(let me know|tell me (which|whether|if|when)|please (confirm|choose|pick|decide|approve|unlock|plug|tap|reply|answer|try|test|install|open|restart|log in|sign in)|tap \S+ (here|once|when)|reply (with|here|once|when)|when you('re| are) (ready|done))\b/i,dp],IO=/^(?:(?:so|and|ok(?:ay)?|now),?\s+)?(?:(?:what|how) (?:else )?(?:can|could|may|shall) i (?:help|assist|do for you)|(?:is there )?anything else(?: i can)?|what(?:'s| is| would you like)(?: to work on)? next|what are we (?:working on|doing)(?: today)?)\b[^?,;:]{0,25}\?$/i,TO=(d)=>(d.replace(/[\s*_`)"'\u201D]+$/,"").split(/(?<=[.!?:\n])\s+/).at(-1)??"").trim();function RO(d){let u=d.trim().slice(-600);if($O.some((p)=>p.test(u)))return!0;return PO.test(u)&&!IO.test(TO(u))}class Gm{deps;nudged=new Set;due=new Map;constructor(d){this.deps=d}onEvent(d,u){let p=d.id;switch(u.type){case"init":this.cancel(p);return;case"user_message":if(this.deps.activity.get(p)?.withPerson)this.cancel(p);return;case"result":this.turnEnded(d,u.outcome==="success");return;case"state":if(u.state==="exited"||u.state==="failed")this.forget(p);return}}turnEnded(d,u){let p=d.id,w=this.deps.activity.get(p),y=this.nudged.delete(p);if(!u||!w||w.askedWithTool||y||w.withPerson)return;if(!RO(w.sinceTool))return;let v=d.kind==="coordinator"?SO:vO,S=setTimeout(()=>void this.send(p,v),this.deps.afterMs??zn*2);S.unref?.(),this.due.set(p,S)}async send(d,u){if(this.due.delete(d),this.nudged.add(d),!await this.deps.nudge(d,u).catch((w)=>(s.warn(`plain asks: nudge to ${d} not sent`,w),!1)))this.nudged.delete(d);else s.info(`plain asks: ${d} asked in plain text; nudged`)}cancel(d){clearTimeout(this.due.get(d)),this.due.delete(d)}forget(d){this.cancel(d),this.nudged.delete(d)}stop(){for(let d of this.due.values())clearTimeout(d);this.due.clear()}}var AO="retry",EO="not_now",CO=(d)=>d.projectId&&d.taskId?{projectId:d.projectId,taskId:d.taskId}:void 0,_O=(d)=>(d.kind==="task"||d.kind==="epic")&&!d.teammate;function OO({from:d,noAccount:u}){if(u==="owner_only")return"Its Claude accounts reach only the sessions the server owner starts, and nobody started this one: it started by itself. **Try again** runs it as yours, on the accounts you may use.";if(u==="none_set")return"No Claude account is set for it, and this machine has no Claude login of its own. Add one in Settings \u203A Claude accounts (it carries on by itself then), or sign this machine in to Claude and **Try again**.";return`Claude refused the login of ${d}, and no other account it may use is signed in. Sign ${d} in again in Settings \u203A Claude accounts, or add another account: it carries on by itself then. **Try again** runs it now, as yours.`}class Vm{deps;constructor(d){this.deps=d}async signedOut(d,u){let p=CO(d);if(!p||!_O(d))return;let w=await this.deps.tasks.get(p).catch(()=>{return});if(!w||w.archived||w.status!=="in_progress"&&w.status!=="needs_input")return;if(w.sessionId&&w.sessionId!==d.id)return;let y=D(w.id,this.deps.projects.keys(w.projectId).key);if(xO(u)){s.info(`sign-in: ${p.taskId}'s agent waits for this machine's Claude login; the server tells its owners`);return}if(await this.deps.questions.postOnce(p,{kind:"choice",purpose:"sign_in",text:`${y}'s agent can't sign in to Claude`,details:OO(u),choices:[{id:AO,label:"Try again",description:"It starts again now, as yours"},{id:EO,label:"Not now",description:"It waits, and carries on once an account is signed in"}],multiSelect:!1,askedBy:d.id}))s.info(`sign-in: asked about ${p.taskId}'s agent ${d.id}, which has no login`)}}var xO=({noAccount:d,machineLogin:u})=>u&&d!=="owner_only";var MO=(d)=>d.status==="in_progress"||d.status==="needs_input",jO=(d)=>!!d&&d.state!=="exited"&&d.state!=="failed",LO={merge:(d)=>d.status==="in_review",continue:(d,u,p)=>d.status==="needs_input"&&(!d.sessionId||d.sessionId===u.askedBy)&&!jO(p),sign_in:(d,u,p)=>MO(d)&&(!d.sessionId||d.sessionId===u.askedBy)&&(!p||p.pausedFor==="signed_out")};function NO(d,u,p){let w=u.purpose?LO[u.purpose]:void 0;if(!w)return!0;return!Yh(d)&&w(d,u,p)}class Km{deps;constructor(d){this.deps=d}async sweep(d){if(!this.deps.holds(d))return;let u=(w)=>w.status==="open"&&!NO(d,w,w.askedBy?this.deps.find(w.askedBy):void 0);if(!d.questions.some(u))return;let p=d.questions.filter(u).map((w)=>`${w.id} (${w.purpose})`);await this.deps.tasks.cancelOpen({projectId:d.projectId,taskId:d.id},u),s.info(`questions: closed ${p.join(", ")} on ${d.id}: no longer needed`)}async sessionChanged(d){if(!d.projectId||!d.taskId)return;let u={projectId:d.projectId,taskId:d.taskId},p=await this.deps.tasks.get(u).catch(()=>{return});if(p)await this.sweep(p)}}import{existsSync as DO}from"fs";import{mkdir as UO}from"fs/promises";import{join as Qm}from"path";var FO=60000,BO=1000,WO=1e4;class RS{nodeId;key;server;calls=new Map;observers=new Set;socket;waiting=new sa((d)=>d.liveOnly);hello;backoff=new na(BO,WO);inFlight=new Set;buffer="";nextId=0;closed=!1;process;constructor(d,u,p){this.nodeId=d;this.key=u;this.server=p;O(u)}get stopped(){return this.closed}async call(d,u){let p=`p-${++this.nextId}`,w=await new Promise((v,S)=>{let x=setTimeout(()=>{this.calls.delete(p),S(new c("unavailable",`the sandbox's agent didn't answer ${d}`))},FO);this.calls.set(p,{resolve:(j)=>{clearTimeout(x),v(j)},reject:(j)=>{clearTimeout(x),S(j)}}),this.process?.write(`${JSON.stringify({kind:"req",id:p,method:d,params:u})}
|
|
359
|
+
`)}),y=Wg(d,w);if(!y.success)throw new c("internal",`the sandbox's ${d} answer breaks the contract`);return y.data}observe(d){return this.observers.add(d),()=>this.observers.delete(d)}fromChild(d){this.buffer+=d;for(let u=this.buffer.indexOf(`
|
|
360
|
+
`);u>=0;u=this.buffer.indexOf(`
|
|
361
|
+
`)){let p=this.buffer.slice(0,u);if(this.buffer=this.buffer.slice(u+1),p.trim())this.line(p)}}async connect(){let d=this.server(),u=await C(d.url,d.pin),p=new WebSocket(ca(d.url),{headers:{"x-api-key":this.key,...d.headers},tls:u});this.socket=p,p.addEventListener("open",()=>{if(this.backoff.reset(),this.hello)this.toServer(p,this.hello);for(let{line:w}of this.waiting.take())this.toServer(p,w)}),p.addEventListener("message",(w)=>{let y=String(w.data);if(this.inFlight.size>0)this.answered(y);this.process?.write(`${y}
|
|
362
|
+
`)}),p.addEventListener("close",()=>{if(this.socket!==p)return;this.socket=void 0,this.failInFlight(),this.retry()})}retry(){if(this.closed)return;setTimeout(()=>{if(this.closed)return;this.connect().catch((d)=>{s.warn(`child ${this.nodeId}: its link can't connect: ${d.message}`),this.retry()})},this.backoff.next())}close(){this.closed=!0,this.socket?.close(1000,"sandbox stopping"),this.process?.closeStdin().catch(()=>{return});for(let d of this.calls.values())d.reject(new c("unavailable","the sandbox's agent stopped"));this.calls.clear()}line(d){let u;try{u=Go.parse(JSON.parse(d))}catch{s.warn(`child ${this.nodeId}: ${d.slice(0,200)}`);return}if((u.kind==="ok"||u.kind==="err")&&u.id.startsWith("p-")){let w=this.calls.get(u.id);if(this.calls.delete(u.id),u.kind==="ok")w?.resolve(u.result);else w?.reject(new c(u.error.code,u.error.message));return}if(u.kind==="push")for(let w of this.observers)w(u.push);if(u.kind==="push"&&u.push.type==="mcp.gaveUp")return;let p=u.kind==="push"&&u.push.type==="hello";if(p)this.hello=d;if(this.socket?.readyState===WebSocket.OPEN)this.toServer(this.socket,d);else if(!p)this.waiting.add({line:d,liveOnly:u.kind==="push"&&Cc(u.push)})}toServer(d,u){let p=JSON.parse(u);if(p.kind==="req"&&p.id)this.inFlight.add(p.id);d.send(u)}answered(d){try{let u=JSON.parse(d);if((u.kind==="ok"||u.kind==="err")&&u.id)this.inFlight.delete(u.id)}catch{}}failInFlight(){for(let d of this.inFlight){let u={code:"unavailable",message:"the link to the server dropped"};this.process?.write(`${JSON.stringify({kind:"err",id:d,error:u})}
|
|
363
|
+
`)}this.inFlight.clear()}}class qf{deps;children=new Map;constructor(d){this.deps=d}available(){return Boolean(this.deps.link()?.connected&&this.deps.server())}for(d,u,p){let w=d.id,y=this.children.get(w);if(y)return y;let v=this.start(d,u,p);return this.children.set(w,v),v.catch(()=>this.children.delete(w)),v}async stopAll(){let d=await Promise.all([...this.children.values()].map((u)=>u.catch(()=>{return})));this.children.clear(),await Promise.all(d.map((u)=>u&&GO(u)))}async handOver(d,u){let p=this.deps.link();if(!p?.connected)throw new c("unavailable","not linked to a server");await p.request("nodes.childSession",{nodeId:d,sessionId:u.id,session:u})}async start(d,u,p){let w=this.deps.link(),y=this.deps.server();if(!w?.connected||!y)throw new c("unavailable","not linked to a server");let v=performance.now(),{nodeId:S,key:x}=await w.request("nodes.enrollChild",{name:d.id,runner:u,projectId:p}),j=new RS(S,x,()=>this.deps.server()??y);return j.process=await d.spawnAgent({binary:await qO(u==="tart"?"darwin":"linux"),args:["child"],env:{SF_NODE_ID:S,SF_PARENT_NODE_ID:this.deps.parentId(),SF_RUNNER:u,SF_NODE_NAME:d.id,SUPERFACTORY_SANDBOX:"1",...process.env.SUPERFACTORY_SANDBOX_CLAUDE_BIN?{SUPERFACTORY_CLAUDE_BIN:process.env.SUPERFACTORY_SANDBOX_CLAUDE_BIN}:{}},onStdout:(L)=>j.fromChild(L),onStderr:(L)=>s.info(`child ${S}: ${L.trimEnd()}`),onExit:({exitCode:L})=>{s.warn(`child ${S} exited (${L})`),this.children.delete(d.id),j.close(),w.request("nodes.revokeChild",{nodeId:S}).catch(()=>{return})}}),await j.connect(),s.info(`children: ${S} in ${d.id} ready in ${((performance.now()-v)/1000).toFixed(2)} s`),j}}var HO=12000;async function GO(d){if(d.close(),!d.process)return;if(await d.process.wait({timeout:HO}).then(()=>!0,()=>!1))return;s.warn("children: a sandbox's agent didn't end in time: ending it"),await d.process.kill("SIGKILL").catch(()=>{return})}var Xm=new Map;function qO(d,u=process.arch==="arm64"?"arm64":"x64"){let p=process.env[`SUPERFACTORY_CHILD_AGENT_${d.toUpperCase()}`];if(p)return Promise.resolve(p);let w=`${d}-${u}`,y=Xm.get(w);if(y)return y;let v=Qm(import.meta.dir,"..","..","main.ts"),S=Qm(m().home,"bin",`superfactory-agent-${d}-${u}`),x=(async()=>{if(!DO(v))throw new c("unavailable",`no ${d} build of the agent: set SUPERFACTORY_CHILD_AGENT_${d.toUpperCase()}`);await UO(Qm(m().home,"bin"),{recursive:!0});let j=r(se).sub("build").flag("--compile").flag("--target",`bun-${d}-${u}`).arg(v).flag("--outfile",S),L=await g(j.build());if(L.exitCode!==0)throw Error(`agent build failed: ${L.stderr}`);return S})();return Xm.set(w,x),x.catch(()=>Xm.delete(w)),x}class Xf{places;projects;nodeId;constructor(d,u,p){this.places=d;this.projects=u;this.nodeId=p}async list(){return await this.places.removeEnded(),this.places.list().map((d)=>this.node(d))}async create(d,u){let p=await this.projects.get(d),w=await this.projects.settings(d);await this.places.devSandbox(p,w,u);let y=rn(d,"dev"),v=this.places.list().find((S)=>S.name===y);if(!v)throw Error(`sandbox ${y} didn't start`);return this.node(v)}destroy(d){return this.places.destroy(d)}node(d){return{id:d.name,name:d.name,kind:"sandbox",os:d.runner==="tart"?"darwin":"linux",arch:process.arch==="arm64"?"arm64":"x64",parentId:this.nodeId(),runner:d.runner,status:"online",agentVersion:H,capabilities:{runners:[],git:!0,gh:!1,screen:!1},lastSeenAt:new Date().toISOString()}}}var VO=/(^|[^A-Za-z0-9_.-])git([ \t]+[^\n;&|()`]*?)?[ \t]worktree[ \t]+add([ \t\n;&|)]|$)/;function AS(d,u){if(u.kind==="coordinator"||!VO.test(rl(d)))return;return["Refused: a task works in its own worktree only, never in one it makes (`git worktree add`).","Your sandbox lets git write only this worktree's own folder in .git/worktrees, so git fails in another one (Read-only file system), and review and Merge follow this worktree's branch.","This worktree on the wrong branch (a stale one, or your PR is on another): ask your project's lead (SendMessage) to put it on the branch you need with task_worktree (from: branch, branch: its name). The task then follows that branch and its PR, and your session goes on there.","Another branch only to read: `git show <branch>:<path>`, or `git diff <branch>`, in this worktree."].join(`
|
|
364
|
+
`)}function ES(d,u=()=>!0){let p=()=>{let y=d();return y?.connected?y:void 0},w=()=>{let y=p();if(!y)throw new c("unavailable","this machine isn't linked to its server: other machines can't be reached");return y};return{start:async(y)=>(await p()?.request("sessions.startPlaced",y))?.session,teamList:async(y)=>(await p()?.request("team.listPlaced",y))?.team,teamSend:async(y)=>(await p()?.request("team.sendPlaced",y))?.sent??!1,startOn:(y)=>w().request("team.startOn",y),stop:async(y)=>p()?.request("team.stop",y),namesake:async(y)=>u()?p()?.request("team.namesake",y):void 0,sendTo:async(y)=>{await w().request("team.sendTo",y)}}}var YO=["UserNotificationCenter","universalAccessAuthWarn","SecurityAgent","CoreServicesUIAgent","ScreenCaptureApprovals"],KO=l`ObjC.import('Foundation');
|
|
365
|
+
ObjC.import('ApplicationServices');
|
|
366
|
+
if (!$.AXIsProcessTrusted()) throw new Error('not allowed assistive access');
|
|
367
|
+
const owners = JSON.parse($.NSString.alloc.initWithDataEncoding($.NSFileHandle.fileHandleWithStandardInput.readDataToEndOfFile, $.NSUTF8StringEncoding).js);
|
|
368
|
+
const se = Application('System Events');
|
|
369
|
+
const out = [];
|
|
370
|
+
for (const owner of owners) {
|
|
371
|
+
let procs = [];
|
|
372
|
+
try { procs = se.processes.whose({ name: owner })(); } catch (e) { continue; }
|
|
373
|
+
for (const p of procs) {
|
|
374
|
+
let wins = [];
|
|
375
|
+
try { wins = p.windows(); } catch (e) { continue; }
|
|
376
|
+
wins.forEach((w, i) => {
|
|
377
|
+
const texts = [], buttons = [];
|
|
378
|
+
try {
|
|
379
|
+
for (const el of w.entireContents()) {
|
|
380
|
+
const role = el.role();
|
|
381
|
+
if (role === 'AXStaticText' || role === 'AXTextArea') texts.push(String(el.value() || ''));
|
|
382
|
+
else if (role === 'AXButton') buttons.push(String(el.name() || el.title() || ''));
|
|
383
|
+
}
|
|
384
|
+
} catch (e) {}
|
|
385
|
+
out.push({ owner, pid: p.unixId(), window: i, title: String(w.name() || ''), texts, buttons });
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
JSON.stringify(out);`,QO=l`ObjC.import('Foundation');
|
|
390
|
+
const want = JSON.parse($.NSString.alloc.initWithDataEncoding($.NSFileHandle.fileHandleWithStandardInput.readDataToEndOfFile, $.NSUTF8StringEncoding).js);
|
|
391
|
+
const se = Application('System Events');
|
|
392
|
+
const p = (want.pid && se.processes.whose({ unixId: want.pid })()[0]) || se.processes.whose({ name: want.owner })()[0];
|
|
393
|
+
if (!p) throw new Error('the dialog is gone');
|
|
394
|
+
const words = (w) => w.entireContents().filter((el) => el.role() === 'AXStaticText').map((el) => String(el.value() || '')).join(' ').replace(/\\s+/g, ' ');
|
|
395
|
+
const wins = p.windows();
|
|
396
|
+
const w = wins.find((x) => { try { return words(x).includes(want.text); } catch (e) { return false; } }) || (want.text ? undefined : wins[want.window]);
|
|
397
|
+
if (!w) throw new Error('the dialog is gone');
|
|
398
|
+
const button = w.entireContents().find((el) => el.role() === 'AXButton' && String(el.name() || el.title() || '') === want.button);
|
|
399
|
+
if (!button) throw new Error('no ' + want.button + ' button');
|
|
400
|
+
button.click();
|
|
401
|
+
'clicked';`,JO=o(t({owner:e(),pid:b().optional(),window:b(),title:e().default(""),texts:o(e()).default([]),buttons:o(e()).default([])}));function zO(d){if(/accept incoming network connections/i.test(d))return"firewall";if(/record (this computer'?s )?(screen|audio)|screen (and system audio )?recording|screen contents/i.test(d))return"screen_recording";if(/accessibility/i.test(d))return"accessibility";if(/wants access to control|would like to control|apple ?events|automation/i.test(d))return"automation";if(/camera/i.test(d))return"camera";if(/microphone/i.test(d))return"microphone";if(/files|folder|desktop|documents|downloads|removable|network volume|full disk/i.test(d))return"files";if(/would like to access|wants to access|would like to/i.test(d))return"privacy";return}function XO(d){let u=/[\u201C"]([^\u201D"]{1,120})[\u201D"]/.exec(d);if(u?.[1])return u[1];return/^(.{1,80}?) (would like|wants) /.exec(d.trim())?.[1]}function ZO(d){return d.flatMap((u)=>{let p=[u.title,...u.texts].filter(Boolean).join(" ").replace(/\s+/g," ").trim(),w=p&&u.buttons.length?zO(p):void 0;if(!w)return[];let y=XO(p);return[{os:"macos",kind:w,what:p.slice(0,600),...y?{process:{name:y}}:{},dialog:{owner:u.owner,...u.pid?{pid:u.pid}:{},window:u.window,buttons:u.buttons.filter(Boolean),text:u.texts.join(" ").replace(/\s+/g," ").trim().slice(0,120)},key:`${u.owner}:${u.pid??""}:${u.window}:${w}:${y??""}`}]})}var ex=["Allow","OK","Always Allow","Allow While Using App","Allow For One Month"],tx=["Don't Allow","Don\u2019t Allow","Deny","Cancel"];function sx(d,u){return u.find((p)=>d.includes(p))}var nx="This Mac's agent can't read its dialogs: give it Accessibility (System Settings \u203A Privacy & Security \u203A Accessibility)",ix="System Events didn't answer: a prompt to let this Mac's agent control it may be waiting on screen (System Settings \u203A Privacy & Security \u203A Automation)";async function CS(){let d=await g(r(Is).flag("-l","JavaScript").script("-e",KO).timeoutMs(15000).by("system.permissions").build(),{input:JSON.stringify(YO)});if(d.timedOut)return{prompts:[],procs:[],blind:ix};if(d.exitCode!==0)return{prompts:[],procs:[],blind:/not allowed|-1719|-1743|-25211|assistive/i.test(d.stderr)?nx:d.stderr.trim().slice(0,300)||"osascript failed"};let u=ZO(JO.parse(JSON.parse(d.stdout.trim()||"[]")));return{prompts:u,procs:u.length?await rx():[]}}async function rx(){let d=await T(r(oe).flag("-axww").flag("-o","pid=,ppid=,comm=").timeoutMs(1e4).by("system.permissions").build());return ox(d)}function ox(d){return d.split(`
|
|
402
|
+
`).flatMap((u)=>{let p=/^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(u);if(!p)return[];let w=p[3].trim();return[{pid:Number(p[1]),ppid:Number(p[2]),name:w.split("/").pop()??w,path:w}]})}async function _S(d,u){let p=d.dialog;if(!p)throw Error("it is no dialog to click");let w=sx(p.buttons,u==="approve"?ex:tx);if(!w)throw Error(u==="approve"?`its dialog has no button that approves (${p.buttons.join(", ")}): grant it in System Settings \u203A Privacy & Security, or deny it`:`its dialog has no button that denies (${p.buttons.join(", ")})`);return await T(r(Is).flag("-l","JavaScript").script("-e",QO).timeoutMs(20000).by("system.permissions").build(),{input:JSON.stringify({owner:p.owner,pid:p.pid,window:p.window,text:p.text,button:w})}),`Clicked \u201C${w}\u201D.`}async function OS(d){let u=await g(r(Z).script("-c",Ii(d)).timeoutMs(60000).by("system.permissions").build());return(u.stdout.trim()||u.stderr.trim()).slice(0,2000)}import{readdir as ax,readFile as tg}from"fs/promises";function dx(d){let u=d.slice(1),p=u.findIndex((w)=>!w.startsWith("-"));return(p<0?u:u.slice(p)).join(" ").slice(0,400)}function xS(d){let u=new Map;for(let w of d)u.set(w.ppid,[...u.get(w.ppid)??[],w]);let p=[];for(let w of d){let y=w.name==="sudo"?"sudo":w.name==="pkexec"?"polkit":void 0;if(!y)continue;if((u.get(w.pid)??[]).filter((x)=>x.name!=="pkttyagent").length)continue;let S=dx(w.args);p.push({os:"linux",kind:y,what:`${y==="sudo"?"sudo":"pkexec"} asks for a password to run: ${S||"(a shell)"}`,process:{pid:w.pid,name:w.name},key:`${y}:${w.pid}`})}return p}function MS(d){let u=d.indexOf("("),p=d.lastIndexOf(")");if(u<0||p<u)return;let w=d.slice(p+2).split(" "),y=Number(w[1]);return Number.isFinite(y)?{name:d.slice(u+1,p),ppid:y}:void 0}async function jS(d="/proc"){let u=(await ax(d).catch(()=>[])).filter((w)=>/^\d+$/.test(w));return(await Promise.all(u.map(async(w)=>{let y=await tg(`${d}/${w}/stat`,"utf8").catch(()=>{return}),v=y?MS(y):void 0;if(!v)return;let S=v.name==="sudo"||v.name==="pkexec"?(await tg(`${d}/${w}/cmdline`,"utf8").catch(()=>"")).split("\x00").filter(Boolean):[];return{pid:Number(w),ppid:v.ppid,name:v.name,args:S}}))).filter((w)=>!!w)}async function LS(d,u,p="/proc"){let w=d.process?.pid;if(!w)throw Error("it names no process to end");let y=async(v)=>MS(await tg(`${p}/${v}/stat`,"utf8").catch(()=>{return})??"");if((await y(w))?.name!==d.process?.name)return"It had ended already.";for(let v=w,S=0;v>1&&!u.has(v)&&v!==process.pid&&S<8;S++){let x=await y(v);if(!x)break;try{return process.kill(v,"SIGTERM"),v===w?`Ended ${x.name} (pid ${w}): the command that ran it fails now instead of waiting.`:`Ended ${x.name} (pid ${v}), which ran the waiting ${d.process?.name} (pid ${w}) as another user: the command fails now instead of waiting.`}catch(j){if(j.code!=="EPERM")throw j;v=x.ppid}}throw Error(`${d.process?.name} (pid ${w}) runs as another user, and nothing above it may be ended from here`)}function NS(d,u,p){let w=new Map(u.map((S)=>[S.pid,S.ppid])),y=new Map(p.map((S)=>[S.pid,S])),v=new Set;for(let S=d;S&&S>1&&!v.has(S);S=w.get(S)){v.add(S);let x=y.get(S);if(x)return x}return}var ng=(d)=>d.split(/[\\/]/).pop()??d,cx=(d,u)=>ng(d).replace(/\.(exe|app)$/i,"").toLowerCase()===ng(u).replace(/\.(exe|app)$/i,"").toLowerCase();function US(d,u,p){let w=d.process;if(!w)return;if(w.pid){let x=NS(w.pid,u,p);if(x)return x}let y=w.path??w.name;if(!y)return;let v=u.filter((x)=>cx(x.name,y)||!!x.path&&!!w.path&&x.path.toLowerCase()===w.path.toLowerCase()),S=new Set(v.flatMap((x)=>NS(x.pid,u,p)??[]).filter((x)=>!!x));return S.size===1?[...S][0]:void 0}function ig(d,u){if(u.role==="main")return!0;if(!d.sessionId)return!0;if(u.role==="lead")return!!u.projectId&&d.projectId===u.projectId;return d.sessionId===u.sessionId||!!u.taskId&&d.projectId===u.projectId&&d.taskId===u.taskId}var DS=["uac"],ux=["sudo","polkit"];function FS(d,u,p,w){if(!ig(d,u))return{act:"refuse",why:`${d.id} isn't yours: another task's work raised it`,notYours:!0};if(p==="deny")return{act:"deny"};if(ux.includes(d.kind))return{act:"refuse",why:`${Rd[d.kind]}: it waits for a password, which no agent types. Deny it (system_permission deny), then do it without ${d.kind==="sudo"?"sudo":"pkexec"}, or ask the user (task_ask) to run it themselves. On a Superfactory VM sudo and polkit never ask.`};if(w&&DS.includes(d.kind))return{act:"refuse",why:"UAC asks on the secure desktop, which no program clicks. Deny it, then run the step from your own shell: on a Superfactory Windows machine the agent runs elevated, so what it starts never asks."};if(w)return{act:"approve"};let y=d.projectId??u.projectId,v=d.taskId??u.taskId;if(!y||!v)return{act:"refuse",why:"This is someone's own computer: only they approve it. No task to ask on: ask them with chat_ask, or deny it."};return{act:"ask",projectId:y,taskId:v,inPerson:DS.includes(d.kind)}}function Td(d){let u=d.process?.name??d.process?.path,p=Rd[d.kind];if(!u||d.kind==="sudo"||d.kind==="polkit")return p;return`${p} for \u201C${ng(u)}\u201D`}var Rd={screen_recording:"Screen Recording",accessibility:"Accessibility",automation:"Automation (Apple Events)",files:"Files and Folders",camera:"Camera",microphone:"Microphone",firewall:"Incoming connections (firewall)",uac:"Administrator rights (UAC)",smartscreen:"Running an unrecognised app (SmartScreen)",sudo:"sudo's password",polkit:"polkit authentication",privacy:"Privacy",dialog:"A system dialog"};var HS=l`Add-Type -AssemblyName System.Windows.Forms, System.Drawing, System.Runtime.WindowsRuntime
|
|
403
|
+
Add-Type -Namespace SfUi -Name Screen -MemberDefinition @'
|
|
404
|
+
[StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; }
|
|
405
|
+
[StructLayout(LayoutKind.Sequential)] public struct RECT { public int L, T, R, B; }
|
|
406
|
+
[DllImport("user32.dll")] static extern System.IntPtr WindowFromPoint(POINT p);
|
|
407
|
+
[DllImport("user32.dll")] static extern System.IntPtr GetAncestor(System.IntPtr h, uint f);
|
|
408
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetClassName(System.IntPtr h, System.Text.StringBuilder s, int n);
|
|
409
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetWindowText(System.IntPtr h, System.Text.StringBuilder s, int n);
|
|
410
|
+
[DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(System.IntPtr h, out uint p);
|
|
411
|
+
[DllImport("user32.dll")] public static extern bool GetWindowRect(System.IntPtr h, out RECT r);
|
|
412
|
+
[DllImport("user32.dll")] public static extern bool IsWindow(System.IntPtr h);
|
|
413
|
+
[DllImport("user32.dll")] public static extern bool IsWindowVisible(System.IntPtr h);
|
|
414
|
+
[DllImport("user32.dll")] public static extern bool PostMessage(System.IntPtr h, uint m, System.IntPtr w, System.IntPtr l);
|
|
415
|
+
[DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);
|
|
416
|
+
[DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT p);
|
|
417
|
+
[DllImport("user32.dll")] public static extern void mouse_event(uint f, uint x, uint y, uint d, System.UIntPtr e);
|
|
418
|
+
public static string ClassOf(System.IntPtr h) { var s = new System.Text.StringBuilder(256); GetClassName(h, s, 256); return s.ToString(); }
|
|
419
|
+
public static string TitleOf(System.IntPtr h) { var s = new System.Text.StringBuilder(256); GetWindowText(h, s, 256); return s.ToString(); }
|
|
420
|
+
public static int PidOf(System.IntPtr h) { uint p; GetWindowThreadProcessId(h, out p); return (int)p; }
|
|
421
|
+
public static long RootAt(int x, int y) { var p = new POINT(); p.X = x; p.Y = y; return (long)GetAncestor(WindowFromPoint(p), 2); }
|
|
422
|
+
public static long[] Find(string cls, int left, int top, int width, int height) {
|
|
423
|
+
var found = new System.Collections.Generic.List<long>();
|
|
424
|
+
for (int y = top + 8; y < top + height; y += 16) for (int x = left + 8; x < left + width; x += 16) {
|
|
425
|
+
var p = new POINT(); p.X = x; p.Y = y;
|
|
426
|
+
var h = GetAncestor(WindowFromPoint(p), 2);
|
|
427
|
+
if (h != System.IntPtr.Zero && !found.Contains((long)h) && ClassOf(h) == cls) found.Add((long)h);
|
|
428
|
+
}
|
|
429
|
+
return found.ToArray();
|
|
430
|
+
}
|
|
431
|
+
'@
|
|
432
|
+
$null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime]
|
|
433
|
+
$null = [Windows.Graphics.Imaging.BitmapDecoder, Windows.Foundation, ContentType = WindowsRuntime]
|
|
434
|
+
$null = [Windows.Storage.StorageFile, Windows.Storage, ContentType = WindowsRuntime]
|
|
435
|
+
$asTask = [System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation\`1' } | Select-Object -First 1
|
|
436
|
+
function Await($op, [Type]$type) { $task = $asTask.MakeGenericMethod($type).Invoke($null, @($op)); $task.Wait(-1) | Out-Null; $task.Result }
|
|
437
|
+
# Windows' own: a program under the system folder (another program may name its window's class the same).
|
|
438
|
+
function SystemOwned([int]$owner) { $path = [string](Get-Process -Id $owner -ErrorAction SilentlyContinue).Path; $path -and $path.StartsWith($env:SystemRoot + '\\', [StringComparison]::OrdinalIgnoreCase) }
|
|
439
|
+
function Rect($h) { $r = New-Object SfUi.Screen+RECT; [SfUi.Screen]::GetWindowRect([IntPtr]$h, [ref]$r) | Out-Null; $r }
|
|
440
|
+
function Ocr($r) {
|
|
441
|
+
$width = $r.R - $r.L; $height = $r.B - $r.T
|
|
442
|
+
if ($width -le 0 -or $height -le 0) { return @() }
|
|
443
|
+
$engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages()
|
|
444
|
+
if (-not $engine) { return @() }
|
|
445
|
+
$bmp = New-Object Drawing.Bitmap $width, $height
|
|
446
|
+
$g = [Drawing.Graphics]::FromImage($bmp); $g.CopyFromScreen($r.L, $r.T, 0, 0, $bmp.Size); $g.Dispose()
|
|
447
|
+
$file = [IO.Path]::Combine([IO.Path]::GetTempPath(), 'sf-ocr-' + [guid]::NewGuid().ToString('N') + '.png')
|
|
448
|
+
$bmp.Save($file, [Drawing.Imaging.ImageFormat]::Png); $bmp.Dispose()
|
|
449
|
+
try {
|
|
450
|
+
$f = Await ([Windows.Storage.StorageFile]::GetFileFromPathAsync($file)) ([Windows.Storage.StorageFile])
|
|
451
|
+
$stream = Await ($f.OpenAsync([Windows.Storage.FileAccessMode]::Read)) ([Windows.Storage.Streams.IRandomAccessStream])
|
|
452
|
+
$decoder = Await ([Windows.Graphics.Imaging.BitmapDecoder]::CreateAsync($stream)) ([Windows.Graphics.Imaging.BitmapDecoder])
|
|
453
|
+
$image = Await ($decoder.GetSoftwareBitmapAsync()) ([Windows.Graphics.Imaging.SoftwareBitmap])
|
|
454
|
+
$read = Await ($engine.RecognizeAsync($image)) ([Windows.Media.Ocr.OcrResult])
|
|
455
|
+
$stream.Dispose()
|
|
456
|
+
foreach ($line in @($read.Lines)) {
|
|
457
|
+
$boxes = @(@($line.Words) | ForEach-Object { $_.BoundingRect })
|
|
458
|
+
$x = ($boxes | Measure-Object X -Minimum).Minimum; $y = ($boxes | Measure-Object Y -Minimum).Minimum
|
|
459
|
+
$right = ($boxes | ForEach-Object { $_.X + $_.Width } | Measure-Object -Maximum).Maximum
|
|
460
|
+
$bottom = ($boxes | ForEach-Object { $_.Y + $_.Height } | Measure-Object -Maximum).Maximum
|
|
461
|
+
[ordered]@{ text = [string]$line.Text; x = [int]($r.L + $x); y = [int]($r.T + $y); w = [int]($right - $x); h = [int]($bottom - $y) }
|
|
462
|
+
}
|
|
463
|
+
} finally { Remove-Item -LiteralPath $file -Force -ErrorAction SilentlyContinue }
|
|
464
|
+
}`,lx=l`$ErrorActionPreference = 'SilentlyContinue'
|
|
465
|
+
Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes
|
|
466
|
+
$A = [Windows.Automation.AutomationElement]; $T = [Windows.Automation.TreeScope]; $C = [Windows.Automation.ControlType]
|
|
467
|
+
function Names($w, $type) { @($w.FindAll($T::Descendants, (New-Object Windows.Automation.PropertyCondition($A::ControlTypeProperty, $type))) | ForEach-Object { $_.Current.Name } | Where-Object { $_ }) }
|
|
468
|
+
$dialogs = @()
|
|
469
|
+
foreach ($w in $A::RootElement.FindAll($T::Children, [Windows.Automation.Condition]::TrueCondition)) {
|
|
470
|
+
$title = $w.Current.Name
|
|
471
|
+
if ($title -match 'Windows Security Alert|Windows protected your PC|SmartScreen') {
|
|
472
|
+
$dialogs += [ordered]@{ title = $title; pid = $w.Current.ProcessId; texts = @(@(Names $w $C::Text) + @(Names $w $C::Pane) | Select-Object -Unique); buttons = @(Names $w $C::Button) + @(Names $w $C::Hyperlink) }
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
$procs = @(Get-CimInstance Win32_Process | ForEach-Object { [ordered]@{ pid = [int]$_.ProcessId; ppid = [int]$_.ParentProcessId; name = [string]$_.Name; path = [string]$_.ExecutablePath } })
|
|
476
|
+
# Windows 11 25H2's dialogs (T-551): hidden from UI Automation, read from the screen.
|
|
477
|
+
${HS}
|
|
478
|
+
$shown = @()
|
|
479
|
+
$v = [Windows.Forms.SystemInformation]::VirtualScreen
|
|
480
|
+
foreach ($h in @([SfUi.Screen]::Find('Shell_SystemDialog', $v.X, $v.Y, $v.Width, $v.Height))) {
|
|
481
|
+
$owner = [SfUi.Screen]::PidOf([IntPtr]$h); $proc = Get-Process -Id $owner -ErrorAction SilentlyContinue
|
|
482
|
+
if (-not (SystemOwned $owner)) { continue }
|
|
483
|
+
$shown += [ordered]@{ window = [int64]$h; pid = $owner; owner = [string]$proc.ProcessName; title = [SfUi.Screen]::TitleOf([IntPtr]$h); started = $proc.StartTime; lines = @(Ocr (Rect $h)) }
|
|
484
|
+
}
|
|
485
|
+
if ($shown.Count) {
|
|
486
|
+
# A firewall alert's program: one listening that Windows has just blocked ("TCP Query User{guid}path").
|
|
487
|
+
$blocked = @{}
|
|
488
|
+
foreach ($r in @(Get-NetFirewallRule -Direction Inbound -Action Block | Where-Object { $_.Name -like '*Query User{*}*' })) {
|
|
489
|
+
$blocked[$r.Name.Substring($r.Name.IndexOf('}') + 1).ToLower()] = [string]$r.Profile
|
|
490
|
+
}
|
|
491
|
+
$local = @('127.0.0.1', '::1')
|
|
492
|
+
$listening = @(@(Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | ForEach-Object { [ordered]@{ pid = [int]$_.OwningProcess; port = 'TCP ' + $_.LocalPort; local = [string]$_.LocalAddress; since = $_.CreationTime } }) + @(Get-NetUDPEndpoint -ErrorAction SilentlyContinue | ForEach-Object { [ordered]@{ pid = [int]$_.OwningProcess; port = 'UDP ' + $_.LocalPort; local = [string]$_.LocalAddress; since = $_.CreationTime } }))
|
|
493
|
+
$paths = @{}; foreach ($p in $procs) { if ($p.path) { $paths[$p.pid] = $p.path } }
|
|
494
|
+
$programs = @($listening | Where-Object { $local -notcontains $_.local -and $paths[$_.pid] -and $blocked.ContainsKey($paths[$_.pid].ToLower()) } | Sort-Object { $_.since } | Group-Object { $_.pid } | ForEach-Object { $f = $_.Group[0]; [ordered]@{ pid = $f.pid; path = $paths[$f.pid]; port = $f.port; profile = $blocked[$paths[$f.pid].ToLower()]; since = $f.since } })
|
|
495
|
+
# Each alert is a process of its own, started as its program began to listen: the closest pairs first,
|
|
496
|
+
# within a minute (a program denied before, still listening, never takes the next one's dialog).
|
|
497
|
+
$pairs = @(foreach ($w in $shown) { foreach ($p in $programs) { if (-not $w.started) { continue }; $gap = [math]::Abs(($w.started - $p.since).TotalSeconds); if ($gap -le 60) { [pscustomobject]@{ gap = $gap; w = $w; p = $p } } } })
|
|
498
|
+
$usedW = @{}; $usedP = @{}
|
|
499
|
+
foreach ($pair in @($pairs | Sort-Object gap)) {
|
|
500
|
+
if ($usedW.ContainsKey($pair.w.window) -or $usedP.ContainsKey($pair.p.pid)) { continue }
|
|
501
|
+
$usedW[$pair.w.window] = $true; $usedP[$pair.p.pid] = $true
|
|
502
|
+
$pair.w.program = [ordered]@{ pid = $pair.p.pid; path = $pair.p.path; port = $pair.p.port; profile = $pair.p.profile }
|
|
503
|
+
}
|
|
504
|
+
foreach ($w in $shown) { $w.Remove('started') }
|
|
505
|
+
}
|
|
506
|
+
ConvertTo-Json -InputObject ([ordered]@{ dialogs = @($dialogs); shown = @($shown); procs = $procs }) -Depth 5 -Compress`,GS=l`$ErrorActionPreference = 'Stop'
|
|
507
|
+
$want = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
508
|
+
if ([int64]$want.window) {
|
|
509
|
+
# A dialog read from the screen (T-551): clicked where OCR finds the button; WM_CLOSE to it is its Cancel.
|
|
510
|
+
${HS}
|
|
511
|
+
$h = [IntPtr][int64]$want.window
|
|
512
|
+
function Shown { [SfUi.Screen]::IsWindow($h) -and [SfUi.Screen]::IsWindowVisible($h) -and [SfUi.Screen]::ClassOf($h) -eq 'Shell_SystemDialog' -and [SfUi.Screen]::PidOf($h) -eq [int]$want.pid -and (SystemOwned $want.pid) }
|
|
513
|
+
function Plain($s) { ([string]$s -replace '[\u2018\u2019]', "'").Trim().ToLower() }
|
|
514
|
+
if (-not (Shown)) { throw 'the dialog is gone' }
|
|
515
|
+
$lines = @(Ocr (Rect $h))
|
|
516
|
+
$button = $null
|
|
517
|
+
foreach ($name in $want.buttons) { $button = $lines | Where-Object { (Plain $_.text) -eq (Plain $name) } | Select-Object -First 1; if ($button) { break } }
|
|
518
|
+
if ($button) {
|
|
519
|
+
$was = New-Object SfUi.Screen+POINT; [SfUi.Screen]::GetCursorPos([ref]$was) | Out-Null
|
|
520
|
+
$x = [int]($button.x + $button.w / 2); $y = [int]($button.y + $button.h / 2)
|
|
521
|
+
[SfUi.Screen]::SetCursorPos($x, $y) | Out-Null
|
|
522
|
+
Start-Sleep -Milliseconds 100
|
|
523
|
+
# Only on the dialog itself: nothing else may have come over its button meanwhile.
|
|
524
|
+
if ([SfUi.Screen]::RootAt($x, $y) -eq [int64]$h) { [SfUi.Screen]::mouse_event(2, 0, 0, 0, [UIntPtr]::Zero); Start-Sleep -Milliseconds 60; [SfUi.Screen]::mouse_event(4, 0, 0, 0, [UIntPtr]::Zero) }
|
|
525
|
+
Start-Sleep -Milliseconds 100
|
|
526
|
+
[SfUi.Screen]::SetCursorPos($was.X, $was.Y) | Out-Null
|
|
527
|
+
for ($i = 0; $i -lt 40 -and (Shown); $i++) { Start-Sleep -Milliseconds 250 }
|
|
528
|
+
if (-not (Shown)) { 'clicked:' + $button.text; return }
|
|
529
|
+
}
|
|
530
|
+
if (-not $want.close) { throw ('none of ' + ($want.buttons -join ', ') + ' could be clicked (it shows: ' + (@($lines | ForEach-Object { $_.text }) -join ' | ') + ')') }
|
|
531
|
+
[SfUi.Screen]::PostMessage($h, 0x10, [IntPtr]::Zero, [IntPtr]::Zero) | Out-Null
|
|
532
|
+
for ($i = 0; $i -lt 20 -and (Shown); $i++) { Start-Sleep -Milliseconds 250 }
|
|
533
|
+
if (Shown) { throw 'it did not close' }
|
|
534
|
+
'closed'; return
|
|
535
|
+
}
|
|
536
|
+
Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes
|
|
537
|
+
$A = [Windows.Automation.AutomationElement]; $T = [Windows.Automation.TreeScope]
|
|
538
|
+
function Dialog { @($A::RootElement.FindAll($T::Children, (New-Object Windows.Automation.PropertyCondition($A::ProcessIdProperty, [int]$want.pid))) | Where-Object { $_.Current.Name -eq $want.title })[0] }
|
|
539
|
+
$w = Dialog
|
|
540
|
+
if (-not $w) { throw 'the dialog is gone' }
|
|
541
|
+
$clicked = 0
|
|
542
|
+
foreach ($name in $want.buttons) {
|
|
543
|
+
$b = $w.FindFirst($T::Descendants, (New-Object Windows.Automation.PropertyCondition($A::NameProperty, [string]$name)))
|
|
544
|
+
$p = $null
|
|
545
|
+
if (-not $b -or -not $b.TryGetCurrentPattern([Windows.Automation.InvokePattern]::Pattern, [ref]$p)) { continue }
|
|
546
|
+
$p.Invoke(); $clicked++
|
|
547
|
+
Start-Sleep -Milliseconds 500
|
|
548
|
+
}
|
|
549
|
+
if ($clicked) { 'clicked'; return }
|
|
550
|
+
if (-not $want.close) { throw ('none of its buttons can be clicked (' + ($want.buttons -join ', ') + ')') }
|
|
551
|
+
Add-Type -Namespace SfUi -Name Win -MemberDefinition '[DllImport("user32.dll")] public static extern bool PostMessage(System.IntPtr h, uint m, System.IntPtr w, System.IntPtr l);'
|
|
552
|
+
[SfUi.Win]::PostMessage([IntPtr]$w.Current.NativeWindowHandle, 0x10, [IntPtr]::Zero, [IntPtr]::Zero) | Out-Null
|
|
553
|
+
for ($i = 0; $i -lt 20 -and (Dialog); $i++) { Start-Sleep -Milliseconds 250 }
|
|
554
|
+
if (Dialog) { throw 'its buttons can not be clicked, and it did not close' }
|
|
555
|
+
'closed'`,px=l`$ErrorActionPreference = 'Stop'
|
|
556
|
+
$want = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
557
|
+
$p = Get-Process -Id ([int]$want.pid)
|
|
558
|
+
if ($p.ProcessName -ne 'consent') { 'gone'; return }
|
|
559
|
+
Stop-Process -Id $p.Id -Force
|
|
560
|
+
'ended'`,qS=l`$ErrorActionPreference = 'Stop'
|
|
561
|
+
$want = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
562
|
+
if (-not (Test-Path -LiteralPath $want.path)) { throw 'no such program' }
|
|
563
|
+
New-NetFirewallRule -DisplayName ('Superfactory: ' + [IO.Path]::GetFileName($want.path)) -Direction Inbound -Action Allow -Program $want.path -Profile Any | Out-Null
|
|
564
|
+
'allowed'`,hx=l`$ErrorActionPreference = 'Stop'
|
|
565
|
+
$want = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
566
|
+
Start-Sleep -Milliseconds 1000
|
|
567
|
+
$rules = @(Get-NetFirewallApplicationFilter -Program $want.path -ErrorAction SilentlyContinue | Get-NetFirewallRule | Where-Object { $_.Direction -eq 'Inbound' -and $_.Action -eq 'Block' })
|
|
568
|
+
if ($rules.Count) { $rules | Remove-NetFirewallRule }
|
|
569
|
+
[string]$rules.Count`,mx=t({dialogs:o(t({title:e(),pid:b(),texts:o(e()).default([]),buttons:o(e()).default([])})).default([]),shown:o(t({window:b(),pid:b(),owner:e().default(""),title:e().default(""),lines:o(t({text:e(),x:b(),y:b(),w:b(),h:b()})).default([]),program:t({pid:b(),path:e(),port:e(),profile:e()}).optional()})).default([]),procs:o(t({pid:b(),ppid:b(),name:e(),path:e().nullish()})).default([])});function fx(d){for(let[u,p]of d.entries()){let w=/^Path:\s*(.+)$/i.exec(p.trim());if(w?.[1])return w[1].trim();if(/^Path:?$/i.test(p.trim())&&d[u+1])return d[u+1]?.trim()}return d.find((u)=>/^[A-Za-z]:\\.+\.exe$/i.test(u.trim()))?.trim()}var ko=(d)=>d.replace(/[\u2018\u2019]/g,"'").trim().toLowerCase(),og={approve:["Allow","Yes","OK","Continue","Allow access","Run anyway"],deny:["Cancel","Don't allow","Deny","No","Block","Not now","Close"]},BS=new Set([...og.approve,...og.deny].map(ko));function gx(d){if(/firewall|networks to access/i.test(d))return"firewall";if(/camera/i.test(d))return"camera";if(/microphone/i.test(d))return"microphone";if(/location|contacts|calendar|notifications|access (to )?your/i.test(d))return"privacy";return"dialog"}function wx(d){let{dialogs:u,shown:p,procs:w}=mx.parse(d),y=[];for(let v of p){let S=v.lines.map((V)=>V.text.trim()).filter(Boolean),x=S.filter((V)=>BS.has(ko(V))),j=S.filter((V)=>!BS.has(ko(V))&&ko(V)!==ko(v.title)),L=gx([v.title,...j].join(" ")),N=L==="firewall"?v.program:void 0,B=j.length?j.join(" "):`its words can't be read (a ${v.owner||"system"} dialog with nothing OCR could read)`,G=N?` The program: ${N.path} (pid ${N.pid}, listening on ${N.port}), the one Windows has just blocked.`:"";y.push({os:"windows",kind:L,what:`${[v.title,B].filter(Boolean).join(": ")}${x.length?` [${x.join("] [")}]`:""}${G}`.replace(/\s+/g," ").trim().slice(0,800),...N?{process:{pid:N.pid,path:N.path,name:N.path.split("\\").pop()??N.path}}:{},dialog:{owner:v.title||v.owner,pid:v.pid,window:v.window,buttons:x},key:`${L}:${v.pid}:${v.window}:${N?.path??""}`})}for(let v of u){let S=/Security Alert/i.test(v.title)?"firewall":"smartscreen",x=S==="firewall"?fx(v.texts):void 0,j=S==="firewall"?v.texts.find((N)=>/^Name:/i.test(N))?.replace(/^Name:\s*/i,"")??void 0:void 0,L=S==="smartscreen"?v.texts.find((N)=>/^App:/i.test(N))?.replace(/^App:\s*/i,""):void 0;y.push({os:"windows",kind:S,what:[v.title,...v.texts].join(" ").replace(/\s+/g," ").trim().slice(0,600),...x||j||L?{process:{...x?{path:x}:{},...j??L?{name:j??L}:{}}}:{},dialog:{owner:v.title,pid:v.pid,window:0,buttons:v.buttons},key:`${S}:${v.pid}:${x??L??""}`})}for(let v of w.filter((S)=>S.name.toLowerCase()==="consent.exe"))y.push({os:"windows",kind:"uac",what:"User Account Control asks for administrator rights, on the secure desktop",process:{pid:v.pid,name:"consent.exe"},key:`uac:${v.pid}`});return{prompts:y,procs:w.map((v)=>({pid:v.pid,ppid:v.ppid,name:v.name,...v.path?{path:v.path}:{}}))}}var On=(d)=>r(Wd).flag("-NoProfile").flag("-NonInteractive").script("-Command",d).timeoutMs(30000).by("system.permissions").build();async function VS(){let d=await g(On(lx));if(d.exitCode!==0)return{prompts:[],procs:[],blind:d.stderr.trim().slice(0,300)};return wx(JSON.parse(d.stdout.trim()||"{}"))}var WS={firewall:{approve:["Allow access","Allow"],deny:["Cancel"]},smartscreen:{approve:["More info","Run anyway"],deny:["Don't run","Don\u2019t run"]}};async function YS(d,u){if(d.kind==="uac"){if(u==="approve")throw Error("UAC asks on the secure desktop, which no program clicks");let L=await g(On(px),{input:JSON.stringify({pid:d.process?.pid})});if(L.exitCode!==0)throw Error("UAC's prompt can't be ended from here (the agent isn't elevated): only someone at the computer can deny it");return L.stdout.includes("gone")?"It had ended already.":"Declined: UAC's prompt is gone, and what asked for elevation was refused."}let p=d.kind==="firewall"?"firewall":"smartscreen",w=d.dialog;if(!w)throw Error("it is no dialog to click");if(w.window)return yx(d,w.pid??0,w.window,u);let y=[],v=!1;if(p==="firewall"&&u==="approve"&&d.process?.path){if(v=(await g(On(qS),{input:JSON.stringify({path:d.process.path})})).exitCode===0,v)y.push(`Allowed ${d.process.path} incoming connections (a firewall rule).`)}let S=WS[p][u],x=u==="deny"||v,j=await T(On(GS),{input:JSON.stringify({pid:w.pid,title:w.owner,buttons:S,close:x})});if(y.push(!j.includes("closed")?`Clicked \u201C${S.join("\u201D, then \u201C")}\u201D.`:u==="deny"?`Closed the dialog, which is its \u201C${WS[p].deny[0]}\u201D (its buttons can't be clicked from here).`:"Closed the dialog: the rule allows it already (its buttons can't be clicked from here)."),v&&d.process?.path){let L=await KS(d.process.path);if(L)y.push(L)}return y.join(" ")}async function KS(d){let u=await g(On(hx),{input:JSON.stringify({path:d})});if(u.exitCode!==0)return`Windows' own block rules for it couldn't be removed: ${u.stderr.trim().slice(0,200)}`;let p=Number(u.stdout.trim())||0;return p?`Removed the ${p} block rule${p===1?"":"s"} Windows had added for it.`:void 0}async function yx(d,u,p,w){let y=(G,V)=>g(On(GS),{input:JSON.stringify({pid:u,window:p,buttons:G,close:V})}),v=await y(og[w],w==="deny");if(v.exitCode===0){let G=/clicked:(.+)$/m.exec(v.stdout)?.[1]?.trim();if(G)return`Clicked \u201C${G}\u201D.`;return"Closed the dialog, which is its \u201CCancel\u201D (none of its buttons could be clicked)."}let S=v.stderr.trim().split(`
|
|
570
|
+
`)[0]?.slice(0,300)||"it could not be clicked",x=d.kind==="firewall"?d.process?.path:void 0;if(w!=="approve"||!x||/the dialog is gone/.test(S))throw Error(S);if((await g(On(qS),{input:JSON.stringify({path:x})})).exitCode!==0)throw Error(`${S}; nor could a firewall rule allow ${x}`);let L=[`Its \u201CAllow\u201D couldn't be clicked (${S}): allowed ${x} incoming connections (a firewall rule).`],N=await y([],!0);L.push(N.exitCode===0?"Closed the dialog: the rule allows it already.":"The dialog stays open.");let B=await KS(x);if(B)L.push(B);return L.join(" ")}var ag="sp-approve",QS="sp-done",cg="sp-deny",kx={linux:3000,darwin:5000,win32:15000},bx=60000;function vx(d=process.platform){if(d==="linux")return async()=>{let u=await jS();return{prompts:xS(u),procs:u}};if(d==="darwin")return CS;if(d==="win32")return VS;return}function Sx(d,u,p){if(d.os==="linux"){if(u==="approve")throw Error("no agent types a password");return LS(d,p)}if(d.os==="macos")return _S(d,u);return YS(d,u)}function Px(d){let{machine:u,prompt:p,inPerson:w}=d,y=[`**${u}** shows a system prompt: ${p.what}`,d.why?`Why the agent wants it: ${d.why}`:"",w?"It asks on the secure desktop, which only someone at the computer can answer: approve it there, or deny it here.":"**Approve** clicks it on that computer. It is your computer: the agent can't approve it by itself."].filter(Boolean);return{kind:"choice",purpose:"system_permission",text:`Approve ${Td(p)} on ${u}?`,details:y.join(`
|
|
571
|
+
|
|
572
|
+
`),choices:w?[{id:QS,label:"Done, I approved it there"},{id:cg,label:"Deny it"}]:[{id:ag,label:"Approve"},{id:cg,label:"Deny"}],multiSelect:!1,askedBy:d.askedBy}}function $x(d,u,p){let w=d.kind==="sudo"||d.kind==="polkit"?"It waits for a password no agent types: deny it (it ends, so the command fails instead of hanging), then do it without, or ask the user to run it.":u?"This machine is set aside for Superfactory: approving it is yours. Approve it if your task needs it, else deny it.":"This is someone's own computer: approving asks them (a question on your task); denying is yours.";return[`A system permission prompt is waiting on this machine (${d.os}): ${Td(d)}, ${d.id}.`,p?"Your work raised it.":"No session's process claims it: it may be your work's (a program you started), or a person's own app.",`It says: ${d.what}`,`${w} Use system_permission with action "approve" or "deny" and id "${d.id}".`].join(`
|
|
573
|
+
`)}class lg{deps;prompts=new Map;pending=new Set;questions=new Map;count=0;timer;looking=!1;blind;blindAt=0;look;actWith;constructor(d){this.deps=d;this.look=d.look??vx(),this.actWith=d.act??Sx}start(d=process.platform){let u=kx[d];if(!this.look||!u||this.timer)return;this.timer=setInterval(()=>void this.tick(),u),this.timer.unref?.()}stop(){if(this.timer)clearInterval(this.timer);this.timer=void 0}async tick(){if(this.looking||!this.look)return;let d=this.deps.sessions();if(!d.length&&!this.prompts.size)return;if(this.blind&&Date.now()-this.blindAt<bx)return;this.looking=!0;try{let u=await this.look();if(u.blind&&u.blind!==this.blind)s.warn(`system-permissions: can't see this system's prompts: ${u.blind}`);this.blind=u.blind,this.blindAt=Date.now(),await this.update(u,d)}catch(u){s.warn("system-permissions: couldn't look for prompts",u)}finally{this.looking=!1}}async update(d,u){let p=new Set(d.prompts.map((v)=>v.key));for(let[v,S]of this.prompts){if(p.has(v))continue;this.prompts.delete(v),s.info(`system-permissions: ${S.id} (${S.kind}) is gone`),await this.closeQuestions(S.id)}let w=[];for(let v of d.prompts){if(this.prompts.has(v.key)||!this.pending.has(v.key))continue;let S=US(v,d.procs,u);if(v.os==="linux"&&!S)continue;let x={...v,id:`SP-${++this.count}`,since:new Date().toISOString(),...S?{sessionId:S.id}:{},...S?.projectId?{projectId:S.projectId}:{},...S?.taskId?{taskId:S.taskId}:{}};this.prompts.set(v.key,x),w.push(x)}if(this.pending=new Set([...p].filter((v)=>!this.prompts.has(v))),!w.length)return;let y=await this.deps.dedicated();for(let v of w){let S=v.sessionId?[v.sessionId]:u.filter((x)=>x.ownAgent).map((x)=>x.id);s.info(`system-permissions: ${v.id} ${v.kind} (${v.process?.name??"?"}), ${v.sessionId?`raised by ${v.sessionId}`:"no session claims it"}; telling ${S.length}`);for(let x of S)await this.deps.send(x,$x(v,y,!!v.sessionId)).catch((j)=>s.warn(`system-permissions: couldn't tell ${x} of ${v.id}`,j))}}act(d,u){return this.actWith(d,u,new Set(this.deps.sessions().map((p)=>p.pid)))}list(d){return[...this.prompts.values()].filter((u)=>ig(u,d))}byId(d){return[...this.prompts.values()].find((u)=>u.id===d)}async decide(d,u,p,w){let y=this.byId(u);if(!y)throw Error(`${u} isn't waiting any more (answered, or what asked ended): system_permission list shows what is`);let v=FS(y,d,p,await this.deps.dedicated());if(v.act==="refuse")throw v.notYours?new P(v.why):Error(v.why);if(v.act==="ask"){let x={projectId:v.projectId,taskId:v.taskId},j=await this.deps.ask(x,Px({machine:this.deps.machineName(),prompt:y,inPerson:v.inPerson,...w?{why:w}:{},askedBy:d.sessionId}));if(!j)return"A question about a system prompt is open on the task already: once it's answered, ask for this one.";return this.questions.set(`${x.projectId}/${x.taskId}/${j.id}`,{promptId:y.id,askedBy:d.sessionId}),s.info(`system-permissions: asked the user to approve ${y.id} on ${x.taskId} (${j.id})`),`This is someone's own computer: asked the user (${this.deps.shownId(x)}, ${j.id}). Their answer reaches you as a message; go on with other work meanwhile.`}let S=await this.act(y,v.act);return this.audited(d.sessionId,y,v.act,S),s.info(`system-permissions: ${d.sessionId} ${p==="approve"?"approved":"denied"} ${y.id} (${y.kind}): ${S}`),`${p==="approve"?"Approved":"Denied"} ${y.id} (${Rd[y.kind]}). ${S}`}async answered(d,u,p){let w=`${d.projectId}/${d.taskId}/${u.id}`,y=this.questions.get(w);if(this.questions.delete(w),!y)return;let v=this.byId(y.promptId),S=u.answer?.choiceIds??[],x;if(!v)x=`${y.promptId} had gone before the answer (answered on the computer, or what asked ended).`;else if(u.status==="dismissed"||S.includes(cg))x=await this.act(v,"deny").then((j)=>(this.audited(y.askedBy,v,"deny",`the user denied it: ${j}`),`The user denied ${v.id}. ${j}`)).catch((j)=>`The user denied ${v.id}, and denying it failed: ${j.message}`);else if(S.includes(QS))x=`The user says they approved ${v.id} at the computer.`;else if(S.includes(ag)&&!p)x=`${v.id} stays: only the computer's owner (the server owner) approves a system prompt there.`;else if(S.includes(ag))x=await this.act(v,"approve").then((j)=>(this.audited(y.askedBy,v,"approve",`the user approved it: ${j}`),`The user approved ${v.id}. ${j}`)).catch((j)=>`The user approved ${v.id}, but approving it failed: ${j.message}`);else x=`The user answered about ${y.promptId} in their own words: ${u.answer?.text??""}`;s.info(`system-permissions: ${u.id} on ${d.taskId}: ${x}`),await this.deps.send(y.askedBy,x).catch((j)=>s.warn("system-permissions: couldn't tell the asker",j))}audited(d,u,p,w){this.deps.audit({sessionId:d,tool:"system_permission",result:p==="approve"?"approved":"denied",...u.projectId&&u.taskId?{target:`${u.projectId}/${u.taskId}`}:{},why:`${u.id} ${Td(u)} on ${this.deps.machineName()}: ${w}`.slice(0,1000)})}async closeQuestions(d){for(let[u,p]of this.questions){if(p.promptId!==d)continue;this.questions.delete(u);let[w,y,v]=u.split("/");await this.deps.cancel({projectId:w,taskId:y},(S)=>S.id===v&&S.status==="open").catch(()=>{return}),await this.deps.send(p.askedBy,`${d} is gone before the user answered (approved or denied at the computer, or what asked ended): its question is closed.`).catch(()=>{return})}}}import{existsSync as jx}from"fs";import{existsSync as Ix,lstatSync as Tx,readdirSync as Rx,realpathSync as Ax}from"fs";import{basename as Ex,join as pg}from"path";function mg(d,u){let p=pg(E(d).root,"worktrees");if(!Ix(p))return[];return Rx(p).filter((w)=>w===u||w.startsWith(`${u}-`))}async function Cx(d,u){let p=await a(d,(v)=>v.sub("worktree list").flag("--porcelain")).catch(()=>""),w=(v)=>{try{return Ax(v)}catch{return v}},y=w(u);return p.split(`
|
|
574
|
+
`).some((v)=>v.startsWith("worktree ")&&w(v.slice(9))===y)}async function _x(d){return(await a(d,(p)=>p.sub("status").flag("--porcelain").env({GIT_OPTIONAL_LOCKS:"0"}))).split(`
|
|
575
|
+
`).filter(Boolean).filter((p)=>{let w=p.slice(3);if(!p.startsWith("?? ")||Ex(w)!=="node_modules")return!0;return!Tx(pg(d,w),{throwIfNoEntry:!1})?.isSymbolicLink()}).length}async function Ox(d,u,p){let w=await os(d,u),y=await a(d,(v)=>{if(v.sub("rev-list").flag("--count").arg("HEAD").flag("--not").flag("--remotes"),p)v.flag("--branches");return v.arg(w)});return Number(y.trim())||0}async function xx(d,{base:u,prMerged:p}){let w=await _x(d);if(w)return{reason:"uncommitted",count:w};if(p)return;let y=(await a(d,(S)=>S.sub("branch").flag("--show-current"))).trim(),v=await Ox(d,u,!y);if(v&&await Wa(d,await os(d,u),"HEAD"))return;return v?{reason:"unpushed",count:v}:void 0}async function JS(d,u,p){let w=[],y=mg(d,u.id);if(!y.length)return w;let v=(await a(d,(S)=>S.sub("remote")).catch(()=>"")).trim().split(`
|
|
576
|
+
`).filter(Boolean).length>0;for(let S of y){let x=pg(E(d).root,"worktrees",S);if(!await Cx(d,x))continue;let j=await We(x,()=>Mx(d,u,p,S,x,v));w.push(j)}return w}async function Mx(d,u,p,w,y,v){let S=w===u.id,x=(await a(y,(G)=>G.sub("branch").flag("--show-current"))).trim()||void 0,j=u.pr?.state==="merged"&&(S||x===u.pr.branch),L=await xx(y,{base:p,prMerged:j});if(L)return{folder:w,removed:!1,kept:{projectId:u.projectId,taskId:u.id,folder:w,path:y,branch:x,canPush:v,...L}};let N=S?await rs(d,u):void 0,B=!!N&&(j||await ef(d,N,p)||!v&&await Wa(d,await os(d,p),N));return await pt(d,async()=>{if(await Fr(d,y),B&&N)await a(d,(G)=>G.sub("branch").flag("--delete").flag("--force").arg(N))}),{folder:w,removed:!0,branchDeleted:B?N:void 0}}var Lx=k("SUPERFACTORY_ENDED_IDLE_MS",900000),zS=(d)=>d.state!=="exited"&&d.state!=="failed",Ad=(d)=>Ne.includes(d.status);class gg{deps;kept=new Map;idleSince=new Map;constructor(d){this.deps=d}sweeping;sweep(){return this.sweeping??=this.sweepAll().finally(()=>{this.sweeping=void 0}),this.sweeping}async sweepAll(){for(let d of this.deps.projects.ids())await this.sweepProject(d).catch((u)=>s.warn(`finished tasks: ${d}`,u))}async sweepProject(d){let u=await this.deps.tasks.list(d),p=new Map(u.filter((x)=>pe(x)).map((x)=>[x.id,x])),w=new Map([...p.keys()].map((x)=>[x,this.deps.removals.mark({projectId:d,taskId:x})])),y=await this.deps.sessions().list(d);await this.stopIdle(d,y.filter((x)=>x.taskId&&p.has(x.taskId)));let v=new Set((await this.deps.sessions().list(d)).filter(zS).map((x)=>x.taskId)),S=[];for(let x of p.values()){if(v.has(x.id))continue;let j={projectId:d,taskId:x.id};if(await this.deps.removals.remove(j,w.get(x.id)??0,()=>this.deps.places.taskEnded(d,x.id)).catch((N)=>(s.warn(`places: ${x.id}'s sandbox`,N),!0))&&Ad(x))S.push(...await this.tidy(x))}this.kept.set(d,S)}async stopIdle(d,u){let p=Date.now();for(let w of u){if(w.state!=="idle"||w.kind!=="task"&&w.kind!=="epic"){this.idleSince.delete(w.id);continue}let y=this.idleSince.get(w.id)?.since??p;if(this.idleSince.set(w.id,{projectId:d,since:y}),p-y<Lx)continue;this.idleSince.delete(w.id),await this.deps.sessions().stop(w.id).then(()=>s.info(`finished tasks: stopped ${w.id}, idle in ${w.taskId}, which ended`)).catch((v)=>s.warn(`finished tasks: stopping ${w.id}`,v))}for(let[w,{projectId:y}]of this.idleSince)if(y===d&&!u.some((v)=>v.id===w))this.idleSince.delete(w)}async tidy(d,{note:u=!1,mark:p}={}){if(At(d))return[];let w={projectId:d.projectId,taskId:d.id};if(!mg(this.deps.projects.path(d.projectId),d.id).length)return[];let y=p??this.deps.removals.mark(w),v=[];await this.deps.removals.remove(w,y,async()=>{if(this.deps.removals.startedSince(w,y)||await this.inUse(w))return;let j=this.deps.projects.path(d.projectId),L=ut(await this.deps.projects.settings(d.projectId));v=await JS(j,d,L)});for(let j of v){if(j.removed){s.info(`worktrees: removed ${XS(d.id,j.folder)}, its work is safe${j.branchDeleted?` (branch ${j.branchDeleted} merged, deleted)`:""}`);continue}let L=this.kept.get(d.projectId)?.find((N)=>N.path===j.kept.path);if(L?.reason!==j.kept.reason||L.count!==j.kept.count)s.info(`worktrees: kept ${XS(d.id,j.folder)}: ${ZS(j.kept)}`);if(u)await this.deps.tasks.appendNote(w,`Kept its worktree (${j.kept.path}): ${ZS(j.kept)}. See Sandboxes to keep or remove it.`)}if(v.some((j)=>j.removed))this.deps.worktreeChanged(w);let S=v.flatMap((j)=>j.removed?[]:[j.kept]),x=(this.kept.get(d.projectId)??[]).filter((j)=>j.taskId!==d.id);return this.kept.set(d.projectId,[...x,...S]),S}list(d){return(d?[this.kept.get(d)??[]]:[...this.kept.values()]).flat().filter((p)=>jx(p.path))}async settle(d,u){let p=this.list(d.projectId).find((v)=>v.taskId===d.taskId&&v.folder===d.folder);if(!p)throw new c("not_found",`${d.folder} isn't a kept worktree of ${d.taskId}`);let w=await this.deps.tasks.get(d);if(!pe(w)||!Ad(w)||await this.inUse(d))throw new c("conflict",`${d.taskId} is in use again: its worktree stays as it is`);if(!await this.deps.removals.remove(d,this.deps.removals.mark(d),()=>We(p.path,()=>this.act(p,u))))throw new c("conflict",`${d.taskId} is in use again: its worktree stays as it is`);return s.info(`worktrees: ${u} on ${p.folder} of ${p.taskId}, as asked`),await this.tidy(w),this.list(d.projectId)}async act(d,u){let p=d.path,w=this.deps.projects.path(d.projectId);if(u==="commit"){await a(p,(v)=>v.sub("add").flag("--all"));let y=await he(p);await a(p,(v)=>v.env(y).sub("commit").flag("--quiet").flag("--no-verify").flag("--message",`${d.taskId}: the uncommitted work left in its worktree`))}else if(u==="discard")await a(p,(y)=>y.sub("reset").flag("--hard").flag("--quiet")),await a(p,(y)=>y.sub("clean").flag("--force").flag("-d").flag("--quiet"));else if(u==="push"){if(!d.branch)throw new c("conflict",`${d.folder} isn't on a branch: nothing to push`);let y=d.branch;if(!Jt(d.taskId,y))throw new c("conflict",`${d.folder} is on ${y}, not ${d.taskId}'s own branch: Superfactory pushes a task's own branch only`);await a(p,(v)=>v.sub("push").flag("--quiet").flag("--no-verify").flag("--set-upstream").arg("origin").arg(y))}else await pt(w,async()=>{if(await Fr(w,p),d.branch&&p===Re(w,d.taskId)){let y=d.branch;await a(w,(v)=>v.sub("branch").flag("--delete").flag("--force").arg(y))}}),this.deps.worktreeChanged(d)}async inUse(d){let u=await this.deps.tasks.get(d).catch(()=>{return});if(u&&!pe(u))return!0;return(await this.deps.sessions().list(d.projectId)).some((w)=>w.taskId===d.taskId&&zS(w))}}var XS=(d,u)=>u===d?`${d}'s worktree`:`${u}, beside ${d}'s worktree`;function ZS({reason:d,count:u}){let p=u===1?"":"s";return d==="uncommitted"?`${u} uncommitted change${p}`:`${u} commit${p} not pushed or merged`}var Nx=150000,Dx=500;class wg{deps;constructor(d){this.deps=d}async onTaskChange({task:d,previous:u},p=Promise.resolve()){if(!pe(d)||pe(u))return;let w={projectId:d.projectId,taskId:d.id},y=this.deps.removals.mark(w);await p;let v=await this.deps.tasks.get(w).catch(()=>{return});if(v&&!pe(v))return s.info(`closed task: ${d.id} is open again, kept`);if(await this.ended(await this.deps.teams.endSessions(d),w,y),await this.inUseAgain(w,y))return s.info(`closed task: ${d.id} is in use again, kept`);if(await this.deps.places.taskEnded(d.projectId,d.id).catch((x)=>s.warn(`places: ${d.id}'s sandbox`,x)),!Ad(d))return;let S=d.kind==="epic"?(await this.deps.tasks.list(d.projectId)).filter((x)=>x.epic===d.id&&pe(x)):[];for(let x of[d,...S])await this.deps.finished.tidy(x,{note:!0,mark:x===d?y:void 0}).catch((j)=>s.warn(`worktrees: ${x.id}'s`,j))}async ended(d,u,p){let w=Date.now()+Nx,y=()=>d.some((v)=>{let S=this.deps.sessions().find(v)?.state;return S!==void 0&&S!=="exited"&&S!=="failed"});while(y()&&!this.deps.removals.startedSince(u,p)&&Date.now()<w)await Bun.sleep(Dx)}async inUseAgain(d,u){if(this.deps.removals.startedSince(d,u))return!0;let p=await this.deps.tasks.get(d).catch(()=>{return});if(p&&!pe(p))return!0;return(await this.deps.sessions().list(d.projectId)).some((y)=>y.taskId===d.taskId&&y.state!=="exited"&&y.state!=="failed")}}import{readdir as Ux}from"fs/promises";var Fx=(d)=>/^\/[\w:.-]+(\s|$)/.test(d),eP=(Hs.maxLength??20000)-100,Bx=new Set(["starting","running","idle","waiting_input","stopping"]);class yg{tasks;sessions;coordinators;talk;holds;commands=new Map;said=new Map;ended=new Map;running=new Set;waiters=new Map;checkedTasks=!1;constructor(d,u,p,w,y){this.tasks=d;this.sessions=u;this.coordinators=p;this.talk=w;this.holds=y}async taskSession(d,u){if(!u)return;let p=await this.tasks.get(d),w=await this.session(u,d.projectId),y=w?.taskId===p.id||!!p.epic&&w?.taskId===p.epic||!!w?.taskId&&!!p.bundle?.tasks.includes(w.taskId);return w?.projectId===d.projectId&&y?u:void 0}async session(d,u){let p=this.sessions();return p.find(d)??(await p.list(u)).find((w)=>w.id===d)}async asker(d,u){let p=await this.taskSession(d,u);if(p||!u)return p;let w=await this.session(u);return w?.kind==="coordinator"&&(w.projectId??d.projectId)===d.projectId?u:void 0}async workingSession(d){let u=await this.tasks.get(d),p=u.epic?await this.tasks.get({projectId:d.projectId,taskId:u.epic}).catch(()=>{return}):u.bundle?Ee(await this.tasks.list(d.projectId),u):void 0,w;for(let y of[u.sessionId,p?.sessionId]){let v=await this.taskSession(d,y);if(!v)continue;if(this.runs(v))return{sessionId:v,running:!0};w??=v}return w?{sessionId:w,running:!1}:void 0}async expect(d,u,p,w){await this.tasks.setReply(d,u.id,{state:"working",to:"task",sessionId:p}),await w({...d,commentId:u.id,to:"task"})}answerOf(d,u,p){return new Promise((w)=>{let y=this.waiters.get(d)??new Set;this.waiters.set(d,y);let v=(L)=>{if(clearTimeout(j),p?.removeEventListener("abort",x),y.delete(S),!y.size)this.waiters.delete(d);w(L)},S=(L)=>v({text:L}),x=()=>v(void 0),j=setTimeout(x,u);j.unref?.(),p?.addEventListener("abort",x,{once:!0}),y.add(S)})}answered(d,u){for(let p of[...this.waiters.get(d)??[]])p(u)}async route(d,u,p=""){let w=await this.taskSession(d,(await this.tasks.get(d)).sessionId);if(w&&Fx(p))return{sessionId:w,to:"task"};let y=this.sessions().replyTarget(await this.coordinators.get(d),d.projectId,u);if(y)return{sessionId:y,to:"coordinator"};return w?{sessionId:w,to:"task"}:void 0}toSession(d){return{sessionId:d,to:this.roleOf(this.sessions().find(d)??{kind:"task"})}}async send(d,u,p,w,y){let v=y?this.toSession(y):await this.route(d,w,u);if(!v)return;let S=await this.message(d,v.to,u,p);if(v.to==="coordinator")this.talk.replyHanded(v.sessionId,d,S);return await this.sessions().send(v.sessionId,S,p,{callerIsOwner:w,byPerson:!0}),v}async deliver(d,u,p,w){let y=w?this.toSession(w):await this.route(d,p,u.body);if(!y)return this.tasks.setReply(d,u.id,{state:"waiting"});return await this.hand(d,u,y.sessionId,y.to,p),this.tasks.setReply(d,u.id,{state:"working",...y})}async answering(d,u,p){let{to:w}=this.toSession(p);if(w==="coordinator")this.talk.tagTurn(p,[d]);let y={...d,commentId:u.id,to:w};return await this.sessions().answering(p,u.body,u.author.handle,y),this.said.set(p,[]),this.tasks.setReply(d,u.id,{state:"working",to:w,sessionId:p})}async sessionStarted(d){if(!d.projectId||!d.taskId||d.kind==="coordinator"||d.teammate)return;let u={projectId:d.projectId,taskId:d.taskId},p=await this.tasks.get(u);if(p.sessionId!==d.id||!this.holds(p))return;for(let w of p.comments.filter((y)=>y.reply?.state==="waiting")){if(w.reply?.sessionId===d.id){let y={...u,commentId:w.id,to:w.reply.to??"task"};await this.sessions().answering(d.id,w.body,w.author.handle,y)}else await this.hand(u,w,d.id,"task");await this.tasks.setReply(u,w.id,{state:"working",to:"task",sessionId:d.id})}}async commented(d,u,p){let w=this.take(d,(y)=>tP(y.reply,u)&&y.state!=="queued");for(let y of w)await this.tasks.setReply(u,y.reply.commentId,{state:"answered",to:y.reply.to,sessionId:d,answer:p.id}),this.answered(y.reply.commentId,p.body)}roleOf(d){return d.kind==="coordinator"?"coordinator":"task"}onEvent(d,u){let p=d.id;if(u.type==="state"){this.stateChanged(d,u.state);return}if(!this.held(p).length&&!this.commands.get(p)?.length)return;switch(u.type){case"init":this.ended.delete(p),this.said.set(p,[]);return;case"tool_use":{if(u.parentToolUseId)return;this.said.set(p,[]);let w=Wx(d,u);if(w)this.clear(p,(y)=>y.state==="read"&&tP(y.reply,w),"it asked a question there").catch((y)=>s.warn(`replies: ${p}'s question didn't close its replies`,y));return}case"assistant_text":if(!u.delta&&!u.parentToolUseId)this.said.set(p,[...this.said.get(p)??[],u]);return;case"command_output":{let[w,...y]=this.commands.get(p)??[];if(!w)return;this.commands.set(p,y),this.post(d,[{id:"",reply:w,state:"read"}],u.text,u.seq).catch((v)=>s.warn(`replies: couldn't answer ${p}'s command`,v));return}case"result":{let w=this.said.get(p)??[],y=w.map((x)=>x.text).join(`
|
|
577
|
+
|
|
578
|
+
`).trim();this.said.set(p,[]);let v=w.at(-1)?.seq??u.seq,S=Symbol(p);this.ended.set(p,S),setTimeout(()=>{if(this.ended.get(p)!==S)return;this.ended.delete(p),(u.outcome==="success"&&y?this.answer(d,y,v):this.clear(p,(j)=>j.state==="read",`its turn ended (${u.outcome}) with no answer`)).catch((j)=>s.warn(`replies: couldn't settle ${p}'s replies`,j))},zn);return}}}stateChanged(d,u){let p=d.id;if(Bx.has(u)){if(this.running.has(p))return;this.running.add(p),this.sessionStarted(d).catch((w)=>s.warn(`replies: couldn't hand ${p} its replies`,w));return}this.running.delete(p),this.dropLater(p)}async afterRestart(d){let u=await Ux(m().outboxes).catch(()=>[]);for(let p of u.filter((w)=>w.endsWith(".json"))){let w=p.replace(/\.json$/,"");if(this.runs(w))continue;await this.dropped(w,await q.open(w)).catch((y)=>s.warn(`replies: ${w}'s replies not settled`,y))}if(this.checkedTasks)return;this.checkedTasks=!0;for(let p of d)for(let w of await this.tasks.list(p).catch(()=>[]))for(let y of w.comments)await this.settle({projectId:p,taskId:w.id},w,y).catch((v)=>s.warn(`replies: ${y.id} on ${w.id}`,v))}async settle(d,u,p){let w=p.reply?.sessionId;if(p.reply?.state!=="working"||!w||!this.holds(u))return;if(!this.sessions().ranHere(w))return;if((this.sessions().outboxOf(w)??await q.open(w)).replies().some((S)=>S.reply?.commentId===p.id))return;let v=`${p.id} on ${u.id} was working, with no session holding it`;if(Hx(u,p.at)){await this.tasks.setReply(d,p.id,{...p.reply,state:"answered"}),s.info(`replies: ${v}: answered (the agent wrote after it)`);return}if(this.runs(w)){let S={...d,commentId:p.id,to:p.reply.to??"task"};await this.sessions().answering(w,p.body,p.author.handle,S),s.info(`replies: ${v}: its session ${w}, which goes on, has it again`);return}await this.tasks.setReply(d,p.id,{state:"waiting"}),s.info(`replies: ${v}: waiting again`)}held(d){return(this.sessions().outboxOf(d)?.replies()??[]).flatMap((u)=>u.reply?[{id:u.id,reply:u.reply,state:u.state}]:[])}dropLater(d){setTimeout(()=>{if(this.runs(d)||this.sessions().stopping)return;let u=this.sessions().outboxOf(d);this.dropped(d,u).catch((p)=>s.warn(`replies: ${d}'s replies not dropped`,p))},zn*5)}runs(d){let u=this.sessions().find(d)?.state;return!!u&&u!=="exited"&&u!=="failed"}async clear(d,u,p){for(let w of this.take(d,u)){let{reply:y}=w;await this.tasks.setReply(y,y.commentId,{state:"answered",to:y.to,sessionId:d}),s.info(`replies: ${y.commentId} on ${y.taskId} answered: ${p}`),this.answered(y.commentId)}}async hand(d,u,p,w,y=!1){let v=await this.message(d,w,u.body,u.author.handle);if(w==="coordinator")this.talk.replyHanded(p,d,v);let S={...d,commentId:u.id,to:w},x=u.author.handle;if(w==="task"&&Zf(v,y))return this.commands.set(p,[...this.commands.get(p)??[],S]),this.sessions().send(p,v,x,{callerIsOwner:y});await this.sessions().send(p,v,x,{callerIsOwner:y,reply:S})}async message(d,u,p,w){if(u==="task")return p;let y=await this.tasks.get(d);return`About task ${y.id} (${y.title}) in ${y.projectId}: ${p}
|
|
579
|
+
|
|
580
|
+
(${w} wrote this on ${y.id}. Your reply to it is posted in ${y.id}'s conversation for them; write it for them.)`}answer(d,u,p){return this.post(d,this.take(d.id,(w)=>w.state==="read"),u,p)}async post(d,u,p,w){for(let{reply:S}of u.filter((x)=>x.reply.to==="coordinator"))await this.tasks.setReply(S,S.commentId,{state:"answered",to:S.to,sessionId:d.id,message:lr(d.id,w)});let y=p.length>eP?`${p.slice(0,eP)}\u2026`:p,v=new Map;for(let{reply:S}of u.filter((x)=>x.reply.to==="task"))v.set(Ed(S),[...v.get(Ed(S))??[],S]);for(let S of v.values()){let[x]=S;if(!x)continue;let j=await this.tasks.addComment(x,{kind:"claude",handle:"claude",sessionId:d.id,role:x.to},y);for(let L of S)await this.tasks.setReply(L,L.commentId,{state:"answered",to:L.to,sessionId:d.id,answer:j.id}),this.answered(L.commentId,y)}}async dropped(d,u){this.said.delete(d),this.ended.delete(d);let p=u?.replies()??[],w=this.commands.get(d)??[];this.commands.delete(d),u?.remove(p.map((v)=>v.id));let y=[...p.flatMap((v)=>v.reply?[{reply:v.reply,read:v.state==="read"}]:[]),...w.map((v)=>({reply:v,read:!1}))];for(let{reply:v,read:S}of y)await this.tasks.setReply(v,v.commentId,{state:"waiting",...S?{to:v.to,sessionId:d}:{}}).catch((x)=>s.warn(`replies: ${v.commentId} on ${v.taskId}`,x))}take(d,u){let p=this.held(d).filter(u);if(this.sessions().outboxOf(d)?.remove(p.map((w)=>w.id)),!this.held(d).length)this.said.delete(d);return p}}var Ed=(d)=>`${d.projectId}/${d.taskId}`;function Wx(d,u){if(!/__task_ask$/.test(u.name))return;let p=u.input??{},w=p.projectId??d.projectId,y=p.taskId??d.taskId;return w&&y?{projectId:w,taskId:y}:void 0}function Hx(d,u){return d.comments.some((p)=>p.author.kind==="claude"&&p.at>u)||d.questions.some((p)=>!!p.askedBy&&!p.purpose&&p.askedAt>u)}var tP=(d,u)=>Ed(d)===Ed(u);function sP(d,u){if(d.node)return d.node===u.nodeId||u.sandboxNodes.has(d.node);return u.ownProjects.includes(d.projectId)}var Gx=new Set(["id","createdAt","updatedAt","extra","questions","comments","reviewComments","mergeApproval"]),qx={questions:"Q-",comments:"C-",reviewComments:"RC-"},Vx=new Set(["description","notes"]),Ts=(d,u)=>JSON.stringify(d)===JSON.stringify(u),nP=(...d)=>[...new Set(d.flatMap((u)=>Object.keys(u)))];function iP(d,u,p){let w={},y=structuredClone(u),v=(N,B,G,V,Y,ne)=>{if(Ts(ne,V)||Ts(ne,Y))return;let ie=Vx.has(B)&&typeof V==="string"&&typeof Y==="string"&&typeof ne==="string"?Yx(V,Y,ne):void 0;if(Ts(Y,V))N[B]=structuredClone(ne);else if(ie!==void 0)N[B]=ie;else w[G]=ne},[S,x,j]=[d,u,p].map((N)=>N),L=y;for(let N of nP(S,x,j).filter((B)=>!Gx.has(B)))v(L,N,N,S[N],x[N],j[N]);for(let N of nP(d.extra,u.extra,p.extra))v(y.extra,N,`extra.${N}`,d.extra[N],u.extra[N],p.extra[N]);for(let[N,B]of Object.entries(qx)){let{items:G,lostItems:V}=Kx(d[N],u[N],p[N],B);if(L[N]=G,V.length)w[N]=V}for(let N of Object.keys(L))if(L[N]===void 0)delete L[N];return{merged:y,lost:w}}function Yx(d,u,p){let w=d.trimEnd();if(!u.startsWith(w)||!p.startsWith(w))return;return`${u.trimEnd()}
|
|
581
|
+
${p.slice(w.length).replace(/^\s+/,"")}`}function Kx(d,u,p,w){let[y,v,S]=[d,u,p].map((N)=>new Map(N.map((B)=>[B.id,B]))),x=[],j=[];for(let N of u){let B=y.get(N.id),G=S.get(N.id);if(!B||G&&Ts(G,B))x.push(N);else if(!G){if(!Ts(N,B))x.push(N)}else if(Ts(N,B))x.push(G);else if(x.push(N),!Ts(G,N))j.push(G)}let L=new Set(x.map((N)=>N.id));for(let N of p){let B=y.get(N.id);if(B){if(!v.has(N.id)&&!Ts(N,B))j.push(N);continue}if(x.some((V)=>Ts(V,N)))continue;let G=L.has(N.id)?hn(w,L):N.id;x.push({...N,id:G}),L.add(G)}return{items:x,lostItems:j}}import{existsSync as kg,watch as Qx}from"fs";import{mkdir as bg,readdir as _d,readFile as Od,unlink as rP,writeFile as Jx}from"fs/promises";import{basename as oP,join as hr}from"path";class vg{projects;edited;sprintEdited;bases=new Map;watchers=new Map;saves=new Map;constructor(d,u,p=()=>{return}){this.projects=d;this.edited=u;this.sprintEdited=p}async enabled(d){return(await this.projects.settings(d))["tasks.syncToRepo"]}async write(d,u){if(!kg(this.projects.path(d)))return;let p=this.dir(d);await bg(p,{recursive:!0});let w=await this.projects.settings(d),y=await ae(p,Ml(u.id,u.title,w["tasks.fileName"])),v=Rc(u),S=await this.basesOf(d),x=await this.unseenEdit(d,u.id,S.get(u.id),v);if(x)return void this.edited(d,x.file,x.text);S.set(u.id,{file:oP(y),text:v}),this.save(d),await Ce(y,v);for(let j of await this.filesOf(d,u.id))if(j!==oP(y))await rP(hr(p,j)).catch(()=>{return})}async saw(d,u,p){let w=hs(u);if(w)(await this.basesOf(d)).set(w,{file:u,text:p})}async unseenEdit(d,u,p,w){for(let y of await this.filesOf(d,u)){let v=await Od(hr(this.dir(d),y),"utf8").catch(()=>{return});if(v!==void 0&&v!==w&&v!==p?.text)return{file:y,text:v}}return}async writeSprint(d,u){if(!kg(this.projects.path(d)))return;let p=E(this.projects.path(d));await bg(p.sprints,{recursive:!0}),await Jx(p.sprint(u.id),ms(u))}async sprintFileIds(d){return(await _d(E(this.projects.path(d)).sprints).catch(()=>[])).filter((p)=>p.endsWith(".json")).map((p)=>p.slice(0,-5))}async removeSprint(d,u){await rP(E(this.projects.path(d)).sprint(u)).catch(()=>{return})}async base(d,u){let p=(await this.basesOf(d)).get(u);return p&&Nl(p.text)}async isBase(d,u,p){let w=hs(u),y=w&&(await this.basesOf(d)).get(w);return!!y&&y.file===u&&y.text===p}async texts(d){let u=this.dir(d),p=(await _d(u).catch(()=>[])).filter((y)=>hs(y)),w=await Promise.all(p.map((y)=>Od(hr(u,y),"utf8").catch(()=>"")));return new Map(p.map((y,v)=>[y,w[v]??""]))}async readAll(d){let u=[],p=[];for(let[w,y]of await this.texts(d)){let v=Ac(y);if(v.success)u.push(v.data);else p.push({file:w,error:v.error.message.slice(0,1000)})}return{docs:u,skipped:p}}async fileIds(d){return(await _d(this.dir(d)).catch(()=>[])).map(hs).filter((p)=>p!==void 0)}folderThere(d){return kg(this.dir(d))}async filesOf(d,u){return(await _d(this.dir(d)).catch(()=>[])).filter((w)=>hs(w)===u)}watch(d){if(this.watchers.has(d))return;let{tasks:u,sprints:p}=E(this.projects.path(d));this.watchers.set(d,[...aP(u,hs,(w)=>void this.changed(d,w)),...aP(p,(w)=>w.endsWith(".json")&&rr(w.slice(0,-5)),(w)=>void Od(hr(p,w),"utf8").then((y)=>this.sprintEdited(d,y)).catch(()=>{return}))])}unwatch(d){for(let p of this.watchers.get(d)??[])p.close();this.watchers.delete(d);let u=this.saves.get(d);if(u)clearTimeout(u);this.saves.delete(d)}close(){for(let d of[...this.watchers.values()].flat())d.close();for(let[d,u]of this.saves)clearTimeout(u),this.bases.get(d)?.then((p)=>this.writeBases(d,p,!0))}async changed(d,u){let p=await Od(hr(this.dir(d),u),"utf8").catch(()=>{return});if(p!==void 0&&await this.isBase(d,u,p))return;this.edited(d,u,p)}dir(d){return E(this.projects.path(d)).tasks}basesOf(d){let u=this.bases.get(d);if(!u)u=Ge(this.basesFile(d),{}).then((p)=>new Map(Object.entries(p))).catch(()=>new Map),this.bases.set(d,u);return u}basesFile(d){return hr(m().repoSync,`${d}.json`)}save(d){clearTimeout(this.saves.get(d)),this.saves.set(d,setTimeout(()=>{this.saves.delete(d),this.bases.get(d)?.then((u)=>this.writeBases(d,u))},300))}async writeBases(d,u,p=!1){let w=Object.fromEntries(u);try{if(p)return qn(this.basesFile(d),w);await bg(m().repoSync,{recursive:!0}),await $e(this.basesFile(d),w)}catch(y){s.warn(`tasks: can't keep ${d}'s repo copy bases`,y)}}}function aP(d,u,p){let w=new Map;try{return[Qx(d,(y,v)=>{if(!v||!u(v))return;clearTimeout(w.get(v)),w.set(v,setTimeout(()=>p(v),150))})]}catch(y){return s.warn(`tasks: can't watch ${d}`,y),[]}}var Sg=()=>new Date().toISOString(),ys=(d,{extra:u,...p})=>({projectId:d,...p}),$g=({task:{projectId:d,...u},extra:p,version:w})=>({doc:{...u,extra:p},version:w}),xd=(d,u)=>JSON.stringify(d)===JSON.stringify(u),dP=5;class Cg{projects;server;onChange;onSprints;locks=new Map;replicas=new Map;repo;constructor(d,u,p,w=()=>{return}){this.projects=d;this.server=u;this.onChange=p;this.onSprints=w;this.repo=new vg(d,(y,v,S)=>this.locked(y,()=>this.fileEdited(y,v,S)).catch((x)=>s.warn(`tasks: couldn't take in ${v}`,x)),(y,v)=>void this.sprintEdited(y,v).catch((S)=>s.warn(`tasks: couldn't take in ${y}'s sprint file`,S)))}async list(d){let{tasks:u}=await this.replica(d);return[...u.values()].map((p)=>ys(d,p.doc)).sort((p,w)=>p.id.localeCompare(w.id))}async fileId(d,u){let p=this.projects.keys(d),w=To(u)?.prefix;if(!w||w!==p.key&&!p.oldKeys.includes(w))return u;let y=await this.projects.settings(d);return Oh(u,p,await this.ids(d),{fallbackPrefix:y["tasks.idPrefix"],digits:y["tasks.idDigits"]})}async get(d){let u=(await this.replica(d.projectId)).tasks.get(d.taskId);if(!u)throw new c("not_found",`no task ${d.taskId} in ${d.projectId}`);return ys(d.projectId,u.doc)}create(d,u){return this.locked(d.projectId,async()=>{let{today:p,weeks:w}=di(u),y=gs(p,w).id,v=await this.repo.fileIds(d.projectId),S=await this.commit(d.projectId,(x)=>{let j=Wm([...x.keys(),...v],{prefix:u["tasks.idPrefix"],digits:u["tasks.idDigits"],start:u["tasks.firstNumber"]});return{doc:lf(d,j,Rg(x),y)}});return ys(d.projectId,S.doc)})}update(d,u){return this.change(d,(p,w)=>Yu(p,u,Rg(w)))}updateIf(d,u,p){return this.locked(d.projectId,async()=>{let w=await this.commit(d.projectId,(y)=>{let v=y.get(d.taskId);if(!v||!u(ys(d.projectId,v.doc)))return;let S=structuredClone(v.doc);return Yu(S,p,Rg(y)),S.updatedAt=Sg(),{doc:S}});return w&&ys(d.projectId,w.doc)})}setReview(d,u){return this.change(d,(p)=>pf(p,u))}setMergeApproval(d,u){return this.change(d,(p)=>Ju(p,u))}forgetPr(d){return this.change(d,(u)=>{delete u.pr,delete u.mergeApproval})}appendNote(d,u){return this.change(d,(p)=>hi(p,u))}async addQuestion(d,u){return this.changed(d,(p)=>Zu(p,u))}appendCountedNote(d,u){return this.change(d,(p)=>ff(p,u))}async addQuestionOnce(d,u,p){let w;return await this.locked(d.projectId,()=>this.commit(d.projectId,(y)=>{w=void 0;let v=y.get(d.taskId);if(!v)throw new c("not_found",`no task ${d.taskId} in ${d.projectId}`);if(v.doc.questions.some(p))return;let S=structuredClone(v.doc);return w=Zu(S,u),S.updatedAt=Sg(),{doc:S}})),w}async answerQuestion(d,u,p){let w=()=>this.changed(d,(y)=>mf(y,u,p));try{return await w()}catch(y){if(!(y instanceof c&&(y.code==="not_found"||y.code==="conflict"))||!this.server.enrolled()||!this.replicas.get(d.projectId)?.loaded)throw y;return await this.locked(d.projectId,()=>this.catchUp(d.projectId)),w()}}reopenQuestion(d,u){return this.changed(d,(p)=>hf(p,u))}refuseAnswer(d,u,p,w){return this.changed(d,(y)=>gf(y,u,p,w))}expireQuestion(d,u){return this.change(d,(p)=>wf(p,u))}cancelOpenPrompts(d,u){return this.cancelOpen(d,(p)=>p.askedBy===u&&p.kind==="permission")}cancelOpen(d,u){return this.change(d,(p)=>yf(p,u))}addReviewComment(d,u){return this.changed(d,(p)=>bf(p,u))}addComment(d,u,p,w={}){return this.changed(d,(y)=>vf(y,u,p,w))}editComment(d,u,p,w){return this.changed(d,(y)=>Sf(y,u,p,w))}removeComment(d,u,p){return this.change(d,(w)=>$f(w,u,p))}setReply(d,u,p){return this.changed(d,(w)=>xf(w,u,p))}setCommentStatus(d,u,p){return this.change(d,(w)=>kf(w,u,p))}received(d){let{projectId:u}=d.task;return this.locked(u,()=>this.heard(u,d))}async resync(){for(let[d,u]of this.replicas){if(!u.loaded)continue;await this.locked(d,()=>this.catchUp(d)).catch((p)=>s.warn(`tasks: couldn't catch up on ${d}`,p))}}async catchUp(d){let u=await this.replica(d),{tasks:p,sprints:w}=await this.snapshot(d),y=new Set(p.map((v)=>v.task.id));for(let v of p)await this.heard(d,v);u.sprints=w,this.onSprints(d);for(let v of[...u.tasks.keys()].filter((S)=>!y.has(S)))u.tasks.delete(v);await this.reconcile(d)}async resyncRepo(d){for(let[u,p]of this.replicas)if(p.loaded&&(!d||d===u))await this.locked(u,()=>this.reconcile(u)).catch((w)=>s.warn(`tasks: couldn't write ${u}'s repo copy`,w))}async sprints(d){return(await this.replica(d)).sprints}knownSprints(d){let u=this.replicas.get(d);return u?.loaded?u.sprints:void 0}async sprintEdited(d,u){if(this.server.enrolled()&&!await this.repo.enabled(d))return;let p=ea(u),w=(await this.sprints(d)).find((y)=>y.id===p.id);if(!xd(w,p))await this.putSprint(d,p)}putSprint(d,u){return this.locked(d,async()=>{let p=await this.replica(d);if(this.server.enrolled())await this.ask("sprints.put",{projectId:d,sprint:u});if(p.sprints=qa([u,...p.sprints.filter((w)=>w.id!==u.id)]),await this.copies(d))await this.repo.writeSprint(d,u);this.onSprints(d)})}sprintsChanged(d,u){return this.locked(d,async()=>{let p=this.replicas.get(d);if(!p?.loaded)return;if(p.sprints=qa([...u]),await this.copies(d))for(let w of u)await this.repo.writeSprint(d,w);this.onSprints(d)})}inFiles(){return!this.server.enrolled()}dropSprints(d,u){return this.locked(d,async()=>{let p=await this.replica(d);p.sprints=p.sprints.filter((w)=>!u.includes(w.id));for(let w of u)await this.repo.removeSprint(d,w);this.onSprints(d)})}async caughtUp(d){await(await this.replica(d)).caughtUp}watch(d){this.repo.watch(d)}forget(d){this.repo.unwatch(d),this.replicas.delete(d)}close(){this.repo.close()}async ids(d){return[...(await this.replica(d)).tasks.keys()]}async replica(d){let u=this.replicas.get(d);if(!u){let p={tasks:new Map,sprints:[],ready:Promise.resolve(),loaded:!1,caughtUp:Promise.resolve()};p.ready=this.load(d,p).catch((w)=>{throw this.replicas.delete(d),w}),this.replicas.set(d,p),u=p}return await u.ready,u}async load(d,u){if(!this.server.enrolled()){for(let y of(await this.repo.readAll(d)).docs)u.tasks.set(y.id,{doc:y,version:0});u.sprints=await ci(this.projects.path(d)),u.loaded=!0;return}let{tasks:p,sprints:w}=await this.snapshot(d);for(let y of p)u.tasks.set(y.task.id,$g(y));u.sprints=w,u.loaded=!0,this.onSprints(d),u.caughtUp=this.locked(d,()=>this.reconcile(d)).catch((y)=>s.warn(`tasks: couldn't bring ${d}'s repo copy up to date`,y))}async snapshot(d){let u=await this.ask("tasks.snapshot",{projectId:d});if(!u.imported)await this.importFiles(d),u=await this.ask("tasks.snapshot",{projectId:d});let{sprints:p}=u,w=[...u.tasks];while(u.more)u=await this.ask("tasks.snapshot",{projectId:d,after:w.at(-1)?.task.id}),w.push(...u.tasks);return{tasks:w,sprints:p}}async importFiles(d){let{docs:u,skipped:p}=await this.repo.readAll(d),w=Math.max(1,Math.ceil(u.length/gr));for(let y=0;y<w;y++){let v=y===w-1;await this.ask("tasks.import",{projectId:d,tasks:u.slice(y*gr,(y+1)*gr).map((S)=>({task:ys(d,S),extra:S.extra})),final:v,sprints:v?await ci(this.projects.path(d)):[],skipped:v?p:[]})}s.info(`tasks: ${d}'s ${u.length} task files are in the database now`);for(let{file:y,error:v}of p)s.warn(`tasks: ${d}'s ${y} doesn't parse, left out: ${v}`)}async change(d,u){return(await this.write(d,u)).task}async changed(d,u){let p;return await this.write(d,(w)=>{p=u(w)}),p}write(d,u){return this.locked(d.projectId,async()=>{let p=await this.commit(d.projectId,(w)=>{let y=w.get(d.taskId);if(!y)throw new c("not_found",`no task ${d.taskId} in ${d.projectId}`);let v=structuredClone(y.doc);return u(v,w),v.updatedAt=Sg(),{doc:v}});return{task:ys(d.projectId,p.doc)}})}async commit(d,u,p="agent"){let w=await this.replica(d);for(let y=1;;y++){let v=Xx(()=>u(w.tasks));if(!v)return;let S=w.tasks.get(v.doc.id),x=await this.store(d,v,S?.version??0,p);if(x)return await this.apply(d,x,S),x;if(y>=dP)throw new c("conflict",`${v.doc.id} keeps changing elsewhere: try again in a moment`)}}async store(d,{doc:u,lost:p},w,y){if(!this.server.enrolled())return{doc:u,version:w+1};let v=ys(d,u),S=await this.ask("tasks.put",{task:v,extra:u.extra,base:w,source:y,lost:p});if(!S.conflict||xd(S.stored.task,v)&&xd(S.stored.extra,u.extra))return $g(S.stored);await this.heard(d,S.stored);return}async ask(d,u){for(let p=1;;p++){await this.server.linked();try{return await this.server.request(d,u)}catch(w){if(!(w instanceof c&&w.code==="unavailable")||p>=dP)throw w}}}async apply(d,u,p){if((await this.replica(d)).tasks.set(u.doc.id,u),await this.copies(d))await this.repo.write(d,u.doc);this.onChange({task:ys(d,u.doc),previous:p&&ys(d,p.doc)})}async heard(d,u){let p=this.replicas.get(d);if(!p?.loaded)return;let w=p.tasks.get(u.task.id);if(w&&w.version>=u.version)return;await this.apply(d,$g(u),w)}async copies(d){return!this.server.enrolled()||await this.repo.enabled(d)}async reconcile(d){if(!this.server.enrolled()||!await this.repo.enabled(d))return;let{tasks:u,sprints:p}=await this.replica(d);for(let[w,y]of await this.repo.texts(d)){let v=hs(w),S=v&&u.get(v),x=await this.repo.isBase(d,w,y);if(S&&y===Rc(S.doc)){if(!x)await this.repo.write(d,S.doc)}else if(S&&x)await this.repo.write(d,S.doc);else await this.fileEdited(d,w,y)}for(let w of u.values())if(!(await this.repo.filesOf(d,w.doc.id)).length)await this.repo.write(d,w.doc);for(let w of p)await this.repo.writeSprint(d,w);for(let w of await this.repo.sprintFileIds(d))if(Fs(w)&&!p.some((y)=>y.id===w))await this.repo.removeSprint(d,w)}async fileEdited(d,u,p){let{tasks:w}=await this.replica(d),y=this.server.enrolled();if(y&&!await this.repo.enabled(d))return;let v=hs(u);if(p===void 0){let G=v&&w.get(v);if(!G||!this.repo.folderThere(d))return;if((await this.repo.filesOf(d,G.doc.id)).length)return;if(y)return this.repo.write(d,G.doc);w.delete(G.doc.id);return}if(await this.repo.isBase(d,u,p))return;let S=Ac(p);if(!S.success)return s.warn(`tasks: skipping ${u}: ${S.error.message}`);let x=S.data,j=w.get(x.id)?.doc;Ju(x,j?.mergeApproval),x.questions=x.questions.map(({head:G,...V})=>{let Y=j?.questions.find((ne)=>ne.id===V.id)?.head;return Y?{...V,head:Y}:V});let L=await this.repo.base(d,x.id);if(await this.repo.saw(d,u,p),!y){let G=w.get(x.id);return this.apply(d,{doc:x,version:(G?.version??0)+1},G)}let N=await this.commit(d,(G)=>{let V=G.get(x.id)?.doc;if(!V)return{doc:x};let Y=L??V;if(x.updatedAt<Y.updatedAt)return;let{merged:ne,lost:ie}=iP(Y,V,x);if(xd({...ne,updatedAt:""},{...V,updatedAt:""}))return;if(ne.updatedAt=x.updatedAt>V.updatedAt?x.updatedAt:V.updatedAt,!Object.keys(ie).length)return{doc:ne};return hi(ne,zx(ie)),{doc:ne,lost:ie}},"repo"),B=w.get(x.id);if(!N&&B)await this.repo.write(d,B.doc)}locked(d,u){let w=(this.locks.get(d)??Promise.resolve()).catch(()=>{return}).then(u);return this.locks.set(d,w),w}}function zx(d){return`The repo copy's change to ${Object.keys(d).join(", ")} lost to a newer change in Superfactory; it is kept in the task's history.`}function Xx(d){try{return d()}catch(u){if(u instanceof ze)throw new c(u.code,u.message);throw u}}var Rg=(d)=>new Map([...d].map(([u,p])=>[u,p.doc]));import{appendFile as cP,mkdir as Zx,readFile as Og,writeFile as eM}from"fs/promises";import{join as Ld}from"path";var tM=new Set(["task_update","task_ask","task_comment","notify_user"].map((d)=>`mcp__${Me}__${d}`)),sM=/\bT-\d{1,6}\b/g,Rs=(d)=>`${d.projectId}/${d.taskId}`,uP=()=>({person:!1,about:new Map,touched:new Map,asked:[],said:[],times:new Map}),lP=100;class Lg{deps;index;current=new Map;next=new Map;expected=new Map;reading=new Map;writing=new Map;constructor(d){this.deps=d}expect(d,u,p){if(p.length)this.wait(d,{text:u,refs:p,reply:!1})}replyHanded(d,u,p){this.wait(d,{text:p,refs:[u],reply:!0})}tagTurn(d,u){let p=this.current.get(d)??this.turn(this.next,d);for(let w of u)p.about.set(Rs(w),w)}onEvent(d,u){if(d.kind!=="coordinator")return;let p=d.id;switch(u.type){case"user_message":{let w=this.turn(this.next,p),y=(this.reading.get(p)??Promise.resolve()).then(()=>this.message(d,w,u).catch((v)=>s.warn(`task talk: ${p}'s message ${u.seq} not read`,v)));this.reading.set(p,y);return}case"init":this.current.set(p,this.next.get(p)??uP()),this.next.delete(p);return;case"tool_use":{if(u.parentToolUseId)return;let w=this.now(p);w.said=[];let y=u.input,v=typeof y?.projectId==="string"?y.projectId:d.projectId;if(tM.has(u.name)&&typeof y?.taskId==="string"&&v)w.touched.set(Rs({projectId:v,taskId:y.taskId}),{projectId:v,taskId:y.taskId});return}case"task_created":this.now(p).touched.set(Rs(u),{projectId:u.projectId,taskId:u.taskId});return;case"assistant_text":if(!u.delta&&!u.parentToolUseId)this.now(p).said.push(u.seq),this.now(p).times.set(u.seq,u.ts);return;case"result":{let w=this.current.get(p)??this.next.get(p);if(this.current.has(p))this.current.delete(p);else this.next.delete(p);if(w)(this.reading.get(p)??Promise.resolve()).then(()=>this.tag(d,w)).catch((y)=>s.warn(`task talk: ${p}'s turn not tagged`,y));return}}}async decorate(d,u){let p=new Map;for(let w of await this.entries())if(w.sessionId===d)p.set(w.seq,[...p.get(w.seq)??[],{projectId:w.projectId,taskId:w.taskId}]);if(!p.size)return u;return u.map((w)=>(w.type==="user_message"||w.type==="assistant_text")&&p.has(w.seq)?{...w,taskRefs:p.get(w.seq)}:w)}recordMessage(d,u){let p=this.messagesFile(d),w=(this.writing.get(p)??Promise.resolve()).then(()=>this.append(p,u)),y=w.catch(()=>{return});return this.writing.set(p,y),y.then(()=>{if(this.writing.get(p)===y)this.writing.delete(p)}),w}async append(d,u){await Zx(Ld(d,".."),{recursive:!0}),await cP(d,`${JSON.stringify(u)}
|
|
582
|
+
`);let p=(await Og(d,"utf8")).split(`
|
|
583
|
+
`).filter(Boolean);if(p.length>pP*1.2)await eM(d,`${p.slice(-pP).join(`
|
|
584
|
+
`)}
|
|
585
|
+
`)}async messages(d){let u=(await this.entries()).filter((y)=>Rs(y)===Rs(d)),p=[...new Set(u.map((y)=>y.sessionId))],w=await this.sessionMessages(d);for(let y of p){let v=new Map(u.filter((S)=>S.sessionId===y).map((S)=>[S.seq,S]));for(let S of await Ms(Ld(this.logs,`${y}.jsonl`))){let x=v.get(S.seq),j=x&&this.toMessage(x,S);if(j)w.push(j)}}return w.sort((y,v)=>y.at.localeCompare(v.at)||y.seq-v.seq)}async messagesPage(d,u){let{before:p,limit:w}=u;if(!w)return{messages:await this.messages(d),older:null};let y=(await this.entries()).filter((j)=>Rs(j)===Rs(d)),v=[],S=(j)=>!!p&&!!j.at&&Ea({at:j.at,id:lr(j.sessionId,j.seq)})>=p;for(let j=y.length;j>0&&v.length<=w;j-=lP){let L=y.slice(Math.max(0,j-lP),j).filter((N)=>!S(N));for(let N of await this.read(L))if(!p||Ea(N)<p)v.push(N)}let x=Ag([...v,...await this.sessionMessages(d)],u);return{messages:x.items,older:x.older}}async read(d){let u=[];for(let p of new Set(d.map((w)=>w.sessionId))){let w=new Map(d.filter((S)=>S.sessionId===p).map((S)=>[S.seq,S])),y=Math.min(...w.keys()),v=Ld(this.logs,`${p}.jsonl`);for(let S of await ic(v,(x)=>x.seq>y)){let x=w.get(S.seq),j=x&&this.toMessage(x,S);if(!j||!x)continue;x.at??=j.at,u.push(j)}}return u}toMessage(d,u){let{sessionId:p}=d;if(u.type==="user_message")return{id:lr(p,u.seq),sessionId:p,seq:u.seq,author:{kind:"user",handle:u.author},body:u.text,at:u.ts};if(u.type==="assistant_text")return{id:lr(p,u.seq),sessionId:p,seq:u.seq,author:{kind:"claude",handle:"claude",sessionId:p,role:"coordinator",name:d.managerId?this.deps.managers.get(d.managerId)?.name:void 0},body:u.text,at:u.ts};return}async sessionMessages(d){return(await Og(this.messagesFile(d),"utf8").catch(()=>"")).split(`
|
|
586
|
+
`).filter(Boolean).flatMap((p)=>{try{let w=JSON.parse(p);return[{id:lr(w.fromSessionId,w.seq),sessionId:w.fromSessionId,seq:w.seq,author:{kind:"claude",handle:"claude",sessionId:w.fromSessionId,name:w.from.slice(0,60)},body:`To ${w.to}${w.untrusted?" (from a sandbox)":""}:
|
|
587
|
+
${w.text}`,at:w.at}]}catch{return[]}})}messagesFile(d){let u=this.deps.messagesDir??m().sessionMessages;return Ld(u,hP(d.projectId),`${hP(d.taskId)}.jsonl`)}get logs(){return this.deps.logs??m().sessionLogs}get file(){return this.deps.file??m().taskTalk}wait(d,u){this.expected.set(d,[...this.expected.get(d)??[],u])}turn(d,u){let p=d.get(u);if(p)return p;let w=uP();return d.set(u,w),w}now(d){return this.current.get(d)??this.turn(this.next,d)}async message(d,u,p){let w=this.expected.get(d.id)??[],y=w.find((v)=>v.text===p.text);if(y)this.expected.set(d.id,w.filter((v)=>v!==y));if(p.author==="superfactory"&&!y)return;u.person=!0;for(let v of y?.refs??[])u.about.set(Rs(v),v);if(y?.reply)return;u.asked.push(p.seq),u.times.set(p.seq,p.ts);for(let v of await this.mentions(d,p.text))u.about.set(Rs(v),v)}async mentions(d,u){let p=d.projectId;if(!p)return[];let w=[...new Set(u.match(sM)??[])];return(await Promise.all(w.map((v)=>this.deps.tasks.get({projectId:p,taskId:v}).then(()=>({projectId:p,taskId:v})).catch(()=>{return})))).filter((v)=>!!v)}async tag(d,u){let p=new Map(u.about);if(u.person)for(let[x,j]of u.touched)p.set(x,j);let w=[...u.asked,...u.said];if(!p.size||!w.length)return;let y=this.deps.managerOf(d)?.id,v=[...p.values()].flatMap((x)=>w.map((j)=>({...x,sessionId:d.id,seq:j,managerId:y,at:u.times.get(j)})));(await this.entries()).push(...v),await cP(this.file,v.map((x)=>`${JSON.stringify(x)}
|
|
588
|
+
`).join(""));for(let x of p.values())await this.deps.talked(x,d),this.deps.push({type:"task.talk.changed",...x,sessionId:d.id,seqs:w})}entries(){return this.index??=Og(this.file,"utf8").catch(()=>"").then((d)=>d.split(`
|
|
589
|
+
`).filter(Boolean).flatMap((u)=>{try{return[JSON.parse(u)]}catch{return[]}})),this.index}}var pP=500,hP=(d)=>d.replace(/[^\w.-]/g,"_");var Nd=60000,nM=Nd,iM=60*Nd;function fP(d,u=Date.now()){let p=k("SUPERFACTORY_JOB_WAIT_MS",iM);return!!d?.jobs?.some((w)=>u-Date.parse(w.startedAt)<p)}function mP(d){return k("SUPERFACTORY_STATUS_AFTER_MS",d["agents.statusAfterMinutes"]*Nd)}function rM(d,u,p){let w=`${d.id} (${d.title}) has had no turn from you for ${Math.max(1,Math.round(p/Nd))} min, and nothing is on its way to you.`,y='End your reply with one line: "Status: <what is left; what blocks you; your next step>", at most 150 characters.';return u.teammate?`Status check from Superfactory: ${w} Finish what your role still needs now, commit only your own files, and tell the lead what it should know with SendMessage. If your role here is done, end with "Status: done \u2014 <one line>" and you are ended. ${'End your reply with one line: "Status: <what is left; what blocks you; your next step>", at most 150 characters.'}`:`Status check from Superfactory: ${w} Finish what is left now: commit your work, and if the task is done (its video, when wanted, and your summary comment first), set it to in_review with task_update. If you are blocked, ask with task_ask. End your reply with one line: "Status: <what is left; what blocks you; your next step>", at most 150 characters.`}function oM(d){let u=d.split(`
|
|
590
|
+
`).map((y)=>y.trim()).filter(Boolean),w=(u.findLast((y)=>/^status:/i.test(y.replace(/^[*_`]+/,"")))??u.at(-1)??"").replace(/^[*_`]*status:[*_`]*\s*/i,"").replace(/[*_`]+$/,"");return w.length>200?`${w.slice(0,199)}\u2026`:w||"(no answer)"}var aM=(d,u)=>d.toLowerCase().replace(/[^a-z0-9]+/g,"")===u.toLowerCase().replace(/[^a-z0-9]+/g,"");class Ng{deps;timers=new Map;ours=new Set;lastReal=new Map;lastStatus=new Map;stuck=new Set;constructor(d){this.deps=d}onEvent(d,u){let p=d.id;if(!d.projectId||!d.taskId)return;switch(u.type){case"init":case"user_message":this.cancel(p);return;case"result":this.turnEnded(d);return;case"state":if(u.state==="exited"||u.state==="failed")this.forget(p);else if(u.state==="idle"&&!this.timers.has(p)&&!this.ours.has(p)&&!this.stuck.has(p)){if(!this.lastReal.has(p))this.lastReal.set(p,Date.now());this.schedule(d).catch((w)=>s.warn(`idle turns: ${p} not scheduled`,w))}return}}turnEnded(d){let u=d.id;if(this.ours.delete(u))this.statusAnswered(d);else this.lastReal.set(u,Date.now()),this.lastStatus.delete(u),this.stuck.delete(u);if(this.stuck.has(u))return;this.schedule(d).catch((p)=>s.warn(`idle turns: ${u} not scheduled`,p))}statusAnswered(d){let u=d.id,p=this.deps.activity.get(u),w=oM(p?.lastText??""),y=this.lastStatus.get(u),v=!p?.acted||y!==void 0&&aM(y.text,w);if(this.lastStatus.set(u,{at:Date.now(),text:w,idle:v}),this.deps.answered(d,w),v&&y?.idle)this.stuck.add(u),this.cancel(u),s.info(`idle turns: ${u} made no progress twice; stopping its idle turns`),this.deps.stuckNow(d,w)}async schedule(d){this.cancel(d.id);let u=await this.deps.settings(d.projectId??""),p=Date.now(),w=mP(u);if(!w)return;let y=this.statusDue(d.id,w),v=Math.max(y,p+(y<=p?Math.min(nM,w):0)),S=setTimeout(()=>void this.fire(d),v-p);S.unref?.(),this.timers.set(d.id,S)}statusDue(d,u){return Math.max(this.lastReal.get(d)??0,this.lastStatus.get(d)?.at??0)+u}async fire(d){let u=d.id;if(this.timers.delete(u),this.deps.activity.get(u)?.inTurn||this.stuck.has(u)||!this.deps.idle(u))return;let p=await this.deps.task(d);if(p?.parked)s.info(`idle turns: ${u}'s ${p.id} is parked; no status check`);if(!p||p.archived||p.parked||!Le.includes(p.status)){this.forget(u);return}let w=await this.deps.settings(p.projectId),y=Date.now(),v=mP(w);if(p.dependsOn.length&&await this.deps.dependencyOpen(p)){s.info(`idle turns: ${u} waits on its dependsOn; no status check`);return}let S=this.deps.waiting(d);if(v&&y>=this.statusDue(u,v)-1000&&p.status==="in_progress"&&!S){let x=y-(this.lastReal.get(u)??y);await this.send(d,rM(p,d,x));return}if(v&&p.status==="in_progress")await this.schedule(d)}async send(d,u){if(this.ours.add(d.id),!await this.deps.ask(d.id,u).catch((w)=>(s.warn(`idle turns: status to ${d.id} not sent`,w),!1)))this.ours.delete(d.id);else s.info(`idle turns: status to ${d.id}`)}cancel(d){clearTimeout(this.timers.get(d)),this.timers.delete(d)}forget(d){this.cancel(d);for(let u of[this.lastReal,this.lastStatus])u.delete(d);for(let u of[this.ours,this.stuck])u.delete(d)}stop(){for(let d of this.timers.values())clearTimeout(d);this.timers.clear()}}import{createHash as dM}from"crypto";import{readdir as cM,readFile as uM}from"fs/promises";import{homedir as lM}from"os";import{join as Dg}from"path";var yP=3600000,pM=(d)=>/^(lead|machine) /i.test(d)||st(d,bp),gP=(d)=>d.includes(" ");class Ug{deps;seq=0;sent=new ei;delivered=new Map;constructor(d){this.deps=d}async send(d,u,p,w){let y=await this.decide(d,u,p);if(!y.allow&&y.sent)this.deps.sent?.(d.sessionId,{toolUseId:w,...y.sent});return y}async decide(d,u,p){let w=this.deps.find(d.sessionId);if(!w)return{allow:!1,reason:"Superfactory doesn't know this session: not sent."};let y=await this.party({address:this.nameOf(w),session:w});if(Ho(u)==="*"&&!y.mainLead)return{allow:!1,reason:"Not sent: write to each session by its name, not to all of them."};let v=await this.addressFor(Ho(u)),S=this.deps.addressed().find((B)=>st(B.address,v))?.address??v;if(!S)return{allow:!1,reason:`Not sent: ${u} isn't a session you may write to.`};if(!p.trim())return this.toOther(y,u);if(Mr(p))return{allow:!1,reason:Nr};let x=nd(u)?.toLowerCase(),j=(x?`${S} [${x}]`:S).toLowerCase(),L=this.sent.seen(w.id,j,p,S);if(L)return{allow:!1,reason:L};let N=await this.route(w,y,u,S,p);if(N.allow?!gP(S):N.sent)this.sent.keep(w.id,j,p);return N}async route(d,u,p,w,y){if(!u.mainLead&&!u.sandboxed&&u.kind!=="coordinator"&&u.projectId&&u.taskId&&pM(w)){let x=this.deps.reports.take(`${u.projectId}/${u.taskId}`);if(x)return{allow:!1,reason:`Not sent: ${x.replace(/^inform is/,"what a task tells its leads is")}`}}let v=nd(p)?.toLowerCase(),S=fM(d.id,v?`${w} [${v}]`:w,y);try{let x=this.deps.addressed().filter((V)=>xg(V.address,w)&&(V.ambiguous||V.session?.id!==d.id)),j=v?x.filter((V)=>!!V.session&&Tg(v,V.session.id)):x,L=(j.length||x.some((V)=>V.session?.teammate)?j:x).sort((V,Y)=>Number(!!V.session?.sandbox)-Number(!!Y.session?.sandbox)),N=L[0];if(N?.ambiguous)return{allow:!1,reason:`Not sent: two leads are named ${N.address}; ask the user to rename one.`};let B=L.filter((V)=>!!V.session?.sandbox===!!N?.session?.sandbox);if(B.length>1&&B.some((V)=>V.session?.teammate))return{allow:!1,reason:`Not sent: ${hM(w,B)}`};let G=gP(w)?this.deps.server():void 0;if(N&&!(G&&N.session?.teammate))return await this.toLocal(u,N,y,S);if(G){let V=this.depth(d,w),Y=await G.message({by:d.id,to:v?`${w} [${v}]`:w,text:y,deliver:!0,depth:V,key:S}).catch((ne)=>{if(N&&!mM(ne))return;throw ne});if(Y&&!Y.unknown)return wP({to:Y.address??w,machine:Y.machine,started:Y.started})}if(N)return await this.toLocal(u,N,y,S)}catch(x){let j=x.message;return{allow:!1,reason:/timed? ?out|timeout|disconnected|closed/i.test(j)?`Not confirmed: ${j}. It may have arrived: sent again, the same message isn't delivered twice.`:`Not sent: ${j}`}}return this.toOther(u,p)}async reachable(d){let u=this.deps.find(d.sessionId);if(!u)return"";let p=await this.party({address:this.nameOf(u),session:u}),w=[];for(let x of this.deps.addressed()){if(x.ambiguous)continue;let j=await this.party(x);if($p(p,j))continue;let L=x.session?_g(x.session):`${j.projectId?`a lead of ${j.projectId}`:"a lead for all projects"}, not running: it starts with your message`;w.push({address:x.address,what:L,...x.session&&{ref:Sp(x.session.id)},relayed:!0})}let y=await this.deps.server()?.reachable({by:u.id}).then((x)=>x.sessions).catch((x)=>(s.warn(`session messages: the server's reachable sessions for ${u.id} failed`,x),[])),v=Eg([...w,...y??[]]);if(!v.length)return"";return["Superfactory sessions you may write to with SendMessage, by these names (others are refused; Superfactory delivers to them, not Claude):",...v.map((x)=>`- ${x.address}: ${x.what}${x.machine?`, on ${x.machine}`:""}`),"Write only when they need it; never only to acknowledge."].join(`
|
|
591
|
+
`)}async deliver(d){let u=d.key&&`${d.from}
|
|
592
|
+
${d.sessionId??`lead:${d.managerId}`}
|
|
593
|
+
${d.key}`;if(u){let S=Date.now();for(let[x,j]of this.delivered)if(S-j>yP)this.delivered.delete(x);if(this.delivered.has(u))return;this.delivered.set(u,S)}let p={from:d.from,machine:d.machine,untrusted:d.untrusted||void 0,report:d.report||void 0,text:d.text},w=Th(p),y=d.sessionId?this.deps.find(d.sessionId):void 0,v=d.managerId??(y?.kind==="coordinator"?this.deps.manager(y)?.id:void 0);try{if(v)await this.deps.wakeLead(v,w,d.depth,d.report,p);else if(d.sessionId)await this.deps.wake(d.sessionId,w,d.depth,p)}catch(S){if(u)this.delivered.delete(u);throw S}}async toLocal(d,u,p,w){let y=await this.party(u),v=$p(d,y);if(v)return{allow:!1,reason:`Not sent: ${v}`};let S=this.depth(this.deps.find(d.sessionId),y.address);return await this.deliver({sessionId:u.session?.id,managerId:u.session?void 0:u.lead?.id,from:d.address,text:p,untrusted:!!d.sandboxed,report:Ig(d,y),depth:S,key:w}),await this.keep(d,y,p),wP({to:y.address,started:!u.session||void 0})}async toOther(d,u){if(d.mainLead||d.sandboxed)return{allow:!0};let p={allow:!1,reason:`Not sent: ${u} isn't a Superfactory session you may write to. ListAgents lists those you may.`},w=Ho(u);if(w.startsWith("uds:"))return p;let y=this.deps.native?await this.deps.native().catch(()=>{return}):[];if(!y)return{allow:!1,reason:"Not sent: Superfactory couldn't read Claude's sessions on this machine."};let v=nd(u)?.toLowerCase(),S=(x)=>{let j=x?.toLowerCase();return!!j&&y.some((L)=>st(L.name,j)||String(L.pid)===j||j.length>=4&&!!L.id?.toLowerCase().startsWith(j)||L.socket===j)};if(S(w)||S(v))return p;return{allow:!0}}async addressFor(d){if(!d.startsWith("uds:"))return d;let u=d.slice(4),w=(await this.deps.native?.().catch(()=>[])??[]).find((y)=>y.socket===u)?.name;return w&&this.deps.addressed().find((y)=>st(y.address,w))?.address||d}async keep(d,u,p){let w=d.taskId&&d.kind!=="coordinator"?d:u.kind!=="coordinator"?u:void 0;if(!w?.projectId||!w.taskId)return;let y={projectId:w.projectId,taskId:w.taskId},v={seq:this.nextSeq(),fromSessionId:d.sessionId,from:d.address,to:u.address,text:p,relayed:!0,untrusted:!!d.sandboxed,at:(this.deps.now?.()??new Date).toISOString()},S=this.deps.ownsProject(y.projectId)?void 0:this.deps.server(),x=[d,u].find((L)=>!L.sandboxed)?.sessionId;await(S?S.message({by:d.sessionId,to:u.address,text:p,deliver:!1,depth:1}).then(()=>{return}):this.deps.record(y,v,x)).catch((L)=>s.warn(`session messages: ${d.address} \u2192 ${u.address} not recorded`,L))}nextSeq(){return this.seq=Math.max(this.seq+1,Date.now()),this.seq}depth(d,u){if(!d)return 1;let p=d.teammate&&this.deps.addressOf({...d,teammate:void 0});return this.deps.nextDepth(d.id,!!p&&st(p,u))}nameOf(d){return d.address??this.deps.addressOf(d)??d.id}async party(d){let{session:u,lead:p}=d;if(!u)return{sessionId:`lead:${p?.id}`,address:d.address,kind:"coordinator",projectId:p?.projectId,managerId:p?.id,bossId:p?.bossId,mainLead:p?.mainLead,allProjects:p?.allProjects};let w=this.deps.manager(u),y=u.projectId&&u.taskId&&u.kind!=="coordinator"?await this.deps.epicOf({projectId:u.projectId,taskId:u.taskId}).catch(()=>{return}):void 0,v=bt(u)&&!u.sandbox&&this.deps.holdsLead();return{sessionId:u.id,address:this.nameOf(u),kind:u.kind,projectId:u.projectId,taskId:u.taskId,epicId:y,managerId:w?.id,bossId:w?.bossId,mainLead:v,allProjects:u.kind==="coordinator"&&!u.projectId&&!u.sandbox&&!!w&&w.scope.kind==="global"&&!w.main&&w.type!=="machine"&&w.nodeId===this.deps.nodeId(),sandboxed:!!u.sandbox,leadProject:!!u.projectId&&this.deps.isLeadProject(u.projectId)}}}var hM=(d,u)=>`${u.length} sessions answer to ${d}: not sent to a guess. Write to one by its full name: ${u.map((p)=>p.session&&u.some((w)=>w!==p&&st(w.address,p.address))?`"${Pg(p.address,p.session.id)}"`:`"${p.address}"`).join(", ")}`,mM=(d)=>["forbidden","not_found","bad_request","conflict"].includes(d.code??""),fM=(d,u,p)=>dM("sha256").update(`${d}
|
|
594
|
+
${u.toLowerCase()}
|
|
595
|
+
${p.trim()}
|
|
596
|
+
${Math.floor(Date.now()/yP)}`).digest("hex").slice(0,40),wP=(d)=>({allow:!1,reason:_h(d),sent:d});async function kP(d=process.env){let u=Dg(d.CLAUDE_CONFIG_DIR||Dg(lM(),".claude"),"sessions"),p=(await cM(u).catch((y)=>{if(y.code==="ENOENT")return[];throw y})).filter((y)=>/^\d+\.json$/.test(y));return(await Promise.all(p.map(async(y)=>{let v;try{v=JSON.parse(await uM(Dg(u,y),"utf8"))}catch{return}if(typeof v.pid!=="number"||!gM(v.pid))return;return{pid:v.pid,id:typeof v.sessionId==="string"?v.sessionId:void 0,name:typeof v.name==="string"?v.name:void 0,socket:typeof v.messagingSocketPath==="string"?v.messagingSocketPath:void 0}}))).filter((y)=>!!y)}function gM(d){try{return process.kill(d,0),!0}catch{return!1}}var wM=(d)=>d.author.kind==="user"?`@${d.author.handle}`:"Claude",xs=(d)=>`${d.title}
|
|
597
|
+
${d.description.slice(0,2000)}`,bP=(d)=>rg(d)?void 0:ap(d)?.id,Dd=(d)=>d.length>140?`${d.slice(0,137)}...`:d;function yM({task:d,previous:u}){let p=`${d.id} "${d.title}"`,w=(L,N,B)=>({type:L,projectId:d.projectId,taskId:d.id,text:`${d.projectId}/${N}`,labels:d.labels,about:xs(d),actor:B}),y={...w("tasks_changed",`${d.id} ${d.status}`),digest:d.id};if(!u)return[w("task_created",`${p} was created (${d.status}).`),y];let v=[];if(d.status!==u.status){if(v.push(y),d.status==="in_review")v.push(w("task_ready",`${p} is ready for review.`));if(d.status==="done")v.push(w("task_done",`${p} is done.`))}let S=new Map(u.questions.map((L)=>[L.id,L.status])),x=bP(d);if(x&&x!==bP(u))v.push({...w("task_ready",`${p} waits for your approval: in review, its checks green, its video and summary in. Read its diff and watch its video, then task_approve it, or task_approve with decision "changes" and what to fix.`),approve:!0,userApproves:`${d.projectId}/${p} waits for the user's Approve: in review, its checks green, its video and summary in. Only the user approves ${d.projectId}'s tasks (tasks.approvedBy is "me"): you only check it (its diff, its video) and tell its agent what to fix; never task_approve it.`});for(let L of d.questions){if(!S.has(L.id)&&L.status==="open"&&L.kind!=="permission")v.push(w("question_asked",`${d.id} asks: ${Dd(L.text)}`,L.askedBy));if(L.status==="answered"&&S.get(L.id)==="open")v.push({...w("question_answered",`${d.id}: "${Dd(L.text)}" was answered.`),told:L.purpose==="merge"?d.sessionId:L.askedBy})}let j=new Set(u.comments.map((L)=>L.id));for(let L of d.comments)if(!j.has(L.id))v.push(w("comment_added",`${wM(L)} on ${d.id}: ${Dd(L.body)}`,L.author.kind==="claude"?L.author.sessionId:void 0));if(d.pr&&!u.pr)v.push(w("pr_opened",`${d.id} opened PR #${d.pr.number}: ${d.pr.url}`));if(d.pr?.state==="merged"&&u.pr?.state!=="merged")v.push(w("pr_merged",`${d.id}: PR #${d.pr.number} was merged.`));if(d.pr?.checks==="failing"&&u.pr?.checks!=="failing")v.push(w("pr_checks_failed",`${d.id}: the checks of PR #${d.pr.number} fail.`));return v}var Fg=5;function kM(d,u){let p=new Set(u.filter((x)=>x.status==="done").map((x)=>x.id)),w=u.filter((x)=>!x.archived&&!x.epic&&(x.status==="backlog"||x.status==="todo")&&(x.buildsOn===d.id||x.dependsOn.includes(d.id)));if(!w.length)return;let y=(x)=>{let j=x.dependsOn.filter((N)=>N!==d.id&&!p.has(N)),L=j.length?`it still waits for ${j.join(", ")}`:void 0;if(x.buildsOn===d.id)return`buildsOn: ${L??"it can start now"}`;if(d.status==="done")return`dependsOn: ${L??"it can start now"}`;return`dependsOn: it starts once ${d.id} is done${L?` (${L})`:""}, or now from its branch (task_update buildsOn ${d.id}, then task_start)`},v=w.slice(0,Fg).map((x)=>`${x.id} "${Dd(x.title)}" (${y(x)})`),S=w.length>Fg?` and ${w.length-Fg} more`:"";return{ids:w.map((x)=>x.id),text:`Waiting on it: ${v.join("; ")}${S}.`}}async function vP(d,u,p){let w=yM(d),v=w.some((x)=>x.type==="task_ready"||x.type==="task_done")?await u(d.task.projectId).catch(()=>{return}):void 0,S=v&&kM(d.task,v);for(let x of w)p(S&&(x.type==="task_ready"||x.type==="task_done")?{...x,text:`${x.text} ${S.text}`,...x.userApproves?{userApproves:`${x.userApproves} ${S.text}`}:{},waiting:S.ids}:x)}class Hg{held=new Map;async lock(d,u,p,w,y=600000){let v=Bg(d,u),S=Date.now(),x=this.held.get(v);if(!x)return this.held.set(v,{holder:p,since:S,waiting:[]}),{waitedMs:0};if(x.holder===p)return{waitedMs:0};return await new Promise((j,L)=>{let N={id:p,take:()=>Y(j)},B=(ne)=>{x.waiting=x.waiting.filter((ie)=>ie!==N),Y(()=>L(Error(ne)))},G=setTimeout(()=>B(`"${u}" is still held by another session after ${Math.round(y/60000)} min`),y),V=()=>B("stopped waiting"),Y=(ne)=>{clearTimeout(G),w.removeEventListener("abort",V),ne()};w.addEventListener("abort",V,{once:!0}),x.waiting.push(N)}),{waitedMs:Date.now()-S}}unlock(d,u,p){let w=Bg(d,u),y=this.held.get(w);if(y?.holder!==p)return!1;return this.handOn(w,y),!0}releaseAll(d){for(let[u,p]of this.held)if(p.holder===d)this.handOn(u,p)}list(d){let u=Bg(d,"");return[...this.held].filter(([p])=>p.startsWith(u)).map(([p,w])=>({name:p.slice(u.length),holder:w.holder,since:new Date(w.since).toISOString(),waiting:w.waiting.map((y)=>y.id)}))}handOn(d,u){let p=u.waiting.shift();if(!p){this.held.delete(d);return}u.holder=p.id,u.since=Date.now(),p.take()}}var Bg=(d,u)=>`${d.projectId}/${d.taskId}/${u}`;var Gg="superfactory",SP=5,bM=120000,vM=(d)=>`Task ${d} is closed. Wrap up now: commit or note what's left (tell the lead with SendMessage if it matters), then stop. You are ended when this turn ends.`,SM=(d)=>`Task ${d} is closed. Wrap up now: commit or note what's left, then stop. This session ends when this turn ends; it goes on from here if the task is reopened.`,PM=(d)=>`${d} waits for a person to merge it, so this Claude stopped meanwhile. It goes on here, in the same conversation, if a review comment, a merge problem or a message comes.`,PP=`too many messages back and forth without a person (${ps*2} in a row): stop here and wait for a person to write to you; what they should know, put on your task with task_comment. A teammate's report to its own task's lead still gets through`,$M=new Set(["starting","running","waiting_input","stopping"]);class Vg{deps;members=new Map;saving=Promise.resolve();acted=new Set;said=new Map;heads=new Map;early=new Map;nameOnServer;locks=new Hg;constructor(d){this.deps=d;d.watchers.addSource((u)=>this.watchersOf(u))}async load(){let d=await Ge(m().teams,{}).catch((u)=>(s.warn("teams: starting empty",u),{}));this.members=new Map(Object.entries(d))}async team(d){let u=await this.deps.tasks.get(d),p=[...this.members.values()].filter((x)=>Ds(x,d)),w=u.sessionId?p.find((x)=>x.sessionId===u.sessionId)??{...d,sessionId:u.sessionId,watch:[]}:void 0,y=p.filter((x)=>x.teammate).sort((x,j)=>(x.teammate?.name??"").localeCompare(j.teammate?.name??"")),v=(await this.deps.projects.settings(d.projectId))["agents.maxTeammates"],S=[...w?[w]:[],...y];return{...d,members:S.map(IM),maxTeammates:v}}async start(d,u){let{projectId:p,taskId:w}=d,y=d.teammate&&Kt.parse(d.teammate),v=d.watch&&ke.array().parse(d.watch),S=this.deps.sessions();if(!y||!p||!w){let V=await S.start(d);if(v&&V.projectId&&V.taskId)await this.setWatch({projectId:V.projectId,taskId:V.taskId},V.id,v);return V}let x={projectId:p,taskId:w},j=this.byName(x,y.name);if(j?.nodeId&&!j.endedAt)throw new c("conflict",`"${y.name}" is already on ${w}'s team, on ${j.machine}: write to it with SendMessage`);let L=j?.nodeId?void 0:j,N=L&&S.find(L.sessionId);if(!N||L?.endedAt){let V=await this.deps.placed.namesake({...x,name:y.name}).catch((Y)=>s.warn(`teams: the server didn't say who else is ${y.name}`,Y));if(V?.sessionId)throw new c("conflict",`${y.name} is already on ${w}${V.machine?`, on ${V.machine}`:""}: stop it (team_stop) or pick another name`)}if(j?.nodeId)this.members.delete(j.sessionId);if(!L||L.endedAt)await this.refuseOverCap(x);if(L&&N){if(L.endedAt=void 0,d.prompt)await S.send(L.sessionId,d.prompt,"user");if(v)await this.setWatch(x,L.sessionId,v);return N}await this.rememberHead(x);let B=await S.start({...d,resume:d.resume??L?.sessionId}),G=L?.sessionId===B.id?L:void 0;if(L&&!G)this.members.delete(L.sessionId);if(this.members.set(B.id,{...x,sessionId:B.id,teammate:y,watch:v??G?.watch??[],addedBy:u??G?.addedBy}),await this.changed(x),u)await this.tellLead(x,`${u} added "${y.name}" to your team: ${y.role.slice(0,300)}`);return B}async joined(d,{waiting:u,...p}){if(p.teammate.leadOn)this.nameOnServer=p.teammate.leadOn;let w=this.byName(d,p.teammate.name);if(w&&w.sessionId!==p.sessionId)this.members.delete(w.sessionId);let y={...d,...p,state:"starting"};this.members.set(p.sessionId,y);let v=this.early.get(p.sessionId);if(this.early.delete(p.sessionId),v?.nodeId===p.nodeId)this.update(y,v);let S=await this.hearTeammatesDone(d),x=await this.changed(d),j=p.addedBy?`${p.addedBy} added`:"You added",L=`${p.machine}${p.platform?` (${p.platform})`:""}`,N=u?`
|
|
598
|
+
${p.machine} is a VM that was stopped: it is starting now, which takes a few minutes. You hear when "${p.teammate.name}" is up; until then it can't read messages.`:"";return await this.tellLead(d,`${j} "${p.teammate.name}" on ${L}: ${p.teammate.role.slice(0,300)}${N}
|
|
599
|
+
It works in its own checkout of this task's branch there: it pushes its commits to the branch, and you take them with git pull --rebase (push yours first when it should have them). SendMessage reaches it by the name ListAgents shows, its machine's in it.${S?" You now hear when a teammate finishes a turn (teammate_done); watch_set changes what wakes you.":""}`),x}async hearTeammatesDone(d){let{sessionId:u}=await this.deps.tasks.get(d);if(!u)return!1;let p=this.members.get(u)??{...d,sessionId:u,watch:[]};if(p.teammate||p.watch.some((w)=>w.event==="teammate_done"))return!1;return p.watch=[...p.watch,{event:"teammate_done",labels:[],taskIds:[]}],this.members.set(u,p),!0}async awayEvent(d,{nodeId:u,sessionId:p,event:w,text:y}){let v=this.members.get(p);if(!v?.teammate||v.nodeId!==u||!Ds(v,d))return;let S=`"${v.teammate.name}"`,x=v.machine??y??"its machine";if(w==="turn_done"){let L=await this.deps.tasks.get(d);this.deps.watchers.emit({type:"teammate_done",...d,labels:L.labels,about:xs(L),actor:p,text:`${qg(y??`${L.id}: ${v.teammate.name} finished a turn`)} (on ${x})`});return}let j={started:`${S} is up on ${x} and starts on its role. SendMessage reaches it by the name ListAgents shows, its machine's in it.`,failed:`${S} couldn't start on ${x}: ${qg(y??"no reason given")}. team_start it again, on another machine if need be.`,offline:`${x}, where ${S} works, went offline: it goes on once the machine is back. To go on without it, team_stop it and team_start another on a machine that is online.`,back:`${x} is back online: ${S} goes on.`}[w];if(w==="failed")v.endedAt=new Date().toISOString();v.state={started:"running",failed:"failed",offline:"offline",back:"idle"}[w],this.members.set(p,v),await this.changed(d),await this.tellLead(d,j)}async awayChanged(d,u,p){for(let w of p){let y=this.members.get(w.sessionId);if(y?.teammate&&y.nodeId===u&&Ds(y,d))this.update(y,w);else if(!y){this.early.set(w.sessionId,{...w,nodeId:u});for(let v of[...this.early.keys()].slice(0,Math.max(0,this.early.size-20)))this.early.delete(v)}}return this.changed(d)}update(d,u){Object.assign(d,{watch:u.watch,status:u.status,endedAt:u.endedAt,state:u.state})}isAway(d){let u=this.members.get(d);return Boolean(u?.teammate?.leadOn&&!u.nodeId)}async publish(d){let u=this.worktree(d);if(!u)return{};let p=(await a(u,(v)=>v.sub("branch").flag("--show-current")).catch(()=>"")).trim();if(!p)return{};if(!Jt(d.taskId,p))return s.warn(`teams: ${d.taskId}'s worktree is on ${p}, not its own branch: not pushed for a teammate`),{};return await(await this.sandboxed(d)?a(u,(v)=>v.sub("push").arg("origin").arg(`HEAD:refs/heads/${p}`)):Nn(u,p)).then(()=>!0,(v)=>(s.warn(`teams: ${d.taskId}'s branch not pushed for a teammate elsewhere`,v),!1))?{branch:p}:{}}async sandboxed(d){let u=await this.deps.tasks.get(d).catch(()=>{return});if(!u||u.runner&&u.runner!=="host")return!0;return!!this.deps.sessions().sandboxPlaceOf(d.projectId,d.taskId)}async tellLead(d,u){let{sessionId:p}=await this.deps.tasks.get(d),w=this.deps.sessions(),y=p&&w.find(p)?.state;if(!p||!y||y==="exited"||y==="failed")return;await w.send(p,`From Superfactory: ${u}`,Gg).catch((v)=>s.warn(`teams: couldn't tell ${d.taskId}'s lead`,v))}async refuseOverCap(d){let u=(await this.deps.projects.settings(d.projectId))["agents.maxTeammates"],p=[...this.members.values()].filter((w)=>Ds(w,d)&&w.teammate&&!w.endedAt).length;if(p>=u)throw new c("conflict",`This task already has ${p} ${p===1?"teammate":"teammates"}; remove one or raise Settings \u203A Agent defaults \u203A Teammates per task`)}async setWatch(d,u,p){let w=this.members.get(u)??await this.leadOf(d,u);return w.watch=p,this.members.set(u,w),this.changed(d)}async remove(d,u){let p=this.members.get(u);if(!p?.teammate||!Ds(p,d))throw new c("not_found",`no teammate ${u} on ${d.taskId}`);return await this.deps.sessions().stop(u).catch(()=>{return}),this.members.delete(u),this.locks.releaseAll(u),this.changed(d)}async describe(d){let u=await this.team(d),p=this.deps.sessions(),w=(y)=>u.members.find((v)=>v.sessionId===y)?.name??y;return{members:u.members.map((y)=>{let v=p.find(y.sessionId),S=!y.endedAt&&!y.nodeId?v:void 0;return{name:y.name,role:y.role,state:y.endedAt?"ended":y.nodeId?y.state??"unknown":S?.queued?"queued":S?.state??"exited",...S?.queued?{waits:He(S.queued)}:{},...S?.state==="failed"&&S.error?{error:S.error}:{},status:y.status?.text,watch:y.watch.map((x)=>x.filePattern?`${x.event} (${x.filePattern})`:x.event),...this.placeOf(y,v)}}),locks:this.locks.list(d).map((y)=>({name:y.name,heldBy:w(y.holder),since:y.since,waiting:y.waiting.map(w)}))}}placeOf(d,u){if(d.nodeId)return{machine:d.machine,platform:d.platform};let{machine:p,os:w}=this.deps.here();return{machine:this.nameOnServer??p,...w?{platform:dg(u?.runner??"host",w)}:{}}}async isLead(d,u){if(this.members.get(u)?.teammate)return!1;return(await this.deps.tasks.get(d)).sessionId===u}async send(d,u,p,w,y={},v=u?this.nextDepth(u,p==="lead"&&!!this.members.get(u)?.teammate):1){if(v>ps*2)throw Error(PP);let S=u?this.members.get(u):void 0;if(u&&S?.teammate?.leadOn&&!S.nodeId){if(await this.deps.placed.teamSend({by:u,...d,to:p,text:w,depth:v}))return;throw Error(`your team is on ${S.teammate.leadOn}, which this machine can't reach now`)}let x=await this.team(d),j=x.members.filter((G)=>G.name===p&&G.sessionId!==u),L=j.filter((G)=>!G.endedAt);if(L.length>1)throw Error(`${L.length} of ${d.taskId}'s team are named "${p}" (${L.map((G)=>G.machine??"here").join(", ")}): write with SendMessage to one by its ref, as ListAgents names it`);let N=L[0]??j[0]??x.members.find((G)=>G.name===p);if(!N)throw Error(`no "${p}" on ${d.taskId}'s team: ${x.members.map((G)=>G.name).join(", ")}`);if(N.sessionId===u)throw Error("that is you");if(N.nodeId){let G=u??y.by;if(!G)throw Error(`${p} runs on ${N.machine}: only the team's sessions and managers write there`);return this.deps.placed.sendTo({by:G,...d,sessionId:N.sessionId,text:w,depth:v})}let B=u&&!y.manager?`${this.nameOf(u)} (your teammate on ${d.taskId})`:y.from?`${y.from} (your teammate on ${d.taskId})`:`${y.manager??"A lead"} (a lead, about ${d.taskId})`;await this.wake(N.sessionId,`From ${B}:
|
|
600
|
+
${w}`,v)}nextDepth(d,u=!1){let p=this.deps.watchers.depthOf(d)+1;if(p<=ps*2)return p;if(u)return ps*2;throw Error(PP)}byName(d,u){return[...this.members.values()].find((p)=>Ds(p,d)&&p.teammate?.name===u)}nameOf(d){return this.members.get(d)?.teammate?.name??"lead"}othersBusy(d){let{projectId:u,taskId:p}=d;return this.deps.sessions().busy().some((w)=>w.id!==d.id&&w.projectId===u&&w.taskId===p)}async statusAnswered(d,u){let p=$P(d);if(!p)return;let w=this.members.get(d.id)??await this.leadOf(p,d.id).catch(()=>{return});if(!w)return;if(w.status={text:u,at:new Date().toISOString()},this.members.set(d.id,w),w.teammate&&/^done\b/i.test(u))await this.end(w);else await this.changed(p)}async stuck(d,u){let p=$P(d);if(!p)return;let w=await this.deps.tasks.get(p),y=this.nameOf(d.id),v=`${w.id}: ${y} made no progress on two status checks: ${u}`;this.deps.watchers.emit({type:"task_stuck",...p,ownAgent:w.sessionId===d.id,labels:w.labels,about:xs(w),actor:d.id,text:v});let x=(w.sessionId&&w.sessionId!==d.id?this.members.get(w.sessionId):void 0)?.watch.some((j)=>j.event==="task_stuck");if(this.isAway(d.id))return void await this.deps.placed.teamSend({by:d.id,...p,to:"lead",text:`${v}. Look at what I need.`,depth:1}).catch((j)=>s.warn(`teams: couldn't tell ${w.id}'s lead`,j));if(this.members.get(d.id)?.teammate&&w.sessionId&&!x)await this.deps.sessions().send(w.sessionId,`From Superfactory: ${v}. Look at what it needs, or take it off the team.`,Gg).catch((j)=>s.warn(`teams: couldn't tell ${w.id}'s lead`,j))}ended(d){return Boolean(this.members.get(d)?.endedAt)}async endSessions(d){let u={projectId:d.projectId,taskId:d.id},p=[...this.members.values()].filter((y)=>Ds(y,u)&&y.teammate&&!y.endedAt&&!y.nodeId),w=this.deps.sessions().sessionForTask(d.projectId,d.id);return await Promise.all([...p.map((y)=>this.end(y)),...w?[this.stopSession(w,SM(d.id))]:[]]),[...p.map((y)=>y.sessionId),...w?[w]:[]]}async rest(d){let u={projectId:d.projectId,taskId:d.id},p=this.deps.sessions(),w=(x)=>p.find(x)?.state==="idle",y=[...this.members.values()].filter((x)=>Ds(x,u)&&x.teammate&&!x.endedAt&&!x.nodeId&&w(x.sessionId));await Promise.all(y.map((x)=>this.end(x)));let v=p.sessionForTask(d.projectId,d.id),S=v?await p.rest(v,PM(d.id)).catch(()=>!1):!1;return[...y.map((x)=>x.sessionId),...v&&S?[v]:[]]}async stopSession(d,u){let p=this.deps.sessions(),w=p.find(d)?.state;await(w&&$M.has(w)?p.wrapUp(d,bM,u):p.stop(d)).catch((v)=>s.warn(`teams: couldn't end ${d}`,v))}async end(d){await this.stopSession(d.sessionId,vM(d.taskId)),this.locks.releaseAll(d.sessionId),d.endedAt=new Date().toISOString(),this.members.set(d.sessionId,d),s.info(`teams: ${d.teammate?.name} on ${d.taskId} ended`),await this.changed(d)}async wake(d,u,p,w,y){this.deps.watchers.woke(d,p);let v=this.deps.sessions(),S=this.members.get(d);if(!v.find(d)&&S?.teammate){await v.start({projectId:S.projectId,taskId:S.taskId,kind:"task",teammate:S.teammate,resume:d,prompt:u,relay:y}),this.deps.watchers.woke(d,p);return}await v.send(d,u,Gg,{reply:w,relay:y})}async watchersOf(d){let u=[...this.members.values()].filter((w)=>w.projectId===d&&w.watch.length&&!w.endedAt&&!w.nodeId),p=await Promise.all(u.map((w)=>this.deps.tasks.get(w).then((y)=>Le.includes(y.status)&&this.stillOn(y,w)).catch(()=>!1)));return u.filter((w,y)=>p[y]).map((w)=>({id:w.sessionId,subscriptions:w.watch,onlyTask:w.taskId,wake:(y,v)=>this.wake(w.sessionId,y,v)}))}stillOn(d,u){return Boolean(u.teammate)||d.sessionId===u.sessionId}onEvent(d,u){let p=d.id;if(!d.projectId||!d.taskId)return;switch(u.type){case"init":this.acted.delete(p),this.said.delete(p);return;case"tool_use":if(!u.parentToolUseId)this.acted.add(p);return;case"assistant_text":if(!u.delta&&!u.parentToolUseId)this.said.set(p,u.text);return;case"result":if(this.locks.releaseAll(p),!this.acted.has(p))return;this.acted.delete(p),this.turnDone(d,u.outcome).catch((w)=>s.warn(`teams: ${p}'s turn not reported`,w));return;case"state":if(u.state==="exited"||u.state==="failed")this.locks.releaseAll(p);if(this.isAway(p))this.changed({projectId:d.projectId,taskId:d.taskId}).catch((w)=>s.warn(`teams: ${p}'s state not passed on`,w));return}}async turnDone(d,u){let p={projectId:d.projectId??"",taskId:d.taskId??""},w=await this.deps.tasks.get(p),y=qg(this.said.get(d.id)??""),v=`${w.id}: ${this.nameOf(d.id)} finished a turn${u==="success"?"":` (${u})`}${y?`: ${y}`:""}`;if(this.deps.watchers.emit({type:"teammate_done",...p,labels:w.labels,about:xs(w),actor:d.id,text:v}),this.isAway(d.id))this.deps.push({type:"team.awayTurnDone",...p,sessionId:d.id,text:v})}async onTurnSynced(d){let{projectId:u,taskId:p}=d;if(!u||!p)return;let w={projectId:u,taskId:p},y=this.worktree(w);if(!y)return;let v=`${u}/${p}`,S=this.heads.get(v),x=await IP(y);if(!x)return;if(this.heads.set(v,x),!S||S===x)return;let[j,L]=await Promise.all([a(y,(V)=>V.sub("log").flag("--format","%h %s").flag("--max-count",50).arg(`${S}..${x}`)),a(y,(V)=>V.sub("diff").flag("--name-only").arg(S).arg(x))]).catch(()=>["",""]),N=j.split(`
|
|
601
|
+
`).filter(Boolean);if(!N.length)return;let B=await this.deps.tasks.get(w),G=N.slice(0,SP).join("; ");this.deps.watchers.emit({type:"new_commits",...w,labels:B.labels,about:xs(B),files:L.split(`
|
|
602
|
+
`).filter(Boolean),actor:d.id,text:`${B.id}: ${N.length} new commit${N.length===1?"":"s"} by ${this.nameOf(d.id)}: ${G}${N.length>SP?"; \u2026":""}`})}async rememberHead(d){let u=this.worktree(d),p=u&&await IP(u);if(p&&!this.heads.has(`${d.projectId}/${d.taskId}`))this.heads.set(`${d.projectId}/${d.taskId}`,p)}worktree(d){let u=this.deps.projects.path(d.projectId),p=ee(u,d.taskId);return p===u?void 0:p}async leadOf(d,u){if((await this.deps.tasks.get(d)).sessionId!==u)throw new c("not_found",`session ${u} isn't on ${d.taskId}'s team`);return{...d,sessionId:u,watch:[]}}async changed(d){this.saving=this.saving.then(()=>$e(m().teams,Object.fromEntries(this.members),384).catch((w)=>s.warn("teams: not saved",w))),await this.saving;let u=await this.team(d),p=u.members.filter((w)=>this.isAway(w.sessionId));if(p.length){let w=this.deps.sessions(),y=p.map((v)=>({...v,state:w.find(v.sessionId)?.state??"exited"}));this.deps.push({type:"team.awayChanged",...d,members:y})}else this.deps.push({type:"team.changed",team:u});return u}}function IM(d){return{sessionId:d.sessionId,name:d.teammate?.name??"lead",role:d.teammate?.role??"",lead:!d.teammate,watch:d.watch,status:d.status,endedAt:d.endedAt,addedBy:d.addedBy,...d.nodeId?{nodeId:d.nodeId,machine:d.machine,state:d.state,platform:d.platform}:{}}}var $P=({projectId:d,taskId:u})=>d&&u?{projectId:d,taskId:u}:void 0,Ds=(d,u)=>d.projectId===u.projectId&&d.taskId===u.taskId;async function IP(d){return(await a(d,(p)=>p.sub("rev-parse").arg("HEAD")).catch(()=>"")).trim()||void 0}function qg(d){let u=d.replace(/\s+/g," ").trim();return u.length>200?`${u.slice(0,199)}\u2026`:u}import{readFileSync as TM,statSync as RM}from"fs";import{open as AM}from"fs/promises";import{dirname as TP}from"path";var EM=t({sessionId:e(),projectId:e(),taskId:e().optional(),runFile:e(),log:e(),head:e(),queuedAt:e(),tries:i().min(0).default(0)}),CM=o(EM),_M=5000,OM=120000,xM=20,MM=65536,jM=30;function LM(d){try{return process.kill(d,0),!0}catch(u){return u.code==="EPERM"}}function NM(d){try{return JSON.parse(TM(d,"utf8"))}catch{return}}async function RP(d){try{let u=RM(d).size,p=await AM(d,"r");try{let w=Math.min(u,MM),y=Buffer.alloc(w);return await p.read(y,0,w,u-w),y.toString("utf8")}finally{await p.close()}}catch{return""}}function AP(d){let u=d.trimEnd().split(`
|
|
603
|
+
`),p=u.findLastIndex((y)=>y.startsWith("\u2500\u2500 ready summary"));return(p>=0?u.slice(p+1):u).slice(-jM).join(`
|
|
604
|
+
`)}function DM(d,u,p=Date.now()){if(!d)return{kind:"died",why:"its run file is gone"};if(d.exit!==void 0)return{kind:d.exit===0?"passed":"failed",exit:d.exit,signal:d.signal};if(d.pid===void 0)return p-Date.parse(u)>OM?{kind:"died",why:"it never started"}:void 0;return LM(d.pid)?void 0:{kind:"died",why:`its process (pid ${d.pid}) is gone without an end`}}async function UM(d,u){let p=d.head.slice(0,12);if(u.kind==="died")return`Superfactory: your \`bun run ready\` of ${p} died without a result: ${u.why} (killed with its agent, or out of memory?). Its log: ${d.log}
|
|
605
|
+
Run \`bun run ready\` again, once; it goes on apart from you, and its result comes as a message like this one.
|
|
606
|
+
|
|
607
|
+
Its log's last lines:
|
|
608
|
+
${AP(await RP(d.log))}`;let w=u.kind==="passed"?"passed":`failed (exit ${u.exit}${u.signal?`, stopped by ${u.signal}`:""})`,y=u.kind==="passed"?"Go on with your task's next steps.":"Fix what failed, commit, push, and run `bun run ready` again.";return`Superfactory: your \`bun run ready\` of ${p} ${w}. Its log: ${d.log}
|
|
609
|
+
${y}
|
|
610
|
+
|
|
611
|
+
${AP(await RP(d.log))}`}class Yg{deps;file;runs=[];timer;polling;constructor(d,u=m().readyRuns){this.deps=d;this.file=u}async load(){if(this.runs=await Ge(this.file,[],(d)=>CM.parse(d)).catch((d)=>(s.warn("ready runs: couldn't read the queued runs",d),[])),this.runs.length)s.info(`ready runs: ${this.runs.length} handed over by the agent before`);this.timer=setInterval(()=>void this.poll(),k("SUPERFACTORY_READY_POLL_MS",_M)),this.timer.unref?.(),await this.poll()}async queue(d){let u=TP(d.runFile);this.runs=[...this.runs.filter((p)=>TP(p.runFile)!==u),{...d,queuedAt:new Date().toISOString(),tries:0}],await this.save(),s.info(`ready runs: ${d.sessionId}'s run of ${d.head.slice(0,12)} queued (${d.runFile})`)}awaits(d){return this.runs.some((u)=>u.sessionId===d)}poll(){return this.polling??=this.look().finally(()=>{this.polling=void 0}),this.polling}async look(){let d=!1;for(let u of[...this.runs]){let p=DM(NM(u.runFile),u.queuedAt);if(!p)continue;if(this.deps.gone?.(u.sessionId)){s.info(`ready runs: ${u.sessionId} is gone; its run's result (${p.kind}) told to nobody`),this.drop(u),d=!0;continue}try{await this.deps.tell(u.sessionId,await UM(u,p)),s.info(`ready runs: ${u.sessionId} told its run ${p.kind}`),this.drop(u)}catch(w){if(u.tries++,s.warn(`ready runs: couldn't tell ${u.sessionId} (try ${u.tries})`,w),u.tries>=xM)this.drop(u)}d=!0}if(d)await this.save()}drop(d){this.runs=this.runs.filter((u)=>u!==d)}save(){return $e(this.file,this.runs).catch((d)=>s.warn("ready runs: couldn't keep the queued runs",d))}stop(){clearInterval(this.timer)}}import{existsSync as BP}from"fs";import{mkdir as XM,readFile as ZM,writeFile as HP}from"fs/promises";import{join as Ud}from"path";var EP="./tray-4rr0y1dv.png";var CP="./tray-mac-tvtavf0g.png";var _P="./tray-mac-offline-89dva0gs.png";var OP="./tray-mac-paused-hq3a1cxv.png";var xP="./tray-offline-xj6b5ta4.png";var MP="./tray-paused-6pzdv5ze.png";var jP=`"""The Superfactory agent's tray on a Linux desktop (T-407): a StatusNotifierItem through Ayatana's (or the
|
|
612
|
+
older) AppIndicator, else GTK's StatusIcon. The agent (apps/agent/src/features/tray) sends the menu on stdin,
|
|
613
|
+
one JSON object a line ({icon, tooltip, items}); a click answers {"clicked": "<id>"} on stdout. It ends when
|
|
614
|
+
stdin closes. Exit 3: no tray can show here (no GTK, no indicator), which the agent doesn't try again."""
|
|
615
|
+
|
|
616
|
+
import json
|
|
617
|
+
import os
|
|
618
|
+
import sys
|
|
619
|
+
|
|
620
|
+
try:
|
|
621
|
+
import gi
|
|
622
|
+
|
|
623
|
+
gi.require_version("Gtk", "3.0")
|
|
624
|
+
from gi.repository import GLib, Gtk
|
|
625
|
+
except (ImportError, ValueError) as error:
|
|
626
|
+
print(f"no GTK for Python here (python3-gi): {error}", file=sys.stderr)
|
|
627
|
+
sys.exit(3)
|
|
628
|
+
|
|
629
|
+
Indicator = None
|
|
630
|
+
for name, version in (("AyatanaAppIndicator3", "0.1"), ("AppIndicator3", "0.1")):
|
|
631
|
+
try:
|
|
632
|
+
gi.require_version(name, version)
|
|
633
|
+
Indicator = getattr(__import__("gi.repository", fromlist=[name]), name)
|
|
634
|
+
break
|
|
635
|
+
except (ImportError, ValueError):
|
|
636
|
+
continue
|
|
637
|
+
|
|
638
|
+
if not Gtk.init_check(sys.argv)[0]:
|
|
639
|
+
print("GTK can't open the display", file=sys.stderr)
|
|
640
|
+
sys.exit(3)
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def send(message):
|
|
644
|
+
sys.stdout.write(json.dumps(message) + "\\n")
|
|
645
|
+
sys.stdout.flush()
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def menu_of(items):
|
|
649
|
+
menu = Gtk.Menu()
|
|
650
|
+
for entry in items:
|
|
651
|
+
if entry.get("separator"):
|
|
652
|
+
menu.append(Gtk.SeparatorMenuItem())
|
|
653
|
+
continue
|
|
654
|
+
line = Gtk.MenuItem(label=entry["label"])
|
|
655
|
+
if entry.get("items"):
|
|
656
|
+
line.set_submenu(menu_of(entry["items"]))
|
|
657
|
+
elif entry.get("id"):
|
|
658
|
+
line.connect("activate", lambda _, action=entry["id"]: send({"clicked": action}))
|
|
659
|
+
line.set_sensitive(entry.get("enabled", True) is not False and bool(entry.get("id") or entry.get("items")))
|
|
660
|
+
menu.append(line)
|
|
661
|
+
menu.show_all()
|
|
662
|
+
return menu
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
class Tray:
|
|
666
|
+
def __init__(self):
|
|
667
|
+
self.indicator = None
|
|
668
|
+
self.icon = None
|
|
669
|
+
self.menu = Gtk.Menu()
|
|
670
|
+
self.shown = False
|
|
671
|
+
self.last_icon = ""
|
|
672
|
+
if Indicator:
|
|
673
|
+
self.indicator = Indicator.Indicator.new(
|
|
674
|
+
"superfactory-agent", "", Indicator.IndicatorCategory.APPLICATION_STATUS
|
|
675
|
+
)
|
|
676
|
+
self.indicator.set_status(Indicator.IndicatorStatus.ACTIVE)
|
|
677
|
+
else:
|
|
678
|
+
self.icon = Gtk.StatusIcon()
|
|
679
|
+
self.icon.connect("popup-menu", self.popup)
|
|
680
|
+
self.icon.connect("activate", lambda _: self.popup(self.icon, 1, Gtk.get_current_event_time()))
|
|
681
|
+
|
|
682
|
+
def popup(self, icon, button, time):
|
|
683
|
+
self.menu.popup(None, None, Gtk.StatusIcon.position_menu, icon, button, time)
|
|
684
|
+
|
|
685
|
+
def show(self, model):
|
|
686
|
+
self.menu = menu_of(model["items"])
|
|
687
|
+
if not os.path.exists(model["icon"]):
|
|
688
|
+
model = {**model, "icon": self.last_icon}
|
|
689
|
+
self.last_icon = model["icon"]
|
|
690
|
+
if self.indicator:
|
|
691
|
+
self.indicator.set_icon_full(model["icon"], model["tooltip"])
|
|
692
|
+
self.indicator.set_title(model["tooltip"])
|
|
693
|
+
self.indicator.set_menu(self.menu)
|
|
694
|
+
else:
|
|
695
|
+
self.icon.set_from_file(model["icon"])
|
|
696
|
+
self.icon.set_tooltip_text(model["tooltip"])
|
|
697
|
+
self.icon.set_visible(True)
|
|
698
|
+
if not self.shown:
|
|
699
|
+
self.shown = True
|
|
700
|
+
send({"ready": True})
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
tray = Tray()
|
|
704
|
+
pending = b""
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def heard(fd, condition):
|
|
708
|
+
global pending
|
|
709
|
+
chunk = os.read(fd, 65536) if condition & GLib.IO_IN else b""
|
|
710
|
+
if not chunk:
|
|
711
|
+
Gtk.main_quit()
|
|
712
|
+
return False
|
|
713
|
+
pending += chunk
|
|
714
|
+
*lines, pending = pending.split(b"\\n")
|
|
715
|
+
last = [line for line in lines if line.strip()]
|
|
716
|
+
if last:
|
|
717
|
+
try:
|
|
718
|
+
tray.show(json.loads(last[-1]))
|
|
719
|
+
except Exception as error: # noqa: BLE001 - said to the agent, and the next menu tries again
|
|
720
|
+
send({"error": f"the menu didn't show: {error}"})
|
|
721
|
+
return True
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
GLib.io_add_watch(sys.stdin.fileno(), GLib.IO_IN | GLib.IO_HUP, heard)
|
|
725
|
+
Gtk.main()
|
|
726
|
+
`;var LP=`// The Superfactory agent's menu bar on a Mac (T-407): an NSStatusItem, from JavaScript for Automation
|
|
727
|
+
// (osascript -l JavaScript). The agent (apps/agent/src/features/tray) sends the menu on stdin, one JSON
|
|
728
|
+
// object a line ({icon, tooltip, items}); a click answers {"clicked": "<id>"} on stdout. It ends when
|
|
729
|
+
// stdin closes, or once its agent is gone (its parent changed) or its folder deleted: an osascript left
|
|
730
|
+
// behind spins at full CPU.
|
|
731
|
+
ObjC.import("Cocoa");
|
|
732
|
+
ObjC.import("stdlib");
|
|
733
|
+
ObjC.bindFunction("getppid", ["int", []]);
|
|
734
|
+
|
|
735
|
+
function run() {
|
|
736
|
+
const app = $.NSApplication.sharedApplication;
|
|
737
|
+
// No Dock icon, no menu of its own: the menu bar item only.
|
|
738
|
+
app.setActivationPolicy($.NSApplicationActivationPolicyAccessory);
|
|
739
|
+
const item = $.NSStatusBar.systemStatusBar.statusItemWithLength($.NSVariableStatusItemLength);
|
|
740
|
+
const stdout = $.NSFileHandle.fileHandleWithStandardOutput;
|
|
741
|
+
const stdin = $.NSFileHandle.fileHandleWithStandardInput;
|
|
742
|
+
const send = (message) =>
|
|
743
|
+
stdout.writeData($(\`\${JSON.stringify(message)}\\n\`).dataUsingEncoding($.NSUTF8StringEncoding));
|
|
744
|
+
const images = {};
|
|
745
|
+
const image = (path) => {
|
|
746
|
+
if (!images[path]) {
|
|
747
|
+
const loaded = $.NSImage.alloc.initWithContentsOfFile(path);
|
|
748
|
+
// Gone or unreadable: the icon it has stays.
|
|
749
|
+
if (loaded.isNil()) return undefined;
|
|
750
|
+
loaded.setSize($.NSMakeSize(18, 18));
|
|
751
|
+
// Drawn in the menu bar's own colour, light or dark.
|
|
752
|
+
loaded.setTemplate(true);
|
|
753
|
+
images[path] = loaded;
|
|
754
|
+
}
|
|
755
|
+
return images[path];
|
|
756
|
+
};
|
|
757
|
+
let pending = "";
|
|
758
|
+
let shown = false;
|
|
759
|
+
// Its agent and its folder (the agent's home's tray/), as it started.
|
|
760
|
+
const parent = $.getppid();
|
|
761
|
+
const args = ObjC.deepUnwrap($.NSProcessInfo.processInfo.arguments);
|
|
762
|
+
const script = args.find((arg) => /tray\\.jxa$/.test(arg)) || "";
|
|
763
|
+
const folder = script.replace(/\\/[^/]*$/, "");
|
|
764
|
+
const end = () => {
|
|
765
|
+
$.NSStatusBar.systemStatusBar.removeStatusItem(item);
|
|
766
|
+
$.exit(0);
|
|
767
|
+
};
|
|
768
|
+
|
|
769
|
+
ObjC.registerSubclass({
|
|
770
|
+
name: "SuperfactoryTray",
|
|
771
|
+
methods: {
|
|
772
|
+
"clicked:": {
|
|
773
|
+
types: ["void", ["id"]],
|
|
774
|
+
implementation: (sender) => send({ clicked: ObjC.unwrap(sender.representedObject) }),
|
|
775
|
+
},
|
|
776
|
+
"tick:": {
|
|
777
|
+
types: ["void", ["id"]],
|
|
778
|
+
implementation: () => {
|
|
779
|
+
const gone = folder && !$.NSFileManager.defaultManager.fileExistsAtPath(folder);
|
|
780
|
+
// Its agent gone: its parent is another (launchd's 1, an agent never is).
|
|
781
|
+
const ppid = $.getppid();
|
|
782
|
+
if (ppid !== parent || ppid === 1 || gone) end();
|
|
783
|
+
},
|
|
784
|
+
},
|
|
785
|
+
"heard:": {
|
|
786
|
+
types: ["void", ["id"]],
|
|
787
|
+
implementation: (note) => {
|
|
788
|
+
const data = note.userInfo.objectForKey($.NSFileHandleNotificationDataItem);
|
|
789
|
+
// JXA gives NSData's length as a string ("0" at the end): compared as one, the end was never
|
|
790
|
+
// seen, and the read was asked again and again at full CPU.
|
|
791
|
+
if (!data || Number(data.length) === 0) return end();
|
|
792
|
+
pending += ObjC.unwrap($.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding));
|
|
793
|
+
const lines = pending.split("\\n");
|
|
794
|
+
pending = lines.pop();
|
|
795
|
+
const last = lines.filter((line) => line.trim()).pop();
|
|
796
|
+
if (last)
|
|
797
|
+
try {
|
|
798
|
+
show(JSON.parse(last));
|
|
799
|
+
if (!shown) {
|
|
800
|
+
shown = true;
|
|
801
|
+
send({ ready: true });
|
|
802
|
+
}
|
|
803
|
+
} catch (error) {
|
|
804
|
+
send({ error: \`the menu didn't show: \${error}\` });
|
|
805
|
+
}
|
|
806
|
+
stdin.readInBackgroundAndNotify;
|
|
807
|
+
},
|
|
808
|
+
},
|
|
809
|
+
},
|
|
810
|
+
});
|
|
811
|
+
const target = $.SuperfactoryTray.alloc.init;
|
|
812
|
+
|
|
813
|
+
const menuOf = (items) => {
|
|
814
|
+
const menu = $.NSMenu.alloc.init;
|
|
815
|
+
menu.autoenablesItems = false;
|
|
816
|
+
for (const entry of items) {
|
|
817
|
+
if (entry.separator) {
|
|
818
|
+
menu.addItem($.NSMenuItem.separatorItem);
|
|
819
|
+
continue;
|
|
820
|
+
}
|
|
821
|
+
const line = $.NSMenuItem.alloc.initWithTitleActionKeyEquivalent(entry.label, entry.id ? "clicked:" : null, "");
|
|
822
|
+
if (entry.id) {
|
|
823
|
+
line.target = target;
|
|
824
|
+
line.representedObject = $(entry.id);
|
|
825
|
+
}
|
|
826
|
+
if (entry.items) line.submenu = menuOf(entry.items);
|
|
827
|
+
line.enabled = entry.enabled !== false && !!(entry.id || entry.items);
|
|
828
|
+
menu.addItem(line);
|
|
829
|
+
}
|
|
830
|
+
return menu;
|
|
831
|
+
};
|
|
832
|
+
|
|
833
|
+
const show = (model) => {
|
|
834
|
+
const icon = image(model.icon);
|
|
835
|
+
if (icon) item.button.image = icon;
|
|
836
|
+
item.button.toolTip = model.tooltip;
|
|
837
|
+
item.menu = menuOf(model.items);
|
|
838
|
+
};
|
|
839
|
+
|
|
840
|
+
$.NSNotificationCenter.defaultCenter.addObserverSelectorNameObject(
|
|
841
|
+
target,
|
|
842
|
+
"heard:",
|
|
843
|
+
$.NSFileHandleReadCompletionNotification,
|
|
844
|
+
stdin,
|
|
845
|
+
);
|
|
846
|
+
stdin.readInBackgroundAndNotify;
|
|
847
|
+
$.NSTimer.scheduledTimerWithTimeIntervalTargetSelectorUserInfoRepeats(5, target, "tick:", null, true);
|
|
848
|
+
app.run;
|
|
849
|
+
}
|
|
850
|
+
`;var NP=`# The Superfactory agent's tray on Windows (T-407): an icon in the notification area, drawn with WinForms'
|
|
851
|
+
# NotifyIcon. The agent (apps/agent/src/features/tray) sends the menu on stdin, one JSON object a line
|
|
852
|
+
# ({icon, tooltip, items}); a click answers {"clicked": "<id>"} on stdout. It ends when stdin closes.
|
|
853
|
+
$ErrorActionPreference = 'Stop'
|
|
854
|
+
Add-Type -AssemblyName System.Windows.Forms
|
|
855
|
+
Add-Type -AssemblyName System.Drawing
|
|
856
|
+
[System.Windows.Forms.Application]::EnableVisualStyles()
|
|
857
|
+
|
|
858
|
+
$utf8 = New-Object System.Text.UTF8Encoding $false
|
|
859
|
+
$script:in = New-Object System.IO.StreamReader ([Console]::OpenStandardInput()), $utf8
|
|
860
|
+
$script:out = New-Object System.IO.StreamWriter ([Console]::OpenStandardOutput()), $utf8
|
|
861
|
+
$script:out.AutoFlush = $true
|
|
862
|
+
function Send($message) { $script:out.WriteLine(($message | ConvertTo-Json -Compress)) }
|
|
863
|
+
|
|
864
|
+
$tray = New-Object System.Windows.Forms.NotifyIcon
|
|
865
|
+
$menu = New-Object System.Windows.Forms.ContextMenuStrip
|
|
866
|
+
$tray.ContextMenuStrip = $menu
|
|
867
|
+
# A left click opens the menu too, as the right does.
|
|
868
|
+
$tray.add_MouseUp({
|
|
869
|
+
param($s, $e)
|
|
870
|
+
if ($e.Button -eq [System.Windows.Forms.MouseButtons]::Left) {
|
|
871
|
+
$show = [System.Windows.Forms.NotifyIcon].GetMethod('ShowContextMenu', [Reflection.BindingFlags] 'Instance,NonPublic')
|
|
872
|
+
$show.Invoke($tray, $null)
|
|
873
|
+
}
|
|
874
|
+
})
|
|
875
|
+
|
|
876
|
+
$script:icons = @{}
|
|
877
|
+
function Get-TrayIcon([string] $path) {
|
|
878
|
+
if (-not $script:icons.ContainsKey($path)) {
|
|
879
|
+
$bitmap = New-Object System.Drawing.Bitmap $path
|
|
880
|
+
$script:icons[$path] = [System.Drawing.Icon]::FromHandle($bitmap.GetHicon())
|
|
881
|
+
}
|
|
882
|
+
$script:icons[$path]
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
function Add-TrayItems($into, $items) {
|
|
886
|
+
foreach ($item in $items) {
|
|
887
|
+
if ($item.separator) {
|
|
888
|
+
[void] $into.Add((New-Object System.Windows.Forms.ToolStripSeparator))
|
|
889
|
+
continue
|
|
890
|
+
}
|
|
891
|
+
$entry = New-Object System.Windows.Forms.ToolStripMenuItem ([string] $item.label)
|
|
892
|
+
if ($item.items) { Add-TrayItems $entry.DropDownItems $item.items }
|
|
893
|
+
elseif ($item.id) {
|
|
894
|
+
$entry.Tag = [string] $item.id
|
|
895
|
+
$entry.add_Click({ param($s, $e) Send @{ clicked = $s.Tag } })
|
|
896
|
+
}
|
|
897
|
+
if ($item.enabled -eq $false) { $entry.Enabled = $false }
|
|
898
|
+
[void] $into.Add($entry)
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
function Show-Tray($model) {
|
|
903
|
+
# Gone or unreadable: the icon it has stays.
|
|
904
|
+
try { $tray.Icon = Get-TrayIcon ([string] $model.icon) } catch { if (-not $tray.Icon) { throw } }
|
|
905
|
+
# Windows cuts a tooltip at 63 characters, and WinForms refuses a longer one.
|
|
906
|
+
$tip = [string] $model.tooltip
|
|
907
|
+
if ($tip.Length -gt 63) { $tip = $tip.Substring(0, 62) + [char] 0x2026 }
|
|
908
|
+
$tray.Text = $tip
|
|
909
|
+
$menu.Items.Clear()
|
|
910
|
+
Add-TrayItems $menu.Items $model.items
|
|
911
|
+
$tray.Visible = $true
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
# Stdin is read on a thread of its own (ReadLineAsync); the UI thread looks at it 5 times a second.
|
|
915
|
+
$script:read = $script:in.ReadLineAsync()
|
|
916
|
+
$script:shown = $false
|
|
917
|
+
$timer = New-Object System.Windows.Forms.Timer
|
|
918
|
+
$timer.Interval = 200
|
|
919
|
+
$timer.add_Tick({
|
|
920
|
+
while ($script:read.IsCompleted) {
|
|
921
|
+
$line = if ($script:read.IsFaulted) { $null } else { $script:read.Result }
|
|
922
|
+
if ($null -eq $line) {
|
|
923
|
+
$timer.Stop()
|
|
924
|
+
$tray.Visible = $false
|
|
925
|
+
$tray.Dispose()
|
|
926
|
+
[System.Windows.Forms.Application]::Exit()
|
|
927
|
+
return
|
|
928
|
+
}
|
|
929
|
+
try {
|
|
930
|
+
Show-Tray ($line | ConvertFrom-Json)
|
|
931
|
+
if (-not $script:shown) { $script:shown = $true; Send @{ ready = $true } }
|
|
932
|
+
} catch { Send @{ error = "the menu didn't show: $_" } }
|
|
933
|
+
$script:read = $script:in.ReadLineAsync()
|
|
934
|
+
}
|
|
935
|
+
})
|
|
936
|
+
$timer.Start()
|
|
937
|
+
[System.Windows.Forms.Application]::Run()
|
|
938
|
+
`;var UP=["pause","pause-move","resume","away","open","logs","restart","quit"],QM=(d)=>{try{return d?new URL(d).host:void 0}catch{return d}};function JM(d,u){if(!d)return"";let p=new Date(d);if(Number.isNaN(p.getTime()))return"";let w=p.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"});return p.toDateString()===u.toDateString()?` at ${w}`:` on ${p.toLocaleDateString("en-US",{month:"short",day:"numeric"})}, ${w}`}function zM(d,u=new Date){return`Paused${!d?.by?"":d.by==="machine"?" from this machine":` by @${d.by}`}${JM(d?.at,u)}`}var DP=(d,u)=>`${d} ${u}${d===1?"":"s"}`;function FP(d,u=new Date){let p=QM(d.serverUrl),w=!d.linked?"offline":d.paused?"paused":"linked",y=[];if(d.notice)y.push({label:d.notice,enabled:!1},{separator:!0});if(y.push({label:!p?"Not connected to a server":d.linked?`Connected to ${p}`:`Offline: can't reach ${p}`,enabled:!1}),d.paused)y.push({label:`${zM(d.pause,u)}: it takes no new work`,enabled:!1});if(y.push(d.running.length?{label:`${DP(d.running.length,"session")} running here`,items:d.running.map((x)=>({label:x,enabled:!1}))}:{label:"Nothing running here",enabled:!1}),y.push({separator:!0}),d.paused)y.push({id:"resume",label:"Resume",enabled:d.linked});else if(!d.linked||!d.running.length)y.push({id:"pause",label:d.linked?"Pause":"Pause (needs the server)",enabled:d.linked});else y.push({label:"Pause",items:[{id:"pause",label:`Let ${d.running.length===1?"it":"them"} finish here`},{id:"pause-move",label:"Move the tasks to another machine"}]});if(d.away)y.push({id:"away",label:d.away.since?"Away: Screens Off (on)":"Away: Screens Off"});y.push({separator:!0}),y.push({id:"open",label:"Open Superfactory",enabled:!!p}),y.push({id:"logs",label:"View Logs"}),y.push({separator:!0}),y.push(d.stop==="restart"?{id:"restart",label:"Restart Agent"}:{id:"quit",label:"Quit Agent"});let S=`Superfactory: ${w==="offline"?"offline":w==="paused"?"paused":`connected to ${p}`}${d.running.length?`, ${DP(d.running.length,"session")}`:""}`;return{state:w,tooltip:S,items:y}}var ej=2000,WP=[5000,30000,120000,600000],tj=60000,sj=3,nj=60000;class zg{deps;child;sent="";notice;failures=0;timer;retry;stopped=!1;icons;constructor(d){this.deps=d}async start(){let d=await this.command();if(!d)return;this.timer??=setInterval(()=>this.refresh(),ej),this.timer.unref?.(),this.launch(d)}stop(){this.stopped=!0,clearInterval(this.timer),clearTimeout(this.retry),this.child?.stdin.end(),this.child=void 0}refresh(){let d=this.child;if(!d||!this.icons)return;if(this.notice&&Date.now()>this.notice.until)this.notice=void 0;let u=FP({...this.deps.snapshot(),notice:this.notice?.text}),p=this.icons[u.state];if(!BP(p)){this.writeIcons().then(()=>this.refresh(),()=>{return});return}let w=JSON.stringify({...u,icon:p});if(w===this.sent)return;this.sent=w,d.stdin.write(`${w}
|
|
939
|
+
`)}launch(d){if(this.stopped)return;let u=Date.now(),p;try{p=_(d)}catch(v){s.warn("tray: didn't start",v),this.again(u);return}this.child=p,this.sent="";let w="",y="";p.stdout.setEncoding("utf8"),p.stdout.on("data",(v)=>{y+=v;let S=y.split(`
|
|
940
|
+
`);y=S.pop()??"";for(let x of S)this.heard(x)}),p.stderr.setEncoding("utf8"),p.stderr.on("data",(v)=>{w=(w+v).slice(-2000)}),p.stdin.on("error",()=>{return}),p.on("error",(v)=>s.warn("tray: its script failed",v)),p.on("close",(v)=>{if(this.child===p)this.child=void 0;if(this.stopped)return;let S=w.trim().split(`
|
|
941
|
+
`).slice(-3).join(" / ");if(v===sj){s.info(`tray: none on this desktop${S?`: ${S}`:""}`);return}s.warn(`tray: its script ended (exit ${v})${S?`: ${S}`:""}`),this.again(u)}),this.refresh()}again(d){if(Date.now()-d>=tj)this.failures=0;let u=WP[Math.min(this.failures,WP.length-1)]??0;this.failures++,this.retry=setTimeout(()=>void this.start().catch((p)=>s.warn("tray: didn't start",p)),u),this.retry.unref?.()}heard(d){let u;try{u=JSON.parse(d)}catch{return}if(u.ready)this.failures=0,s.info("tray: showing");if(u.error)s.warn(`tray: ${u.error}`);let p=UP.find((w)=>w===u.clicked);if(p)this.chose(p)}async chose(d){s.info(`tray: ${d}`);try{if(d==="open")await this.openPage();else if(d==="logs")await this.openLogs();else await this.deps.act(d)}catch(u){let p=u.message;s.warn(`tray: ${d} failed`,u),this.notice={text:`${ij[d]} didn't work: ${p}`,until:Date.now()+nj}}this.refresh()}async openPage(){let d=this.deps.page();if(d)await Jg(d)}async openLogs(){let d=Ud(this.deps.home,"agent.log");if(BP(d))return Jg(d);if(process.platform!=="linux")throw Error("this agent writes no log file");let u=await g(r(fu).flag("--user").flag("-u","superfactory-agent").flag("-n","5000").flag("--no-pager").flag("-o","short-iso").by("tray").timeoutMs(15000).build());if(u.exitCode!==0||!u.stdout.trim())throw Error("no log file, and no journal of it");let p=Ud(this.deps.home,"tray","agent-log.txt");await HP(p,u.stdout,{mode:384}),await Jg(p)}async writeIcons(){let d=Ud(this.deps.home,"tray");await XM(d,{recursive:!0,mode:448});let u=process.platform==="darwin"?{linked:CP,paused:OP,offline:_P}:{linked:EP,paused:MP,offline:xP};return this.icons={linked:await Kg(d,"tray.png",u.linked),paused:await Kg(d,"tray-paused.png",u.paused),offline:await Kg(d,"tray-offline.png",u.offline)},d}async command(){let d=process.env.SUPERFACTORY_TRAY_SHELL;if(!d&&(process.env.SUPERFACTORY_TRAY==="0"||process.env.SUPERFACTORY_SANDBOX||X()))return;let u=await this.writeIcons(),p=process.platform==="darwin";if(d)return r(lu).programPath(d).by("tray").build();if(process.platform==="win32")return r(cu).flag("-NoProfile").flag("-NonInteractive").flag("-STA").flag("-ExecutionPolicy","Bypass").flag("-WindowStyle","Hidden").flag("-File",await Qg(u,"tray.ps1",NP)).by("tray").build();if(p)return r(du).flag("-l","JavaScript").arg(await Qg(u,"tray.jxa",LP)).by("tray").build();if(process.platform!=="linux")return;let w=await rj();if(!w){s.info("tray: no desktop here (no DISPLAY or WAYLAND_DISPLAY)");return}return r(uu).flag("-I").arg(await Qg(u,"tray.py",jP)).env(w).by("tray").build()}}var ij={pause:"Pause","pause-move":"Pause",resume:"Resume",away:"Away",open:"Open Superfactory",logs:"View Logs",restart:"Restart",quit:"Quit"};async function Kg(d,u,p){return GP(d,u,Buffer.from(await Bun.file(p).arrayBuffer()))}async function Qg(d,u,p){return GP(d,u,Buffer.from(p,"utf8"))}async function GP(d,u,p){let w=Ud(d,u);if(!await ZM(w).then((v)=>v.equals(p),()=>!1))await HP(w,p,{mode:384});return w}async function rj(){let d=["DISPLAY","WAYLAND_DISPLAY","XAUTHORITY","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR"],u={};for(let p of d)if(process.env[p])u[p]=process.env[p];if(!u.DISPLAY&&!u.WAYLAND_DISPLAY&&process.env.SUPERFACTORY_SERVICE==="systemd"){let p=await g(r(jt).flag("--user").sub("show-environment").by("tray").timeoutMs(1e4).build()).catch(()=>{return});for(let w of p?.exitCode===0?p.stdout.split(`
|
|
942
|
+
`):[]){let y=w.indexOf("="),v=w.slice(0,y);if(y>0&&d.includes(v)&&!u[v])u[v]=w.slice(y+1)}}return u.DISPLAY||u.WAYLAND_DISPLAY?u:void 0}async function Jg(d){let u=process.env.SUPERFACTORY_OPEN,p=process.platform==="win32"&&!u?r(pu).arg(d):r(process.platform==="darwin"?Zs:Qs).programPath(u&&(Bun.which(u)??u)).arg(d),w=await g(p.by("tray").timeoutMs(15000).build());if(w.exitCode!==0&&process.platform!=="win32")throw Error(`couldn't open ${d} (exit ${w.exitCode})`)}import{readFileSync as VP}from"fs";import{rename as oj,stat as aj,writeFile as dj}from"fs/promises";import{homedir as cj}from"os";import{join as qP}from"path";var uj={darwin:"/Library/Application Support/ClaudeCode/managed-settings.json",linux:"/etc/claude-code/managed-settings.json",win32:"C:\\Program Files\\ClaudeCode\\managed-settings.json"},lj=/^\d+\.\d+\.\d+$/;function YP(d,u=process.env){if(d)return d.name.endsWith("@latest")?"latest":"stable";return Zg()??ew(QP(u))??"latest"}async function KP(d,u){if(d==="latest")return{latest:!0,why:"this machine's setting says the newest"};if(d==="own")return{latest:!1,why:"this machine's setting keeps its own channel"};return await u()?{latest:!0,why:"it is set aside for Superfactory"}:{latest:!1,why:"it is someone's own computer: their Claude's channel stays theirs"}}function Zg(){let d=uj[process.platform];return d?ew(d):void 0}var QP=(d)=>qP(d.CLAUDE_CONFIG_DIR||qP(cj(),".claude"),"settings.json");async function JP(d=process.env){let u=QP(d);if(ew(u)!=="stable")return!1;let p=JSON.parse(VP(u,"utf8")),w=(await aj(u)).mode&511,y=`${u}.superfactory-new`,v=`${JSON.stringify({...p,autoUpdatesChannel:"latest"},null,2)}
|
|
943
|
+
`;return await dj(y,v,{mode:w}),await oj(y,u),!0}function ew(d){try{let u=JSON.parse(VP(d,"utf8")).autoUpdatesChannel;return u==="stable"||u==="latest"?u:void 0}catch{return}}async function zP(d,u=process.env){let p=u.SUPERFACTORY_CLAUDE_RELEASES??(X()?void 0:Ht);if(!p)return;try{let w=await fetch(`${p}/${d}`,{signal:AbortSignal.timeout(15000)});if(!w.ok)return;let y=(await w.text()).trim();return lj.test(y)?y:void 0}catch{return}}import{existsSync as n$,realpathSync as wj}from"fs";import{existsSync as pj,realpathSync as hj}from"fs";import{join as mj}from"path";var fj=/^(.+)\/(Caskroom|Cellar)\/([\w@.+-]+)\/[^/]+\//;function nw(d=process.env.SUPERFACTORY_CLAUDE_BIN){let u=Bun.which(d||"claude");if(!u)return;let p=fj.exec(gj(u));if(!p)return;let[,w="",y,v=""]=p,S=mj(w,"bin","brew");if(!pj(S))return;return{brew:S,kind:y==="Caskroom"?"cask":"formula",name:v}}function XP(d,u){return vo(d,"upgrade",d.name,u)}var Fd="claude-code",tw="claude-code@latest",ZP=(d)=>d.kind==="cask"&&d.name===Fd;async function e$(d,u,p){let w=await vo(d,"uninstall",Fd,p);if(!w.ok)return w;let y=await vo(d,"install",tw,p);if(y.ok&&await mt(u))return{ok:!0,output:y.output};let v=y.ok?`${tw} installed, but its claude --version didn't answer`:y.output;if(y.ok)await vo(d,"uninstall",tw,p);let S=await vo(d,"install",Fd,p);return{ok:!1,output:`${v}
|
|
944
|
+
${S.ok?`${Fd} is back`:S.output}`.trim()}}async function vo(d,u,p,w){let y=r($t).programPath(d.brew).sub(u).flag(d.kind==="cask"?"--cask":"--formula").arg(p).env({HOMEBREW_AUTO_UPDATE_SECS:"3600",HOMEBREW_NO_ENV_HINTS:"1",HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK:"1",NONINTERACTIVE:"1"}).timeoutMs(900000).by("claude update").build();try{let v=await g(y,{onStart:w,detached:!0});return{ok:v.exitCode===0,output:`${v.stdout}
|
|
945
|
+
${v.stderr}`.trim()}}catch(v){return{ok:!1,output:v instanceof Error?v.message:String(v)}}}function gj(d){try{return hj(d)}catch{return d}}var So=60000,t$=()=>k("SUPERFACTORY_UPDATE_PATIENCE_MS",30*So),s$=()=>k("SUPERFACTORY_UPDATE_CAP_MS",120*So),ks=(d)=>d>=So?`${Math.round(d/So)} min`:`${d/1000} s`;class Po{here;what;since;constructor(d,u="update"){this.here=d;this.what=u}get waitingSince(){return this.since}waitFrom(d){this.since=Math.min(this.since??d,d)}now(d=Date.now()){if(!this.here.ready())return!1;this.since??=d;let u=d-this.since;if(this.here.idle())return!0;if(u>=t$()&&this.here.betweenTools())return s.info(`${this.what}: no idle moment in ${ks(u)}: updating between tool calls`),!0;if(u<s$())return!1;return s.warn(`${this.what}: no idle moment in ${ks(u)}: updating anyway; the turns it cuts resume`),!0}wanted(d=Date.now()){this.since??=d}when(d=Date.now()){let u=(p)=>Math.max(0,Math.ceil((p-(this.since?d-this.since:0))/So));return`once no turn runs here, between two tool calls in ${u(t$())} min, at the latest in ${u(s$())} min`}reset(){this.since=void 0}}var Hd=()=>k("SUPERFACTORY_CLAUDE_UPDATE_MS",3600000),yj=()=>k("SUPERFACTORY_CLAUDE_UPDATE_MS",300000),kj=()=>Math.min(60000,Hd()),bj=()=>k("SUPERFACTORY_CLAUDE_FRESH_MS",900000),vj=()=>k("SUPERFACTORY_CLAUDE_START_WAIT_MS",120000),Sj=1500;class rw{deps;auto=!1;why="not checked yet";last;found;follows;timer;first;idleTimer;running;updating;stopped=!1;moment;constructor(d){this.deps=d;this.moment=new Po(d.here,"claude update")}get state(){return{auto:this.auto,...this.why?{why:this.why}:{},...this.auto&&this.follows?{follow:this.follows}:{},...this.last?{last:this.last}:{}}}get version(){return this.found}start(){this.allowed(),this.first=setTimeout(()=>this.due(),yj()),this.timer=setInterval(()=>this.due(),Hd()),this.first.unref?.(),this.timer.unref?.()}async stop(d=1e4){this.stopped=!0,clearTimeout(this.first),clearInterval(this.timer),clearInterval(this.idleTimer);let u=this.running;if(!u)return;if(await Promise.race([u.then(()=>!0),Bun.sleep(d).then(()=>!1)])||this.updating===void 0)return;s.warn("claude update: still running as the agent stops: ending it"),await Tt(this.updating)}async allowed(){let d=Pj()??(await this.deps.enabled()?void 0:"turned off in this machine's settings"),u=d?void 0:await this.followsNow();if(d!==this.why||this.auto!==!d||JSON.stringify(u)!==JSON.stringify(this.follows))this.auto=!d,this.why=d,this.follows=u,this.deps.changed();return this.auto}async followsNow(){if(Zg()==="stable")return{latest:!1,why:"its organization's managed settings say stable"};return this.deps.follow?.()}async beforeStart(){if(this.stopped||!this.deps.here.ready())return;let d=this.last?Date.parse(this.last.at):void 0;if(d!==void 0&&Date.now()-d<bj())return;if(process.platform==="win32"&&this.deps.claudeRuns?.())return;let u=this.check();clearInterval(this.idleTimer),this.idleTimer=void 0,this.moment.reset();let p,w=new Promise((v)=>{p=setTimeout(()=>v(!1),vj())});if(!await Promise.race([u.then(()=>!0),w]).finally(()=>clearTimeout(p)))s.warn("claude update: still running as a session starts: it starts on the Claude Code there")}due(){let d=()=>{if(!this.moment.now())return!1;return this.moment.reset(),clearInterval(this.idleTimer),this.idleTimer=void 0,this.check(),!0};if(this.idleTimer||d())return;this.idleTimer=setInterval(d,kj()),this.idleTimer.unref?.()}check(){return this.running??=this.checkNow().catch((d)=>this.record({result:"failed",error:d.message})).finally(()=>{this.running=void 0}),this.running}async checkNow(){if(this.stopped||!await this.allowed())return;if(await this.deps.busy?.())return s.info("claude update: another install runs here: next time");let d=process.env.SUPERFACTORY_CLAUDE_BIN,u=await mt(d);if(this.found=u,!u)return this.record({result:"failed",error:"Claude Code isn't installed here."});let p=(Y)=>{this.updating=Y},w=await this.followLatest(nw(d),d,p);if(w&&!w.ok)return this.record({result:"failed",from:u,error:i$(w.output)||"brew install failed"});let y=nw(d),v=()=>(y?XP(y,p):Gl(d,p)).finally(()=>{this.updating=void 0}),S=YP(y),[x,j]=await Promise.all([zP(S),this.deps.holdingInstalls?.(v)??v()]),L=j;if(this.stopped)return;let N=await mt(d),B=(Y)=>!!Y&&!!x&&nt(Y,x),G=!L.ok||N===u&&B(N)?this.deps.otherWay?.():void 0;if(G)L=await G().then(()=>({ok:!0,output:""}),(Y)=>({ok:!1,output:`${L.output}
|
|
946
|
+
${Y.message}`.trim()})),N=await mt(d);this.found=N??u;let V={...S==="stable"?{channel:S}:{},...x?{newest:x}:{}};if(N&&N!==u)return this.record({result:"updated",from:u,to:N,...V});if(!L.ok||!y&&Tj(L.output))return this.record({result:"failed",from:u,error:i$(L.output)||"claude update failed",...V});if(B(u))return this.record({result:"failed",from:u,error:Ij(d,u,V),...V});return this.record({result:"current",from:u,...V})}async followLatest(d,u,p){if(!this.follows?.latest)return;if(!d){if(await JP().catch((v)=>(s.warn("claude update: couldn't set its Claude settings to the latest channel",v.message),!1)))s.info("claude update: its Claude settings follow the latest channel now, not stable");return}if(!ZP(d)||this.deps.claudeRuns?.())return;s.info("claude update: Homebrew's stable claude-code cask: moving to claude-code@latest");let w=()=>e$(d,u,p).finally(()=>{this.updating=void 0});return this.deps.holdingInstalls?.(w)??w()}record(d){let u=this.last;if(this.last={...d,at:new Date().toISOString()},u?.result===d.result&&u.from===d.from&&u.to===d.to&&u.error===d.error&&u.newest===d.newest)return;if(d.result==="updated")s.info(`claude update: Claude Code ${d.from} -> ${d.to}`);else if(d.result==="failed")s.warn(`claude update: couldn't update Claude Code: ${d.error}`);this.deps.changed()}}function Pj(d=process.env){if(d.SUPERFACTORY_SANDBOX)return"a sandbox's Claude Code comes with its image";let u=d[ls];if(u)return`root keeps Claude Code current on this machine (superfactory host's ${u})`;let p=$j(d);if(p)return p;if(n$("/.dockerenv")||n$("/run/.containerenv")||d.KUBERNETES_SERVICE_HOST)return"Claude Code comes with this agent's image";if(d.DISABLE_UPDATES)return"DISABLE_UPDATES is set for this agent";return}function $j(d=process.env){if(!X())return;let u=d.SUPERFACTORY_CLAUDE_BIN,p=Bun.which("claude",{PATH:process.env.PATH??""});if(u&&(!p||iw(u)!==iw(p)))return;return"a test's agent doesn't update the machine's Claude Code"}var iw=(d)=>{try{return wj(d)}catch{return d}};function Ij(d,u,p){let w=Bun.which(d||"claude");return`claude update finished, but the Claude Code sessions run here${w?` (${iw(w)})`:""} is still ${u}, while the newest${p.channel?` on its ${p.channel} channel`:""} is ${p.newest}: it updated another install. Remove the other one, or put the one sessions run first on the agent's PATH.`}var Tj=(d)=>/\b(brew|winget) upgrade\b/i.test(d),i$=(d)=>d.trim().slice(-Sj);import{createHash as Rj}from"crypto";import{chmodSync as Aj,existsSync as r$,readFileSync as l$,renameSync as Ej,rmSync as Gd,writeFileSync as ow}from"fs";var o$=()=>k("SUPERFACTORY_UPDATE_CHECK_MS",3600000),a$=[1,2,5,10,30],aw=()=>k("SUPERFACTORY_UPDATE_RETRY_MS",60000),dw=()=>k("SUPERFACTORY_UPDATE_STALL_MS",60000),p$=900000,Cj=()=>k("SUPERFACTORY_UPDATE_CHECK_CAP_MS",p$+300000),_j=1000,Oj=120000,xj=[1,3],Mj=()=>k("SUPERFACTORY_UPDATE_AGAIN_MS",3000),jj=3,Lj=t({version:e(),sum:e(),since:b()});class cw{install;deps;staged;checking;run;swapping;joinFor;swapAfter=0;timer;idleTimer;retryTimer;failures=0;joinFailures=0;said="";starting=!1;moment;reported={};joinWatch;constructor(d,u){this.install=d;this.deps=u;this.moment=new Po(u.here)}start(){let d=Bi(this.install.bin);if(d.length)s.warn(`update: couldn't remove what an earlier update left (still running?): ${d.join("; ")}`);this.staged=this.stagedEarlier(),this.timer=setInterval(()=>void this.check(),o$()),this.timer.unref?.()}async beforeResume(){let d;this.starting=!0;let u=await Promise.race([this.check().then(()=>!0),new Promise((w)=>{d=setTimeout(()=>w(!1),Oj)})]);if(clearTimeout(d),this.starting=!1,this.joinFor)this.swapWhenIdle();let p=this.staged;if(!u)s.info("update: the new build isn't ready yet: the sessions resume first");if(!u||!p?.checked||this.swapping)return!1;s.info(`update: installing ${p.version} before the sessions resume`),this.swapping=this.swap(p);try{return await this.swapping,!0}catch(w){return s.warn(`update: couldn't swap in ${p.version}: ${w.message}; the sessions resume first`),this.failedWith(w.message,p.version),this.swapAfter=Date.now()+aw(),this.swapWhenIdle(),!1}finally{this.swapping=void 0}}stop(){clearInterval(this.timer),clearInterval(this.idleTimer),clearTimeout(this.retryTimer),this.joinWatch?.abort()}get state(){let d=u$(this.install.bin);return d&&/^[0-9a-f]{64}$/.test(d)?{...this.reported,build:d}:this.reported}tell(d){if(JSON.stringify(d)===JSON.stringify(this.reported))return;this.reported=d,this.deps.changed?.()}waitingFor(d,u){let p=new Date(this.moment.waitingSince??Date.now()).toISOString();this.tell({...this.reported,waiting:{version:d,...u?{build:fr(u)}:{},since:p}})}failedWith(d,u){let p={...u?{version:u}:{},error:d.slice(0,2000),at:new Date().toISOString()};this.tell({...this.reported,failed:p})}settled({keepFailure:d=!1}={}){this.tell(d&&this.reported.failed?{failed:this.reported.failed}:{})}check(){if(clearTimeout(this.retryTimer),this.checking){let v=this.run;if(v)s.info(`update: the check since ${new Date(v.since).toISOString()} is still under way (${v.step})`);return this.checking}let d=new AbortController,u={since:Date.now(),step:"starting",signal:d.signal},p=Cj(),w=setTimeout(()=>d.abort(Error(`the check hung for ${ks(p)}, ${u.step}`)),p),y=new Promise((v,S)=>d.signal.addEventListener("abort",()=>S(d.signal.reason),{once:!0}));return this.run=u,this.checking=Promise.race([this.checkAgain(u),y]).then(()=>{this.failures=0}).catch((v)=>{if(this.sayOnce(`update: couldn't update itself: ${v.message}`),++this.failures>=jj)this.failedWith(`its check failed: ${v.message}`);this.retryLater(this.failures-1)}).finally(()=>{clearTimeout(w),this.checking=void 0,this.run=void 0}),this.checking}retryLater(d){clearTimeout(this.retryTimer);let u=a$[Math.min(d,a$.length-1)]??1,p=Math.min(o$(),u*aw());s.info(`update: trying again in ${ks(p)}`),this.retryTimer=setTimeout(()=>void this.check(),p),this.retryTimer.unref?.()}async checkAgain(d){for(let u=0;;u++)try{return await this.checkNow(d)}catch(p){let w=xj[u];if(w===void 0||d.signal.aborted||!m$(p))throw p;let y=w*Mj();s.info(`update: ${p.message}; checking again in ${ks(y)}`),await Bun.sleep(y),d.signal.throwIfAborted()}}async checkNow(d){let u=this.deps.server();if(!u)return s.info("update: not linked to a server: no check");if(this.swapping)return s.info("update: a new build is going in: no check");let p=async(V,Y)=>{d.step=V;let ne=await Y();return d.signal.throwIfAborted(),ne},w=await p("reading the server's certificate",()=>C(u.serverUrl,u.pin)),y=(V,Y)=>fetch(new URL(V,u.serverUrl),{tls:w,headers:u.headers??{},signal:AbortSignal.any([Y,d.signal])}),{version:v}=ja.parse(await p("asking the server's version",()=>d$(y,"/api/version"))),S=u$(this.install.bin),x=v===H,j=(V)=>{this.drop(),this.settled(),s.info(`update: the server runs ${v}, as this agent does${V}: nothing to update`)};if(x&&!S)return j(`; no checksum beside ${this.install.bin} tells its build`);if(!x)this.moment.wanted();let L=Vh.parse(await p("reading the server's manifest",()=>d$(y,"/downloads/manifest.json"))),N=Nj(),B=L.files[N];if(x&&L.version!==v)return j(`, and hands out ${L.version??"unknown"} builds`);if(x&&!B)return j(`, and hands out no ${N} build`);if(x&&B&&S===B)return this.joinFailures=0,this.drop(),this.settled(),s.info(`update: the server's ${v} build (${fr(B)}) is installed: up to date`);if(this.moment.wanted(),L.version!==v||!B)throw new yr(`the server runs ${v} but hands out ${L.version??"unknown"} builds${B?"":`, none named ${N}`}`);if(S===B){let V=`the server's ${v} build is installed, yet it says ${H}`;return this.failedWith(V,v),this.sayOnce(`update: ${V}`)}if(this.install.restart==="join"&&!u.pin){if(s.info(this.joinFor?.sum!==B?`update: ${v} is ready; it updates ${this.moment.when()}`:`update: ${v} still waits; it updates ${this.moment.when()}`),this.joinFor={version:v,sum:B},this.waitingFor(v,B),!this.starting)this.swapWhenIdle();return}let G=this.staged;if(G?.sum===B&&!G.checked)await p(`checking the ${v} build an earlier run got ready`,()=>this.checkStaged(G));if(this.staged?.sum!==B)this.drop({keepWaiting:!0}),this.staged=await p(`getting its ${v} build`,()=>this.stage(y,N,B,v)),s.info(`update: ${v} is ready; it updates ${this.moment.when()}`);else s.info(`update: ${v} (${fr(B)}) still waits; it updates ${this.moment.when()}`);if(this.settled(),this.waitingFor(v,B),!this.starting)this.swapWhenIdle()}async stage(d,u,p,w){s.info(`update: downloading the server's ${w} build (${u})`);let y=await h$(d,`/downloads/${u}?sha256=${p}`,p$),v=Rj("sha256").update(y).digest("hex");if(v!==p)throw new yr(`${u} doesn't match its checksum (${fr(v)}, not ${fr(p)}: another replica's build, mid-rollout?)`);let S=Ro(this.install.bin);if(ow(S,Bun.gunzipSync(y)),Aj(S,493),process.platform==="darwin")await Dj(S);await this.checkRuns(S,w);let x={version:w,sum:p,file:S,checked:!0};return this.moment.waitFrom(Date.now()),ow(Ao(this.install.bin),JSON.stringify({version:w,sum:p,since:this.moment.waitingSince})),x}stagedEarlier(){let{bin:d}=this.install;try{let u=Lj.parse(JSON.parse(l$(Ao(d),"utf8")));if(r$(Ro(d)))return this.moment.waitFrom(u.since),s.info(`update: ${u.version} is ready since ${new Date(u.since).toISOString()}`),{version:u.version,sum:u.sum,file:Ro(d),checked:!1}}catch{}for(let u of[Ro(d),Ao(d)])Gd(u,{force:!0});return}async checkStaged(d){try{await this.checkRuns(d.file,d.version),d.checked=!0,s.info(`update: the ${d.version} build an earlier run got ready runs: no download`)}catch(u){s.warn(`update: the ${d.version} build an earlier run got ready: ${u.message}`),this.drop({keepWaiting:!0})}}async checkRuns(d,u){let p=await T(r(rt).programPath(d).flag("--version").timeoutMs(60000).build()).catch((w)=>w.message);if(p.trim().split(/\s+/).includes(u))return;throw Gd(d,{force:!0}),Error(`the server's build says "${p.trim()}", not ${u}`)}swapWhenIdle(){this.attempt(),this.idleTimer??=setInterval(()=>this.attempt(),_j),this.idleTimer.unref?.()}attempt(){let d=this.staged,u=this.joinFor?.version??d?.version;if(!(this.joinFor||d?.checked)||this.swapping||Date.now()<this.swapAfter||!this.moment.now())return;let p=this.joinFor?this.joinAgain(this.joinFor):this.swap(d);this.swapping=p.catch((w)=>{let y=aw();this.swapAfter=Date.now()+y,s.warn(`update: couldn't update to ${u}: ${w.message}; trying again in ${ks(y)}`),this.failedWith(w.message,u)}).finally(()=>{this.swapping=void 0})}async joinAgain({version:d,sum:u}){s.info(`update: ${H} -> ${d} (${fr(u)}): running the server's join.ps1 again (its log: update.log)`);let p=Date.now();await xc(u),this.joinFor=void 0,this.moment.reset(),clearInterval(this.idleTimer),this.idleTimer=void 0,this.settled({keepFailure:!0}),this.followJoin(d,p)}async followJoin(d,u){this.joinWatch?.abort();let p=new AbortController;this.joinWatch=p;let w=await Cm(u,p.signal).catch((y)=>y.message);if(!w||p.signal.aborted)return;s.warn(`update: couldn't update to ${d}: ${w}`),this.failedWith(w,d),this.retryLater(this.joinFailures++)}async swap(d){let{bin:u}=this.install;if(!r$(d.file))throw this.drop({keepWaiting:!0}),this.check(),Error(`${d.file} is gone: getting the build again`);await kc(u,d.file),this.staged=void 0;try{Gd(Ao(u),{force:!0}),ow(`${u}.sha256.new`,`${d.sum}
|
|
947
|
+
`),Ej(`${u}.sha256.new`,`${u}.sha256`)}catch(w){s.warn(`update: couldn't note the new build beside ${u} (join.sh would download it again)`,w)}s.info(`update: ${H} -> ${d.version}: restarting`);let p=this.install.restart==="relaunch"?r(rt).programPath(u).sub("agent run").in(process.cwd()).build():process.platform==="darwin"&&Ze()==="launchd"?Pc():void 0;await this.deps.restart(p)}drop({keepWaiting:d=!1}={}){if(this.staged=void 0,!d)this.joinFor=void 0;if(!d){if(this.moment.reset(),clearInterval(this.idleTimer),this.idleTimer=void 0,this.reported.waiting)this.tell(this.reported.failed?{failed:this.reported.failed}:{})}for(let u of[Ro(this.install.bin),Ao(this.install.bin)])Gd(u,{force:!0})}sayOnce(d){if(d===this.said)s.info(d);else s.warn(d);this.said=d}}async function d$(d,u){return JSON.parse(new TextDecoder().decode(await h$(d,u,dw())))}async function h$(d,u,p){let w=new AbortController,y=(B)=>w.abort(Error(B)),v=Date.now(),S=setTimeout(()=>y(`not done after ${ks(p)}`),p),x,j=()=>{clearTimeout(x),x=setTimeout(()=>y(`no bytes for ${ks(dw())}`),dw())},L=[],N=0;try{j();let B=await d(u,w.signal);if(!B.ok){await B.body?.cancel().catch(()=>{return});let G=`the server answered with ${B.status}`;throw[409,502,503,504].includes(B.status)?new yr(G):Error(G)}for await(let G of B.body??[])L.push(G),N+=G.byteLength,j();if(N>1e6)s.info(`update: downloaded ${u} (${c$(N)}) in ${ks(Date.now()-v)}`);return new Uint8Array(Bun.concatArrayBuffers(L))}catch(B){let G=w.signal.aborted?w.signal.reason:B,V=`getting ${u.replace(/\?.*$/,"")} stopped after ${c$(N)}: ${G.message}`;throw!w.signal.aborted&&m$(B)?new yr(V):Error(V)}finally{clearTimeout(S),clearTimeout(x)}}class yr extends Error{}function m$(d){if(d instanceof yr)return!0;if(!(d instanceof Error)||d.name==="AbortError"||d.name==="TimeoutError")return!1;let u=d.code,p=`${typeof u==="string"?u:""} ${d.message}`;return/ECONNREFUSED|ECONNRESET|EPIPE|EHOSTUNREACH|ENETUNREACH|EAI_AGAIN|ConnectionRefused|ConnectionClosed|socket connection was closed|Unable to connect/i.test(p)}var fr=(d)=>d.slice(0,8),c$=(d)=>`${(d/1e6).toFixed(1)} MB`;function Nj(){return`superfactory-${process.platform==="win32"?"windows":process.platform}-${process.arch==="arm64"?"arm64":"x64"}.gz`}var Ro=(d)=>d.replace(/(\.exe)?$/i,".update$1"),Ao=(d)=>d.replace(/(\.exe)?$/i,".update.json");function u$(d){try{return l$(`${d}.sha256`,"utf8").trim()}catch{return}}async function Dj(d){await T(r(fd).flag("--force").flag("--sign","-").flag("--identifier",Ma).flag("--requirements",`=${pd}`).arg(d).timeoutMs(60000).build())}var Rt=({projectId:d,taskId:u})=>`${d}/${u}`;class uw{starts=new Map;underWay=new Map;opening=new Map;mark(d){return this.starts.get(Rt(d))??0}startedSince(d,u){return this.mark(d)!==u||(this.opening.get(Rt(d))??0)>0}async starting(d){this.starts.set(Rt(d),this.mark(d)+1),this.opening.set(Rt(d),(this.opening.get(Rt(d))??0)+1),await this.settled(d)}started(d){let u=(this.opening.get(Rt(d))??1)-1;if(u>0)this.opening.set(Rt(d),u);else this.opening.delete(Rt(d))}async settled(d){await this.underWay.get(Rt(d))?.catch(()=>{return})}async remove(d,u,p){if(this.startedSince(d,u))return!1;let w=this.settled(d).then(p);this.underWay.set(Rt(d),w);try{return await w,!0}finally{if(this.underWay.get(Rt(d))===w)this.underWay.delete(Rt(d))}}}import{existsSync as lw}from"fs";var Uj=1800000,f$=(d)=>d.projectId&&d.taskId&&d.kind==="task"?{projectId:d.projectId,taskId:d.taskId}:void 0,Bs=({projectId:d,taskId:u})=>`${d}/${u}`,pw=(d,u)=>`${d} ${u}${d===1?"":"s"}`;class hw{deps;queues=new Map;branchPushedAt=new Map;leftNoted=new Map;constructor(d){this.deps=d}onTurnEnd(d){this.later(d,!1)}onEnded(d){this.later(d,!0)}later(d,u){let p=f$(d),w=this.deps.movedAway(d);if(!p||d.teammate?.leadOn||w==="moving")return;let y=!this.deps.sandboxed(d)&&(!d.runner||d.runner==="host");this.inTurn(p,()=>this.backUp(p,{ended:u,hooks:y,sessionId:d.id,branchToo:w!=="moved"})).catch((v)=>s.warn(`backup: ${Bs(p)}'s work not pushed`,v))}async backUp(d,{ended:u,hooks:p,sessionId:w,branchToo:y=!0}){let v=Re(this.deps.projects.path(d.projectId),d.taskId);if(!lw(v))return!1;if(w&&(await this.deps.tasks.get(d).catch(()=>{return}))?.sessionId!==w)return!1;let S=(await a(v,(B)=>B.sub("branch").flag("--show-current")).catch(()=>"")).trim();if(!S)return!1;let x=await nn(v),j=await ui(v);if(!x&&!j)return!1;let L=Bs(d),N=u||Date.now()-(this.branchPushedAt.get(L)??0)>=Uj;if(y&&x&&N&&Jt(d.taskId,S)){if(this.branchPushedAt.set(L,Date.now()),await Qp(v,S,p))s.info(`backup: ${L}'s ${pw(x,"commit")} pushed to ${S}`),x=await nn(v)}if(x||j)await this.pushBackup(v,d,S);return this.deps.worktreeChanged(d),!0}async pushBackup(d,u,p){let w=Sn(u.taskId),y=await Ka(d,`Superfactory's backup of ${u.taskId}'s work on ${p}`);if(!y)return;let v=y.left.join(", ");if(v&&this.leftNoted.get(Bs(u))!==v)await this.deps.tasks.appendNote(u,`Left out of the backup on ${w}, as they look like secrets: ${v}.`);if(this.leftNoted.set(Bs(u),v),await Fj(d,y.sha,`refs/remotes/origin/${w}`))return;await Bu(d,y.sha,w),s.info(`backup: ${Bs(u)}'s work pushed to ${w}`)}async leftBehind(d){let u=f$(d);if(!u||d.teammate?.leadOn)return;await this.inTurn(u,async()=>{let p=Re(this.deps.projects.path(u.projectId),u.taskId);if(!lw(p))return;let[w,y]=await Promise.all([nn(p),ui(p)]);if(!w&&!y)return;let v=(await a(p,(N)=>N.sub("branch").flag("--show-current")).catch(()=>"")).trim(),S=this.deps.machine(),x=Jh(u.taskId,S),j=await Ka(p,`What ${S} still had of ${u.taskId} after it moved away`);if(!j)return;await Bu(p,j.sha,x);let L=[w?`${pw(w,"commit")} not pushed`:"",y?`${pw(y,"uncommitted file")}`:""].filter(Boolean).join(" and ");await this.deps.tasks.appendNote(u,[`${S} is back: what it still had of this task (${L}) is kept on the branch ${x}.`,v?`${v} stays as it is.`:"",j.left.length?`Left out, as they look like secrets (still on ${S}): ${j.left.join(", ")}.`:""].filter(Boolean).join(" ")),s.info(`backup: ${Bs(u)}'s work left on ${S} pushed to ${x}`)})}handOff(d,u){return this.inTurn(d,async()=>{let p=Re(this.deps.projects.path(d.projectId),d.taskId);if(!lw(p))return;let w=(await a(p,(x)=>x.sub("branch").flag("--show-current")).catch(()=>"")).trim();if(!w||!Jt(d.taskId,w))throw Error(`its worktree is on ${w||"no branch"}, not ${d.taskId}'s own branch: switch back to it first`);let y=await ui(p),v=[];if(y){let x=await Ka(p,`WIP: ${d.taskId}'s work as it moved to ${u}`);if(x)await a(p,(j)=>j.sub("reset").flag("--quiet").arg(x.sha)),v=x.left}if(await nn(p))await a(p,(x)=>x.sub("push").flag("--quiet").flag("--no-verify").arg("origin").arg(`HEAD:refs/heads/${w}`));let S=(await a(p,(x)=>x.sub("rev-parse").arg("HEAD"))).trim();return this.deps.worktreeChanged(d),s.info(`backup: ${Bs(d)}'s work pushed to ${w} as it moved to ${u}`),{branch:w,head:S,committed:Math.max(0,y-v.length),left:v}})}inTurn(d,u){let p=Bs(d),w=(this.queues.get(p)??Promise.resolve()).then(u),y=w.catch(()=>{return});return this.queues.set(p,y),y.then(()=>{if(this.queues.get(p)===y)this.queues.delete(p)}),w}}async function Fj(d,u,p){let w=(L)=>a(d,(N)=>N.sub("rev-parse").flag("--verify").flag("--quiet").arg(L)).then((N)=>N.trim(),()=>""),y=await w(`${p}^{commit}`);if(!y)return!1;if(y===u)return!0;let[v,S,x,j]=await Promise.all([w(`${u}^{tree}`),w(`${y}^{tree}`),w(`${u}^1`),w(`${y}^1`)]);return!!v&&v===S&&x===j}import{existsSync as Bj,lstatSync as Wj}from"fs";import{join as Hj}from"path";var g$=500,Gj=new Set(["read","fetch","search"]),w$={head:"",work:"",origin:""};class mw{deps;seen=new Map;pending=new Map;checking=new Set;constructor(d){this.deps=d}onEvent(d,u){let p=y$(d);if(!p)return;if(!(u.type==="tool_result"&&!Gj.has(u.detail?.kind??"")||u.type==="result"))return;this.touch(p,this.deps.sandboxed(d)?["changes","worktree"]:[])}onSession(d){let u=y$(d);if(u)this.touch(u)}touch(d,u=[]){let p=Vj(d),w=this.pending.get(p);if(w){for(let y of u)w.always.add(y);return}this.pending.set(p,{ref:d,always:new Set(u)}),setTimeout(()=>void this.check(p),g$)}async check(d){if(this.checking.has(d)){setTimeout(()=>void this.check(d),g$);return}let u=this.pending.get(d);if(!u)return;this.pending.delete(d),this.checking.add(d);try{let p=await this.fingerprint(u.ref),w=this.seen.get(d);this.seen.set(d,p);let y=new Set(u.always);if(!w||w.head!==p.head)for(let S of["commits","changes","worktree"])y.add(S);else if(w.work!==p.work)for(let S of["changes","worktree"])y.add(S);if(w&&w.origin!==p.origin)y.add("worktree");if(y.size>0)this.deps.push({type:"task.parts.changed",...u.ref,parts:[...y]});if((!w||w.head!==p.head||w.work!==p.work||w.origin!==p.origin)&&p!==w$)await this.reportWork(u.ref)}catch(p){s.warn(`work pulse: ${d}`,p)}finally{this.checking.delete(d)}}async reportWork(d){if(!this.deps.serverReadsWork())return;let u=await Zp(Re(this.deps.projects.path(d.projectId),d.taskId),d.taskId);if(u)this.deps.push({type:"task.work",...d,work:u})}async originOf(d,u,p){let w=(await p(d,(S)=>S.sub("branch").flag("--show-current")).catch(()=>"")).trim(),y=[...w?[`refs/remotes/origin/${w}`]:[],`refs/remotes/origin/${Sn(u)}`];return(await Promise.all(y.map((S)=>p(d,(x)=>x.sub("rev-parse").flag("--verify").flag("--quiet").arg(S)).then((x)=>x.trim(),()=>"")))).join(" ")}async fingerprint({projectId:d,taskId:u}){let p=Re(this.deps.projects.path(d),u);if(!Bj(p))return w$;let w=(L,N)=>a(L,(B)=>N(B.env({GIT_OPTIONAL_LOCKS:"0"}))),[y,v,S,x]=await Promise.all([w(p,(L)=>L.sub("rev-parse").arg("HEAD")).catch(()=>""),w(p,(L)=>L.sub("status").flag("--porcelain").flag("--untracked-files","all")),w(p,(L)=>L.sub("diff").flag("--numstat").arg("HEAD")).catch(()=>""),this.originOf(p,u,w)]),j=v.split(`
|
|
948
|
+
`).filter((L)=>L.startsWith("?? ")).slice(0,qj).map((L)=>{try{let N=Wj(Hj(p,L.slice(3)));return`${N.size}:${N.mtimeMs}`}catch{return"-"}});return{head:y.trim()||"none",work:`${v}
|
|
949
|
+
${S}
|
|
950
|
+
${j.join(",")}`,origin:x}}}var qj=200,y$=(d)=>d.projectId&&d.taskId?{projectId:d.projectId,taskId:d.taskId}:void 0,Vj=({projectId:d,taskId:u})=>`${d}/${u}`;import{existsSync as fw}from"fs";import{homedir as Yj}from"os";import{join as kr}from"path";var Kj=(d)=>[kr(d,".local","bin"),kr(d,".claude","local"),"/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"],Qj=(d,u)=>[kr(u.LOCALAPPDATA??kr(d,"AppData","Local"),"Microsoft","WinGet","Links"),kr(d,".bun","bin")];function k$(d="",u=Yj(),p=process.platform,w=process.env){if(p==="win32"){let x=d.split(";").filter(Boolean),j=Qj(u,w).filter((L)=>!x.some((N)=>N.toLowerCase()===L.toLowerCase())&&fw(L));return[...x,...j].join(";")}let y=kr(u,".bun","bin"),v=d.split(":").filter((x)=>x&&x!==y),S=Kj(u).filter((x)=>!v.includes(x)&&fw(x));return[...fw(y)?[y]:[],...v,...S].join(":")}var Zj="local",eL=30000,tL=900000,sL=1000;class zp{state;link;removedFrom;uninstalling;linkWaiters=[];claudeSignIns=new wp;server;pushGateway;projects;tasks;questions;systemPermissions;virtualMachine;permissionRules=new Tm;recordings=new Wu;chatQuestions;sessions;crons;removals=new uw;places=new zu((d,u,p)=>this.children.available()?this.children.for(d,u,p):Promise.resolve(),{node:()=>this.state.nodeId,gone:async(d)=>this.link?.connected?new Set((await this.link.request("nodes.gone",{nodeIds:d})).gone):new Set},new ro(()=>void this.pushNode(),async()=>(await this.projects.globalSettings())["machine.setupSudo"]===!0,(d,u)=>this.setupSource(d,u),()=>this.setup.settled()));tunnel=new El(()=>this.directLink(),()=>this.link instanceof gn?this.link.redial():void 0,void 0,()=>this.state.reach?.listen);children=new qf({link:()=>this.link,server:()=>this.state.serverUrl?this.tunnel.routed(this.state.serverUrl,this.state.certSpkiSha256):void 0,parentId:()=>this.nodeId});checkouts;commandRuns=new Sr(m().commands);platformPlaces=new xl({runs:this.commandRuns,places:this.places,project:(d)=>this.projects.get(d),settings:(d)=>this.projects.settings(d),downloadBundle:(d,u)=>{let p=this.httpLink();return p?fh(p,d,u):Promise.resolve(void 0)},uploadLog:async(d,u,p)=>{let w=this.httpLink();if(w)await hh(w,d,u,p)},push:(d)=>this.push(d),machineScreen:async()=>ds()??await wl(),githubEnv:async(d)=>{let u=d,p=await this.sessions.taskGithub.forSession(u).catch(()=>{return});return this.sessions.taskGithub.env(u,p,{})},copyServer:(d,u)=>{let p=this.httpLink();return p?mh(p,d,u):void 0},sessionFolder:(d,u)=>{let p=this.sessions.find(d);if(!p||p.projectId!==u.projectId||p.taskId!==u.taskId)throw new c("forbidden","not this machine's session of that task");let w=this.sessions.sandboxFor(p.id);if(w&&!w.shared)throw new c("bad_request","this session works in a sandbox: copies reach its machine's folders only");return p.cwd}});ports;terminals;sandboxTerminals=new Map;sandboxes;placed=ES(()=>this.link,()=>!!this.serverVersion&&!nt(this.serverVersion,H));macos;tartVms=new tm(process.env.SUPERFACTORY_TART_HYPERVISOR_DIR||void 0);vmVault=new fm(()=>this.link,()=>this.state.nodeKey);instructions;managers;watchers=new op;wakeCosts=new pp;reports=new ti;teams;closedTasks;finishedTasks;diskCleanup;workPulse;workBackup;idleTurns;readyRuns;activity=new ou;plainAsks=new Gm({activity:this.activity,nudge:async(d,u)=>{if(this.sessions.find(d)?.state!=="idle")return!1;return await this.sessions.send(d,u,"superfactory"),!0}});taskCoordinators=new Tp;replies;talk;sessionMessages;merges;continues;signIns;ownLogin=process.env.SUPERFACTORY_SANDBOX?void 0:Qf();questionSweep;gate=new bm(()=>this.state.serverUrl);automation;repoMirror;away=new Sh(()=>{this.pushNode(),this.tray.refresh()});tray=new zg({home:m().home,snapshot:()=>this.traySnapshot(),act:(d)=>this.trayAction(d),page:()=>this.state.serverUrl&&new URL(`/machines/${encodeURIComponent(this.nodeId)}`,this.state.serverUrl).href});setup=new Os({changed:()=>void this.pushNode(this.setup.state?.state!=="running"),enabled:async()=>(await this.projects.globalSettings())["machine.setup"]!==!1,projectPaths:()=>this.state.projects.map((d)=>d.path),projectNeeds:()=>this.projectNeeds("linux"),mirrors:async()=>Bt(await this.projects.globalSettings())});claudeUpdates=new rw({enabled:async()=>(await this.projects.globalSettings())["machine.claudeUpdates"]!==!1,here:{ready:()=>this.settled,idle:()=>this.sessions.inTurn().length===0,betweenTools:()=>this.sessions.inTool().length===0},changed:()=>void this.pushNode(!0).then(()=>this.sessions.claudeInstalled()),otherWay:()=>oS(Hd()),busy:()=>gd(),holdingInstalls:dS,claudeRuns:()=>this.sessions.claudeRunsHere(),follow:async()=>KP((await this.projects.globalSettings())["machine.claudeChannel"],()=>this.dedicated())});node;nodePushes=Promise.resolve();monitors;monitorsCheck;serverName;periodic=new Cr;usage;measureUsage=lb(()=>this.state.projects.map((d)=>d.path));screenWatch;repoWatch;networkSaid="";github;mcp;secretEnvs=new oo(async(d)=>{let u=await Wb(this,d),p=this.mcp.contextOfSession(d);return p?{...u,SF_DEPLOY_GRANT:this.deployGrants.mint(p)}:u});deployGrants=new zd(m().deployGrants);stopped=Promise.withResolvers();stopping;stoppingStep="";settled=!1;serverVersion;selfUpdate;stallWatch=new bh((d)=>this.stalled(d));relaunch;updating=!1;constructor(d){this.state=d;O(d.nodeKey),O(d.controlToken),am(()=>void this.pushNode(!0)),sm(()=>void this.pushNode(!0)),um(()=>void this.pushNode(!0)),this.ownLogin?.onChange(()=>void this.pushNode(!0)),this.ownLogin?.load().then(()=>this.ownLogin?.signedOutNow&&this.pushNode(!0));let u=(y)=>this.push(y);this.projects=new Fu(d,()=>this.nodeId,(y)=>this.tasks?.knownSprints(y)),this.checkouts=new Su({state:d,projects:this.projects,link:()=>this.httpLink()}),this.repoMirror=new gu({own:()=>this.projects.ownIds().filter((y)=>!this.projects.isLead(y)).map((y)=>({id:y,path:this.projects.path(y)})),link:()=>this.httpLink()}),Ym(new Oc({state:d,ask:(y)=>this.link?.connected?this.link.request("github.token",{projectId:y}):Promise.reject(new c("unavailable","not connected to the server")),fresh:(y,v)=>void this.sessions?.github.taken(y,v)}),new Oc({state:d,ask:(y)=>this.link?.connected?this.link.request("github.token",{projectId:y,tasks:!0}):Promise.reject(new c("unavailable","not connected to the server"))})),this.pushGateway=new Jd({pusher:(y)=>this.pusher(y),projectToken:(y)=>Dl(y)}),this.managers=new ym(d,()=>this.nodeId),this.tasks=new Cg(this.projects,{enrolled:()=>!!this.state.serverUrl&&!!this.state.nodeKey,linked:()=>this.linked(),request:(y,v)=>this.link?.connected?this.link.request(y,v):Promise.reject(new c("unavailable","not connected to the server"))},(y)=>{vP(y,(x)=>this.tasks.list(x),(x)=>this.watchers.emit(x));let v=this.automation.onTaskChange(y).catch((x)=>s.warn("automation failed",x)),S=this.github.onTaskChange(y);this.merges.onTaskChange(y).catch((x)=>s.warn(`merge: ${y.task.id}'s question`,x)),this.questionSweep.sweep(y.task).catch((x)=>s.warn(`questions: ${y.task.id}'s questions not swept`,x)),this.sessions.onTaskChange(y),this.closedTasks.onTaskChange(y,Promise.all([v,S.catch((x)=>s.warn("github",x))])).catch((x)=>s.warn("closed task",x))},(y)=>void this.projects.get(y).then((v)=>u({type:"project.updated",project:v})).catch((v)=>s.warn(`projects: couldn't tell ${y}'s sprints`,v)));let p=new Bm({task:(y)=>this.tasks.get(y),coordinatorOf:(y)=>this.taskCoordinators.get(y),managersChat:(y)=>this.sessions.managersChat(y),record:(y,v)=>this.sessions.recordInHistory(y,v)});this.systemPermissions=new lg({sessions:()=>this.sessions.processes().map(({session:y,pid:v})=>({id:y.id,pid:v,...y.projectId?{projectId:y.projectId}:{},...y.taskId?{taskId:y.taskId}:{},ownAgent:(y.kind==="task"||y.kind==="epic")&&!y.teammate})),send:(y,v)=>this.sessions.send(y,v,"superfactory"),ask:(y,v)=>this.questions.postOnce(y,v),cancel:async(y,v)=>void await this.tasks.cancelOpen(y,v),dedicated:()=>this.dedicated(),shownId:(y)=>D(y.taskId,this.projects.keys(y.projectId).key),machineName:()=>this.serverName??this.node?.name??this.state.name,audit:(y)=>u({type:"mcp.audited",entry:y})}),this.questions=new Nu(this.tasks,(y)=>{if(u(y),y.type!=="question.asked")return;p.show({projectId:y.projectId,taskId:y.taskId},y.question)},(y,v)=>{if(p.show(v,y),!y.askedBy)return;if(y.kind!=="permission")this.sessions.markBoundary(y.askedBy,{kind:"answer",text:Lu(y)})},(y,v)=>p.show(v,y),(y)=>this.sessions.reconcileWaiting(y)),this.chatQuestions=new Um({record:(y,v)=>this.sessions.recordEvent(y,v),send:(y,v,S)=>this.sessions.send(y,v,S)}),this.crons=new Ap(this.projects,u,()=>({running:(y)=>this.sessions.isRunning(y),send:(y,v)=>this.sessions.send(y,v,"superfactory"),toCoordinator:async(y,v,S)=>(await this.sessions.start({projectId:y,kind:"coordinator",prompt:v,startTicket:S})).id})),this.macos=new Gh(this.projects,u),dl(this.vmVault.vaultFor),this.instructions=new Ip(this.projects,(y,v,S,x)=>{u({type:"coordinator.instructions.changed",...y,text:v,revision:S,...x});let j=this.sessions.coordinator(y.scope,y.managerId);if(j)this.sessions.restart(j.session.id,"Your instructions (your CLAUDE.md) changed. Follow the new version from now on; reply only: ok.").catch((L)=>s.warn("instructions: the manager didn't restart on them",L))}),this.teams=new Vg({projects:this.projects,tasks:this.tasks,sessions:()=>this.sessions,watchers:this.watchers,push:u,placed:this.placed,here:()=>({machine:this.serverName??this.node?.name??this.state.name,os:this.node?.os})}),this.workPulse=new mw({projects:this.projects,sandboxed:(y)=>!!this.sessions.sandboxFor(y.id),push:u,serverReadsWork:()=>!!this.serverVersion&&!nt(this.serverVersion,H)}),this.workBackup=new hw({projects:this.projects,tasks:this.tasks,sandboxed:(y)=>!!this.sessions.sandboxFor(y.id),movedAway:(y)=>this.sessions.wentElsewhere(y.id),machine:()=>this.serverName??this.node?.name??this.state.name,worktreeChanged:(y)=>this.workPulse.touch(y)}),this.finishedTasks=new gg({projects:this.projects,tasks:this.tasks,sessions:()=>this.sessions,places:this.places,removals:this.removals,worktreeChanged:(y)=>this.workPulse.touch(y)}),this.diskCleanup=new Ch({projects:this.projects,tasks:this.tasks,sessions:()=>this.sessions,removals:this.removals,settings:()=>this.projects.globalSettings(),changed:()=>void this.pushNode()}),this.closedTasks=new wg({teams:this.teams,sessions:()=>this.sessions,places:this.places,tasks:this.tasks,projects:this.projects,removals:this.removals,finished:this.finishedTasks}),this.talk=new Lg({tasks:this.tasks,managers:this.managers,push:u,managerOf:(y)=>this.sessions.managerOf(y),talked:async(y,v)=>{if(v.projectId===y.projectId)await this.taskCoordinators.set(y,v.id)}}),this.replies=new yg(this.tasks,()=>this.sessions,this.taskCoordinators,this.talk,(y)=>this.holds(y)),this.sessionMessages=new Ug({addressed:()=>this.sessions.addressed(),find:(y)=>this.sessions.find(y),addressOf:(y)=>this.sessions.addressOf(y),wake:(y,v,S,x)=>this.teams.wake(y,v,S,void 0,x),wakeLead:async(y,v,S,x,j)=>{let L=this.managers.get(y);if(!L)throw Error(`no lead ${y} on this machine`);if(x&&!await this.wakeCosts.take(L))throw Error(`${L.name}'s wake budget for today is spent (${L.wakeBudget}): put it in your task's conversation with task_comment, or tell them tomorrow`);let N=await kn(this.sessions,L,v,j).catch((B)=>{if(x)this.wakeCosts.giveBack(L.id);throw B});if(this.watchers.woke(N,S),x)this.wakeCosts.expect(N,L,"",!0)},sent:(y,v)=>this.sessions.recordEvent(y,{type:"hook",hookEvent:"PreToolUse",hookName:"PreToolUse:SendMessage",sent:v}),nextDepth:(y,v)=>this.teams.nextDepth(y,v),epicOf:async(y)=>(await this.tasks.get(y)).epic,manager:(y)=>this.sessions.managerOf(y),nodeId:()=>this.nodeId,holdsLead:()=>this.projects.holdsLead(),reports:this.reports,isLeadProject:(y)=>this.projects.isLead(y),server:()=>{let y=this.link?.connected?this.link:void 0;return y&&{message:(v)=>y.request("sessions.message",v),reachable:(v)=>y.request("sessions.reachable",v)}},ownsProject:(y)=>this.projects.ownIds().includes(y),record:async(y,v,S)=>{if(await this.talk.recordMessage(y,v),S)u({type:"task.talk.changed",...y,sessionId:S,seqs:[]})},native:()=>kP()}),this.merges=new tl({projects:this.projects,tasks:this.tasks,questions:this.questions,replies:this.replies,send:(y,v,S)=>this.sessions.send(y,v,S),holds:(y)=>this.holds(y),published:(y)=>this.github.idle(y),prHead:(y)=>this.github.prHeadOf(y),sinceAsked:(y,v,S)=>this.github.sinceAsked(y,v,S),sinceApproval:(y,v)=>this.github.sinceApproval(y,v),nothingToMerge:(y)=>this.github.nothingToMerge(y),unmergeable:(y)=>this.github.unmergeable(y),upToDate:(y)=>this.github.upToDate(y),rest:(y)=>this.teams.rest(y)}),this.continues=new Fm({projects:this.projects,tasks:this.tasks,questions:this.questions,send:(y,v,S)=>this.sessions.send(y,v,S),tellLead:async(y,v)=>{let S=this.managers.forProject(y.projectId),x=S.find((j)=>j.main&&j.scope.kind==="project")??S.find((j)=>j.main)??S[0];if(x)await kn(this.sessions,x,v)}}),this.signIns=new Vm({projects:this.projects,tasks:this.tasks,questions:this.questions}),this.questionSweep=new Km({tasks:this.tasks,find:(y)=>this.sessions.find(y),holds:(y)=>this.holds(y)}),this.readyRuns=new Yg({tell:(y,v)=>this.sessions.send(y,v,"superfactory")});let w=Bb(this,u);this.mcp=new jr(Me,Bn(w),Hf(w),(y,v)=>si(y)??vi(y,Ci)??AS(y,v)),this.sessions=new Cl({activity:this.activity,ownLogin:this.ownLogin,memory:Yv(),machineName:()=>this.serverName??this.node?.name??this.state.name,projects:this.projects,tasks:this.tasks,waitsForUser:(y)=>this.questions.waitedOnBy(y).length>0,asksUser:(y)=>this.asksUser(y),linkedSoon:()=>this.linkedSoon(),mcp:this.mcp,mcpUrl:()=>`http://127.0.0.1:${this.state.controlPort}/mcp`,places:this.places,removals:this.removals,children:this.children,attachMedia:(y,v,S,x)=>gi({projects:this.projects,tasks:this.tasks,upload:(j,L,N)=>this.uploadMedia(j,L,N)},y,v,S,x),nodeId:()=>this.nodeId,secretEnvs:this.secretEnvs,secretsNow:async(y)=>(await this.linkedSoon())?.request("secrets.env",{sessionId:y})??{env:{},leadEnv:{}},reservedPorts:()=>[this.state.controlPort],push:u,managers:this.managers,away:()=>this.away.set(!0),transcripts:new Kr(()=>this.link?.connected?this.link:void 0,()=>!!this.serverVersion&&!nt(this.serverVersion,H)),claude:{found:()=>sr(),repair:async()=>{let y=await aS();if(!y)this.pushNode(!0);return y}},installedClaude:()=>this.claudeUpdates.version??this.node?.claudeVersion,claudeCurrent:()=>this.claudeUpdates.beforeStart(),askSlot:async(y)=>{let v=await this.linkedSoon();if(!v)throw new c("unavailable","not linked to the server");return(await v.request("slots.ask",y)).queued},claudeLogin:async(y,{startTicket:v,origin:S,limited:x,rebalance:j,signedOut:L})=>{let N=await this.linkedSoon();if(!N)return{};return N.request("claude.login",{sessionId:y.id,projectId:y.projectId,startTicket:v,origin:S,limited:x,rebalance:j,signedOut:L})},systemPrompt:jb(this),hooks:{onLine:(y,v)=>this.crons.onLine(y,v),onEvent:(y,v)=>{if(this.replies.onEvent(y,v),v.type==="state")this.questionSweep.sessionChanged(y).catch((S)=>s.warn(`questions: ${y.id}'s task not swept`,S));this.talk.onEvent(y,v),this.watchers.onEvent(y,v),this.wakeCosts.onEvent(y,v),this.teams.onEvent(y,v),this.idleTurns.onEvent(y,v),this.plainAsks.onEvent(y,v),this.workPulse.onEvent(y,v)},onTaskSession:(y)=>{if(this.workPulse.onSession(y),y.projectId&&y.taskId)this.teams.rememberHead({projectId:y.projectId,taskId:y.taskId})},onTurnSynced:(y)=>{this.workPulse.onSession(y),this.teams.onTurnSynced(y).catch((v)=>s.warn(`teams: ${y.id}'s commits not checked`,v))},onTurnEnd:(y,v)=>{this.automation.onTurnEnd(y,v),this.workBackup.onTurnEnd(y),this.merges.onTurnEnd(y).catch((S)=>s.warn(`merge: ${y.id} couldn't rest`,S))},onEnded:(y,v)=>{this.workBackup.onEnded(y),this.continues.ended(y,v).catch((S)=>s.warn(`continue: couldn't ask about ${y.id}`,S))},onMovedAway:(y)=>void this.workBackup.leftBehind(y).catch((v)=>s.warn(`backup: ${y.id}'s work left here not kept`,v)),onSignedOut:(y,v)=>void this.signIns.signedOut(y,v).catch((S)=>s.warn(`sign-in: couldn't ask about ${y.id}`,S)),onOrphansSettled:()=>void this.replies.afterRestart(this.projects.ids()).catch((y)=>s.warn("replies: couldn't settle after the restart",y)),onStateChange:(y)=>{if(y.state==="exited"||y.state==="failed")this.crons.sessionEnded(y);this.automation.onSessionState()}}}),this.watchers.addSource(Fb(this.managers,()=>this.sessions,this.wakeCosts,this.watchers,async(y)=>Zc(await this.projects.settings(y)))),this.watchers.useChanges(async(y)=>{let v=await ia(this.projects.path(y.projectId),y.taskId);return v?nh(v):void 0}),this.idleTurns=new Ng({activity:this.activity,settings:(y)=>this.projects.settings(y),task:(y)=>y.projectId&&y.taskId?this.tasks.get({projectId:y.projectId,taskId:y.taskId}).catch(()=>{return}):Promise.resolve(void 0),dependencyOpen:async(y)=>(await this.tasks.list(y.projectId).catch(()=>[])).some((S)=>y.dependsOn.includes(S.id)&&Le.includes(S.status)),waiting:(y)=>this.teams.othersBusy(y)||fP(this.sessions.find(y.id))||this.readyRuns.awaits(y.id),idle:(y)=>{let v=this.sessions.find(y);return v?.state==="idle"&&!v.pausedUntil&&!this.teams.ended(y)},ask:async(y,v)=>{let S=this.sessions.find(y);if(S?.state!=="idle"||S.pausedUntil)return!1;return await this.sessions.send(y,v,"superfactory"),!0},answered:(y,v)=>void this.teams.statusAnswered(y,v).catch((S)=>s.warn(`teams: ${y.id}'s status not kept`,S)),stuckNow:(y,v)=>{this.sessions.recordEvent(y.id,{type:"notice",level:"warning",kind:hk,text:`No progress on two status checks: ${v.slice(0,300)}`}),this.teams.stuck(y,v).catch((S)=>s.warn("teams: stuck not reported",S))}}),this.ports=new Vr((y,v)=>this.sessions.portAddress(y,v),(y)=>this.link?.send(y)),this.terminals=new Yr(()=>this.nodeId,(y)=>this.link?.send(y)),this.sandboxes=new Xf(this.places,this.projects,()=>this.nodeId),this.places.onDestroyed((y)=>this.sessions.sandboxGone(y)),this.automation=new fp(this.projects,this.tasks,()=>this.sessions,this.placed,async(y)=>this.push({type:"project.updated",project:await this.projects.get(y)}),(y)=>this.merges.mergeLocal(y)),this.github=new kh({projects:this.projects,tasks:this.tasks,deliverComment:(y,v)=>Hl(this.tasks,this.sessions,y,v),mediaUrl:(y,v)=>this.state.serverUrl&&`${this.state.serverUrl}/api/projects/${y.projectId}/tasks/${y.taskId}/media/${encodeURIComponent(v)}`,sandboxFor:(y)=>y.sessionId?this.sessions.sandboxFor(y.sessionId):void 0,resumeMerge:(y)=>this.merges.resumeMerge(y),prMoved:(y)=>this.merges.prMoved(y),mergeFailed:(y,v,S)=>this.merges.failed(y,v,S),recordTest:(y,v,S)=>this.recordTest(y,v,S),testsUrl:(y)=>this.state.serverUrl&&zm(this.state.serverUrl,y),nodeId:()=>this.nodeId,runsElsewhere:async(y)=>{let v=y.machine||(await this.projects.settings(y.projectId))["tasks.machine"];return typeof v==="string"&&!!v&&v!==this.nodeId}})}async wakeManagerWith(d,u){let p=this.managers.get(d);if(!p)throw new c("not_found","no such manager here");if(!await this.wakeCosts.take(p))throw new c("conflict",`${p.name}'s wake budget for today is spent`);let w=await kn(this.sessions,p,u).catch((y)=>{throw this.wakeCosts.giveBack(p.id),y});return this.watchers.woke(w,1),this.wakeCosts.expect(w,p,u,!0),w}async asksUser(d){if(await this.chatQuestions.latestWaiting(d.id))return!0;if(!d.projectId||!d.taskId)return!1;return(await this.tasks.get({projectId:d.projectId,taskId:d.taskId})).questions.some((p)=>p.askedBy===d.id&&(p.status==="open"||p.status==="expired")&&p.kind!=="permission"&&!p.purpose)}previewsChanged(d,u){let p=this.sessions.find(d);if(!p?.projectId||!p.taskId)return;let w={projectId:p.projectId,taskId:p.taskId},y=u.map((v)=>v.label).join(", ")||"none";this.tasks.get(w).then((v)=>this.watchers.emit({type:"preview_updated",...w,labels:v.labels,about:xs(v),actor:d,text:`${p.taskId}: ${this.teams.nameOf(d)} updated the previews (${y})`}))}static async start(){let d=Gt();if(process.env.PATH=k$(process.env.PATH),jm())s.info("machine: the server's machine: nothing it starts gains privileges but its sudo");if(await Al(),hm(),lt())await qi();let u=await W()??fs.parse({name:Xj(),controlToken:Jj(24).toString("hex")}),p=new zp(u),w=await p.serve(zj(m().handedOver));await p.crons.load(),await p.teams.load(),await zi().catch((v)=>s.warn("secrets: couldn't write the sf command",v)),await Ri().catch((v)=>s.warn("plugins: couldn't write out the built-in plugins",v)),await p.places.displays.adopt().catch((v)=>s.warn("displays: couldn't take back what the agent before handed over",v)),await p.places.displays.endLeftovers().catch((v)=>s.warn("displays: couldn't end what an earlier run left",v)),ce().then((v)=>v&&ka(v,0)).catch(()=>{return}),p.state.pid=process.pid,await F(p.state);for(let v of p.projects.ids())p.watch(v);if(p.instructions.watch({scope:{kind:"global"}}),p.automation.start(),p.github.start(),p.repoMirror.start(),p.stallWatch.start(),d.updates)p.selfUpdate=new cw(d,{server:()=>{let v=p.link instanceof gn?p.link.via:void 0;return v?{serverUrl:v.url,pin:v.pin,headers:v.headers}:p.httpLink()},here:{ready:()=>p.settled,idle:()=>p.sessions.cutByRestart().length===0&&!p.terminals.inUse(tL),betweenTools:()=>p.sessions.inTool().length===0},restart:(v)=>(p.relaunch=v,p.updating=!0,p.stop()),changed:()=>void p.pushNode()}),p.selfUpdate.start(),s.info("update: it updates itself to the server's version");else s.info(`update: it doesn't update itself: ${d.why}`);if(p.claudeUpdates.start(),!process.env.SUPERFACTORY_SANDBOX){if(p.systemPermissions.start(),process.platform==="darwin"){let v=async()=>!X()&&await p.dedicated();v().then(async(S)=>{if(!S)return;let x=process.env.SUPERFACTORY_CLAUDE_BIN??Bun.which("claude")??void 0,j=await OS([process.execPath,...x?[x]:[]]);s.info(`system-permissions: this Mac is set aside for Superfactory; ${j.replace(/\n/g,"; ")}`)}).catch((S)=>s.warn("system-permissions: couldn't pre-grant this Mac's tools",S)).finally(()=>lm(v))}}await p.tunnel.start().catch((v)=>s.warn("tunnel: couldn't start",v)),await km().catch((v)=>s.warn("sessions: couldn't keep the agent's sessions through its restarts",v)),await p.sessions.takeHandedBack(w?void 0:"this agent couldn't listen on the port it calls").catch((v)=>s.warn("sessions: couldn't take sessions back",v));for(let v of[p.sessions.github,p.sessions.taskGithub])await v.clear().catch((S)=>s.warn("github: couldn't clear the sessions' token files",S));if(p.sessions.github.start(),p.sessions.taskGithub.start(),await p.connect(),await p.selfUpdate?.beforeResume())return p;p.enrollUnattended(),p.projects.pauseChanged=()=>p.tray.refresh(),p.tray.start().catch((v)=>s.warn("tray: didn't start",v)),await p.sessions.recover(),p.settled=!0,p.readyRuns.load().catch((v)=>s.warn("ready runs: couldn't take them over",v));let y=Promise.all(p.projects.ids().map((v)=>p.tasks.list(v))).then((v)=>v.flat());return y.then((v)=>p.questions.cancelStale(v)).catch((v)=>s.warn("questions: couldn't cancel stale permission prompts",v)),y.then((v)=>p.merges.resume(v)).catch((v)=>s.warn("merge: couldn't ask the questions an earlier run didn't",v)),_b(p),s.info(`agent ${H} listening on 127.0.0.1:${p.state.controlPort} (home ${m().home})`),p}async previewPlanFor(d,u,p){let w=await ai(d.path,u),y=p?.runner==="host"?await this.places.worktreePorts.of(p.cwd):void 0;return y?Vp(w,y,li):w}removeOrphanSandboxes(){return xb(this)}holds(d){return sP(d,{nodeId:this.nodeId,sandboxNodes:this.sessions?.sandboxNodes()??new Set,ownProjects:this.projects.ownIds()})}get nodeId(){return this.state.nodeId??Zj}status(){return{pid:process.pid,version:H,nodeId:this.state.nodeId,serverUrl:this.state.serverUrl,linked:this.link?.connected??!1,removedFrom:this.removedFrom,projects:this.state.projects,sessions:this.sessions.busy().length,settled:this.settled,awaySince:this.away.state?.since,disabled:this.projects.disabled(),paused:this.projects.disabled(),pause:this.projects.pause()}}async setPaused(d,u="finish"){let p=this.link?.connected?this.link:void 0;if(!p)throw new c("unavailable",`${d?"Pause":"Resume"} needs the server: this machine is offline`);let w=this.serverVersion;if(!w||nt(w,H))throw new c("conflict",`the server runs Superfactory ${w??"(not known yet)"}, older than this agent: ${d?"pause":"resume"} it on its page in Machines`);let y=await p.request("nodes.pause",{paused:d,running:u});return await this.projects.setDisabled(y.paused,y.pause),y}traySnapshot(){let d=(u)=>{let p=u.projectId&&u.taskId&&D(u.taskId,this.projects.keys(u.projectId).key);if(u.kind==="coordinator")return p?`the lead of ${p}`:"a lead";if(!p)return`a ${u.kind==="epic"?"epic's":"task's"} session`;return u.teammate?`${p} (${u.teammate.name})`:p};return{serverUrl:this.state.serverUrl,linked:this.link?.connected??!1,paused:this.projects.disabled(),pause:this.projects.pause(),running:this.sessions.busy().map(d),away:process.platform==="darwin"?{since:this.away.state?.since}:void 0,stop:Mm()?"restart":"quit"}}async trayAction(d){if(d==="pause"||d==="pause-move")await this.setPaused(!0,d==="pause-move"?"move":"finish");else if(d==="resume")await this.setPaused(!1);else if(d==="away")await this.setAway(!0);else if(d==="restart")await Tc("agent",(u)=>this.restartForLead(u));else if(d==="quit")setTimeout(()=>void this.stop(),10)}async setAway(d){return await this.away.set(d),this.node&&{...this.node,away:this.away.state}}linked(){return Qk(this)}linkedSoon(){return Jk(this)}onLinked(){zk(this)}learnServerVersion(){return Xk(this)}versionMismatch(d){return Zk(this,d)}async pusher(d){let u=this.mcp.contextOfToken(d);if(!u?.projectId)return;let{projectId:p,taskId:w}=u;if((await this.projects.settings(p).catch(()=>{return}))?.["git.flow"]==="direct")return{projectId:p,rule:{any:!0}};return{projectId:p,rule:{taskId:w}}}serverLink(){return eb(this)}dedicated(){return bb(this)}pushNode(d=!1){return hb(this,d)}checkUsage(){return mb(this)}withMonitors(d){return fb(this,d)}recheckMonitors(){return gb(this)}recheckScreen(){return wb(this)}watchScreenFile(){yb(this)}setUpAgain(){if(!this.node)throw new c("unavailable","the agent hasn't said hello yet");if(!Os.applies())throw new c("conflict","Only a Linux machine with apt sets itself up.");return this.setup.rerun(),{...this.node,setup:this.setup.state}}async setUpProjects(d=this.projects.ids()){for(let u of d){let p=await this.projects.settings(u).catch(()=>{return});if(!p||!Gu(p))continue;await this.setUpProject(u).catch((w)=>s.warn(`project setup: ${u}`,w))}}async prepareLibraries(){await rm(Bt(await this.projects.globalSettings()))}async setupSource(d,u){if(!await this.sessionsConfined())return no(u);let p=(await this.projects.settings(d).catch(()=>{return}))?.["git.baseBranch"];return kl(d,this.projects.path(d),p)}async sessionsConfined(){let d=await this.projects.globalSettings();return await ce().catch(()=>"not ready")!==void 0||d["machine.taskSudo"]===!1&&d["machine.setupSudo"]===!0}async setUpProject(d,u=!1){let p=await this.projects.get(d),w=dn(Bt(await this.projects.settings(d)));if(await this.places.setups.ensure(p.id,p.path,Hi(p.path),{retry:u,env:w}).catch(async(y)=>{if(y instanceof xe&&!u)await y.done}),!this.node)throw new c("unavailable","the agent hasn't said hello yet");return{...this.node,projectSetups:this.places.setups.list()}}async projectNeeds(d){let u=[];for(let p of this.projects.ids()){let w=(await this.projects.settings(p).catch(()=>{return}))?.["git.baseBranch"],y=await this.projects.repoConfigs.of(p,this.projects.path(p),w).catch(()=>{return});for(let v of y?.file?.machines??[])if(v.os===d)u.push(...v.needs)}return[...new Set(u)]}repoTips=new Map;checkRepoConfigs(d){return Mb(this,d)}enroll(d){return ob(this,d)}enrollUnattended(){return ab(this)}linkTo(d){return db(this,d)}async registerProject({path:d,name:u}){let p=await this.projects.init(d,u);return this.announce(p),p}async ensureLeadProject(d,u){if(await this.projects.setHoldsLead(d),await this.sessions.endStrayLeads(),!d)return;let p=await this.projects.ensureLead(u);if(p)this.announce(await this.projects.get(p))}announce(d){this.watch(d.id),this.push({type:"project.updated",project:d}),this.tasks.list(d.id).catch((u)=>s.warn(`tasks: couldn't read ${d.id}'s`,u))}watch(d){this.tasks.watch(d),this.instructions.watch({scope:{kind:"project",projectId:d}}),xa(this)}untilStopped(){return this.stopped.promise}applyNetwork(){return kb(this)}restartForLead(d){return this.relaunch=d,this.updating=!0,this.stop()}stop(){let d=!1;return this.stopping??=Promise.race([this.stopAll().then(()=>{d=!0}),Bun.sleep(eL).then(()=>{if(!d)s.warn(`agent: stopping took too long (still stopping ${this.stoppingStep}); ending now`)})]).finally(()=>{if(this.relaunch){s.info("agent: starting the new build"),Rl();let u={file:m().log};_(this.relaunch,{stdin:"ignore",stdout:u,stderr:u,detached:!0}).unref()}this.stopped.resolve()}),this.stopping}async stopAll(){let d=async(u,p)=>{this.stoppingStep=u;try{await p()}catch(w){s.warn(`agent: stopping ${u} failed`,w)}};await d("the network gate",()=>this.gate.close()),s.info("agent: stopping"),Ob(this),this.stallWatch.stop(),this.selfUpdate?.stop(),this.ownLogin?.stop(),await d("installs",()=>Promise.all([this.claudeUpdates.stop(),lS(),this.places.dependencies.stop()])),this.systemPermissions.stop(),pm(),await d("automation",()=>this.automation.stop()),this.repoMirror.stop(),await d("idle turns",()=>this.idleTurns.stop()),this.readyRuns.stop(),await d("plain asks",()=>this.plainAsks.stop()),await d("watchers",()=>this.watchers.stop()),await d("wake costs",()=>this.wakeCosts.stop()),await d("away",()=>this.away.end("the agent stopped")),await d("tray",()=>this.tray.stop()),await d("github",()=>this.github.stop()),await d("the link",()=>this.link?.stop(this.updating)),await d("terminals",()=>this.terminals.closeAll()),await d("screen recordings",()=>this.recordings.stopAll()),await d("commands",()=>this.commandRuns.stopAll()),await d("sessions",async()=>{if(this.updating)await this.sessions.handOver();await this.sessions.stopAll()}),await d("session logs",()=>Vf()),await d("warm sandboxes",()=>this.places.removeWarm()),await d("worktree displays",async()=>{if(this.updating)await this.places.displays.handOver();await this.places.displays.closeAll()}),await d("sandbox agents",()=>this.children.stopAll()),await d("the WireGuard tunnel",()=>this.tunnel.stop()),await d("tasks",()=>this.tasks.close()),await d("instructions",()=>this.instructions.close()),await d("the control server",()=>this.server?.stop(!0))}recordTest(d,u,p){return Hm({upload:(y,v,S)=>{let x=this.httpLink();return x?lh(x,{...y,runId:v},S):Promise.resolve(void 0)}},d,u,p)}async uploadMedia(d,u,p){let w=this.httpLink();if(w)await ah(w,{...d,name:u},p)}httpLink(){return tb(this)}directLink(){return sb(this)}stalled(d){let u=this.link instanceof gn?this.link.pingedAt:0,p=Date.parse(d.at)-d.ms,w=u?Math.max(0,Math.round(p-u)):void 0,y={busy:"its own work held it",slept:"the machine slept",held:"the process was held up (stopped, swapped out or starved)"}[d.why];if(s.warn(`agent: stalled for ${Math.round(d.ms/1000)} s: ${y} (CPU ${Math.round(d.cpuPct)}%)${w===void 0?"":`; its link last pinged ${Math.round(w/1000)} s before`}`),this.serverVersion&&!nt(this.serverVersion,H))this.push({type:"agent.stalled",...d,cpuPct:Math.round(d.cpuPct),pingedMsBefore:w})}push(d){if(this.link)this.link.push(d);else if(this.early.length<sL)this.early.push(d)}early=[];async openSandboxTerminal(d){let u=await this.projects.get(d.projectId),p=await this.projects.settings(d.projectId),w=p["runner.kind"];if(w==="host")throw new c("conflict","this project has no dev sandbox: choose one in its settings, under Sandboxes");if(!this.children.available())throw new c("unavailable","a sandbox's terminal needs the link to the server");let y=await this.places.devSandbox(u,p),S=await(await this.children.for(y,w,u.id)).call("terminals.start",{...d,cwd:y.workdir});return this.sandboxTerminals.set(S.id,S),S}async openTaskTerminal(d,u,p){let w={kind:"task",taskId:u},y=this.sessions.sandboxPlaceOf(d.projectId,u);if(y?.sandbox){if(!this.children.available())throw new c("unavailable","a sandbox's terminal needs the link to the server");let j={...await(await this.children.for(y.sandbox,y.runner,d.projectId)).call("terminals.start",{...d,cwd:y.sandbox.workdir}),target:w};return this.sandboxTerminals.set(j.id,j),j}if(!p)throw new c("forbidden","only the server owner opens a shell on this machine");let v=await ia(this.projects.path(d.projectId),u);if(!v)throw new c("not_found",`${u} has no worktree here: it gets one when it starts`);return this.terminals.start({...d,target:w,cwd:v})}serverPin(){return nb(this)}connect(){return ib(this)}linkOptions(){return rb(this)}serve(d){return bw(this,d)}route(d){return vw(this,d)}}
|
|
951
|
+
export{Mu,Dp,Up,Fp,Bp,Hp,zp};
|